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"
53#include "llvm/Support/ModRef.h"
56#include <optional>
57
58using namespace llvm;
59using namespace llvm::SDPatternMatch;
60
61#define DEBUG_TYPE "si-lower"
62
63STATISTIC(NumTailCalls, "Number of tail calls");
64
66 return MF.getInfo<SIMachineFunctionInfo>()->getMode().getDenormalFPEnv();
67}
68
73
78
79static unsigned findFirstFreeSGPR(CCState &CCInfo) {
80 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
81 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
82 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
83 return AMDGPU::SGPR0 + Reg;
84 }
85 }
86 llvm_unreachable("Cannot allocate sgpr");
87}
88
90 const GCNSubtarget &STI)
91 : AMDGPUTargetLowering(TM, STI, STI), Subtarget(&STI) {
92 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
93 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
94
95 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
96
97 const SIRegisterInfo *TRI = STI.getRegisterInfo();
98 const TargetRegisterClass *V32RegClass =
99 TRI->getDefaultVectorSuperClassForBitWidth(32);
100 addRegisterClass(MVT::f32, V32RegClass);
101
102 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
103
104 const TargetRegisterClass *V64RegClass =
105 TRI->getDefaultVectorSuperClassForBitWidth(64);
106
107 addRegisterClass(MVT::f64, V64RegClass);
108 addRegisterClass(MVT::v2f32, V64RegClass);
109 addRegisterClass(MVT::Untyped, V64RegClass);
110
111 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
112 addRegisterClass(MVT::v3f32, TRI->getDefaultVectorSuperClassForBitWidth(96));
113
114 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
115 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
116
117 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
118 addRegisterClass(MVT::v4f32, TRI->getDefaultVectorSuperClassForBitWidth(128));
119
120 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
121 addRegisterClass(MVT::v5f32, TRI->getDefaultVectorSuperClassForBitWidth(160));
122
123 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
124 addRegisterClass(MVT::v6f32, TRI->getDefaultVectorSuperClassForBitWidth(192));
125
126 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
127 addRegisterClass(MVT::v3f64, TRI->getDefaultVectorSuperClassForBitWidth(192));
128
129 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
130 addRegisterClass(MVT::v7f32, TRI->getDefaultVectorSuperClassForBitWidth(224));
131
132 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
133 addRegisterClass(MVT::v8f32, TRI->getDefaultVectorSuperClassForBitWidth(256));
134
135 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
136 addRegisterClass(MVT::v4f64, TRI->getDefaultVectorSuperClassForBitWidth(256));
137
138 addRegisterClass(MVT::v9i32, &AMDGPU::SGPR_288RegClass);
139 addRegisterClass(MVT::v9f32, TRI->getDefaultVectorSuperClassForBitWidth(288));
140
141 addRegisterClass(MVT::v10i32, &AMDGPU::SGPR_320RegClass);
142 addRegisterClass(MVT::v10f32,
143 TRI->getDefaultVectorSuperClassForBitWidth(320));
144
145 addRegisterClass(MVT::v11i32, &AMDGPU::SGPR_352RegClass);
146 addRegisterClass(MVT::v11f32,
147 TRI->getDefaultVectorSuperClassForBitWidth(352));
148
149 addRegisterClass(MVT::v12i32, &AMDGPU::SGPR_384RegClass);
150 addRegisterClass(MVT::v12f32,
151 TRI->getDefaultVectorSuperClassForBitWidth(384));
152
153 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
154 addRegisterClass(MVT::v16f32,
155 TRI->getDefaultVectorSuperClassForBitWidth(512));
156
157 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
158 addRegisterClass(MVT::v8f64, TRI->getDefaultVectorSuperClassForBitWidth(512));
159
160 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
161 addRegisterClass(MVT::v16f64,
162 TRI->getDefaultVectorSuperClassForBitWidth(1024));
163
164 if (Subtarget->has16BitInsts()) {
165 if (Subtarget->useRealTrue16Insts()) {
166 addRegisterClass(MVT::i16, &AMDGPU::VGPR_16RegClass);
167 addRegisterClass(MVT::f16, &AMDGPU::VGPR_16RegClass);
168 addRegisterClass(MVT::bf16, &AMDGPU::VGPR_16RegClass);
169 } else {
170 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
171 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
172 addRegisterClass(MVT::bf16, &AMDGPU::SReg_32RegClass);
173 }
174
175 // Unless there are also VOP3P operations, not operations are really legal.
176 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
177 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
178 addRegisterClass(MVT::v2bf16, &AMDGPU::SReg_32RegClass);
179 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
180 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
181 addRegisterClass(MVT::v4bf16, &AMDGPU::SReg_64RegClass);
182 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
183 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
184 addRegisterClass(MVT::v8bf16, &AMDGPU::SGPR_128RegClass);
185 addRegisterClass(MVT::v16i16, &AMDGPU::SGPR_256RegClass);
186 addRegisterClass(MVT::v16f16, &AMDGPU::SGPR_256RegClass);
187 addRegisterClass(MVT::v16bf16, &AMDGPU::SGPR_256RegClass);
188 addRegisterClass(MVT::v32i16, &AMDGPU::SGPR_512RegClass);
189 addRegisterClass(MVT::v32f16, &AMDGPU::SGPR_512RegClass);
190 addRegisterClass(MVT::v32bf16, &AMDGPU::SGPR_512RegClass);
191 }
192
193 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
194 addRegisterClass(MVT::v32f32,
195 TRI->getDefaultVectorSuperClassForBitWidth(1024));
196
197 computeRegisterProperties(Subtarget->getRegisterInfo());
198
201
202 // The boolean content concept here is too inflexible. Compares only ever
203 // really produce a 1-bit result. Any copy/extend from these will turn into a
204 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
205 // it's what most targets use.
208
209 // We need to custom lower vector stores from local memory
211 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
212 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
213 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32,
214 MVT::i1, MVT::v32i32},
215 Custom);
216
218 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
219 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
220 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32,
221 MVT::i1, MVT::v32i32},
222 Custom);
223
224 if (isTypeLegal(MVT::bf16)) {
225 for (unsigned Opc :
234 ISD::SETCC}) {
235 setOperationAction(Opc, MVT::bf16, Promote);
236 }
237
238 // Only targets with packed bf16 instructions, e.g. gfx13.
239 if (Subtarget->hasBF16PackedInsts()) {
240 // Don't use Expand for fsub - the DAG combiner will undo fadd+fneg back
241 // to fsub, causing a libcall (which doesn't exist for bf16). Instead,
242 // directly expand to widened v2bf16 operations.
245 Promote);
246 // Promote scalar operations to a v2bf16 operation with an unused high
247 // lane.
248 for (unsigned Opc :
251 AddPromotedToType(Opc, MVT::bf16, MVT::v2bf16);
252 }
253
255
257 AddPromotedToType(ISD::SELECT, MVT::bf16, MVT::i16);
258
262
263 // We only need to custom lower because we can't specify an action for bf16
264 // sources.
267 }
268
269 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
270 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
271 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
272 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
273 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
274 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
275 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
276 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
277 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
278 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
279 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
280 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
281 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
282 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
283 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
284 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
285
286 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
287 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
288 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
289 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
290 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
291 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
292 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
293
294 setOperationAction(ISD::GlobalAddress, {MVT::i32, MVT::i64}, Custom);
295
296 // Only for an alloca in the VGPR ("as memory") address space.
298 setOperationAction(ISD::BlockAddress, {MVT::i32, MVT::i64}, Custom);
299 setOperationAction(ISD::ExternalSymbol, {MVT::i32, MVT::i64}, Custom);
300
304 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
305
306 setOperationAction(ISD::FSQRT, {MVT::f32, MVT::f64}, Custom);
307
309 {MVT::f32, MVT::i32, MVT::i64, MVT::f64, MVT::i1}, Expand);
310
312 setOperationAction(ISD::SETCC, {MVT::v2i1, MVT::v4i1}, Expand);
313 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
314
316 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
317 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
318 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32},
319 Expand);
321 {MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32,
322 MVT::v6f32, MVT::v7f32, MVT::v8f32, MVT::v9f32,
323 MVT::v10f32, MVT::v11f32, MVT::v12f32, MVT::v16f32},
324 Expand);
325
327 {MVT::v2i1, MVT::v4i1, MVT::v2i8, MVT::v4i8, MVT::v2i16,
328 MVT::v3i16, MVT::v4i16, MVT::Other},
329 Custom);
330
333 {MVT::i1, MVT::i32, MVT::i64, MVT::f32, MVT::f64}, Expand);
334
337
340
342 Expand);
343
345
346 // We only support LOAD/STORE and vector manipulation ops for vectors
347 // with > 4 elements.
348 for (MVT VT :
349 {MVT::v8i32, MVT::v8f32, MVT::v9i32, MVT::v9f32, MVT::v10i32,
350 MVT::v10f32, MVT::v11i32, MVT::v11f32, MVT::v12i32, MVT::v12f32,
351 MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64, MVT::v4i16,
352 MVT::v4f16, MVT::v4bf16, MVT::v3i64, MVT::v3f64, MVT::v6i32,
353 MVT::v6f32, MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
354 MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::v16i16, MVT::v16f16,
355 MVT::v16bf16, MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32,
356 MVT::v32i16, MVT::v32f16, MVT::v32bf16}) {
357 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
358 switch (Op) {
359 case ISD::LOAD:
360 case ISD::STORE:
361 case ISD::ATOMIC_LOAD:
364 case ISD::BITCAST:
365 case ISD::UNDEF:
366 case ISD::POISON:
370 case ISD::IS_FPCLASS:
371 break;
376 break;
377 default:
379 break;
380 }
381 }
382 }
383
385
386 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
387 // is expanded to avoid having two separate loops in case the index is a VGPR.
388
389 // Most operations are naturally 32-bit vector operations. We only support
390 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
391 for (MVT Vec64 : {MVT::v2i64, MVT::v2f64}) {
393 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
394
396 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
397
399 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
400
402 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
403 }
404
405 for (MVT Vec64 : {MVT::v3i64, MVT::v3f64}) {
407 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
408
410 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
411
413 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
414
416 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
417 }
418
419 for (MVT Vec64 : {MVT::v4i64, MVT::v4f64}) {
421 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
422
424 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
425
427 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
428
430 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
431 }
432
433 for (MVT Vec64 : {MVT::v8i64, MVT::v8f64}) {
435 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
436
438 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
439
441 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
442
444 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
445 }
446
447 for (MVT Vec64 : {MVT::v16i64, MVT::v16f64}) {
449 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
450
452 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
453
455 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
456
458 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
459 }
460
462 {MVT::v4i32, MVT::v4f32, MVT::v8i32, MVT::v8f32,
463 MVT::v16i32, MVT::v16f32, MVT::v32i32, MVT::v32f32},
464 Custom);
465
466 if (Subtarget->hasPkMovB32()) {
467 // TODO: 16-bit element vectors should be legal with even aligned elements.
468 // TODO: Can be legal with wider source types than the result with
469 // subregister extracts.
470 setOperationAction(ISD::VECTOR_SHUFFLE, {MVT::v2i32, MVT::v2f32}, Legal);
471 }
472
474 // Prevent SELECT v2i32 from being implemented with the above bitwise ops and
475 // instead lower to cndmask in SITargetLowering::LowerSELECT().
477 // Enable MatchRotate to produce ISD::ROTR, which is later transformed to
478 // alignbit.
479 setOperationAction(ISD::ROTR, MVT::v2i32, Custom);
480
481 setOperationAction(ISD::BUILD_VECTOR, {MVT::v4f16, MVT::v4i16, MVT::v4bf16},
482 Custom);
483
484 // Avoid stack access for these.
485 // TODO: Generalize to wider i8 vectors.
487 {MVT::v2i16, MVT::v2f16, MVT::v2bf16, MVT::v2i8, MVT::v4i8,
488 MVT::v8i8, MVT::v4i16, MVT::v4f16, MVT::v4bf16},
489 Custom);
490
491 // Deal with vec3 vector operations when widened to vec4.
493 {MVT::v3i32, MVT::v3f32, MVT::v4i32, MVT::v4f32}, Custom);
494
495 // Deal with vec5/6/7 vector operations when widened to vec8.
497 {MVT::v5i32, MVT::v5f32, MVT::v6i32, MVT::v6f32,
498 MVT::v7i32, MVT::v7f32, MVT::v8i32, MVT::v8f32,
499 MVT::v9i32, MVT::v9f32, MVT::v10i32, MVT::v10f32,
500 MVT::v11i32, MVT::v11f32, MVT::v12i32, MVT::v12f32},
501 Custom);
502
503 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
504 // and output demarshalling
505 setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i32, MVT::i64}, Custom);
506
507 // We can't return success/failure, only the old value,
508 // let LLVM add the comparison
510 Expand);
511
512 setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom);
513
514 setOperationAction(ISD::BITREVERSE, {MVT::i32, MVT::i64}, Legal);
515
516 // FIXME: This should be narrowed to i32, but that only happens if i64 is
517 // illegal.
518 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
519 setOperationAction(ISD::BSWAP, {MVT::i64, MVT::i32}, Legal);
520
521 // On SI this is s_memtime and s_memrealtime on VI.
523
524 if (Subtarget->hasSMemRealTime() ||
525 Subtarget->getGeneration() >= AMDGPUSubtarget::GFX11)
528
529 if (Subtarget->has16BitInsts()) {
532 setOperationAction(ISD::IS_FPCLASS, {MVT::f16, MVT::f32, MVT::f64}, Legal);
535 } else {
537 }
538
539 if (Subtarget->hasMadMacF32Insts())
541
545
546 // We only really have 32-bit BFE instructions (and 16-bit on VI).
547 //
548 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
549 // effort to match them now. We want this to be false for i64 cases when the
550 // extraction isn't restricted to the upper or lower half. Ideally we would
551 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
552 // span the midpoint are probably relatively rare, so don't worry about them
553 // for now.
555
556 // Clamp modifier on add/sub
557 if (Subtarget->hasIntClamp())
559
560 if (Subtarget->hasAddNoCarryInsts())
561 setOperationAction({ISD::SADDSAT, ISD::SSUBSAT}, {MVT::i16, MVT::i32},
562 Legal);
563
564 // Do not have s_{min|max}_*f64 instruction f64 will only be lowered to
565 // v_{min|max}_*f64
566 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
569 {MVT::f64, MVT::f32}, Legal);
570 } else {
573 {MVT::f64, MVT::f32}, Custom);
574 // These are really only legal for ieee_mode functions. We should be
575 // avoiding them for functions that don't have ieee_mode enabled, so just
576 // say they are legal.
578 {MVT::f64, MVT::f32}, Legal);
579 }
580
581 if (Subtarget->haveRoundOpsF64())
583 Legal);
584 else
586 MVT::f64, Custom);
587
589 setOperationAction({ISD::FLDEXP, ISD::STRICT_FLDEXP}, {MVT::f32, MVT::f64},
590 Legal);
591 setOperationAction(ISD::FFREXP, {MVT::f32, MVT::f64}, Custom);
592
595
596 setOperationAction(ISD::BF16_TO_FP, {MVT::i16, MVT::f32, MVT::f64}, Expand);
597 setOperationAction(ISD::FP_TO_BF16, {MVT::i16, MVT::f32, MVT::f64}, Expand);
598
600 Custom);
602 Custom);
604 Custom);
605
606 // Custom lower these because we can't specify a rule based on an illegal
607 // source bf16.
610
611 if (Subtarget->has16BitInsts()) {
614 MVT::i16, Legal);
615
616 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
617
619 MVT::i16, Expand);
620
624 ISD::CTPOP},
625 MVT::i16, Promote);
626
628
629 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
630
632 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
634 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
635
640
642
643 // F16 - Constant Actions.
646
647 // F16 - Load/Store Actions.
649 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
651 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
652
653 // BF16 - Load/Store Actions.
655 AddPromotedToType(ISD::LOAD, MVT::bf16, MVT::i16);
657 AddPromotedToType(ISD::STORE, MVT::bf16, MVT::i16);
658
659 if (!Subtarget->useRealTrue16Insts() ||
660 !Subtarget->d16PreservesUnusedBits()) {
661 for (MVT VT : {MVT::i16, MVT::f16, MVT::bf16}) {
663 AddPromotedToType(ISD::ATOMIC_LOAD, VT, MVT::i32);
664 }
665 }
666
667 if (!Subtarget->useRealTrue16Insts()) {
668 for (MVT VT : {MVT::i16, MVT::f16, MVT::bf16}) {
671 }
672 }
673
674 // F16 - VOP1 Actions.
677 MVT::f16, Custom);
678
679 // BF16 - VOP1 Actions.
680 if (Subtarget->hasBF16TransInsts())
682
683 // F16 - VOP2 Actions.
684 setOperationAction({ISD::BR_CC, ISD::SELECT_CC}, {MVT::f16, MVT::bf16},
685 Expand);
689
690 // F16 - VOP3 Actions.
692 if (STI.hasMadF16())
694
695 for (MVT VT :
696 {MVT::v2i16, MVT::v2f16, MVT::v2bf16, MVT::v4i16, MVT::v4f16,
697 MVT::v4bf16, MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::v16i16,
698 MVT::v16f16, MVT::v16bf16, MVT::v32i16, MVT::v32f16}) {
699 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
700 switch (Op) {
701 case ISD::LOAD:
702 case ISD::STORE:
703 case ISD::ATOMIC_LOAD:
706 case ISD::BITCAST:
707 case ISD::UNDEF:
708 case ISD::POISON:
713 case ISD::IS_FPCLASS:
714 break;
717 case ISD::FSIN:
718 case ISD::FCOS:
720 break;
721 default:
723 break;
724 }
725 }
726 }
727
728 // v_perm_b32 can handle either of these.
729 setOperationAction(ISD::BSWAP, {MVT::i16, MVT::v2i16}, Legal);
731
732 // Legalize vector types for sat conversions to select v_cvt_pk_[iu]16_f32.
733 if (Subtarget->hasVCvtPkIU16F32())
736 {MVT::v2i16, MVT::v4i16, MVT::v8i16, MVT::v16i16, MVT::v32i16},
737 Custom);
738
739 // XXX - Do these do anything? Vector constants turn into build_vector.
740 setOperationAction(ISD::Constant, {MVT::v2i16, MVT::v2f16}, Legal);
741
743 {MVT::v2i16, MVT::v2f16, MVT::v2bf16}, Legal);
744
746 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
748 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
749
751 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
753 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
754
755 setOperationAction(ISD::AND, MVT::v2i16, Promote);
756 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
757 setOperationAction(ISD::OR, MVT::v2i16, Promote);
758 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
759 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
760 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
761
763 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
765 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
766 setOperationAction(ISD::LOAD, MVT::v4bf16, Promote);
767 AddPromotedToType(ISD::LOAD, MVT::v4bf16, MVT::v2i32);
768
770 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
772 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
774 AddPromotedToType(ISD::STORE, MVT::v4bf16, MVT::v2i32);
775
777 AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
779 AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
780 setOperationAction(ISD::LOAD, MVT::v8bf16, Promote);
781 AddPromotedToType(ISD::LOAD, MVT::v8bf16, MVT::v4i32);
782
784 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
786 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
787
789 AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
791 AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
793 AddPromotedToType(ISD::STORE, MVT::v8bf16, MVT::v4i32);
794
795 setOperationAction(ISD::LOAD, MVT::v16i16, Promote);
796 AddPromotedToType(ISD::LOAD, MVT::v16i16, MVT::v8i32);
797 setOperationAction(ISD::LOAD, MVT::v16f16, Promote);
798 AddPromotedToType(ISD::LOAD, MVT::v16f16, MVT::v8i32);
799 setOperationAction(ISD::LOAD, MVT::v16bf16, Promote);
800 AddPromotedToType(ISD::LOAD, MVT::v16bf16, MVT::v8i32);
801
803 AddPromotedToType(ISD::STORE, MVT::v16i16, MVT::v8i32);
805 AddPromotedToType(ISD::STORE, MVT::v16f16, MVT::v8i32);
806 setOperationAction(ISD::STORE, MVT::v16bf16, Promote);
807 AddPromotedToType(ISD::STORE, MVT::v16bf16, MVT::v8i32);
808
809 setOperationAction(ISD::LOAD, MVT::v32i16, Promote);
810 AddPromotedToType(ISD::LOAD, MVT::v32i16, MVT::v16i32);
811 setOperationAction(ISD::LOAD, MVT::v32f16, Promote);
812 AddPromotedToType(ISD::LOAD, MVT::v32f16, MVT::v16i32);
813 setOperationAction(ISD::LOAD, MVT::v32bf16, Promote);
814 AddPromotedToType(ISD::LOAD, MVT::v32bf16, MVT::v16i32);
815
817 AddPromotedToType(ISD::STORE, MVT::v32i16, MVT::v16i32);
819 AddPromotedToType(ISD::STORE, MVT::v32f16, MVT::v16i32);
820 setOperationAction(ISD::STORE, MVT::v32bf16, Promote);
821 AddPromotedToType(ISD::STORE, MVT::v32bf16, MVT::v16i32);
822
824 MVT::v2i32, Expand);
826
828 MVT::v4i32, Expand);
829
831 MVT::v8i32, Expand);
832
833 setOperationAction(ISD::BUILD_VECTOR, {MVT::v2i16, MVT::v2f16, MVT::v2bf16},
834 Subtarget->hasVOP3PInsts() ? Legal : Custom);
835
836 setOperationAction(ISD::FNEG, {MVT::v2f16, MVT::v2bf16}, Legal);
837 // This isn't really legal, but this avoids the legalizer unrolling it (and
838 // allows matching fneg (fabs x) patterns)
839 setOperationAction(ISD::FABS, {MVT::v2f16, MVT::v2bf16}, Legal);
840
841 // Can do this in one BFI plus a constant materialize.
843 {MVT::v2f16, MVT::v2bf16, MVT::v4f16, MVT::v4bf16,
844 MVT::v8f16, MVT::v8bf16, MVT::v16f16, MVT::v16bf16,
845 MVT::v32f16, MVT::v32bf16},
846 Custom);
847 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
850 MVT::f16, Legal);
851
854 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16}, Custom);
855 } else {
858 MVT::f16, Custom);
859
861 Legal);
862
865 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
866 Custom);
867
869 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
870 Expand);
871 }
872
873 for (MVT Vec16 :
874 {MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::v16i16, MVT::v16f16,
875 MVT::v16bf16, MVT::v32i16, MVT::v32f16, MVT::v32bf16}) {
878 Vec16, Custom);
879 }
880 }
881
882 if (Subtarget->hasVOP3PInsts()) {
886 MVT::v2i16, Legal);
887
890 MVT::v2f16, Legal);
891
893 {MVT::v2i16, MVT::v2f16, MVT::v2bf16}, Custom);
894
896 {MVT::v4f16, MVT::v4i16, MVT::v4bf16, MVT::v8f16,
897 MVT::v8i16, MVT::v8bf16, MVT::v16f16, MVT::v16i16,
898 MVT::v16bf16, MVT::v32f16, MVT::v32i16, MVT::v32bf16},
899 Custom);
900
901 for (MVT VT : {MVT::v4i16, MVT::v8i16, MVT::v16i16, MVT::v32i16})
902 // Split vector operations.
907 VT, Custom);
908
909 for (MVT VT : {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16})
910 // Split vector operations.
913 VT, Custom);
914
915 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
918 MVT::v2f16, Legal);
919 } else {
921 Legal);
922
925 {MVT::v2f16, MVT::v4f16}, Custom);
926 }
927 setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
928 setOperationAction(ISD::SELECT, {MVT::v4i16, MVT::v4f16, MVT::v4bf16},
929 Custom);
930
931 if (Subtarget->hasBF16PackedInsts()) {
935 MVT::v2bf16, Legal);
936
937 for (MVT VT : {MVT::v4bf16, MVT::v8bf16, MVT::v16bf16, MVT::v32bf16})
938 // Split vector operations.
942 VT, Custom);
943 }
944
945 if (Subtarget->hasAnyPackedFP32Ops()) {
947 MVT::v2f32, Legal);
949 {MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32},
950 Custom);
951 }
952 if (Subtarget->hasAnyPackedFP64Ops()) {
955 MVT::v2f64, Legal);
958 {MVT::v4f64, MVT::v8f64, MVT::v16f64, MVT::v32f64}, Custom);
959
960 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
963 MVT::v2f64, Legal);
964
967 {MVT::v4f64, MVT::v8f64, MVT::v16f64, MVT::v32f64}, Custom);
968 } else {
970 Legal);
973 MVT::v2f64, Custom);
976 {MVT::v4f64, MVT::v8f64, MVT::v16f64, MVT::v32f64},
977 Custom);
978 }
979 }
980
981 if (Subtarget->hasAnyPackedU64Ops()) {
983 MVT::v2i64, Legal);
985 {MVT::v4i64, MVT::v8i64, MVT::v16i64, MVT::v32i64},
986 Custom);
987 }
988 }
989
991
992 if (Subtarget->has16BitInsts()) {
994 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
996 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
998 AddPromotedToType(ISD::SELECT, MVT::v2bf16, MVT::i32);
999 } else {
1000 // Legalization hack.
1001 setOperationAction(ISD::SELECT, {MVT::v2i16, MVT::v2f16}, Custom);
1002
1004 }
1005
1007 {MVT::v4i16, MVT::v4f16, MVT::v4bf16, MVT::v2i8, MVT::v4i8,
1008 MVT::v8i8, MVT::v8i16, MVT::v8f16, MVT::v8bf16,
1009 MVT::v16i16, MVT::v16f16, MVT::v16bf16, MVT::v32i16,
1010 MVT::v32f16, MVT::v32bf16},
1011 Custom);
1012
1014
1015 if (Subtarget->useVMulU64Inst())
1016 setOperationAction(ISD::MUL, MVT::i64, Legal);
1017 else if (Subtarget->hasScalarSMulU64())
1019
1020 if (Subtarget->hasMad64_32())
1022
1023 if (Subtarget->hasSafeSmemPrefetch() || Subtarget->hasVmemPrefInsts())
1025 // Type legalization cannot expand the i128 pointer of a buffer resource
1026 // prefetch; lowerPREFETCH drops the prefetch instead.
1028
1029 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
1031 {MVT::f16, MVT::f32, MVT::f64, MVT::v2f16}, Legal);
1032 } else {
1033 // FIXME: For nnan fmaximum, emit the fmaximum3 instead of fmaxnum
1034 if (Subtarget->hasMinimum3Maximum3F32())
1036
1037 if (Subtarget->hasMinimum3Maximum3PKF16()) {
1039
1040 // If only the vector form is available, we need to widen to a vector.
1041 if (!Subtarget->hasMinimum3Maximum3F16())
1043 MVT::v2f16);
1044 }
1045 }
1046
1047 if (Subtarget->hasVOP3PInsts()) {
1048 // We want to break these into v2f16 pieces, not scalarize.
1050 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
1051 Custom);
1052 }
1053
1054 if (Subtarget->useMinMaxI64Insts())
1056 Legal);
1057
1059 {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16,
1060 MVT::bf16, MVT::v2i16, MVT::v2f16, MVT::v2bf16, MVT::i128,
1061 MVT::i8},
1062 Custom);
1063
1065 {MVT::v2f16, MVT::v2i16, MVT::v2bf16, MVT::v3f16,
1066 MVT::v3i16, MVT::v4f16, MVT::v4i16, MVT::v4bf16,
1067 MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::Other, MVT::f16,
1068 MVT::i16, MVT::bf16, MVT::i8, MVT::i128},
1069 Custom);
1070
1071 // The s_buffer_load intrinsics accept any result type in IR, but only a few
1072 // of them can be selected. Mark the remaining illegal result types Custom so
1073 // ReplaceNodeResults gets a chance to diagnose them instead of letting the
1074 // type legalizer abort. Its INTRINSIC_WO_CHAIN case dispatches on the
1075 // intrinsic ID, but INTRINSIC_W_CHAIN does not, so remember the types added
1076 // here to keep other chained intrinsics on generic legalization.
1077 for (MVT VT : MVT::all_valuetypes()) {
1078 if (VT.isScalableVector() || isTypeLegal(VT))
1079 continue;
1083 SBufferLoadDiagnosticVTs.set(VT.SimpleTy);
1084 }
1085 }
1086
1088 {MVT::Other, MVT::v2i16, MVT::v2f16, MVT::v2bf16,
1089 MVT::v3i16, MVT::v3f16, MVT::v4f16, MVT::v4i16,
1090 MVT::v4bf16, MVT::v8i16, MVT::v8f16, MVT::v8bf16,
1091 MVT::f16, MVT::i16, MVT::bf16, MVT::i8, MVT::i128},
1092 Custom);
1093
1099
1100 // TODO: Could move this to custom lowering, could benefit from combines on
1101 // extract of relevant bits.
1103
1105
1106 if (Subtarget->hasBF16ConversionInsts()) {
1108 {MVT::bf16, MVT::v2bf16}, Custom);
1110 }
1111
1112 if (Subtarget->hasBF16TransInsts()) {
1114 }
1115
1116 const bool HasE5M3ConversionInsts =
1117 Subtarget->hasFP8ConversionInsts() && Subtarget->hasFP8E5M3Insts();
1118 if (Subtarget->hasOCPFP8ConversionInsts() || HasE5M3ConversionInsts) {
1119 setOperationAction(ISD::CONVERT_FROM_ARBITRARY_FP, {MVT::f32, MVT::v2f32},
1120 Custom);
1122
1123 // i8 result promotes to i16, wider vectors split down to v2i8, and v2i8 is
1124 // handled in ReplaceNodeResults before the legalizer splits it per lane.
1125 setOperationAction(ISD::CONVERT_TO_ARBITRARY_FP, {MVT::i16, MVT::v2i8},
1126 Custom);
1127 }
1128
1129 if (Subtarget->hasFP8F16ConversionInsts()) {
1130 setOperationAction(ISD::CONVERT_FROM_ARBITRARY_FP, {MVT::f16, MVT::v2f16},
1131 Custom);
1132 }
1133
1134 if (Subtarget->hasCvtPkF16F32Inst()) {
1136 {MVT::v2f16, MVT::v4f16, MVT::v8f16, MVT::v16f16},
1137 Custom);
1138 }
1139
1142 ISD::SUB,
1143 ISD::MUL,
1144 ISD::FADD,
1145 ISD::FSUB,
1146 ISD::FDIV,
1147 ISD::FMUL,
1156 ISD::FMA,
1157 ISD::ABS,
1158 ISD::SMIN,
1159 ISD::SMAX,
1160 ISD::UMIN,
1161 ISD::UMAX,
1162 ISD::SETCC,
1164 ISD::SMIN,
1165 ISD::SMAX,
1166 ISD::UMIN,
1167 ISD::UMAX,
1170 ISD::AND,
1171 ISD::OR,
1172 ISD::XOR,
1173 ISD::SHL,
1174 ISD::SRL,
1175 ISD::SRA,
1176 ISD::FSHR,
1188
1189 if (Subtarget->has16BitInsts() && !Subtarget->hasMed3_16())
1191
1192 // All memory operations. Some folding on the pointer operand is done to help
1193 // matching the constant offsets in the addressing modes.
1195 ISD::STORE,
1220
1221 // FIXME: In other contexts we pretend this is a per-function property.
1223
1225}
1226
1227const GCNSubtarget *SITargetLowering::getSubtarget() const { return Subtarget; }
1228
1230 static const MCPhysReg RCRegs[] = {AMDGPU::MODE};
1231 return RCRegs;
1232}
1233
1234//===----------------------------------------------------------------------===//
1235// TargetLowering queries
1236//===----------------------------------------------------------------------===//
1237
1238// v_mad_mix* support a conversion from f16 to f32.
1239//
1240// There is only one special case when denormals are enabled we don't currently,
1241// where this is OK to use.
1242bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
1243 EVT DestVT, EVT SrcVT) const {
1244 return DestVT.getScalarType() == MVT::f32 &&
1245 ((((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
1246 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
1247 SrcVT.getScalarType() == MVT::f16) ||
1248 (Opcode == ISD::FMA && Subtarget->hasFmaMixBF16Insts() &&
1249 SrcVT.getScalarType() == MVT::bf16)) &&
1250 // TODO: This probably only requires no input flushing?
1252}
1253
1255 LLT DestTy, LLT SrcTy) const {
1256 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
1257 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
1258 DestTy.getScalarSizeInBits() == 32 &&
1259 SrcTy.getScalarSizeInBits() == 16 &&
1260 // TODO: This probably only requires no input flushing?
1261 denormalModeIsFlushAllF32(*MI.getMF());
1262}
1263
1265 // SI has some legal vector types, but no legal vector operations. Say no
1266 // shuffles are legal in order to prefer scalarizing some vector operations.
1267 return false;
1268}
1269
1272 EVT VT) const {
1275
1276 if (VT.isVector()) {
1277 EVT ScalarVT = VT.getScalarType();
1278 unsigned Size = ScalarVT.getSizeInBits();
1279 if (Size == 16) {
1280 return Subtarget->has16BitInsts()
1281 ? MVT::getVectorVT(ScalarVT.getSimpleVT(), 2)
1282 : MVT::i32;
1283 }
1284
1285 if (Size < 16)
1286 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
1287 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
1288 }
1289
1290 if (!Subtarget->has16BitInsts() && VT.getSizeInBits() == 16)
1291 return MVT::i32;
1292
1293 if (VT.getSizeInBits() > 32)
1294 return MVT::i32;
1295
1297}
1298
1301 EVT VT) const {
1304
1305 if (VT.isVector()) {
1306 unsigned NumElts = VT.getVectorNumElements();
1307 EVT ScalarVT = VT.getScalarType();
1308 unsigned Size = ScalarVT.getSizeInBits();
1309
1310 // FIXME: Should probably promote 8-bit vectors to i16.
1311 if (Size == 16)
1312 return (NumElts + 1) / 2;
1313
1314 if (Size <= 32)
1315 return NumElts;
1316
1317 if (Size > 32)
1318 return NumElts * ((Size + 31) / 32);
1319 } else if (VT.getSizeInBits() > 32)
1320 return (VT.getSizeInBits() + 31) / 32;
1321
1323}
1324
1326 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
1327 unsigned &NumIntermediates, MVT &RegisterVT) const {
1328 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1329 unsigned NumElts = VT.getVectorNumElements();
1330 EVT ScalarVT = VT.getScalarType();
1331 unsigned Size = ScalarVT.getSizeInBits();
1332 // FIXME: We should fix the ABI to be the same on targets without 16-bit
1333 // support, but unless we can properly handle 3-vectors, it will be still be
1334 // inconsistent.
1335 if (Size == 16) {
1336 MVT SimpleIntermediateVT =
1338 IntermediateVT = SimpleIntermediateVT;
1339 RegisterVT = Subtarget->has16BitInsts() ? SimpleIntermediateVT : MVT::i32;
1340 NumIntermediates = (NumElts + 1) / 2;
1341 return (NumElts + 1) / 2;
1342 }
1343
1344 if (Size == 32) {
1345 RegisterVT = ScalarVT.getSimpleVT();
1346 IntermediateVT = RegisterVT;
1347 NumIntermediates = NumElts;
1348 return NumIntermediates;
1349 }
1350
1351 if (Size < 16 && Subtarget->has16BitInsts()) {
1352 // FIXME: Should probably form v2i16 pieces
1353 RegisterVT = MVT::i16;
1354 IntermediateVT = ScalarVT;
1355 NumIntermediates = NumElts;
1356 return NumIntermediates;
1357 }
1358
1359 if (Size != 16 && Size <= 32) {
1360 RegisterVT = MVT::i32;
1361 IntermediateVT = ScalarVT;
1362 NumIntermediates = NumElts;
1363 return NumIntermediates;
1364 }
1365
1366 if (Size > 32) {
1367 RegisterVT = MVT::i32;
1368 IntermediateVT = RegisterVT;
1369 NumIntermediates = NumElts * ((Size + 31) / 32);
1370 return NumIntermediates;
1371 }
1372 }
1373
1375 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1376}
1377
1379 const DataLayout &DL, Type *Ty,
1380 unsigned MaxNumLanes) {
1381 assert(MaxNumLanes != 0);
1382
1383 LLVMContext &Ctx = Ty->getContext();
1384 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1385 unsigned NumElts = std::min(MaxNumLanes, VT->getNumElements());
1386 return EVT::getVectorVT(Ctx, TLI.getValueType(DL, VT->getElementType()),
1387 NumElts);
1388 }
1389
1390 return TLI.getValueType(DL, Ty);
1391}
1392
1393// Peek through TFE struct returns to only use the data size.
1395 const DataLayout &DL, Type *Ty,
1396 unsigned MaxNumLanes) {
1397 auto *ST = dyn_cast<StructType>(Ty);
1398 if (!ST)
1399 return memVTFromLoadIntrData(TLI, DL, Ty, MaxNumLanes);
1400
1401 // TFE intrinsics return an aggregate type.
1402 assert(ST->getNumContainedTypes() == 2 &&
1403 ST->getContainedType(1)->isIntegerTy(32));
1404 return memVTFromLoadIntrData(TLI, DL, ST->getContainedType(0), MaxNumLanes);
1405}
1406
1407/// Map address space 7 to MVT::amdgpuBufferFatPointer because that's its
1408/// in-memory representation. This return value is a custom type because there
1409/// is no MVT::i160 and adding one breaks integer promotion logic. While this
1410/// could cause issues during codegen, these address space 7 pointers will be
1411/// rewritten away by then. Therefore, we can return MVT::amdgpuBufferFatPointer
1412/// in order to allow pre-codegen passes that query TargetTransformInfo, often
1413/// for cost modeling, to work. (This also sets us up decently for doing the
1414/// buffer lowering in GlobalISel if SelectionDAG ever goes away.)
1416 if (AMDGPUAS::BUFFER_FAT_POINTER == AS && DL.getPointerSizeInBits(AS) == 160)
1417 return MVT::amdgpuBufferFatPointer;
1419 DL.getPointerSizeInBits(AS) == 192)
1420 return MVT::amdgpuBufferStridedPointer;
1422}
1423/// Similarly, the in-memory representation of a p7 is {p8, i32}, aka
1424/// v8i32 when padding is added.
1425/// The in-memory representation of a p9 is {p8, i32, i32}, which is
1426/// also v8i32 with padding.
1428 if ((AMDGPUAS::BUFFER_FAT_POINTER == AS &&
1429 DL.getPointerSizeInBits(AS) == 160) ||
1431 DL.getPointerSizeInBits(AS) == 192))
1432 return MVT::v8i32;
1434}
1435
1436static unsigned getIntrMemWidth(unsigned IntrID) {
1437 switch (IntrID) {
1438 case Intrinsic::amdgcn_global_load_async_to_lds_b8:
1439 case Intrinsic::amdgcn_cluster_load_async_to_lds_b8:
1440 case Intrinsic::amdgcn_global_store_async_from_lds_b8:
1441 return 8;
1442 case Intrinsic::amdgcn_global_load_async_to_lds_b32:
1443 case Intrinsic::amdgcn_cluster_load_async_to_lds_b32:
1444 case Intrinsic::amdgcn_global_store_async_from_lds_b32:
1445 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
1446 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
1447 case Intrinsic::amdgcn_flat_load_monitor_b32:
1448 case Intrinsic::amdgcn_global_load_monitor_b32:
1449 return 32;
1450 case Intrinsic::amdgcn_global_load_async_to_lds_b64:
1451 case Intrinsic::amdgcn_cluster_load_async_to_lds_b64:
1452 case Intrinsic::amdgcn_global_store_async_from_lds_b64:
1453 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
1454 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
1455 case Intrinsic::amdgcn_flat_load_monitor_b64:
1456 case Intrinsic::amdgcn_global_load_monitor_b64:
1457 return 64;
1458 case Intrinsic::amdgcn_global_load_async_to_lds_b128:
1459 case Intrinsic::amdgcn_cluster_load_async_to_lds_b128:
1460 case Intrinsic::amdgcn_global_store_async_from_lds_b128:
1461 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B:
1462 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B:
1463 case Intrinsic::amdgcn_flat_load_monitor_b128:
1464 case Intrinsic::amdgcn_global_load_monitor_b128:
1465 return 128;
1466 default:
1467 llvm_unreachable("Unknown width");
1468 }
1469}
1470
1472 unsigned ArgIdx) {
1473 Value *OrderingArg = CI.getArgOperand(ArgIdx);
1474 unsigned Ord = cast<ConstantInt>(OrderingArg)->getZExtValue();
1475 switch (AtomicOrderingCABI(Ord)) {
1478 break;
1481 break;
1484 break;
1485 default:
1487 }
1488}
1489
1490static unsigned parseSyncscopeMDArg(const CallBase &CI, unsigned ArgIdx) {
1491 MDNode *ScopeMD = cast<MDNode>(
1492 cast<MetadataAsValue>(CI.getArgOperand(ArgIdx))->getMetadata());
1493 StringRef Scope = cast<MDString>(ScopeMD->getOperand(0))->getString();
1494 return CI.getContext().getOrInsertSyncScopeID(Scope);
1495}
1496
1498 const CallBase &CI,
1499 MachineFunction &MF,
1500 unsigned IntrID) const {
1502 if (CI.hasMetadata(LLVMContext::MD_invariant_load))
1504 if (CI.hasMetadata(LLVMContext::MD_nontemporal))
1506 Flags |= getTargetMMOFlags(CI);
1507
1508 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1510 AttributeSet Attr =
1512 MemoryEffects ME = Attr.getMemoryEffects();
1513 if (ME.doesNotAccessMemory())
1514 return;
1515
1516 const AMDGPU::BufferIntrinsicInfo *BufInfo =
1518 bool IsSPrefetch = BufInfo && BufInfo->Kind == AMDGPU::BufferKindPrefetch;
1519 std::optional<unsigned> AuxArg =
1520 BufInfo ? BufInfo->getAuxArg() : CI.arg_size() - 1;
1521 if (AuxArg) {
1522 auto *Aux = cast<ConstantInt>(CI.getArgOperand(*AuxArg));
1523 if (Aux->getZExtValue() & AMDGPU::CPol::VOLATILE)
1525 }
1526
1528
1529 IntrinsicInfo Info;
1530 // TODO: Should images get their own address space?
1532
1533 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = nullptr;
1534 if (RsrcIntr->IsImage) {
1535 const AMDGPU::ImageDimIntrinsicInfo *Intr =
1537 BaseOpcode = AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1538 Info.align.reset();
1539 }
1540
1541 Value *RsrcArg = CI.getArgOperand(RsrcIntr->RsrcArg);
1542 if (auto *RsrcPtrTy = dyn_cast<PointerType>(RsrcArg->getType())) {
1543 if (RsrcPtrTy->getAddressSpace() == AMDGPUAS::BUFFER_RESOURCE)
1544 // We conservatively set the memory operand of a buffer intrinsic to the
1545 // base resource pointer, so that we can access alias information about
1546 // those pointers. Cases like "this points at the same value
1547 // but with a different offset" are handled in
1548 // areMemAccessesTriviallyDisjoint.
1549 Info.ptrVal = RsrcArg;
1550 }
1551
1552 if (ME.onlyReadsMemory()) {
1553 if (RsrcIntr->IsImage) {
1554 unsigned MaxNumLanes = 4;
1555
1556 if (!BaseOpcode->Gather4) {
1557 // If this isn't a gather, we may have excess loaded elements in the
1558 // IR type. Check the dmask for the real number of elements loaded.
1559 unsigned DMask =
1560 cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1561 MaxNumLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1562 }
1563
1564 Info.memVT = memVTFromLoadIntrReturn(*this, MF.getDataLayout(),
1565 CI.getType(), MaxNumLanes);
1566 } else {
1567 Info.memVT =
1569 std::numeric_limits<unsigned>::max());
1570 }
1571
1572 // FIXME: What does alignment mean for an image?
1573 Info.opc = ISD::INTRINSIC_W_CHAIN;
1574 Info.flags = Flags | MachineMemOperand::MOLoad;
1575 } else if (ME.onlyWritesMemory()) {
1576 Info.opc = ISD::INTRINSIC_VOID;
1577
1578 Type *DataTy = CI.getArgOperand(0)->getType();
1579 if (RsrcIntr->IsImage) {
1580 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1581 unsigned DMaskLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1582 Info.memVT = memVTFromLoadIntrData(*this, MF.getDataLayout(), DataTy,
1583 DMaskLanes);
1584 } else
1585 Info.memVT = getValueType(MF.getDataLayout(), DataTy);
1586
1587 Info.flags = Flags | MachineMemOperand::MOStore;
1588 } else {
1589 // Atomic, NoReturn Sampler or prefetch
1590 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID
1592
1593 if (BufInfo && BufInfo->Kind == AMDGPU::BufferKindLoadToLDS) {
1594 unsigned Width =
1596 ->getZExtValue();
1597
1598 // Entry 0: Load from buffer.
1599 // Don't set an offset, since the pointer value always represents the
1600 // base of the buffer.
1601 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1602 Info.flags = Flags | MachineMemOperand::MOLoad;
1603 Infos.push_back(Info);
1604
1605 // Entry 1: Store to LDS.
1606 // Instruction offset is applied, and an additional per-lane offset
1607 // which we simulate using a larger memory type.
1608 Info.memVT = EVT::getIntegerVT(
1609 CI.getContext(), Width * 8 * Subtarget->getWavefrontSize());
1610 Info.ptrVal = CI.getArgOperand(*BufInfo->getLDSPtrArg());
1611 Info.offset =
1613 ->getZExtValue();
1614 Info.fallbackAddressSpace = AMDGPUAS::LOCAL_ADDRESS;
1615 Info.flags = Flags | MachineMemOperand::MOStore;
1616 Infos.push_back(Info);
1617 return;
1618 }
1619 if (BufInfo && BufInfo->Kind == AMDGPU::BufferKindAtomicLoad) {
1620 Info.memVT =
1622 std::numeric_limits<unsigned>::max());
1623 Info.flags = Flags | MachineMemOperand::MOLoad;
1624 Infos.push_back(Info);
1625 return;
1626 }
1627
1628 Info.flags = Flags | MachineMemOperand::MOLoad;
1629 if (!IsSPrefetch)
1630 Info.flags |= MachineMemOperand::MOStore;
1631
1632 if ((RsrcIntr->IsImage && BaseOpcode->NoReturn) || IsSPrefetch) {
1633 // Fake memory access type for no return sampler intrinsics
1634 Info.memVT = MVT::i32;
1635 } else {
1636 // XXX - Should this be volatile without known ordering?
1637 Info.flags |= MachineMemOperand::MOVolatile;
1638 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1639 }
1640 }
1641 Infos.push_back(Info);
1642 return;
1643 }
1644
1645 IntrinsicInfo Info;
1646 switch (IntrID) {
1647 case Intrinsic::amdgcn_ds_ordered_add:
1648 case Intrinsic::amdgcn_ds_ordered_swap: {
1649 Info.opc = ISD::INTRINSIC_W_CHAIN;
1650 Info.memVT = MVT::getVT(CI.getType());
1651 Info.ptrVal = CI.getOperand(0);
1652 Info.align.reset();
1654
1655 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1656 if (!Vol->isZero())
1657 Info.flags |= MachineMemOperand::MOVolatile;
1658
1659 Infos.push_back(Info);
1660 return;
1661 }
1662 case Intrinsic::amdgcn_ds_add_gs_reg_rtn:
1663 case Intrinsic::amdgcn_ds_sub_gs_reg_rtn: {
1664 Info.opc = ISD::INTRINSIC_W_CHAIN;
1665 Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1666 Info.ptrVal = nullptr;
1667 Info.fallbackAddressSpace = AMDGPUAS::STREAMOUT_REGISTER;
1669 Infos.push_back(Info);
1670 return;
1671 }
1672 case Intrinsic::amdgcn_ds_append:
1673 case Intrinsic::amdgcn_ds_consume: {
1674 Info.opc = ISD::INTRINSIC_W_CHAIN;
1675 Info.memVT = MVT::getVT(CI.getType());
1676 Info.ptrVal = CI.getOperand(0);
1677 Info.align.reset();
1679
1680 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1681 if (!Vol->isZero())
1682 Info.flags |= MachineMemOperand::MOVolatile;
1683
1684 Infos.push_back(Info);
1685 return;
1686 }
1687 case Intrinsic::amdgcn_ds_atomic_async_barrier_arrive_b64:
1688 case Intrinsic::amdgcn_ds_atomic_barrier_arrive_rtn_b64: {
1689 Info.opc = (IntrID == Intrinsic::amdgcn_ds_atomic_barrier_arrive_rtn_b64)
1692 Info.memVT = MVT::getVT(CI.getType());
1693 Info.ptrVal = CI.getOperand(0);
1694 Info.memVT = MVT::i64;
1695 Info.size = 8;
1696 Info.align.reset();
1698 Info.order = AtomicOrdering::Monotonic;
1699 Infos.push_back(Info);
1700 return;
1701 }
1702 case Intrinsic::amdgcn_image_bvh_dual_intersect_ray:
1703 case Intrinsic::amdgcn_image_bvh_intersect_ray:
1704 case Intrinsic::amdgcn_image_bvh8_intersect_ray: {
1705 Info.opc = ISD::INTRINSIC_W_CHAIN;
1706 Info.memVT =
1707 MVT::getVT(IntrID == Intrinsic::amdgcn_image_bvh_intersect_ray
1708 ? CI.getType()
1710 ->getElementType(0)); // XXX: what is correct VT?
1711
1712 Info.fallbackAddressSpace = AMDGPUAS::BUFFER_RESOURCE;
1713 Info.align.reset();
1714 Info.flags = Flags | MachineMemOperand::MOLoad |
1716 Infos.push_back(Info);
1717 return;
1718 }
1719 case Intrinsic::amdgcn_global_atomic_fmin_num:
1720 case Intrinsic::amdgcn_global_atomic_fmax_num:
1721 case Intrinsic::amdgcn_global_atomic_ordered_add_b64:
1722 case Intrinsic::amdgcn_flat_atomic_fmin_num:
1723 case Intrinsic::amdgcn_flat_atomic_fmax_num: {
1724 Info.opc = ISD::INTRINSIC_W_CHAIN;
1725 Info.memVT = MVT::getVT(CI.getType());
1726 Info.ptrVal = CI.getOperand(0);
1727 Info.align.reset();
1728 Info.flags =
1731 Infos.push_back(Info);
1732 return;
1733 }
1734 case Intrinsic::amdgcn_cluster_load_b32:
1735 case Intrinsic::amdgcn_cluster_load_b64:
1736 case Intrinsic::amdgcn_cluster_load_b128:
1737 case Intrinsic::amdgcn_ds_load_tr6_b96:
1738 case Intrinsic::amdgcn_ds_load_tr4_b64:
1739 case Intrinsic::amdgcn_ds_load_tr8_b64:
1740 case Intrinsic::amdgcn_ds_load_tr16_b128:
1741 case Intrinsic::amdgcn_global_load_tr6_b96:
1742 case Intrinsic::amdgcn_global_load_tr4_b64:
1743 case Intrinsic::amdgcn_global_load_tr_b64:
1744 case Intrinsic::amdgcn_global_load_tr_b128:
1745 case Intrinsic::amdgcn_ds_read_tr4_b64:
1746 case Intrinsic::amdgcn_ds_read_tr6_b96:
1747 case Intrinsic::amdgcn_ds_read_tr8_b64:
1748 case Intrinsic::amdgcn_ds_read_tr16_b64: {
1749 Info.opc = ISD::INTRINSIC_W_CHAIN;
1750 Info.memVT = MVT::getVT(CI.getType());
1751 Info.ptrVal = CI.getOperand(0);
1752 Info.align.reset();
1753 Info.flags = Flags | MachineMemOperand::MOLoad;
1754 Infos.push_back(Info);
1755 return;
1756 }
1757 case Intrinsic::amdgcn_flat_load_monitor_b32:
1758 case Intrinsic::amdgcn_flat_load_monitor_b64:
1759 case Intrinsic::amdgcn_flat_load_monitor_b128:
1760 case Intrinsic::amdgcn_global_load_monitor_b32:
1761 case Intrinsic::amdgcn_global_load_monitor_b64:
1762 case Intrinsic::amdgcn_global_load_monitor_b128: {
1763 Info.opc = ISD::INTRINSIC_W_CHAIN;
1764 Info.memVT = EVT::getIntegerVT(CI.getContext(), getIntrMemWidth(IntrID));
1765 Info.ptrVal = CI.getOperand(0);
1766 Info.align.reset();
1767 Info.flags = MachineMemOperand::MOLoad;
1768 Info.order = parseAtomicOrderingCABIArg(CI, 1);
1769 Info.ssid = parseSyncscopeMDArg(CI, 2);
1770 Infos.push_back(Info);
1771 return;
1772 }
1773 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
1774 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
1775 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B: {
1776 Info.opc = ISD::INTRINSIC_W_CHAIN;
1777 Info.memVT = MVT::getVT(CI.getType());
1778 Info.ptrVal = CI.getOperand(0);
1779 Info.align.reset();
1781 Info.order = parseAtomicOrderingCABIArg(CI, 1);
1782 Info.ssid = parseSyncscopeMDArg(CI, 2);
1783 Infos.push_back(Info);
1784 return;
1785 }
1786 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
1787 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
1788 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B: {
1789 Info.opc = ISD::INTRINSIC_VOID;
1790 Info.memVT = MVT::getVT(CI.getArgOperand(1)->getType());
1791 Info.ptrVal = CI.getArgOperand(0);
1792 Info.align.reset();
1794 Info.order = parseAtomicOrderingCABIArg(CI, 2);
1795 Info.ssid = parseSyncscopeMDArg(CI, 3);
1796 Infos.push_back(Info);
1797 return;
1798 }
1799 case Intrinsic::amdgcn_ds_gws_init:
1800 case Intrinsic::amdgcn_ds_gws_barrier:
1801 case Intrinsic::amdgcn_ds_gws_sema_v:
1802 case Intrinsic::amdgcn_ds_gws_sema_br:
1803 case Intrinsic::amdgcn_ds_gws_sema_p:
1804 case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1805 Info.opc = ISD::INTRINSIC_VOID;
1806
1807 const GCNTargetMachine &TM =
1808 static_cast<const GCNTargetMachine &>(getTargetMachine());
1809
1811 Info.ptrVal = MFI->getGWSPSV(TM);
1812
1813 // This is an abstract access, but we need to specify a type and size.
1814 Info.memVT = MVT::i32;
1815 Info.size = 4;
1816 Info.align = Align(4);
1817
1818 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1819 Info.flags = Flags | MachineMemOperand::MOLoad;
1820 else
1821 Info.flags = Flags | MachineMemOperand::MOStore;
1822 Infos.push_back(Info);
1823 return;
1824 }
1825 case Intrinsic::amdgcn_global_load_async_to_lds_b8:
1826 case Intrinsic::amdgcn_global_load_async_to_lds_b32:
1827 case Intrinsic::amdgcn_global_load_async_to_lds_b64:
1828 case Intrinsic::amdgcn_global_load_async_to_lds_b128:
1829 case Intrinsic::amdgcn_cluster_load_async_to_lds_b8:
1830 case Intrinsic::amdgcn_cluster_load_async_to_lds_b32:
1831 case Intrinsic::amdgcn_cluster_load_async_to_lds_b64:
1832 case Intrinsic::amdgcn_cluster_load_async_to_lds_b128: {
1833 // Entry 0: Load from source (global/flat).
1834 Info.opc = ISD::INTRINSIC_VOID;
1835 Info.memVT = EVT::getIntegerVT(CI.getContext(), getIntrMemWidth(IntrID));
1836 Info.ptrVal = CI.getArgOperand(0); // Global pointer
1837 Info.offset = cast<ConstantInt>(CI.getArgOperand(2))->getSExtValue();
1838 Info.flags = Flags | MachineMemOperand::MOLoad;
1839 Infos.push_back(Info);
1840
1841 // Entry 1: Store to LDS (same offset).
1842 Info.flags = Flags | MachineMemOperand::MOStore;
1843 Info.ptrVal = CI.getArgOperand(1); // LDS pointer
1844 Infos.push_back(Info);
1845 return;
1846 }
1847 case Intrinsic::amdgcn_global_store_async_from_lds_b8:
1848 case Intrinsic::amdgcn_global_store_async_from_lds_b32:
1849 case Intrinsic::amdgcn_global_store_async_from_lds_b64:
1850 case Intrinsic::amdgcn_global_store_async_from_lds_b128: {
1851 // Entry 0: Load from LDS.
1852 Info.opc = ISD::INTRINSIC_VOID;
1853 Info.memVT = EVT::getIntegerVT(CI.getContext(), getIntrMemWidth(IntrID));
1854 Info.ptrVal = CI.getArgOperand(1); // LDS pointer
1855 Info.offset = cast<ConstantInt>(CI.getArgOperand(2))->getSExtValue();
1856 Info.flags = Flags | MachineMemOperand::MOLoad;
1857 Infos.push_back(Info);
1858
1859 // Entry 1: Store to global (same offset).
1860 Info.flags = Flags | MachineMemOperand::MOStore;
1861 Info.ptrVal = CI.getArgOperand(0); // Global pointer
1862 Infos.push_back(Info);
1863 return;
1864 }
1865 case Intrinsic::amdgcn_av_load_b8:
1866 case Intrinsic::amdgcn_av_load_b16:
1867 case Intrinsic::amdgcn_av_load_b32:
1868 case Intrinsic::amdgcn_av_load_b64:
1869 case Intrinsic::amdgcn_av_load_b128:
1870 case Intrinsic::amdgcn_av_store_b8:
1871 case Intrinsic::amdgcn_av_store_b16:
1872 case Intrinsic::amdgcn_av_store_b32:
1873 case Intrinsic::amdgcn_av_store_b64:
1874 case Intrinsic::amdgcn_av_store_b128: {
1875 bool IsStore = CI.getType()->isVoidTy();
1876 Type *DataTy = IsStore ? CI.getArgOperand(1)->getType() : CI.getType();
1877 Info.opc = IsStore ? ISD::INTRINSIC_VOID : ISD::INTRINSIC_W_CHAIN;
1878 Info.memVT = MVT::getVT(DataTy);
1879 Info.ptrVal = CI.getArgOperand(0);
1880 Info.align = Align(Info.memVT.getStoreSize());
1881 Info.flags |=
1883 Info.flags |= Flags & MachineMemOperand::MONonTemporal;
1884 // Pretend to be atomic so that SIMemoryLegalizer::expandStore sets cache
1885 // flags appropriately.
1886 Info.order = AtomicOrdering::Monotonic;
1887
1888 LLVMContext &Ctx = CI.getContext();
1889 unsigned ScopeIdx = CI.arg_size() - 1;
1890 MDNode *ScopeMD = cast<MDNode>(
1891 cast<MetadataAsValue>(CI.getArgOperand(ScopeIdx))->getMetadata());
1892 StringRef Scope = cast<MDString>(ScopeMD->getOperand(0))->getString();
1893 Info.ssid = Ctx.getOrInsertSyncScopeID(Scope);
1894 Infos.push_back(Info);
1895 return;
1896 }
1897 case Intrinsic::amdgcn_load_to_lds:
1898 case Intrinsic::amdgcn_load_async_to_lds:
1899 case Intrinsic::amdgcn_global_load_lds:
1900 case Intrinsic::amdgcn_global_load_async_lds: {
1901 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1902 auto *Aux = cast<ConstantInt>(CI.getArgOperand(CI.arg_size() - 1));
1903 bool IsVolatile = Aux->getZExtValue() & AMDGPU::CPol::VOLATILE;
1904 if (IsVolatile)
1906
1907 // Entry 0: Load from source (global/flat).
1908 Info.opc = ISD::INTRINSIC_VOID;
1909 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1910 Info.ptrVal = CI.getArgOperand(0); // Source pointer
1911 Info.offset = cast<ConstantInt>(CI.getArgOperand(3))->getSExtValue();
1912 Info.flags = Flags | MachineMemOperand::MOLoad;
1913 Infos.push_back(Info);
1914
1915 // Entry 1: Store to LDS.
1916 // Same offset from the instruction, but an additional per-lane offset is
1917 // added. Represent that using a wider memory type.
1918 Info.memVT = EVT::getIntegerVT(CI.getContext(),
1919 Width * 8 * Subtarget->getWavefrontSize());
1920 Info.ptrVal = CI.getArgOperand(1); // LDS destination pointer
1921 Info.flags = Flags | MachineMemOperand::MOStore;
1922 Infos.push_back(Info);
1923 return;
1924 }
1925 case Intrinsic::amdgcn_ds_bvh_stack_rtn:
1926 case Intrinsic::amdgcn_ds_bvh_stack_push4_pop1_rtn:
1927 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop1_rtn:
1928 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop2_rtn: {
1929 Info.opc = ISD::INTRINSIC_W_CHAIN;
1930
1931 const GCNTargetMachine &TM =
1932 static_cast<const GCNTargetMachine &>(getTargetMachine());
1933
1935 Info.ptrVal = MFI->getGWSPSV(TM);
1936
1937 // This is an abstract access, but we need to specify a type and size.
1938 Info.memVT = MVT::i32;
1939 Info.size = 4;
1940 Info.align = Align(4);
1941
1943 Infos.push_back(Info);
1944 return;
1945 }
1946 case Intrinsic::amdgcn_s_prefetch_data:
1947 case Intrinsic::amdgcn_s_prefetch_inst:
1948 case Intrinsic::amdgcn_flat_prefetch:
1949 case Intrinsic::amdgcn_global_prefetch: {
1950 Info.opc = ISD::INTRINSIC_VOID;
1951 Info.memVT = EVT::getIntegerVT(CI.getContext(), 8);
1952 Info.ptrVal = CI.getArgOperand(0);
1953 Info.flags = Flags | MachineMemOperand::MOLoad;
1954 Infos.push_back(Info);
1955 return;
1956 }
1957 default:
1958 return;
1959 }
1960}
1961
1964 Type *&AccessTy) const {
1965 Value *Ptr = nullptr;
1966 switch (II->getIntrinsicID()) {
1967 case Intrinsic::amdgcn_cluster_load_b128:
1968 case Intrinsic::amdgcn_cluster_load_b64:
1969 case Intrinsic::amdgcn_cluster_load_b32:
1970 case Intrinsic::amdgcn_ds_append:
1971 case Intrinsic::amdgcn_ds_consume:
1972 case Intrinsic::amdgcn_ds_load_tr8_b64:
1973 case Intrinsic::amdgcn_ds_load_tr16_b128:
1974 case Intrinsic::amdgcn_ds_load_tr4_b64:
1975 case Intrinsic::amdgcn_ds_load_tr6_b96:
1976 case Intrinsic::amdgcn_ds_read_tr4_b64:
1977 case Intrinsic::amdgcn_ds_read_tr6_b96:
1978 case Intrinsic::amdgcn_ds_read_tr8_b64:
1979 case Intrinsic::amdgcn_ds_read_tr16_b64:
1980 case Intrinsic::amdgcn_ds_ordered_add:
1981 case Intrinsic::amdgcn_ds_ordered_swap:
1982 case Intrinsic::amdgcn_ds_atomic_async_barrier_arrive_b64:
1983 case Intrinsic::amdgcn_ds_atomic_barrier_arrive_rtn_b64:
1984 case Intrinsic::amdgcn_flat_atomic_fmax_num:
1985 case Intrinsic::amdgcn_flat_atomic_fmin_num:
1986 case Intrinsic::amdgcn_global_atomic_fmax_num:
1987 case Intrinsic::amdgcn_global_atomic_fmin_num:
1988 case Intrinsic::amdgcn_global_atomic_ordered_add_b64:
1989 case Intrinsic::amdgcn_global_load_tr_b64:
1990 case Intrinsic::amdgcn_global_load_tr_b128:
1991 case Intrinsic::amdgcn_global_load_tr4_b64:
1992 case Intrinsic::amdgcn_global_load_tr6_b96:
1993 case Intrinsic::amdgcn_global_store_async_from_lds_b8:
1994 case Intrinsic::amdgcn_global_store_async_from_lds_b32:
1995 case Intrinsic::amdgcn_global_store_async_from_lds_b64:
1996 case Intrinsic::amdgcn_global_store_async_from_lds_b128:
1997 case Intrinsic::amdgcn_av_load_b8:
1998 case Intrinsic::amdgcn_av_load_b16:
1999 case Intrinsic::amdgcn_av_load_b32:
2000 case Intrinsic::amdgcn_av_load_b64:
2001 case Intrinsic::amdgcn_av_load_b128:
2002 case Intrinsic::amdgcn_av_store_b8:
2003 case Intrinsic::amdgcn_av_store_b16:
2004 case Intrinsic::amdgcn_av_store_b32:
2005 case Intrinsic::amdgcn_av_store_b64:
2006 case Intrinsic::amdgcn_av_store_b128:
2007 Ptr = II->getArgOperand(0);
2008 break;
2009 case Intrinsic::amdgcn_load_to_lds:
2010 case Intrinsic::amdgcn_load_async_to_lds:
2011 case Intrinsic::amdgcn_global_load_lds:
2012 case Intrinsic::amdgcn_global_load_async_lds:
2013 case Intrinsic::amdgcn_global_load_async_to_lds_b8:
2014 case Intrinsic::amdgcn_global_load_async_to_lds_b32:
2015 case Intrinsic::amdgcn_global_load_async_to_lds_b64:
2016 case Intrinsic::amdgcn_global_load_async_to_lds_b128:
2017 case Intrinsic::amdgcn_cluster_load_async_to_lds_b8:
2018 case Intrinsic::amdgcn_cluster_load_async_to_lds_b32:
2019 case Intrinsic::amdgcn_cluster_load_async_to_lds_b64:
2020 case Intrinsic::amdgcn_cluster_load_async_to_lds_b128:
2021 Ptr = II->getArgOperand(1);
2022 break;
2023 default:
2024 return false;
2025 }
2026 AccessTy = II->getType();
2027 Ops.push_back(Ptr);
2028 return true;
2029}
2030
2032 unsigned AddrSpace) const {
2033 if (!Subtarget->hasFlatInstOffsets()) {
2034 // Flat instructions do not have offsets, and only have the register
2035 // address.
2036 return AM.BaseOffs == 0 && AM.Scale == 0;
2037 }
2038
2040 FlatAddrSpace FlatVariant =
2041 AddrSpace == AMDGPUAS::GLOBAL_ADDRESS ? FlatAddrSpace::FlatGlobal
2042 : AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ? FlatAddrSpace::FlatScratch
2043 : FlatAddrSpace::FLAT;
2044
2045 return AM.Scale == 0 &&
2046 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
2047 AM.BaseOffs, AddrSpace, FlatVariant));
2048}
2049
2051 if (Subtarget->hasFlatGlobalInsts())
2053
2054 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
2055 // Assume the we will use FLAT for all global memory accesses
2056 // on VI.
2057 // FIXME: This assumption is currently wrong. On VI we still use
2058 // MUBUF instructions for the r + i addressing mode. As currently
2059 // implemented, the MUBUF instructions only work on buffer < 4GB.
2060 // It may be possible to support > 4GB buffers with MUBUF instructions,
2061 // by setting the stride value in the resource descriptor which would
2062 // increase the size limit to (stride * 4GB). However, this is risky,
2063 // because it has never been validated.
2065 }
2066
2067 return isLegalMUBUFAddressingMode(AM);
2068}
2069
2070bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
2071 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
2072 // additionally can do r + r + i with addr64. 32-bit has more addressing
2073 // mode options. Depending on the resource constant, it can also do
2074 // (i64 r0) + (i32 r1) * (i14 i).
2075 //
2076 // Private arrays end up using a scratch buffer most of the time, so also
2077 // assume those use MUBUF instructions. Scratch loads / stores are currently
2078 // implemented as mubuf instructions with offen bit set, so slightly
2079 // different than the normal addr64.
2080 const SIInstrInfo *TII = Subtarget->getInstrInfo();
2081 if (!TII->isLegalMUBUFImmOffset(AM.BaseOffs))
2082 return false;
2083
2084 // FIXME: Since we can split immediate into soffset and immediate offset,
2085 // would it make sense to allow any immediate?
2086
2087 switch (AM.Scale) {
2088 case 0: // r + i or just i, depending on HasBaseReg.
2089 return true;
2090 case 1:
2091 return true; // We have r + r or r + i.
2092 case 2:
2093 if (AM.HasBaseReg) {
2094 // Reject 2 * r + r.
2095 return false;
2096 }
2097
2098 // Allow 2 * r as r + r
2099 // Or 2 * r + i is allowed as r + r + i.
2100 return true;
2101 default: // Don't allow n * r
2102 return false;
2103 }
2104}
2105
2107 const AddrMode &AM, Type *Ty,
2108 unsigned AS,
2109 Instruction *I) const {
2110 // No global is ever allowed as a base.
2111 if (AM.BaseGV)
2112 return false;
2113
2114 if (AS == AMDGPUAS::GLOBAL_ADDRESS)
2115 return isLegalGlobalAddressingMode(AM);
2116
2117 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
2121 // If the offset isn't a multiple of 4, it probably isn't going to be
2122 // correctly aligned.
2123 // FIXME: Can we get the real alignment here?
2124 if (AM.BaseOffs % 4 != 0)
2125 return isLegalMUBUFAddressingMode(AM);
2126
2127 if (!Subtarget->hasScalarSubwordLoads()) {
2128 // There are no SMRD extloads, so if we have to do a small type access we
2129 // will use a MUBUF load.
2130 // FIXME?: We also need to do this if unaligned, but we don't know the
2131 // alignment here.
2132 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
2133 return isLegalGlobalAddressingMode(AM);
2134 }
2135
2136 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
2137 // SMRD instructions have an 8-bit, dword offset on SI.
2138 if (!isUInt<8>(AM.BaseOffs / 4))
2139 return false;
2140 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
2141 // On CI+, this can also be a 32-bit literal constant offset. If it fits
2142 // in 8-bits, it can use a smaller encoding.
2143 if (!isUInt<32>(AM.BaseOffs / 4))
2144 return false;
2145 } else if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX9) {
2146 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
2147 if (!isUInt<20>(AM.BaseOffs))
2148 return false;
2149 } else if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX12) {
2150 // On GFX9 the offset is signed 21-bit in bytes (but must not be negative
2151 // for S_BUFFER_* instructions).
2152 if (!isInt<21>(AM.BaseOffs))
2153 return false;
2154 } else {
2155 // On GFX12, all offsets are signed 24-bit in bytes.
2156 if (!isInt<24>(AM.BaseOffs))
2157 return false;
2158 }
2159
2160 if ((AS == AMDGPUAS::CONSTANT_ADDRESS ||
2162 AM.BaseOffs < 0) {
2163 // Scalar (non-buffer) loads can only use a negative offset if
2164 // soffset+offset is non-negative. Since the compiler can only prove that
2165 // in a few special cases, it is safer to claim that negative offsets are
2166 // not supported.
2167 return false;
2168 }
2169
2170 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
2171 return true;
2172
2173 if (AM.Scale == 1 && AM.HasBaseReg)
2174 return true;
2175
2176 return false;
2177 }
2178
2179 if (AS == AMDGPUAS::PRIVATE_ADDRESS)
2180 return Subtarget->hasFlatScratchEnabled()
2182 : isLegalMUBUFAddressingMode(AM);
2183
2184 if (AS == AMDGPUAS::LOCAL_ADDRESS ||
2185 (AS == AMDGPUAS::REGION_ADDRESS && Subtarget->hasGDS())) {
2186 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
2187 // field.
2188 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
2189 // an 8-bit dword offset but we don't know the alignment here.
2190 if (!isUInt<16>(AM.BaseOffs))
2191 return false;
2192
2193 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
2194 return true;
2195
2196 if (AM.Scale == 1 && AM.HasBaseReg)
2197 return true;
2198
2199 return false;
2200 }
2201
2203 // For an unknown address space, this usually means that this is for some
2204 // reason being used for pure arithmetic, and not based on some addressing
2205 // computation. We don't have instructions that compute pointers with any
2206 // addressing modes, so treat them as having no offset like flat
2207 // instructions.
2209 }
2210
2211 // Assume a user alias of global for unknown address spaces.
2212 return isLegalGlobalAddressingMode(AM);
2213}
2214
2216 const MachineFunction &MF) const {
2218 return (MemVT.getSizeInBits() <= 4 * 32);
2219 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
2220 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
2221 return (MemVT.getSizeInBits() <= MaxPrivateBits);
2222 }
2224 return (MemVT.getSizeInBits() <= 2 * 32);
2225 return true;
2226}
2227
2229 unsigned Size, unsigned AddrSpace, Align Alignment,
2230 MachineMemOperand::Flags Flags, unsigned *IsFast) const {
2231 if (IsFast)
2232 *IsFast = 0;
2233
2234 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
2235 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
2236 // Check if alignment requirements for ds_read/write instructions are
2237 // disabled.
2238 if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
2239 return false;
2240
2241 Align RequiredAlignment(
2242 PowerOf2Ceil(divideCeil(Size, 8))); // Natural alignment.
2243 if (Subtarget->hasLDSMisalignedBugInWGPMode() && Size > 32 &&
2244 Alignment < RequiredAlignment)
2245 return false;
2246
2247 // Either, the alignment requirements are "enabled", or there is an
2248 // unaligned LDS access related hardware bug though alignment requirements
2249 // are "disabled". In either case, we need to check for proper alignment
2250 // requirements.
2251 //
2252 switch (Size) {
2253 case 64:
2254 // SI has a hardware bug in the LDS / GDS bounds checking: if the base
2255 // address is negative, then the instruction is incorrectly treated as
2256 // out-of-bounds even if base + offsets is in bounds. Split vectorized
2257 // loads here to avoid emitting ds_read2_b32. We may re-combine the
2258 // load later in the SILoadStoreOptimizer.
2259 if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
2260 return false;
2261
2262 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
2263 // can do a 4 byte aligned, 8 byte access in a single operation using
2264 // ds_read2/write2_b32 with adjacent offsets.
2265 RequiredAlignment = Align(4);
2266
2267 if (Subtarget->hasUnalignedDSAccessEnabled()) {
2268 // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
2269 // ds_write2_b32 depending on the alignment. In either case with either
2270 // alignment there is no faster way of doing this.
2271
2272 // The numbers returned here and below are not additive, it is a 'speed
2273 // rank'. They are just meant to be compared to decide if a certain way
2274 // of lowering an operation is faster than another. For that purpose
2275 // naturally aligned operation gets it bitsize to indicate that "it
2276 // operates with a speed comparable to N-bit wide load". With the full
2277 // alignment ds128 is slower than ds96 for example. If underaligned it
2278 // is comparable to a speed of a single dword access, which would then
2279 // mean 32 < 128 and it is faster to issue a wide load regardless.
2280 // 1 is simply "slow, don't do it". I.e. comparing an aligned load to a
2281 // wider load which will not be aligned anymore the latter is slower.
2282 if (IsFast)
2283 *IsFast = (Alignment >= RequiredAlignment) ? 64
2284 : (Alignment < Align(4)) ? 32
2285 : 1;
2286 return true;
2287 }
2288
2289 break;
2290 case 96:
2291 if (!Subtarget->hasDS96AndDS128())
2292 return false;
2293
2294 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
2295 // gfx8 and older.
2296
2297 if (Subtarget->hasUnalignedDSAccessEnabled()) {
2298 // Naturally aligned access is fastest. However, also report it is Fast
2299 // if memory is aligned less than DWORD. A narrow load or store will be
2300 // be equally slow as a single ds_read_b96/ds_write_b96, but there will
2301 // be more of them, so overall we will pay less penalty issuing a single
2302 // instruction.
2303
2304 // See comment on the values above.
2305 if (IsFast)
2306 *IsFast = (Alignment >= RequiredAlignment) ? 96
2307 : (Alignment < Align(4)) ? 32
2308 : 1;
2309 return true;
2310 }
2311
2312 break;
2313 case 128:
2314 if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
2315 return false;
2316
2317 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
2318 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a
2319 // single operation using ds_read2/write2_b64.
2320 RequiredAlignment = Align(8);
2321
2322 if (Subtarget->hasUnalignedDSAccessEnabled()) {
2323 // Naturally aligned access is fastest. However, also report it is Fast
2324 // if memory is aligned less than DWORD. A narrow load or store will be
2325 // be equally slow as a single ds_read_b128/ds_write_b128, but there
2326 // will be more of them, so overall we will pay less penalty issuing a
2327 // single instruction.
2328
2329 // See comment on the values above.
2330 if (IsFast)
2331 *IsFast = (Alignment >= RequiredAlignment) ? 128
2332 : (Alignment < Align(4)) ? 32
2333 : 1;
2334 return true;
2335 }
2336
2337 break;
2338 default:
2339 if (Size > 32)
2340 return false;
2341
2342 break;
2343 }
2344
2345 // See comment on the values above.
2346 // Note that we have a single-dword or sub-dword here, so if underaligned
2347 // it is a slowest possible access, hence returned value is 0.
2348 if (IsFast)
2349 *IsFast = (Alignment >= RequiredAlignment) ? Size : 0;
2350
2351 return Alignment >= RequiredAlignment ||
2352 Subtarget->hasUnalignedDSAccessEnabled();
2353 }
2354
2355 // FIXME: We have to be conservative here and assume that flat operations
2356 // will access scratch. If we had access to the IR function, then we
2357 // could determine if any private memory was used in the function.
2358 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
2359 AddrSpace == AMDGPUAS::FLAT_ADDRESS) {
2360 bool AlignedBy4 = Alignment >= Align(4);
2361 if (Subtarget->hasUnalignedScratchAccessEnabled()) {
2362 if (IsFast)
2363 *IsFast = AlignedBy4 ? Size : 1;
2364 return true;
2365 }
2366
2367 if (IsFast)
2368 *IsFast = AlignedBy4;
2369
2370 return AlignedBy4;
2371 }
2372
2373 // So long as they are correct, wide global memory operations perform better
2374 // than multiple smaller memory ops -- even when misaligned
2375 if (AMDGPU::isExtendedGlobalAddrSpace(AddrSpace)) {
2376 if (IsFast)
2377 *IsFast = Size;
2378
2379 return Alignment >= Align(4) ||
2380 Subtarget->hasUnalignedBufferAccessEnabled();
2381 }
2382
2383 // Ensure robust out-of-bounds guarantees for buffer accesses are met when the
2384 // "amdgpu.buffer.oob.mode" module flag has not enabled relaxed untyped-buffer
2385 // OOB semantics. Normally hardware will ensure proper
2386 // out-of-bounds behavior, but in the edge case where an access starts
2387 // out-of-bounds and then enters in-bounds, the entire access would be treated
2388 // as out-of-bounds. Prevent misaligned memory accesses by requiring the
2389 // natural alignment of buffer accesses.
2390 if (AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER ||
2391 AddrSpace == AMDGPUAS::BUFFER_RESOURCE ||
2392 AddrSpace == AMDGPUAS::BUFFER_STRIDED_POINTER) {
2393 if (!Subtarget->hasRelaxedBufferOOBMode() &&
2394 Alignment < Align(PowerOf2Ceil(divideCeil(Size, 8))))
2395 return false;
2396 }
2397
2398 // Smaller than dword value must be aligned.
2399 if (Size < 32)
2400 return false;
2401
2402 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
2403 // byte-address are ignored, thus forcing Dword alignment.
2404 // This applies to private, global, and constant memory.
2405 if (IsFast)
2406 *IsFast = 1;
2407
2408 return Size >= 32 && Alignment >= Align(4);
2409}
2410
2412 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
2413 unsigned *IsFast) const {
2415 Alignment, Flags, IsFast);
2416}
2417
2419 const DataLayout &DL, EVT VT,
2420 unsigned AddrSpace, Align Alignment,
2422 unsigned *IsFast) const {
2423 // Sub-dword accesses aren't lowered yet, so combines must not narrow an
2424 // access to one.
2425 if (AddrSpace == AMDGPUAS::VGPR && VT.getSizeInBits() < 32)
2426 return false;
2427 return TargetLowering::allowsMemoryAccess(Context, DL, VT, AddrSpace,
2428 Alignment, Flags, IsFast);
2429}
2430
2432 LLVMContext &Context, const MemOp &Op,
2433 const AttributeList &FuncAttributes) const {
2434 // FIXME: Should account for address space here.
2435
2436 // The default fallback uses the private pointer size as a guess for a type to
2437 // use. Make sure we switch these to 64-bit accesses.
2438
2439 if (Op.size() >= 16 &&
2440 Op.isDstAligned(Align(4))) // XXX: Should only do for global
2441 return MVT::v4i32;
2442
2443 if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
2444 return MVT::v2i32;
2445
2446 // Use the default.
2447 return MVT::Other;
2448}
2449
2451 const MemSDNode *MemNode = cast<MemSDNode>(N);
2452 return MemNode->getMemOperand()->getFlags() & MONoClobber;
2453}
2454
2459
2461 unsigned DestAS) const {
2462 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
2463 if (DestAS == AMDGPUAS::PRIVATE_ADDRESS &&
2464 Subtarget->hasGloballyAddressableScratch()) {
2465 // Flat -> private requires subtracting src_flat_scratch_base_lo.
2466 return false;
2467 }
2468
2469 // Flat -> private/local is a simple truncate.
2470 // Flat -> global is no-op
2471 return true;
2472 }
2473
2474 const GCNTargetMachine &TM =
2475 static_cast<const GCNTargetMachine &>(getTargetMachine());
2476 return TM.isNoopAddrSpaceCast(DL, SrcAS, DestAS);
2477}
2478
2486
2488 Type *Ty) const {
2489 // FIXME: Could be smarter if called for vector constants.
2490 return true;
2491}
2492
2495 unsigned Index) const {
2498
2499 // TODO: Add more cases that are cheap.
2500 if (Index == 0)
2503}
2504
2505bool SITargetLowering::isExtractVecEltCheap(EVT VT, unsigned Index) const {
2506 // TODO: This should be more aggressive, particular for 16-bit element
2507 // vectors. However there are some mixed improvements and regressions.
2508 EVT EltTy = VT.getVectorElementType();
2509 unsigned MinAlign = Subtarget->useRealTrue16Insts() ? 16 : 32;
2510 return EltTy.getSizeInBits() % MinAlign == 0;
2511}
2512
2514 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
2515 switch (Op) {
2516 case ISD::LOAD:
2517 case ISD::STORE:
2518 return true;
2519 default:
2520 return false;
2521 }
2522 }
2523
2524 // SimplifySetCC uses this function to determine whether or not it should
2525 // create setcc with i1 operands. We don't have instructions for i1 setcc.
2526 if (VT == MVT::i1 && Op == ISD::SETCC)
2527 return false;
2528
2529 if (VT.getScalarType() == MVT::i64 &&
2531 return false;
2532
2533 // The DAGCombiner replaces a conversion from i1 with a select of the two
2534 // exact results. The select avoids an f32 conversion plus rounding for
2535 // f16/bf16, a 64-bit conversion for f64 and a missing libcall for f128, and
2536 // is the same single v_cndmask for f32.
2537 if (VT == MVT::i1 && (Op == ISD::SINT_TO_FP || Op == ISD::UINT_TO_FP))
2538 return false;
2539
2541}
2542
2544 // Do not convert uniform loads to 16-bit.
2545 // Uniform 16-bit loads are legalized to i16 = trunc (zextload i16->i32)
2546 // to match subword load patterns. Allowing conversion back to a 16-bit
2547 // load would create an infinite loop.
2548 if (Subtarget->hasScalarSubwordLoads() && N->getOpcode() == ISD::LOAD &&
2549 !VT.isVector() && VT.getSizeInBits() == 16) {
2550 auto *Load = dyn_cast<LoadSDNode>(N);
2551 if (Load && isUniformLoad(Load)) {
2552 return false;
2553 }
2554 }
2555
2556 return isTypeDesirableForOp(N->getOpcode(), VT);
2557}
2558
2560 const MachineMemOperand *MMO = Load->getMemOperand();
2561
2562 // FIXME: We ought to able able to take the direct isDivergent result. We
2563 // cannot rely on the MMO for a uniformity check, and should stop using
2564 // it. This is a hack for 2 ways that the IR divergence analysis is superior
2565 // to the DAG divergence: Recognizing shift-of-workitem-id as always
2566 // uniform, and isSingleLaneExecution. These should be handled in the DAG
2567 // version, and then this can be dropped.
2568 if (Load->isDivergent() && !AMDGPU::isUniformMMO(MMO))
2569 return false;
2570
2571 return MMO->getSize().hasValue() &&
2572 Load->getAlign() >=
2573 Align(std::min(MMO->getSize().getValue().getKnownMinValue(),
2574 uint64_t(4))) &&
2575 (MMO->isInvariant() ||
2576 (Load->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
2577 Load->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ||
2578 (Load->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
2579 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load)));
2580}
2581
2584 // This isn't really a constant pool but close enough.
2587 return PtrInfo;
2588}
2589
2590SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
2591 const SDLoc &SL,
2592 SDValue Chain,
2593 uint64_t Offset) const {
2594 const DataLayout &DL = DAG.getDataLayout();
2598
2599 auto [InputPtrReg, RC, ArgTy] =
2600 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
2601
2602 // We may not have the kernarg segment argument if we have no kernel
2603 // arguments.
2604 if (!InputPtrReg)
2605 return DAG.getConstant(Offset, SL, PtrVT);
2606
2608 SDValue BasePtr = DAG.getCopyFromReg(
2609 Chain, SL, MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
2610
2611 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Offset));
2612}
2613
2614SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
2615 const SDLoc &SL) const {
2618 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
2619}
2620
2621SDValue SITargetLowering::getLDSKernelId(SelectionDAG &DAG,
2622 const SDLoc &SL) const {
2623
2625 std::optional<uint32_t> KnownSize =
2627 if (KnownSize.has_value())
2628 return DAG.getConstant(*KnownSize, SL, MVT::i32);
2629 return SDValue();
2630}
2631
2632SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
2633 const SDLoc &SL, SDValue Val,
2634 bool Signed,
2635 const ISD::InputArg *Arg) const {
2636 // First, if it is a widened vector, narrow it.
2637 if (VT.isVector() &&
2639 EVT NarrowedVT =
2642 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
2643 DAG.getConstant(0, SL, MVT::i32));
2644 }
2645
2646 // Then convert the vector elements or scalar value.
2647 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && VT.bitsLT(MemVT)) {
2648 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
2649 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
2650 }
2651
2652 if (MemVT.isFloatingPoint()) {
2653 if (VT.isFloatingPoint()) {
2654 Val = getFPExtOrFPRound(DAG, Val, SL, VT);
2655 } else {
2656 assert(!MemVT.isVector());
2657 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
2658 SDValue Cast = DAG.getBitcast(IntVT, Val);
2659 Val = DAG.getAnyExtOrTrunc(Cast, SL, VT);
2660 }
2661 } else if (Signed)
2662 Val = DAG.getSExtOrTrunc(Val, SL, VT);
2663 else
2664 Val = DAG.getZExtOrTrunc(Val, SL, VT);
2665
2666 return Val;
2667}
2668
2669SDValue SITargetLowering::lowerKernargMemParameter(
2670 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
2671 uint64_t Offset, Align Alignment, bool Signed,
2672 const ISD::InputArg *Arg) const {
2673
2674 MachinePointerInfo PtrInfo =
2676
2677 // Try to avoid using an extload by loading earlier than the argument address,
2678 // and extracting the relevant bits. The load should hopefully be merged with
2679 // the previous argument.
2680 if (MemVT.getStoreSize() < 4 && Alignment < 4) {
2681 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
2682 int64_t AlignDownOffset = alignDown(Offset, 4);
2683 int64_t OffsetDiff = Offset - AlignDownOffset;
2684
2685 EVT IntVT = MemVT.changeTypeToInteger();
2686
2687 // TODO: If we passed in the base kernel offset we could have a better
2688 // alignment than 4, but we don't really need it.
2689 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
2690 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr,
2691 PtrInfo.getWithOffset(AlignDownOffset), Align(4),
2694
2695 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
2696 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
2697
2698 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
2699 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
2700 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
2701
2702 return DAG.getMergeValues({ArgVal, Load.getValue(1)}, SL);
2703 }
2704
2705 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
2706 SDValue Load = DAG.getLoad(
2707 MemVT, SL, Chain, Ptr, PtrInfo.getWithOffset(Offset), Alignment,
2709
2710 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
2711 return DAG.getMergeValues({Val, Load.getValue(1)}, SL);
2712}
2713
2714/// Coerce an argument which was passed in a different ABI type to the original
2715/// expected value type.
2716SDValue SITargetLowering::convertABITypeToValueType(SelectionDAG &DAG,
2717 SDValue Val,
2718 CCValAssign &VA,
2719 const SDLoc &SL) const {
2720 EVT ValVT = VA.getValVT();
2721
2722 // If this is an 8 or 16-bit value, it is really passed promoted
2723 // to 32 bits. Insert an assert[sz]ext to capture this, then
2724 // truncate to the right size.
2725 switch (VA.getLocInfo()) {
2726 case CCValAssign::Full:
2727 return Val;
2728 case CCValAssign::BCvt:
2729 return DAG.getNode(ISD::BITCAST, SL, ValVT, Val);
2730 case CCValAssign::SExt:
2731 Val = DAG.getNode(ISD::AssertSext, SL, VA.getLocVT(), Val,
2732 DAG.getValueType(ValVT));
2733 return DAG.getNode(ISD::TRUNCATE, SL, ValVT, Val);
2734 case CCValAssign::ZExt:
2735 Val = DAG.getNode(ISD::AssertZext, SL, VA.getLocVT(), Val,
2736 DAG.getValueType(ValVT));
2737 return DAG.getNode(ISD::TRUNCATE, SL, ValVT, Val);
2738 case CCValAssign::AExt:
2739 Val = DAG.getNode(ISD::TRUNCATE, SL, ValVT.changeTypeToInteger(), Val);
2740 return DAG.getBitcast(ValVT, Val);
2741 default:
2742 llvm_unreachable("Unknown loc info!");
2743 }
2744}
2745
2746SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG,
2747 CCValAssign &VA, const SDLoc &SL,
2748 SDValue Chain,
2749 const ISD::InputArg &Arg) const {
2751 MachineFrameInfo &MFI = MF.getFrameInfo();
2752
2753 if (Arg.Flags.isByVal()) {
2754 unsigned Size = Arg.Flags.getByValSize();
2755 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
2756 return DAG.getFrameIndex(FrameIdx, MVT::i32);
2757 }
2758
2759 unsigned ArgOffset = VA.getLocMemOffset();
2760 unsigned ArgSize = VA.getValVT().getStoreSize();
2761
2762 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
2763
2764 // Create load nodes to retrieve arguments from the stack.
2765 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
2766 MachinePointerInfo PtrInfo =
2768 if (VA.getLocInfo() == CCValAssign::AExt)
2769 return DAG.getLoad(VA.getValVT(), SL, Chain, FIN, PtrInfo);
2770
2771 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2773 MVT MemVT = VA.getValVT();
2774
2775 switch (VA.getLocInfo()) {
2776 default:
2777 break;
2778 case CCValAssign::BCvt:
2779 MemVT = VA.getLocVT();
2780 break;
2781 case CCValAssign::SExt:
2782 ExtType = ISD::SEXTLOAD;
2783 break;
2784 case CCValAssign::ZExt:
2785 ExtType = ISD::ZEXTLOAD;
2786 break;
2787 }
2788
2789 SDValue ArgValue =
2790 DAG.getExtLoad(ExtType, SL, VA.getLocVT(), Chain, FIN, PtrInfo, MemVT);
2791
2792 SDValue ConvertedVal = convertABITypeToValueType(DAG, ArgValue, VA, SL);
2793 if (ConvertedVal == ArgValue)
2794 return ConvertedVal;
2795
2796 return DAG.getMergeValues({ConvertedVal, ArgValue.getValue(1)}, SL);
2797}
2798
2799// Read the cluster ID field of IB_STS2. It is 0 if and only if clusters are
2800// disabled.
2801static SDValue readClusterIdField(SelectionDAG &DAG, const SDLoc &SL, EVT VT) {
2802 using namespace AMDGPU::Hwreg;
2803 SDValue ClusterIdField =
2804 DAG.getTargetConstant(HwregEncoding::encode(ID_IB_STS2, 6, 4), SL, VT);
2805 SDNode *GetReg =
2806 DAG.getMachineNode(AMDGPU::S_GETREG_B32_const, SL, VT, ClusterIdField);
2807 return SDValue(GetReg, 0);
2808}
2809
2810SDValue SITargetLowering::lowerWorkGroupId(
2811 SelectionDAG &DAG, const SIMachineFunctionInfo &MFI, EVT VT,
2814 AMDGPUFunctionArgInfo::PreloadedValue ClusterWorkGroupIdPV) const {
2815 if (!Subtarget->hasClusters())
2816 return getPreloadedValue(DAG, MFI, VT, WorkGroupIdPV);
2817
2818 // Clusters are supported. Return the global position in the grid. If clusters
2819 // are enabled, WorkGroupIdPV returns the cluster ID not the workgroup ID.
2820
2821 // WorkGroupIdXYZ = ClusterId == 0 ?
2822 // ClusterIdXYZ :
2823 // ClusterIdXYZ * (ClusterMaxIdXYZ + 1) + ClusterWorkGroupIdXYZ
2824 SDValue ClusterIdXYZ = getPreloadedValue(DAG, MFI, VT, WorkGroupIdPV);
2825 SDLoc SL(ClusterIdXYZ);
2826 SDValue ClusterMaxIdXYZ = getPreloadedValue(DAG, MFI, VT, ClusterMaxIdPV);
2827 SDValue One = DAG.getConstant(1, SL, VT);
2828 SDValue ClusterSizeXYZ = DAG.getNode(ISD::ADD, SL, VT, ClusterMaxIdXYZ, One);
2829 SDValue ClusterWorkGroupIdXYZ =
2830 getPreloadedValue(DAG, MFI, VT, ClusterWorkGroupIdPV);
2831 SDValue GlobalIdXYZ =
2832 DAG.getNode(ISD::ADD, SL, VT, ClusterWorkGroupIdXYZ,
2833 DAG.getNode(ISD::MUL, SL, VT, ClusterIdXYZ, ClusterSizeXYZ));
2834
2835 switch (MFI.getClusterDims().getKind()) {
2838 return GlobalIdXYZ;
2840 return ClusterIdXYZ;
2842 SDValue ClusterId = readClusterIdField(DAG, SL, VT);
2843 SDValue Zero = DAG.getConstant(0, SL, VT);
2844 return DAG.getNode(ISD::SELECT_CC, SL, VT, ClusterId, Zero, ClusterIdXYZ,
2845 GlobalIdXYZ, DAG.getCondCode(ISD::SETEQ));
2846 }
2847 }
2848
2849 llvm_unreachable("nothing should reach here");
2850}
2851
2852SDValue SITargetLowering::lowerClusterWorkGroupValue(
2853 SelectionDAG &DAG, const SIMachineFunctionInfo &MFI, EVT VT,
2855 if (!Subtarget->hasClusters())
2856 return DAG.getPOISON(VT);
2857
2858 // TTMP6 holds these values only if cluster is enabled. The programming model
2859 // treats a launch without clusters as an implicit 1x1x1 cluster, so all of
2860 // these values are 0.
2861 switch (MFI.getClusterDims().getKind()) {
2864 return getPreloadedValue(DAG, MFI, VT, PV);
2866 return DAG.getConstant(0, SDLoc(), VT);
2868 SDValue Value = getPreloadedValue(DAG, MFI, VT, PV);
2869 SDLoc SL(Value);
2870 SDValue ClusterId = readClusterIdField(DAG, SL, VT);
2871 SDValue Zero = DAG.getConstant(0, SL, VT);
2872 return DAG.getNode(ISD::SELECT_CC, SL, VT, ClusterId, Zero, Zero, Value,
2873 DAG.getCondCode(ISD::SETEQ));
2874 }
2875 }
2876
2877 llvm_unreachable("nothing should reach here");
2878}
2879
2880SDValue SITargetLowering::getPreloadedValue(
2881 SelectionDAG &DAG, const SIMachineFunctionInfo &MFI, EVT VT,
2883 const ArgDescriptor *Reg = nullptr;
2884 const TargetRegisterClass *RC = nullptr;
2885 LLT Ty;
2886
2888 const ArgDescriptor WorkGroupIDX =
2889 ArgDescriptor::createRegister(AMDGPU::TTMP9);
2890 // If GridZ is not programmed in an entry function then the hardware will set
2891 // it to all zeros, so there is no need to mask the GridY value in the low
2892 // order bits.
2893 const ArgDescriptor WorkGroupIDY = ArgDescriptor::createRegister(
2894 AMDGPU::TTMP7,
2895 AMDGPU::isEntryFunctionCC(CC) && !MFI.hasWorkGroupIDZ() ? ~0u : 0xFFFFu);
2896 const ArgDescriptor WorkGroupIDZ =
2897 ArgDescriptor::createRegister(AMDGPU::TTMP7, 0xFFFF0000u);
2898 const ArgDescriptor ClusterWorkGroupIDX =
2899 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x0000000Fu);
2900 const ArgDescriptor ClusterWorkGroupIDY =
2901 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x000000F0u);
2902 const ArgDescriptor ClusterWorkGroupIDZ =
2903 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x00000F00u);
2904 const ArgDescriptor ClusterWorkGroupMaxIDX =
2905 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x0000F000u);
2906 const ArgDescriptor ClusterWorkGroupMaxIDY =
2907 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x000F0000u);
2908 const ArgDescriptor ClusterWorkGroupMaxIDZ =
2909 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x00F00000u);
2910 const ArgDescriptor ClusterWorkGroupMaxFlatID =
2911 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x0F000000u);
2912
2913 auto LoadConstant = [&](unsigned N) {
2914 return DAG.getConstant(N, SDLoc(), VT);
2915 };
2916
2917 if (Subtarget->hasArchitectedSGPRs() &&
2920 AMDGPU::ClusterDimsAttr ClusterDims = MFI.getClusterDims();
2921 bool HasFixedDims = ClusterDims.isFixedDims();
2922
2923 switch (PVID) {
2925 Reg = &WorkGroupIDX;
2926 RC = &AMDGPU::SReg_32RegClass;
2927 Ty = LLT::scalar(32);
2928 break;
2930 Reg = &WorkGroupIDY;
2931 RC = &AMDGPU::SReg_32RegClass;
2932 Ty = LLT::scalar(32);
2933 break;
2935 Reg = &WorkGroupIDZ;
2936 RC = &AMDGPU::SReg_32RegClass;
2937 Ty = LLT::scalar(32);
2938 break;
2940 if (HasFixedDims && ClusterDims.getDims()[0] == 1)
2941 return LoadConstant(0);
2942 Reg = &ClusterWorkGroupIDX;
2943 RC = &AMDGPU::SReg_32RegClass;
2944 Ty = LLT::scalar(32);
2945 break;
2947 if (HasFixedDims && ClusterDims.getDims()[1] == 1)
2948 return LoadConstant(0);
2949 Reg = &ClusterWorkGroupIDY;
2950 RC = &AMDGPU::SReg_32RegClass;
2951 Ty = LLT::scalar(32);
2952 break;
2954 if (HasFixedDims && ClusterDims.getDims()[2] == 1)
2955 return LoadConstant(0);
2956 Reg = &ClusterWorkGroupIDZ;
2957 RC = &AMDGPU::SReg_32RegClass;
2958 Ty = LLT::scalar(32);
2959 break;
2961 if (HasFixedDims)
2962 return LoadConstant(ClusterDims.getDims()[0] - 1);
2963 Reg = &ClusterWorkGroupMaxIDX;
2964 RC = &AMDGPU::SReg_32RegClass;
2965 Ty = LLT::scalar(32);
2966 break;
2968 if (HasFixedDims)
2969 return LoadConstant(ClusterDims.getDims()[1] - 1);
2970 Reg = &ClusterWorkGroupMaxIDY;
2971 RC = &AMDGPU::SReg_32RegClass;
2972 Ty = LLT::scalar(32);
2973 break;
2975 if (HasFixedDims)
2976 return LoadConstant(ClusterDims.getDims()[2] - 1);
2977 Reg = &ClusterWorkGroupMaxIDZ;
2978 RC = &AMDGPU::SReg_32RegClass;
2979 Ty = LLT::scalar(32);
2980 break;
2982 if (HasFixedDims) {
2983 const std::array<unsigned, 3> &Dims = ClusterDims.getDims();
2984 return LoadConstant(Dims[0] * Dims[1] * Dims[2] - 1);
2985 }
2986 Reg = &ClusterWorkGroupMaxFlatID;
2987 RC = &AMDGPU::SReg_32RegClass;
2988 Ty = LLT::scalar(32);
2989 break;
2990 default:
2991 break;
2992 }
2993 }
2994
2995 if (!Reg)
2996 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
2997 if (!Reg) {
2999 // It's possible for a kernarg intrinsic call to appear in a kernel with
3000 // no allocated segment, in which case we do not add the user sgpr
3001 // argument, so just return null.
3002 return DAG.getConstant(0, SDLoc(), VT);
3003 }
3004
3005 // It's undefined behavior if a function marked with the amdgpu-no-*
3006 // attributes uses the corresponding intrinsic.
3007 return DAG.getPOISON(VT);
3008 }
3009
3010 return loadInputValue(DAG, RC, VT, SDLoc(DAG.getEntryNode()), *Reg);
3011}
3012
3014 CallingConv::ID CallConv,
3015 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
3016 FunctionType *FType,
3017 SIMachineFunctionInfo *Info) {
3018 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
3019 const ISD::InputArg *Arg = &Ins[I];
3020
3021 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
3022 "vector type argument should have been split");
3023
3024 // First check if it's a PS input addr.
3025 if (CallConv == CallingConv::AMDGPU_PS && !Arg->Flags.isInReg() &&
3026 PSInputNum <= 15) {
3027 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
3028
3029 // Inconveniently only the first part of the split is marked as isSplit,
3030 // so skip to the end. We only want to increment PSInputNum once for the
3031 // entire split argument.
3032 if (Arg->Flags.isSplit()) {
3033 while (!Arg->Flags.isSplitEnd()) {
3034 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
3035 "unexpected vector split in ps argument type");
3036 if (!SkipArg)
3037 Splits.push_back(*Arg);
3038 Arg = &Ins[++I];
3039 }
3040 }
3041
3042 if (SkipArg) {
3043 // We can safely skip PS inputs.
3044 Skipped.set(Arg->getOrigArgIndex());
3045 ++PSInputNum;
3046 continue;
3047 }
3048
3049 Info->markPSInputAllocated(PSInputNum);
3050 if (Arg->Used)
3051 Info->markPSInputEnabled(PSInputNum);
3052
3053 ++PSInputNum;
3054 }
3055
3056 Splits.push_back(*Arg);
3057 }
3058}
3059
3060// Allocate special inputs passed in VGPRs.
3062 CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI,
3063 SIMachineFunctionInfo &Info) const {
3064 const LLT I32 = LLT::integer(32);
3066
3067 if (Info.hasWorkItemIDX()) {
3068 Register Reg = AMDGPU::VGPR0;
3069 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), I32);
3070
3071 CCInfo.AllocateReg(Reg);
3072 unsigned Mask =
3073 (Subtarget->hasPackedTID() && Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
3074 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
3075 }
3076
3077 if (Info.hasWorkItemIDY()) {
3078 assert(Info.hasWorkItemIDX());
3079 if (Subtarget->hasPackedTID()) {
3080 Info.setWorkItemIDY(
3081 ArgDescriptor::createRegister(AMDGPU::VGPR0, 0x3ff << 10));
3082 } else {
3083 unsigned Reg = AMDGPU::VGPR1;
3084 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), I32);
3085
3086 CCInfo.AllocateReg(Reg);
3087 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
3088 }
3089 }
3090
3091 if (Info.hasWorkItemIDZ()) {
3092 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
3093 if (Subtarget->hasPackedTID()) {
3094 Info.setWorkItemIDZ(
3095 ArgDescriptor::createRegister(AMDGPU::VGPR0, 0x3ff << 20));
3096 } else {
3097 unsigned Reg = AMDGPU::VGPR2;
3098 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), I32);
3099
3100 CCInfo.AllocateReg(Reg);
3101 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
3102 }
3103 }
3104}
3105
3107 const TargetRegisterClass *RC,
3108 unsigned NumArgRegs) {
3109 ArrayRef<MCPhysReg> ArgSGPRs = ArrayRef(RC->begin(), 32);
3110 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
3111 if (RegIdx == ArgSGPRs.size())
3112 report_fatal_error("ran out of SGPRs for arguments");
3113
3114 unsigned Reg = ArgSGPRs[RegIdx];
3115 Reg = CCInfo.AllocateReg(Reg);
3116 assert(Reg != AMDGPU::NoRegister);
3117
3118 MachineFunction &MF = CCInfo.getMachineFunction();
3119 MF.addLiveIn(Reg, RC);
3121}
3122
3123// If this has a fixed position, we still should allocate the register in the
3124// CCInfo state. Technically we could get away with this for values passed
3125// outside of the normal argument range.
3127 const TargetRegisterClass *RC,
3128 MCRegister Reg) {
3129 Reg = CCInfo.AllocateReg(Reg);
3130 assert(Reg != AMDGPU::NoRegister);
3131 MachineFunction &MF = CCInfo.getMachineFunction();
3132 MF.addLiveIn(Reg, RC);
3133}
3134
3135static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
3136 if (Arg) {
3137 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
3138 Arg.getRegister());
3139 } else
3140 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
3141}
3142
3143static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
3144 if (Arg) {
3145 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
3146 Arg.getRegister());
3147 } else
3148 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
3149}
3150
3151/// Allocate implicit function VGPR arguments in fixed registers.
3153 CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI,
3154 SIMachineFunctionInfo &Info) const {
3155 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
3156 if (!Reg)
3157 report_fatal_error("failed to allocate VGPR for implicit arguments");
3158
3159 const unsigned Mask = 0x3ff;
3160 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
3161 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
3162 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
3163}
3164
3166 CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI,
3167 SIMachineFunctionInfo &Info) const {
3168 auto &ArgInfo = Info.getArgInfo();
3169 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info.getUserSGPRInfo();
3170
3171 // TODO: Unify handling with private memory pointers.
3172 if (UserSGPRInfo.hasDispatchPtr())
3173 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
3174
3175 if (UserSGPRInfo.hasQueuePtr())
3176 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
3177
3178 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
3179 // constant offset from the kernarg segment.
3180 if (Info.hasImplicitArgPtr())
3181 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
3182
3183 if (UserSGPRInfo.hasDispatchID())
3184 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
3185
3186 // flat_scratch_init is not applicable for non-kernel functions.
3187
3188 if (Info.hasWorkGroupIDX())
3189 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
3190
3191 if (Info.hasWorkGroupIDY())
3192 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
3193
3194 if (Info.hasWorkGroupIDZ())
3195 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
3196
3197 if (Info.hasLDSKernelId())
3198 allocateSGPR32Input(CCInfo, ArgInfo.LDSKernelId);
3199}
3200
3201// Allocate special inputs passed in user SGPRs.
3203 MachineFunction &MF,
3204 const SIRegisterInfo &TRI,
3205 SIMachineFunctionInfo &Info) const {
3206 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info.getUserSGPRInfo();
3207 if (UserSGPRInfo.hasImplicitBufferPtr()) {
3208 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
3209 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
3210 CCInfo.AllocateReg(ImplicitBufferPtrReg);
3211 }
3212
3213 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
3214 if (UserSGPRInfo.hasPrivateSegmentBuffer()) {
3215 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
3216 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
3217 CCInfo.AllocateReg(PrivateSegmentBufferReg);
3218 }
3219
3220 if (UserSGPRInfo.hasDispatchPtr()) {
3221 Register DispatchPtrReg = Info.addDispatchPtr(TRI);
3222 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
3223 CCInfo.AllocateReg(DispatchPtrReg);
3224 }
3225
3226 if (UserSGPRInfo.hasQueuePtr()) {
3227 Register QueuePtrReg = Info.addQueuePtr(TRI);
3228 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
3229 CCInfo.AllocateReg(QueuePtrReg);
3230 }
3231
3232 if (UserSGPRInfo.hasKernargSegmentPtr()) {
3234 Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
3235 CCInfo.AllocateReg(InputPtrReg);
3236
3237 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
3238 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
3239 }
3240
3241 if (UserSGPRInfo.hasDispatchID()) {
3242 Register DispatchIDReg = Info.addDispatchID(TRI);
3243 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
3244 CCInfo.AllocateReg(DispatchIDReg);
3245 }
3246
3247 if (UserSGPRInfo.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
3248 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
3249 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
3250 CCInfo.AllocateReg(FlatScratchInitReg);
3251 }
3252
3253 if (UserSGPRInfo.hasPrivateSegmentSize()) {
3254 Register PrivateSegmentSizeReg = Info.addPrivateSegmentSize(TRI);
3255 MF.addLiveIn(PrivateSegmentSizeReg, &AMDGPU::SGPR_32RegClass);
3256 CCInfo.AllocateReg(PrivateSegmentSizeReg);
3257 }
3258
3259 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
3260 // these from the dispatch pointer.
3261}
3262
3263// Allocate pre-loaded kernel arguemtns. Arguments to be preloading must be
3264// sequential starting from the first argument.
3266 CCState &CCInfo, SmallVectorImpl<CCValAssign> &ArgLocs,
3268 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
3269 Function &F = MF.getFunction();
3270 unsigned LastExplicitArgOffset = Subtarget->getExplicitKernelArgOffset();
3271 GCNUserSGPRUsageInfo &SGPRInfo = Info.getUserSGPRInfo();
3272 bool InPreloadSequence = true;
3273 unsigned InIdx = 0;
3274 bool AlignedForImplictArgs = false;
3275 unsigned ImplicitArgOffset = 0;
3276 for (auto &Arg : F.args()) {
3277 if (!InPreloadSequence || !Arg.hasInRegAttr())
3278 break;
3279
3280 unsigned ArgIdx = Arg.getArgNo();
3281 // Don't preload non-original args or parts not in the current preload
3282 // sequence.
3283 if (InIdx < Ins.size() &&
3284 (!Ins[InIdx].isOrigArg() || Ins[InIdx].getOrigArgIndex() != ArgIdx))
3285 break;
3286
3287 for (; InIdx < Ins.size() && Ins[InIdx].isOrigArg() &&
3288 Ins[InIdx].getOrigArgIndex() == ArgIdx;
3289 InIdx++) {
3290 assert(ArgLocs[ArgIdx].isMemLoc());
3291 auto &ArgLoc = ArgLocs[InIdx];
3292 const Align KernelArgBaseAlign = Align(16);
3293 unsigned ArgOffset = ArgLoc.getLocMemOffset();
3294 Align Alignment = commonAlignment(KernelArgBaseAlign, ArgOffset);
3295 unsigned NumAllocSGPRs =
3296 alignTo(ArgLoc.getLocVT().getFixedSizeInBits(), 32) / 32;
3297
3298 // Fix alignment for hidden arguments.
3299 if (Arg.hasAttribute("amdgpu-hidden-argument")) {
3300 if (!AlignedForImplictArgs) {
3301 ImplicitArgOffset =
3302 alignTo(LastExplicitArgOffset,
3303 Subtarget->getAlignmentForImplicitArgPtr()) -
3304 LastExplicitArgOffset;
3305 AlignedForImplictArgs = true;
3306 }
3307 ArgOffset += ImplicitArgOffset;
3308 }
3309
3310 // Arg is preloaded into the previous SGPR.
3311 if (ArgLoc.getLocVT().getStoreSize() < 4 && Alignment < 4) {
3312 assert(InIdx >= 1 && "No previous SGPR");
3313 Info.getArgInfo().PreloadKernArgs[InIdx].Regs.push_back(
3314 Info.getArgInfo().PreloadKernArgs[InIdx - 1].Regs[0]);
3315 continue;
3316 }
3317
3318 unsigned Padding = ArgOffset - LastExplicitArgOffset;
3319 unsigned PaddingSGPRs = alignTo(Padding, 4) / 4;
3320 // Check for free user SGPRs for preloading.
3321 if (PaddingSGPRs + NumAllocSGPRs > SGPRInfo.getNumFreeUserSGPRs()) {
3322 InPreloadSequence = false;
3323 break;
3324 }
3325
3326 // Preload this argument.
3327 const TargetRegisterClass *RC =
3328 TRI.getSGPRClassForBitWidth(NumAllocSGPRs * 32);
3329 SmallVectorImpl<MCRegister> *PreloadRegs =
3330 Info.addPreloadedKernArg(TRI, RC, NumAllocSGPRs, InIdx, PaddingSGPRs);
3331
3332 if (PreloadRegs->size() > 1)
3333 RC = &AMDGPU::SGPR_32RegClass;
3334 for (auto &Reg : *PreloadRegs) {
3335 assert(Reg);
3336 MF.addLiveIn(Reg, RC);
3337 CCInfo.AllocateReg(Reg);
3338 }
3339
3340 LastExplicitArgOffset = NumAllocSGPRs * 4 + ArgOffset;
3341 }
3342 }
3343}
3344
3346 const SIRegisterInfo &TRI,
3347 SIMachineFunctionInfo &Info) const {
3348 // Always allocate this last since it is a synthetic preload.
3349 if (Info.hasLDSKernelId()) {
3350 Register Reg = Info.addLDSKernelId();
3351 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3352 CCInfo.AllocateReg(Reg);
3353 }
3354}
3355
3356// Allocate special input registers that are initialized per-wave.
3359 CallingConv::ID CallConv,
3360 bool IsShader) const {
3361 bool HasArchitectedSGPRs = Subtarget->hasArchitectedSGPRs();
3362 if (Subtarget->hasUserSGPRInit16BugInWave32() && !IsShader) {
3363 // Note: user SGPRs are handled by the front-end for graphics shaders
3364 // Pad up the used user SGPRs with dead inputs.
3365
3366 // TODO: NumRequiredSystemSGPRs computation should be adjusted appropriately
3367 // before enabling architected SGPRs for workgroup IDs.
3368 assert(!HasArchitectedSGPRs && "Unhandled feature for the subtarget");
3369
3370 unsigned CurrentUserSGPRs = Info.getNumUserSGPRs();
3371 // Note we do not count the PrivateSegmentWaveByteOffset. We do not want to
3372 // rely on it to reach 16 since if we end up having no stack usage, it will
3373 // not really be added.
3374 unsigned NumRequiredSystemSGPRs =
3375 Info.hasWorkGroupIDX() + Info.hasWorkGroupIDY() +
3376 Info.hasWorkGroupIDZ() + Info.hasWorkGroupInfo();
3377 for (unsigned i = NumRequiredSystemSGPRs + CurrentUserSGPRs; i < 16; ++i) {
3378 Register Reg = Info.addReservedUserSGPR();
3379 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3380 CCInfo.AllocateReg(Reg);
3381 }
3382 }
3383
3384 if (!HasArchitectedSGPRs) {
3385 if (Info.hasWorkGroupIDX()) {
3386 Register Reg = Info.addWorkGroupIDX();
3387 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3388 CCInfo.AllocateReg(Reg);
3389 }
3390
3391 if (Info.hasWorkGroupIDY()) {
3392 Register Reg = Info.addWorkGroupIDY();
3393 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3394 CCInfo.AllocateReg(Reg);
3395 }
3396
3397 if (Info.hasWorkGroupIDZ()) {
3398 Register Reg = Info.addWorkGroupIDZ();
3399 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3400 CCInfo.AllocateReg(Reg);
3401 }
3402 }
3403
3404 if (Info.hasWorkGroupInfo()) {
3405 Register Reg = Info.addWorkGroupInfo();
3406 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3407 CCInfo.AllocateReg(Reg);
3408 }
3409
3410 if (Info.hasPrivateSegmentWaveByteOffset()) {
3411 // Scratch wave offset passed in system SGPR.
3412 unsigned PrivateSegmentWaveByteOffsetReg;
3413
3414 if (IsShader) {
3415 PrivateSegmentWaveByteOffsetReg =
3416 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
3417
3418 // This is true if the scratch wave byte offset doesn't have a fixed
3419 // location.
3420 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
3421 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
3422 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
3423 }
3424 } else
3425 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
3426
3427 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
3428 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
3429 }
3430
3431 assert(!Subtarget->hasUserSGPRInit16BugInWave32() || IsShader ||
3432 Info.getNumPreloadedSGPRs() >= 16);
3433}
3434
3436 MachineFunction &MF,
3437 const SIRegisterInfo &TRI,
3438 SIMachineFunctionInfo &Info) {
3439 // Now that we've figured out where the scratch register inputs are, see if
3440 // should reserve the arguments and use them directly.
3441 MachineFrameInfo &MFI = MF.getFrameInfo();
3442 bool HasStackObjects = MFI.hasStackObjects();
3443 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3444
3445 // Record that we know we have non-spill stack objects so we don't need to
3446 // check all stack objects later.
3447 if (HasStackObjects)
3448 Info.setHasNonSpillStackObjects(true);
3449
3450 // Everything live out of a block is spilled with fast regalloc, so it's
3451 // almost certain that spilling will be required.
3453 HasStackObjects = true;
3454
3455 // For now assume stack access is needed in any callee functions, so we need
3456 // the scratch registers to pass in.
3457 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
3458
3459 if (!ST.hasFlatScratchEnabled()) {
3460 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
3461 // If we have stack objects, we unquestionably need the private buffer
3462 // resource. For the Code Object V2 ABI, this will be the first 4 user
3463 // SGPR inputs. We can reserve those and use them directly.
3464
3465 Register PrivateSegmentBufferReg =
3467 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
3468 } else {
3469 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
3470 // We tentatively reserve the last registers (skipping the last registers
3471 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
3472 // we'll replace these with the ones immediately after those which were
3473 // really allocated. In the prologue copies will be inserted from the
3474 // argument to these reserved registers.
3475
3476 // Without HSA, relocations are used for the scratch pointer and the
3477 // buffer resource setup is always inserted in the prologue. Scratch wave
3478 // offset is still in an input SGPR.
3479 Info.setScratchRSrcReg(ReservedBufferReg);
3480 }
3481 }
3482
3484
3485 // For entry functions we have to set up the stack pointer if we use it,
3486 // whereas non-entry functions get this "for free". This means there is no
3487 // intrinsic advantage to using S32 over S34 in cases where we do not have
3488 // calls but do need a frame pointer (i.e. if we are requested to have one
3489 // because frame pointer elimination is disabled). To keep things simple we
3490 // only ever use S32 as the call ABI stack pointer, and so using it does not
3491 // imply we need a separate frame pointer.
3492 //
3493 // Try to use s32 as the SP, but move it if it would interfere with input
3494 // arguments. This won't work with calls though.
3495 //
3496 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
3497 // registers.
3498 if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
3499 Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
3500 } else {
3502
3503 if (MFI.hasCalls())
3504 report_fatal_error("call in graphics shader with too many input SGPRs");
3505
3506 for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
3507 if (!MRI.isLiveIn(Reg)) {
3508 Info.setStackPtrOffsetReg(Reg);
3509 break;
3510 }
3511 }
3512
3513 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
3514 report_fatal_error("failed to find register for SP");
3515 }
3516
3517 // hasFP should be accurate for entry functions even before the frame is
3518 // finalized, because it does not rely on the known stack size, only
3519 // properties like whether variable sized objects are present.
3520 if (ST.getFrameLowering()->hasFP(MF)) {
3521 Info.setFrameOffsetReg(AMDGPU::SGPR33);
3522 }
3523}
3524
3527 return !Info->isEntryFunction();
3528}
3529
3531
3533 MachineBasicBlock *Entry,
3534 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
3536
3537 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
3538 if (!IStart)
3539 return;
3540
3541 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
3542 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
3543 MachineBasicBlock::iterator MBBI = Entry->begin();
3544 for (const MCPhysReg *I = IStart; *I; ++I) {
3545 const TargetRegisterClass *RC = nullptr;
3546 if (AMDGPU::SReg_64RegClass.contains(*I))
3547 RC = &AMDGPU::SGPR_64RegClass;
3548 else if (AMDGPU::SReg_32RegClass.contains(*I))
3549 RC = &AMDGPU::SGPR_32RegClass;
3550 else
3551 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3552
3553 Register NewVR = MRI->createVirtualRegister(RC);
3554 // Create copy from CSR to a virtual register.
3555 Entry->addLiveIn(*I);
3556 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
3557 .addReg(*I);
3558
3559 // Insert the copy-back instructions right before the terminator.
3560 for (auto *Exit : Exits)
3561 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
3562 TII->get(TargetOpcode::COPY), *I)
3563 .addReg(NewVR);
3564 }
3565}
3566
3568 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3569 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3570 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3572
3574 const Function &Fn = MF.getFunction();
3577 bool IsError = false;
3578
3579 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
3581 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()));
3582 IsError = true;
3583 }
3584
3587 BitVector Skipped(Fn.arg_size());
3588 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3589 *DAG.getContext());
3590
3591 bool IsGraphics = AMDGPU::isGraphics(CallConv);
3592 bool IsKernel = AMDGPU::isKernel(CallConv);
3593 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
3594
3595 if (IsGraphics) {
3596 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info->getUserSGPRInfo();
3597 assert(!UserSGPRInfo.hasDispatchPtr() &&
3598 !UserSGPRInfo.hasKernargSegmentPtr() && !Info->hasWorkGroupInfo() &&
3599 !Info->hasLDSKernelId() && !Info->hasWorkItemIDX() &&
3600 !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ());
3601 (void)UserSGPRInfo;
3602 if (!Subtarget->hasFlatScratchEnabled())
3603 assert(!UserSGPRInfo.hasFlatScratchInit());
3604 if ((CallConv != CallingConv::AMDGPU_CS &&
3605 CallConv != CallingConv::AMDGPU_Gfx &&
3606 CallConv != CallingConv::AMDGPU_Gfx_WholeWave) ||
3607 !Subtarget->hasArchitectedSGPRs())
3608 assert(!Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
3609 !Info->hasWorkGroupIDZ());
3610 }
3611
3612 bool IsWholeWaveFunc = Info->isWholeWaveFunction();
3613
3614 if (CallConv == CallingConv::AMDGPU_PS) {
3615 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
3616
3617 // At least one interpolation mode must be enabled or else the GPU will
3618 // hang.
3619 //
3620 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
3621 // set PSInputAddr, the user wants to enable some bits after the compilation
3622 // based on run-time states. Since we can't know what the final PSInputEna
3623 // will look like, so we shouldn't do anything here and the user should take
3624 // responsibility for the correct programming.
3625 //
3626 // Otherwise, the following restrictions apply:
3627 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
3628 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
3629 // enabled too.
3630 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
3631 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
3632 CCInfo.AllocateReg(AMDGPU::VGPR0);
3633 CCInfo.AllocateReg(AMDGPU::VGPR1);
3634 Info->markPSInputAllocated(0);
3635 Info->markPSInputEnabled(0);
3636 }
3637 if (Subtarget->isAmdPalOS()) {
3638 // For isAmdPalOS, the user does not enable some bits after compilation
3639 // based on run-time states; the register values being generated here are
3640 // the final ones set in hardware. Therefore we need to apply the
3641 // workaround to PSInputAddr and PSInputEnable together. (The case where
3642 // a bit is set in PSInputAddr but not PSInputEnable is where the
3643 // frontend set up an input arg for a particular interpolation mode, but
3644 // nothing uses that input arg. Really we should have an earlier pass
3645 // that removes such an arg.)
3646 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
3647 if ((PsInputBits & 0x7F) == 0 ||
3648 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
3649 Info->markPSInputEnabled(llvm::countr_zero(Info->getPSInputAddr()));
3650 }
3651 } else if (IsKernel) {
3652 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
3653 } else {
3654 Splits.append(IsWholeWaveFunc ? std::next(Ins.begin()) : Ins.begin(),
3655 Ins.end());
3656 }
3657
3658 if (IsKernel)
3659 analyzeFormalArgumentsCompute(CCInfo, Ins);
3660
3661 if (IsEntryFunc) {
3662 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
3663 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
3664 if (IsKernel && Subtarget->hasKernargPreload())
3665 allocatePreloadKernArgSGPRs(CCInfo, ArgLocs, Ins, MF, *TRI, *Info);
3666
3667 allocateLDSKernelId(CCInfo, MF, *TRI, *Info);
3668 } else if (!IsGraphics) {
3669 // For the fixed ABI, pass workitem IDs in the last argument register.
3670 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
3671
3672 // FIXME: Sink this into allocateSpecialInputSGPRs
3673 if (!Subtarget->hasFlatScratchEnabled())
3674 CCInfo.AllocateReg(Info->getScratchRSrcReg());
3675
3676 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
3677 }
3678
3679 if (!IsKernel) {
3680 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
3681 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
3682
3683 // This assumes the registers are allocated by CCInfo in ascending order
3684 // with no gaps.
3685 Info->setNumWaveDispatchSGPRs(
3686 CCInfo.getFirstUnallocated(AMDGPU::SGPR_32RegClass.getRegisters()));
3687 Info->setNumWaveDispatchVGPRs(
3688 CCInfo.getFirstUnallocated(AMDGPU::VGPR_32RegClass.getRegisters()));
3689 } else if (Info->getNumKernargPreloadedSGPRs()) {
3690 Info->setNumWaveDispatchSGPRs(Info->getNumUserSGPRs());
3691 }
3692
3694
3695 if (IsWholeWaveFunc) {
3696 SDValue Setup = DAG.getNode(AMDGPUISD::WHOLE_WAVE_SETUP, DL,
3697 {MVT::i1, MVT::Other}, Chain);
3698 InVals.push_back(Setup.getValue(0));
3699 Chains.push_back(Setup.getValue(1));
3700 }
3701
3702 // FIXME: This is the minimum kernel argument alignment. We should improve
3703 // this to the maximum alignment of the arguments.
3704 //
3705 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
3706 // kern arg offset.
3707 const Align KernelArgBaseAlign = Align(16);
3708
3709 for (unsigned i = IsWholeWaveFunc ? 1 : 0, e = Ins.size(), ArgIdx = 0; i != e;
3710 ++i) {
3711 const ISD::InputArg &Arg = Ins[i];
3712 if ((Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) || IsError) {
3713 InVals.push_back(DAG.getPOISON(Arg.VT));
3714 continue;
3715 }
3716
3717 CCValAssign &VA = ArgLocs[ArgIdx++];
3718 MVT VT = VA.getLocVT();
3719
3720 if (IsEntryFunc && VA.isMemLoc()) {
3721 VT = Ins[i].VT;
3722 EVT MemVT = VA.getLocVT();
3723
3724 const uint64_t Offset = VA.getLocMemOffset();
3725 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
3726
3727 if (Arg.Flags.isByRef()) {
3728 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
3729
3730 const GCNTargetMachine &TM =
3731 static_cast<const GCNTargetMachine &>(getTargetMachine());
3732 if (!TM.isNoopAddrSpaceCast(DAG.getDataLayout(),
3734 Arg.Flags.getPointerAddrSpace())) {
3737 }
3738
3739 InVals.push_back(Ptr);
3740 continue;
3741 }
3742
3743 SDValue NewArg;
3744 if (Arg.isOrigArg() && Info->getArgInfo().PreloadKernArgs.count(i)) {
3745 if (MemVT.getStoreSize() < 4 && Alignment < 4) {
3746 // In this case the argument is packed into the previous preload SGPR.
3747 int64_t AlignDownOffset = alignDown(Offset, 4);
3748 int64_t OffsetDiff = Offset - AlignDownOffset;
3749 EVT IntVT = MemVT.changeTypeToInteger();
3750
3751 const SIMachineFunctionInfo *Info =
3754 Register Reg =
3755 Info->getArgInfo().PreloadKernArgs.find(i)->getSecond().Regs[0];
3756
3757 assert(Reg);
3758 Register VReg = MRI.getLiveInVirtReg(Reg);
3759 SDValue Copy = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i32);
3760
3761 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, DL, MVT::i32);
3762 SDValue Extract = DAG.getNode(ISD::SRL, DL, MVT::i32, Copy, ShiftAmt);
3763
3764 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, Extract);
3765 ArgVal = DAG.getNode(ISD::BITCAST, DL, MemVT, ArgVal);
3766 NewArg = convertArgType(DAG, VT, MemVT, DL, ArgVal,
3767 Ins[i].Flags.isSExt(), &Ins[i]);
3768
3769 NewArg = DAG.getMergeValues({NewArg, Copy.getValue(1)}, DL);
3770 } else {
3771 const SIMachineFunctionInfo *Info =
3774 const SmallVectorImpl<MCRegister> &PreloadRegs =
3775 Info->getArgInfo().PreloadKernArgs.find(i)->getSecond().Regs;
3776
3777 SDValue Copy;
3778 if (PreloadRegs.size() == 1) {
3779 Register VReg = MRI.getLiveInVirtReg(PreloadRegs[0]);
3780 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
3781 NewArg = DAG.getCopyFromReg(
3782 Chain, DL, VReg,
3784 TRI->getRegSizeInBits(*RC)));
3785
3786 } else {
3787 // If the kernarg alignment does not match the alignment of the SGPR
3788 // tuple RC that can accommodate this argument, it will be built up
3789 // via copies from from the individual SGPRs that the argument was
3790 // preloaded to.
3792 for (auto Reg : PreloadRegs) {
3793 Register VReg = MRI.getLiveInVirtReg(Reg);
3794 Copy = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i32);
3795 Elts.push_back(Copy);
3796 }
3797 NewArg =
3798 DAG.getBuildVector(EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3799 PreloadRegs.size()),
3800 DL, Elts);
3801 }
3802
3803 // If the argument was preloaded to multiple consecutive 32-bit
3804 // registers because of misalignment between addressable SGPR tuples
3805 // and the argument size, we can still assume that because of kernarg
3806 // segment alignment restrictions that NewArg's size is the same as
3807 // MemVT and just do a bitcast. If MemVT is less than 32-bits we add a
3808 // truncate since we cannot preload to less than a single SGPR and the
3809 // MemVT may be smaller.
3810 EVT MemVTInt =
3812 if (MemVT.bitsLT(NewArg.getSimpleValueType()))
3813 NewArg = DAG.getNode(ISD::TRUNCATE, DL, MemVTInt, NewArg);
3814
3815 NewArg = DAG.getBitcast(MemVT, NewArg);
3816 NewArg = convertArgType(DAG, VT, MemVT, DL, NewArg,
3817 Ins[i].Flags.isSExt(), &Ins[i]);
3818 NewArg = DAG.getMergeValues({NewArg, Chain}, DL);
3819 }
3820 } else {
3821 // Hidden arguments that are in the kernel signature must be preloaded
3822 // to user SGPRs. Print a diagnostic error if a hidden argument is in
3823 // the argument list and is not preloaded.
3824 if (Arg.isOrigArg()) {
3825 Argument *OrigArg = Fn.getArg(Arg.getOrigArgIndex());
3826 if (OrigArg->hasAttribute("amdgpu-hidden-argument")) {
3828 *OrigArg->getParent(),
3829 "hidden argument in kernel signature was not preloaded",
3830 DL.getDebugLoc()));
3831 }
3832 }
3833
3834 NewArg =
3835 lowerKernargMemParameter(DAG, VT, MemVT, DL, Chain, Offset,
3836 Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
3837 }
3838 Chains.push_back(NewArg.getValue(1));
3839
3840 auto *ParamTy =
3841 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
3842 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
3843 ParamTy &&
3844 (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
3845 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
3846 // On SI local pointers are just offsets into LDS, so they are always
3847 // less than 16-bits. On CI and newer they could potentially be
3848 // real pointers, so we can't guarantee their size.
3849 NewArg = DAG.getNode(ISD::AssertZext, DL, NewArg.getValueType(), NewArg,
3850 DAG.getValueType(MVT::i16));
3851 }
3852
3853 InVals.push_back(NewArg);
3854 continue;
3855 }
3856 if (!IsEntryFunc && VA.isMemLoc()) {
3857 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
3858 InVals.push_back(Val);
3859 if (!Arg.Flags.isByVal())
3860 Chains.push_back(Val.getValue(1));
3861 continue;
3862 }
3863
3864 assert(VA.isRegLoc() && "Parameter must be in a register!");
3865
3866 Register Reg = VA.getLocReg();
3867 const TargetRegisterClass *RC = nullptr;
3868 if (AMDGPU::VGPR_32RegClass.contains(Reg))
3869 RC = &AMDGPU::VGPR_32RegClass;
3870 else if (AMDGPU::SGPR_32RegClass.contains(Reg))
3871 RC = &AMDGPU::SGPR_32RegClass;
3872 else
3873 llvm_unreachable("Unexpected register class in LowerFormalArguments!");
3874
3875 Reg = MF.addLiveIn(Reg, RC);
3876 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
3877 if (Arg.Flags.isInReg() && RC == &AMDGPU::VGPR_32RegClass) {
3878 // FIXME: Need to forward the chains created by `CopyFromReg`s, make sure
3879 // they will read physical regs before any side effect instructions.
3880 SDValue ReadFirstLane =
3881 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
3883 ReadFirstLane, Val);
3884 }
3885
3886 if (Arg.Flags.isSRet()) {
3887 // The return object should be reasonably addressable.
3888 Val = annotateStackObjectPointer(Val, DAG, DL,
3890 }
3891
3892 Val = convertABITypeToValueType(DAG, Val, VA, DL);
3893 InVals.push_back(Val);
3894 }
3895
3896 // Start adding system SGPRs.
3897 if (IsEntryFunc)
3898 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
3899
3900 unsigned StackArgSize = CCInfo.getStackSize();
3901 Info->setBytesInStackArgArea(StackArgSize);
3902
3903 return Chains.empty() ? Chain
3904 : DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3905}
3906
3907// TODO: If return values can't fit in registers, we should return as many as
3908// possible in registers before passing on stack.
3910 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
3911 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context,
3912 const Type *RetTy) const {
3913 // Replacing returns with sret/stack usage doesn't make sense for shaders.
3914 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
3915 // for shaders. Vector types should be explicitly handled by CC.
3916 if (AMDGPU::isEntryFunctionCC(CallConv))
3917 return true;
3918
3920 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3921 if (!CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)))
3922 return false;
3923
3924 // We must use the stack if return would require unavailable registers.
3925 unsigned MaxNumVGPRs = Subtarget->getMaxNumVGPRs(MF);
3926 unsigned TotalNumVGPRs = Subtarget->getAddressableNumArchVGPRs();
3927 for (unsigned i = MaxNumVGPRs; i < TotalNumVGPRs; ++i)
3928 if (CCInfo.isAllocated(AMDGPU::VGPR_32RegClass.getRegister(i)))
3929 return false;
3930
3931 return true;
3932}
3933
3934SDValue
3936 bool isVarArg,
3938 const SmallVectorImpl<SDValue> &OutVals,
3939 const SDLoc &DL, SelectionDAG &DAG) const {
3943
3944 if (AMDGPU::isKernel(CallConv)) {
3945 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
3946 OutVals, DL, DAG);
3947 }
3948
3949 bool IsShader = AMDGPU::isShader(CallConv);
3950
3951 Info->setIfReturnsVoid(Outs.empty());
3952 bool IsWaveEnd = Info->returnsVoid() && IsShader;
3953
3954 // CCValAssign - represent the assignment of the return value to a location.
3956
3957 // CCState - Info about the registers and stack slots.
3958 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3959 *DAG.getContext());
3960
3961 // Analyze outgoing return values.
3962 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3963
3964 SDValue Glue;
3966 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
3967
3968 SDValue ReadFirstLane =
3969 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
3970 // Copy the result values into the output registers.
3971 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
3972 ++I, ++RealRVLocIdx) {
3973 CCValAssign &VA = RVLocs[I];
3974 assert(VA.isRegLoc() && "Can only return in registers!");
3975 // TODO: Partially return in registers if return values don't fit.
3976 SDValue Arg = OutVals[RealRVLocIdx];
3977
3978 // Copied from other backends.
3979 switch (VA.getLocInfo()) {
3980 case CCValAssign::Full:
3981 break;
3982 case CCValAssign::BCvt:
3983 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3984 break;
3985 case CCValAssign::SExt:
3986 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3987 break;
3988 case CCValAssign::ZExt:
3989 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3990 break;
3991 case CCValAssign::AExt:
3992 Arg = DAG.getBitcast(VA.getValVT().changeTypeToInteger(), Arg);
3993 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3994 break;
3995 default:
3996 llvm_unreachable("Unknown loc info!");
3997 }
3998 if (TRI->isSGPRPhysReg(VA.getLocReg()))
4000 ReadFirstLane, Arg);
4001 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Glue);
4002 Glue = Chain.getValue(1);
4003 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4004 }
4005
4006 // FIXME: Does sret work properly?
4007 if (!Info->isEntryFunction()) {
4008 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4009 const MCPhysReg *I =
4010 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4011 if (I) {
4012 for (; *I; ++I) {
4013 if (AMDGPU::SReg_64RegClass.contains(*I))
4014 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4015 else if (AMDGPU::SReg_32RegClass.contains(*I))
4016 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
4017 else
4018 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4019 }
4020 }
4021 }
4022
4023 // Update chain and glue.
4024 RetOps[0] = Chain;
4025 if (Glue.getNode())
4026 RetOps.push_back(Glue);
4027
4028 unsigned Opc = AMDGPUISD::ENDPGM;
4029 if (!IsWaveEnd)
4030 Opc = Info->isWholeWaveFunction() ? AMDGPUISD::WHOLE_WAVE_RETURN
4031 : IsShader ? AMDGPUISD::RETURN_TO_EPILOG
4032 : AMDGPUISD::RET_GLUE;
4033 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
4034}
4035
4037 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
4038 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4039 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
4040 SDValue ThisVal) const {
4041 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
4042
4043 // Assign locations to each value returned by this call.
4045 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
4046 *DAG.getContext());
4047 CCInfo.AnalyzeCallResult(Ins, RetCC);
4048
4049 // Copy all of the result registers out of their specified physreg.
4050 for (CCValAssign VA : RVLocs) {
4051 SDValue Val;
4052
4053 if (VA.isRegLoc()) {
4054 Val =
4055 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InGlue);
4056 Chain = Val.getValue(1);
4057 InGlue = Val.getValue(2);
4058 } else if (VA.isMemLoc()) {
4059 report_fatal_error("TODO: return values in memory");
4060 } else
4061 llvm_unreachable("unknown argument location type");
4062
4063 Val = convertABITypeToValueType(DAG, Val, VA, DL);
4064
4065 InVals.push_back(Val);
4066 }
4067
4068 return Chain;
4069}
4070
4071// Add code to pass special inputs required depending on used features separate
4072// from the explicit user arguments present in the IR.
4074 CallLoweringInfo &CLI, CCState &CCInfo, const SIMachineFunctionInfo &Info,
4075 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4076 SmallVectorImpl<SDValue> &MemOpChains, SDValue Chain) const {
4077 // If we don't have a call site, this was a call inserted by
4078 // legalization. These can never use special inputs.
4079 if (!CLI.CB)
4080 return;
4081
4082 SelectionDAG &DAG = CLI.DAG;
4083 const SDLoc &DL = CLI.DL;
4084 const Function &F = DAG.getMachineFunction().getFunction();
4085
4086 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4087 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
4088
4089 const AMDGPUFunctionArgInfo &CalleeArgInfo =
4091
4092 // TODO: Unify with private memory register handling. This is complicated by
4093 // the fact that at least in kernels, the input argument is not necessarily
4094 // in the same location as the input.
4095 // clang-format off
4096 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
4097 std::array<StringLiteral, 2>> ImplicitAttrs[] = {
4098 {AMDGPUFunctionArgInfo::DISPATCH_PTR, {"amdgpu-no-dispatch-ptr", ""}},
4099 {AMDGPUFunctionArgInfo::QUEUE_PTR, {"amdgpu-no-queue-ptr", ""}},
4100 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, {"amdgpu-no-implicitarg-ptr", ""}},
4101 {AMDGPUFunctionArgInfo::DISPATCH_ID, {"amdgpu-no-dispatch-id", ""}},
4102 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, {"amdgpu-no-workgroup-id-x", "amdgpu-no-cluster-id-x"}},
4103 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, {"amdgpu-no-workgroup-id-y", "amdgpu-no-cluster-id-y"}},
4104 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, {"amdgpu-no-workgroup-id-z", "amdgpu-no-cluster-id-z"}},
4105 {AMDGPUFunctionArgInfo::LDS_KERNEL_ID, {"amdgpu-no-lds-kernel-id", ""}},
4106 };
4107 // clang-format on
4108
4109 for (auto [InputID, Attrs] : ImplicitAttrs) {
4110 // If the callee does not use the attribute value, skip copying the value.
4111 if (all_of(Attrs, [&](StringRef Attr) {
4112 return Attr.empty() || CLI.CB->hasFnAttr(Attr);
4113 }))
4114 continue;
4115
4116 const auto [OutgoingArg, ArgRC, ArgTy] =
4117 CalleeArgInfo.getPreloadedValue(InputID);
4118 if (!OutgoingArg)
4119 continue;
4120
4121 const auto [IncomingArg, IncomingArgRC, Ty] =
4122 CallerArgInfo.getPreloadedValue(InputID);
4123 assert(IncomingArgRC == ArgRC);
4124
4125 // All special arguments are ints for now.
4126 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
4127 SDValue InputReg;
4128
4129 if (IncomingArg) {
4130 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
4131 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
4132 // The implicit arg ptr is special because it doesn't have a corresponding
4133 // input for kernels, and is computed from the kernarg segment pointer.
4134 InputReg = getImplicitArgPtr(DAG, DL);
4135 } else if (InputID == AMDGPUFunctionArgInfo::LDS_KERNEL_ID) {
4136 std::optional<uint32_t> Id =
4138 if (Id.has_value()) {
4139 InputReg = DAG.getConstant(*Id, DL, ArgVT);
4140 } else {
4141 InputReg = DAG.getPOISON(ArgVT);
4142 }
4143 } else {
4144 // We may have proven the input wasn't needed, although the ABI is
4145 // requiring it. We just need to allocate the register appropriately.
4146 InputReg = DAG.getPOISON(ArgVT);
4147 }
4148
4149 if (OutgoingArg->isRegister()) {
4150 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
4151 if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
4152 report_fatal_error("failed to allocate implicit input argument");
4153 } else {
4154 unsigned SpecialArgOffset =
4155 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
4156 SDValue ArgStore =
4157 storeStackInputValue(DAG, DL, Chain, InputReg, SpecialArgOffset);
4158 MemOpChains.push_back(ArgStore);
4159 }
4160 }
4161
4162 // Pack workitem IDs into a single register or pass it as is if already
4163 // packed.
4164
4165 auto [OutgoingArg, ArgRC, Ty] =
4167 if (!OutgoingArg)
4168 std::tie(OutgoingArg, ArgRC, Ty) =
4170 if (!OutgoingArg)
4171 std::tie(OutgoingArg, ArgRC, Ty) =
4173 if (!OutgoingArg)
4174 return;
4175
4176 const ArgDescriptor *IncomingArgX = std::get<0>(
4178 const ArgDescriptor *IncomingArgY = std::get<0>(
4180 const ArgDescriptor *IncomingArgZ = std::get<0>(
4182
4183 SDValue InputReg;
4184 SDLoc SL;
4185
4186 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
4187 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
4188 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
4189
4190 // If incoming ids are not packed we need to pack them.
4191 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX &&
4192 NeedWorkItemIDX) {
4193 if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
4194 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
4195 } else {
4196 InputReg = DAG.getConstant(0, DL, MVT::i32);
4197 }
4198 }
4199
4200 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY &&
4201 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
4202 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
4203 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
4204 DAG.getShiftAmountConstant(10, MVT::i32, SL));
4205 InputReg = InputReg.getNode()
4206 ? DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y)
4207 : Y;
4208 }
4209
4210 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ &&
4211 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
4212 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
4213 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
4214 DAG.getShiftAmountConstant(20, MVT::i32, SL));
4215 InputReg = InputReg.getNode()
4216 ? DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z)
4217 : Z;
4218 }
4219
4220 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
4221 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
4222 // We're in a situation where the outgoing function requires the workitem
4223 // ID, but the calling function does not have it (e.g a graphics function
4224 // calling a C calling convention function). This is illegal, but we need
4225 // to produce something.
4226 InputReg = DAG.getPOISON(MVT::i32);
4227 } else {
4228 // Workitem ids are already packed, any of present incoming arguments
4229 // will carry all required fields.
4230 ArgDescriptor IncomingArg =
4231 ArgDescriptor::createArg(IncomingArgX ? *IncomingArgX
4232 : IncomingArgY ? *IncomingArgY
4233 : *IncomingArgZ,
4234 ~0u);
4235 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
4236 }
4237 }
4238
4239 if (OutgoingArg->isRegister()) {
4240 if (InputReg)
4241 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
4242
4243 CCInfo.AllocateReg(OutgoingArg->getRegister());
4244 } else {
4245 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
4246 if (InputReg) {
4247 SDValue ArgStore =
4248 storeStackInputValue(DAG, DL, Chain, InputReg, SpecialArgOffset);
4249 MemOpChains.push_back(ArgStore);
4250 }
4251 }
4252}
4253
4255 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
4257 const SmallVectorImpl<SDValue> &OutVals,
4258 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4259 if (AMDGPU::isChainCC(CalleeCC))
4260 return true;
4261
4262 if (!AMDGPU::mayTailCallThisCC(CalleeCC))
4263 return false;
4264
4265 // For a divergent call target, we need to do a waterfall loop over the
4266 // possible callees which precludes us from using a simple jump.
4267 if (Callee->isDivergent())
4268 return false;
4269
4271 const Function &CallerF = MF.getFunction();
4272 CallingConv::ID CallerCC = CallerF.getCallingConv();
4274 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4275
4276 // Kernels aren't callable, and don't have a live in return address so it
4277 // doesn't make sense to do a tail call with entry functions.
4278 if (!CallerPreserved)
4279 return false;
4280
4281 bool CCMatch = CallerCC == CalleeCC;
4282
4284 if (AMDGPU::canGuaranteeTCO(CalleeCC) && CCMatch)
4285 return true;
4286 return false;
4287 }
4288
4289 // TODO: Can we handle var args?
4290 if (IsVarArg)
4291 return false;
4292
4293 for (const Argument &Arg : CallerF.args()) {
4294 if (Arg.hasByValAttr())
4295 return false;
4296 }
4297
4298 LLVMContext &Ctx = *DAG.getContext();
4299
4300 // Check that the call results are passed in the same way.
4301 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
4302 CCAssignFnForCall(CalleeCC, IsVarArg),
4303 CCAssignFnForCall(CallerCC, IsVarArg)))
4304 return false;
4305
4306 // The callee has to preserve all registers the caller needs to preserve.
4307 if (!CCMatch) {
4308 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4309 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4310 return false;
4311 }
4312
4313 // Nothing more to check if the callee is taking no arguments.
4314 if (Outs.empty())
4315 return true;
4316
4318 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
4319
4320 // FIXME: We are not allocating special input registers, so we will be
4321 // deciding based on incorrect register assignments.
4322 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
4323
4324 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
4325 // If the stack arguments for this call do not fit into our own save area then
4326 // the call cannot be made tail.
4327 // TODO: Is this really necessary?
4328 if (CCInfo.getStackSize() > FuncInfo->getBytesInStackArgArea())
4329 return false;
4330
4331 for (const auto &[CCVA, ArgVal] : zip_equal(ArgLocs, OutVals)) {
4332 // FIXME: What about inreg arguments that end up passed in memory?
4333 if (!CCVA.isRegLoc())
4334 continue;
4335
4336 // If we are passing an argument in an SGPR, and the value is divergent,
4337 // this call requires a waterfall loop.
4338 if (ArgVal->isDivergent() && TRI->isSGPRPhysReg(CCVA.getLocReg())) {
4339 LLVM_DEBUG(
4340 dbgs() << "Cannot tail call due to divergent outgoing argument in "
4341 << printReg(CCVA.getLocReg(), TRI) << '\n');
4342 return false;
4343 }
4344 }
4345
4346 const MachineRegisterInfo &MRI = MF.getRegInfo();
4347 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
4348}
4349
4351 if (!CI->isTailCall())
4352 return false;
4353
4354 const Function *ParentFn = CI->getFunction();
4356 return false;
4357 return true;
4358}
4359
4360namespace {
4361// Chain calls have special arguments that we need to handle. These are
4362// tagging along at the end of the arguments list(s), after the SGPR and VGPR
4363// arguments (index 0 and 1 respectively).
4364enum ChainCallArgIdx {
4365 Exec = 2,
4366 Flags,
4367 NumVGPRs,
4368 FallbackExec,
4369 FallbackCallee
4370};
4371} // anonymous namespace
4372
4373// The wave scratch offset register is used as the global base pointer.
4375 SmallVectorImpl<SDValue> &InVals) const {
4376 CallingConv::ID CallConv = CLI.CallConv;
4377 bool IsChainCallConv = AMDGPU::isChainCC(CallConv);
4378
4379 SelectionDAG &DAG = CLI.DAG;
4380
4381 const SDLoc &DL = CLI.DL;
4382 SDValue Chain = CLI.Chain;
4383 SDValue Callee = CLI.Callee;
4384
4385 llvm::SmallVector<SDValue, 6> ChainCallSpecialArgs;
4386 bool UsesDynamicVGPRs = false;
4387 if (IsChainCallConv) {
4388 // The last arguments should be the value that we need to put in EXEC,
4389 // followed by the flags and any other arguments with special meanings.
4390 // Pop them out of CLI.Outs and CLI.OutVals before we do any processing so
4391 // we don't treat them like the "real" arguments.
4392 auto RequestedExecIt =
4393 llvm::find_if(CLI.Outs, [](const ISD::OutputArg &Arg) {
4394 return Arg.OrigArgIndex == 2;
4395 });
4396 assert(RequestedExecIt != CLI.Outs.end() && "No node for EXEC");
4397
4398 size_t SpecialArgsBeginIdx = RequestedExecIt - CLI.Outs.begin();
4399 CLI.OutVals.erase(CLI.OutVals.begin() + SpecialArgsBeginIdx,
4400 CLI.OutVals.end());
4401 CLI.Outs.erase(RequestedExecIt, CLI.Outs.end());
4402
4403 assert(CLI.Outs.back().OrigArgIndex < 2 &&
4404 "Haven't popped all the special args");
4405
4406 TargetLowering::ArgListEntry RequestedExecArg =
4407 CLI.Args[ChainCallArgIdx::Exec];
4408 if (!RequestedExecArg.Ty->isIntegerTy(Subtarget->getWavefrontSize()))
4409 return lowerUnhandledCall(CLI, InVals, "Invalid value for EXEC");
4410
4411 // Convert constants into TargetConstants, so they become immediate operands
4412 // instead of being selected into S_MOV.
4413 auto PushNodeOrTargetConstant = [&](TargetLowering::ArgListEntry Arg) {
4414 if (const auto *ArgNode = dyn_cast<ConstantSDNode>(Arg.Node)) {
4415 ChainCallSpecialArgs.push_back(DAG.getTargetConstant(
4416 ArgNode->getAPIntValue(), DL, ArgNode->getValueType(0)));
4417 } else
4418 ChainCallSpecialArgs.push_back(Arg.Node);
4419 };
4420
4421 PushNodeOrTargetConstant(RequestedExecArg);
4422
4423 // Process any other special arguments depending on the value of the flags.
4424 TargetLowering::ArgListEntry Flags = CLI.Args[ChainCallArgIdx::Flags];
4425
4426 const APInt &FlagsValue = cast<ConstantSDNode>(Flags.Node)->getAPIntValue();
4427 if (FlagsValue.isZero()) {
4428 if (CLI.Args.size() > ChainCallArgIdx::Flags + 1)
4429 return lowerUnhandledCall(CLI, InVals,
4430 "no additional args allowed if flags == 0");
4431 } else if (FlagsValue.isOneBitSet(0)) {
4432 if (CLI.Args.size() != ChainCallArgIdx::FallbackCallee + 1) {
4433 return lowerUnhandledCall(CLI, InVals, "expected 3 additional args");
4434 }
4435
4436 if (!Subtarget->isWave32()) {
4437 return lowerUnhandledCall(
4438 CLI, InVals, "dynamic VGPR mode is only supported for wave32");
4439 }
4440
4441 UsesDynamicVGPRs = true;
4442 std::for_each(CLI.Args.begin() + ChainCallArgIdx::NumVGPRs,
4443 CLI.Args.end(), PushNodeOrTargetConstant);
4444 }
4445 }
4446
4448 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
4450 bool &IsTailCall = CLI.IsTailCall;
4451 bool IsVarArg = CLI.IsVarArg;
4452 bool IsSibCall = false;
4454
4455 if (Callee.isUndef() || isNullConstant(Callee)) {
4456 if (!CLI.IsTailCall) {
4457 for (ISD::InputArg &Arg : CLI.Ins)
4458 InVals.push_back(DAG.getPOISON(Arg.VT));
4459 }
4460
4461 return Chain;
4462 }
4463
4464 if (IsVarArg) {
4465 return lowerUnhandledCall(CLI, InVals,
4466 "unsupported call to variadic function ");
4467 }
4468
4469 if (!CLI.CB)
4470 return lowerUnhandledCall(CLI, InVals, "unsupported libcall legalization");
4471
4472 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
4473 return lowerUnhandledCall(CLI, InVals,
4474 "unsupported required tail call to function ");
4475 }
4476
4477 if (IsTailCall) {
4478 IsTailCall = isEligibleForTailCallOptimization(Callee, CallConv, IsVarArg,
4479 Outs, OutVals, Ins, DAG);
4480 if (!IsTailCall &&
4481 ((CLI.CB && CLI.CB->isMustTailCall()) || IsChainCallConv)) {
4482 report_fatal_error("failed to perform tail call elimination on a call "
4483 "site marked musttail or on llvm.amdgcn.cs.chain");
4484 }
4485
4486 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4487
4488 // A sibling call is one where we're under the usual C ABI and not planning
4489 // to change that but can still do a tail call:
4490 if (!TailCallOpt && IsTailCall)
4491 IsSibCall = true;
4492
4493 if (IsTailCall)
4494 ++NumTailCalls;
4495 }
4496
4499 SmallVector<SDValue, 8> MemOpChains;
4500
4501 // Analyze operands of the call, assigning locations to each operand.
4503 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
4504 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
4505
4506 if (CallConv != CallingConv::AMDGPU_Gfx && !AMDGPU::isChainCC(CallConv) &&
4508 // With a fixed ABI, allocate fixed registers before user arguments.
4509 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
4510 }
4511
4512 // Mark the scratch resource descriptor as allocated so the CC analysis
4513 // does not assign user arguments to these registers, matching the callee.
4514 if (!Subtarget->hasFlatScratchEnabled()) {
4515 CCInfo.AllocateReg(
4517 }
4518
4519 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
4520
4521 // Get a count of how many bytes are to be pushed on the stack.
4522 unsigned NumBytes = CCInfo.getStackSize();
4523
4524 if (IsSibCall) {
4525 // Since we're not changing the ABI to make this a tail call, the memory
4526 // operands are already available in the caller's incoming argument space.
4527 NumBytes = 0;
4528 }
4529
4530 // FPDiff is the byte offset of the call's argument area from the callee's.
4531 // Stores to callee stack arguments will be placed in FixedStackSlots offset
4532 // by this amount for a tail call. In a sibling call it must be 0 because the
4533 // caller will deallocate the entire stack and the callee still expects its
4534 // arguments to begin at SP+0. Completely unused for non-tail calls.
4535 int32_t FPDiff = 0;
4536 MachineFrameInfo &MFI = MF.getFrameInfo();
4537 auto *TRI = Subtarget->getRegisterInfo();
4538
4539 // Adjust the stack pointer for the new arguments...
4540 // These operations are automatically eliminated by the prolog/epilog pass
4541 if (!IsSibCall)
4542 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
4543
4544 if (!IsSibCall || IsChainCallConv) {
4545 if (!Subtarget->hasFlatScratchEnabled()) {
4546 SmallVector<SDValue, 4> CopyFromChains;
4547
4548 // In the HSA case, this should be an identity copy.
4549 SDValue ScratchRSrcReg =
4550 DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
4551 RegsToPass.emplace_back(
4553 ScratchRSrcReg);
4554 CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
4555 Chain = DAG.getTokenFactor(DL, CopyFromChains);
4556 }
4557 }
4558
4559 const unsigned NumSpecialInputs = RegsToPass.size();
4560
4561 MVT PtrVT = MVT::i32;
4562
4563 // Walk the register/memloc assignments, inserting copies/loads.
4564 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4565 CCValAssign &VA = ArgLocs[i];
4566 SDValue Arg = OutVals[i];
4567
4568 // Promote the value if needed.
4569 switch (VA.getLocInfo()) {
4570 case CCValAssign::Full:
4571 break;
4572 case CCValAssign::BCvt:
4573 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4574 break;
4575 case CCValAssign::ZExt:
4576 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4577 break;
4578 case CCValAssign::SExt:
4579 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4580 break;
4581 case CCValAssign::AExt:
4582 Arg = DAG.getBitcast(VA.getValVT().changeTypeToInteger(), Arg);
4583 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4584 break;
4585 case CCValAssign::FPExt:
4586 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4587 break;
4588 default:
4589 llvm_unreachable("Unknown loc info!");
4590 }
4591
4592 if (VA.isRegLoc()) {
4593 RegsToPass.push_back(std::pair(VA.getLocReg(), Arg));
4594 } else {
4595 assert(VA.isMemLoc());
4596
4597 SDValue DstAddr;
4598 MachinePointerInfo DstInfo;
4599
4600 unsigned LocMemOffset = VA.getLocMemOffset();
4601 int32_t Offset = LocMemOffset;
4602
4603 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
4604 MaybeAlign Alignment;
4605
4606 if (IsTailCall) {
4607 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4608 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize()
4609 : VA.getValVT().getStoreSize();
4610
4611 // FIXME: We can have better than the minimum byval required alignment.
4612 Alignment =
4613 Flags.isByVal()
4614 ? Flags.getNonZeroByValAlign()
4615 : commonAlignment(Subtarget->getStackAlignment(), Offset);
4616
4617 Offset = Offset + FPDiff;
4618 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
4619
4620 DstAddr = DAG.getFrameIndex(FI, PtrVT);
4621 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
4622
4623 // Make sure any stack arguments overlapping with where we're storing
4624 // are loaded before this eventual operation. Otherwise they'll be
4625 // clobbered.
4626
4627 // FIXME: Why is this really necessary? This seems to just result in a
4628 // lot of code to copy the stack and write them back to the same
4629 // locations, which are supposed to be immutable?
4630 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
4631 } else {
4632 // Stores to the argument stack area are relative to the stack pointer.
4633 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
4634 MVT::i32);
4635 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
4636 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
4637 Alignment =
4638 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
4639 }
4640
4641 if (Outs[i].Flags.isByVal()) {
4642 SDValue SizeNode =
4643 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
4644 SDValue Cpy =
4645 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
4646 Outs[i].Flags.getNonZeroByValAlign(),
4647 Outs[i].Flags.getNonZeroByValAlign(),
4648 /*isVol = */ false, /*AlwaysInline = */ true,
4649 /*CI=*/nullptr, std::nullopt, DstInfo,
4651
4652 MemOpChains.push_back(Cpy);
4653 } else {
4654 SDValue Store =
4655 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
4656 MemOpChains.push_back(Store);
4657 }
4658 }
4659 }
4660
4661 if (!MemOpChains.empty())
4662 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4663
4664 SDValue ReadFirstLaneID =
4665 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
4666
4667 SDValue TokenGlue;
4668 if (CLI.ConvergenceControlToken) {
4669 TokenGlue = DAG.getNode(ISD::CONVERGENCECTRL_GLUE, DL, MVT::Glue,
4671 }
4672
4673 // Build a sequence of copy-to-reg nodes chained together with token chain
4674 // and flag operands which copy the outgoing args into the appropriate regs.
4675 SDValue InGlue;
4676
4677 unsigned ArgIdx = 0;
4678 for (auto [Reg, Val] : RegsToPass) {
4679 if (ArgIdx++ >= NumSpecialInputs &&
4680 (IsChainCallConv || !Val->isDivergent()) && TRI->isSGPRPhysReg(Reg)) {
4681 // For chain calls, the inreg arguments are required to be
4682 // uniform. Speculatively Insert a readfirstlane in case we cannot prove
4683 // they are uniform.
4684 //
4685 // For other calls, if an inreg arguments is known to be uniform,
4686 // speculatively insert a readfirstlane in case it is in a VGPR.
4687 //
4688 // FIXME: We need to execute this in a waterfall loop if it is a divergent
4689 // value, so let that continue to produce invalid code.
4690
4691 SmallVector<SDValue, 3> ReadfirstlaneArgs({ReadFirstLaneID, Val});
4692 if (TokenGlue)
4693 ReadfirstlaneArgs.push_back(TokenGlue);
4695 ReadfirstlaneArgs);
4696 }
4697
4698 Chain = DAG.getCopyToReg(Chain, DL, Reg, Val, InGlue);
4699 InGlue = Chain.getValue(1);
4700 }
4701
4702 // We don't usually want to end the call-sequence here because we would tidy
4703 // the frame up *after* the call, however in the ABI-changing tail-call case
4704 // we've carefully laid out the parameters so that when sp is reset they'll be
4705 // in the correct location.
4706 if (IsTailCall && !IsSibCall) {
4707 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, DL);
4708 InGlue = Chain.getValue(1);
4709 }
4710
4711 std::vector<SDValue> Ops({Chain});
4712
4713 // Add a redundant copy of the callee global which will not be legalized, as
4714 // we need direct access to the callee later.
4716 const GlobalValue *GV = GSD->getGlobal();
4717 Ops.push_back(Callee);
4718 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
4719 } else {
4720 if (IsTailCall) {
4721 // isEligibleForTailCallOptimization considered whether the call target is
4722 // divergent, but we may still end up with a uniform value in a VGPR.
4723 // Insert a readfirstlane just in case.
4724 SDValue ReadFirstLaneID =
4725 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
4726
4727 SmallVector<SDValue, 3> ReadfirstlaneArgs({ReadFirstLaneID, Callee});
4728 if (TokenGlue)
4729 ReadfirstlaneArgs.push_back(TokenGlue); // Wire up convergence token.
4730 Callee = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Callee.getValueType(),
4731 ReadfirstlaneArgs);
4732 }
4733
4734 Ops.push_back(Callee);
4735 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
4736 }
4737
4738 if (IsTailCall) {
4739 // Each tail call may have to adjust the stack by a different amount, so
4740 // this information must travel along with the operation for eventual
4741 // consumption by emitEpilogue.
4742 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4743 }
4744
4745 if (IsChainCallConv)
4746 llvm::append_range(Ops, ChainCallSpecialArgs);
4747
4748 // Add argument registers to the end of the list so that they are known live
4749 // into the call.
4750 for (auto &[Reg, Val] : RegsToPass)
4751 Ops.push_back(DAG.getRegister(Reg, Val.getValueType()));
4752
4753 // Add a register mask operand representing the call-preserved registers.
4754 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
4755 assert(Mask && "Missing call preserved mask for calling convention");
4756 Ops.push_back(DAG.getRegisterMask(Mask));
4757
4758 if (SDValue Token = CLI.ConvergenceControlToken) {
4760 GlueOps.push_back(Token);
4761 if (InGlue)
4762 GlueOps.push_back(InGlue);
4763
4764 InGlue = SDValue(DAG.getMachineNode(TargetOpcode::CONVERGENCECTRL_GLUE, DL,
4765 MVT::Glue, GlueOps),
4766 0);
4767 }
4768
4769 if (InGlue)
4770 Ops.push_back(InGlue);
4771
4772 // If we're doing a tall call, use a TC_RETURN here rather than an
4773 // actual call instruction.
4774 if (IsTailCall) {
4775 MFI.setHasTailCall();
4776 unsigned OPC = AMDGPUISD::TC_RETURN;
4777 switch (CallConv) {
4779 OPC = AMDGPUISD::TC_RETURN_GFX;
4780 break;
4783 OPC = UsesDynamicVGPRs ? AMDGPUISD::TC_RETURN_CHAIN_DVGPR
4784 : AMDGPUISD::TC_RETURN_CHAIN;
4785 break;
4786 }
4787
4788 // If the caller is a whole wave function, we need to use a special opcode
4789 // so we can patch up EXEC.
4790 if (Info->isWholeWaveFunction())
4791 OPC = AMDGPUISD::TC_RETURN_GFX_WholeWave;
4792
4793 SDValue Ret = DAG.getNode(OPC, DL, MVT::Other, Ops);
4794 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
4795 return Ret;
4796 }
4797
4798 // Returns a chain and a flag for retval copy to use.
4799 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, {MVT::Other, MVT::Glue}, Ops);
4800 DAG.addNoMergeSiteInfo(Call.getNode(), CLI.NoMerge);
4801 Chain = Call.getValue(0);
4802 InGlue = Call.getValue(1);
4803
4804 uint64_t CalleePopBytes = NumBytes;
4805 Chain = DAG.getCALLSEQ_END(Chain, 0, CalleePopBytes, InGlue, DL);
4806 if (!Ins.empty())
4807 InGlue = Chain.getValue(1);
4808
4809 // Handle result values, copying them out of physregs into vregs that we
4810 // return.
4811 return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
4812 InVals, /*IsThisReturn=*/false, SDValue());
4813}
4814
4815// This is similar to the default implementation in ExpandDYNAMIC_STACKALLOC,
4816// except for:
4817// 1. Stack growth direction(default: downwards, AMDGPU: upwards), and
4818// 2. Scale size where, scale = wave-reduction(alloca-size) * wave-size
4820 SelectionDAG &DAG) const {
4821 const MachineFunction &MF = DAG.getMachineFunction();
4823
4824 SDLoc dl(Op);
4825 EVT VT = Op.getValueType();
4826 SDValue Chain = Op.getOperand(0);
4827 Register SPReg = Info->getStackPtrOffsetReg();
4828
4829 // Chain the dynamic stack allocation so that it doesn't modify the stack
4830 // pointer when other instructions are using the stack.
4831 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
4832
4833 SDValue Size = Op.getOperand(1);
4834 SDValue BaseAddr = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
4835 Align Alignment = cast<ConstantSDNode>(Op.getOperand(2))->getAlignValue();
4836
4837 const TargetFrameLowering *TFL = Subtarget->getFrameLowering();
4839 "Stack grows upwards for AMDGPU");
4840
4841 Chain = BaseAddr.getValue(1);
4842 // When using flat-scratch, the stack offset is unscaled.
4843 const bool HasFlatScratch = Subtarget->hasFlatScratchEnabled();
4844 const unsigned WavefrontSizeLog2 = Subtarget->getWavefrontSizeLog2();
4845
4846 Align StackAlign = TFL->getStackAlign();
4847 if (Alignment > StackAlign) {
4848 uint64_t ScaledAlignment = Alignment.value()
4849 << (HasFlatScratch ? 0 : WavefrontSizeLog2);
4850 uint64_t StackAlignMask = ScaledAlignment - 1;
4851 SDValue TmpAddr = DAG.getNode(ISD::ADD, dl, VT, BaseAddr,
4852 DAG.getConstant(StackAlignMask, dl, VT));
4853 BaseAddr = DAG.getNode(ISD::AND, dl, VT, TmpAddr,
4854 DAG.getSignedConstant(~StackAlignMask, dl, VT));
4855 }
4856
4857 assert(Size.getValueType() == MVT::i32 && "Size must be 32-bit");
4858 SDValue NewSP;
4860 // Increase the stack pointer by the size of the alloca.
4861 // If not using flat-scratch, we have to scale the size by the wave-size.
4862 SDValue ScaledSize =
4863 HasFlatScratch
4864 ? Size
4865 : DAG.getNode(ISD::SHL, dl, VT, Size,
4866 DAG.getConstant(WavefrontSizeLog2, dl, MVT::i32));
4867 NewSP = DAG.getNode(ISD::ADD, dl, VT, BaseAddr, ScaledSize); // Value
4868 } else {
4869 // For dynamic sized alloca, perform wave-wide reduction to get max of
4870 // alloca size(divergent), and then scale it (when not using flat-scratch)
4871 // by wave-size.
4872 SDValue WaveReduction =
4873 DAG.getTargetConstant(Intrinsic::amdgcn_wave_reduce_umax, dl, MVT::i32);
4874 Size = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, WaveReduction,
4875 Size, DAG.getTargetConstant(0, dl, MVT::i32));
4876 SDValue ScaledSize = Size;
4877 if (!HasFlatScratch) {
4878 ScaledSize =
4879 DAG.getNode(ISD::SHL, dl, VT, Size,
4880 DAG.getConstant(WavefrontSizeLog2, dl, MVT::i32));
4881 }
4882 NewSP =
4883 DAG.getNode(ISD::ADD, dl, VT, BaseAddr, ScaledSize); // Value in vgpr.
4884 SDValue ReadFirstLaneID =
4885 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, dl, MVT::i32);
4886 NewSP = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, ReadFirstLaneID,
4887 NewSP);
4888 }
4889
4890 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP); // Output chain
4891 SDValue CallSeqEnd = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
4892
4893 return DAG.getMergeValues({BaseAddr, CallSeqEnd}, dl);
4894}
4895
4897 if (Op.getValueType() != MVT::i32)
4898 return Op; // Defer to cannot select error.
4899
4901 SDLoc SL(Op);
4902
4903 SDValue CopyFromSP = DAG.getCopyFromReg(Op->getOperand(0), SL, SP, MVT::i32);
4904
4905 // Convert from wave uniform to swizzled vector address. This should protect
4906 // from any edge cases where the stacksave result isn't directly used with
4907 // stackrestore.
4908 SDValue VectorAddress =
4909 DAG.getNode(AMDGPUISD::WAVE_ADDRESS, SL, MVT::i32, CopyFromSP);
4910 return DAG.getMergeValues({VectorAddress, CopyFromSP.getValue(1)}, SL);
4911}
4912
4914 SelectionDAG &DAG) const {
4915 SDLoc SL(Op);
4916 assert(Op.getValueType() == MVT::i32);
4917
4918 uint32_t BothRoundHwReg =
4920 SDValue GetRoundBothImm = DAG.getTargetConstant(BothRoundHwReg, SL, MVT::i32);
4921
4922 SDValue IntrinID =
4923 DAG.getTargetConstant(Intrinsic::amdgcn_s_getreg, SL, MVT::i32);
4924 SDValue GetReg = DAG.getNode(ISD::INTRINSIC_W_CHAIN, SL, Op->getVTList(),
4925 Op.getOperand(0), IntrinID, GetRoundBothImm);
4926
4927 // There are two rounding modes, one for f32 and one for f64/f16. We only
4928 // report in the standard value range if both are the same.
4929 //
4930 // The raw values also differ from the expected FLT_ROUNDS values. Nearest
4931 // ties away from zero is not supported, and the other values are rotated by
4932 // 1.
4933 //
4934 // If the two rounding modes are not the same, report a target defined value.
4935
4936 // Mode register rounding mode fields:
4937 //
4938 // [1:0] Single-precision round mode.
4939 // [3:2] Double/Half-precision round mode.
4940 //
4941 // 0=nearest even; 1= +infinity; 2= -infinity, 3= toward zero.
4942 //
4943 // Hardware Spec
4944 // Toward-0 3 0
4945 // Nearest Even 0 1
4946 // +Inf 1 2
4947 // -Inf 2 3
4948 // NearestAway0 N/A 4
4949 //
4950 // We have to handle 16 permutations of a 4-bit value, so we create a 64-bit
4951 // table we can index by the raw hardware mode.
4952 //
4953 // (trunc (FltRoundConversionTable >> MODE.fp_round)) & 0xf
4954
4955 SDValue BitTable =
4957
4958 SDValue Two = DAG.getConstant(2, SL, MVT::i32);
4959 SDValue RoundModeTimesNumBits =
4960 DAG.getNode(ISD::SHL, SL, MVT::i32, GetReg, Two);
4961
4962 // TODO: We could possibly avoid a 64-bit shift and use a simpler table if we
4963 // knew only one mode was demanded.
4964 SDValue TableValue =
4965 DAG.getNode(ISD::SRL, SL, MVT::i64, BitTable, RoundModeTimesNumBits);
4966 SDValue TruncTable = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, TableValue);
4967
4968 SDValue EntryMask = DAG.getConstant(0xf, SL, MVT::i32);
4969 SDValue TableEntry =
4970 DAG.getNode(ISD::AND, SL, MVT::i32, TruncTable, EntryMask);
4971
4972 // There's a gap in the 4-bit encoded table and actual enum values, so offset
4973 // if it's an extended value.
4974 SDValue Four = DAG.getConstant(4, SL, MVT::i32);
4975 SDValue IsStandardValue =
4976 DAG.getSetCC(SL, MVT::i1, TableEntry, Four, ISD::SETULT);
4977 SDValue EnumOffset = DAG.getNode(ISD::ADD, SL, MVT::i32, TableEntry, Four);
4978 SDValue Result = DAG.getNode(ISD::SELECT, SL, MVT::i32, IsStandardValue,
4979 TableEntry, EnumOffset);
4980
4981 return DAG.getMergeValues({Result, GetReg.getValue(1)}, SL);
4982}
4983
4985 SelectionDAG &DAG) const {
4986 SDLoc SL(Op);
4987
4988 SDValue NewMode = Op.getOperand(1);
4989 assert(NewMode.getValueType() == MVT::i32);
4990
4991 // Index a table of 4-bit entries mapping from the C FLT_ROUNDS values to the
4992 // hardware MODE.fp_round values.
4993 if (auto *ConstMode = dyn_cast<ConstantSDNode>(NewMode)) {
4994 uint32_t ClampedVal = std::min(
4995 static_cast<uint32_t>(ConstMode->getZExtValue()),
4997 NewMode = DAG.getConstant(
4998 AMDGPU::decodeFltRoundToHWConversionTable(ClampedVal), SL, MVT::i32);
4999 } else {
5000 // If we know the input can only be one of the supported standard modes in
5001 // the range 0-3, we can use a simplified mapping to hardware values.
5002 KnownBits KB = DAG.computeKnownBits(NewMode);
5003 const bool UseReducedTable = KB.countMinLeadingZeros() >= 30;
5004 // The supported standard values are 0-3. The extended values start at 8. We
5005 // need to offset by 4 if the value is in the extended range.
5006
5007 if (UseReducedTable) {
5008 // Truncate to the low 32-bits.
5009 SDValue BitTable = DAG.getConstant(
5010 AMDGPU::FltRoundToHWConversionTable & 0xffff, SL, MVT::i32);
5011
5012 SDValue Two = DAG.getConstant(2, SL, MVT::i32);
5013 SDValue RoundModeTimesNumBits =
5014 DAG.getNode(ISD::SHL, SL, MVT::i32, NewMode, Two);
5015
5016 NewMode =
5017 DAG.getNode(ISD::SRL, SL, MVT::i32, BitTable, RoundModeTimesNumBits);
5018
5019 // TODO: SimplifyDemandedBits on the setreg source here can likely reduce
5020 // the table extracted bits into inline immediates.
5021 } else {
5022 // table_index = umin(value, value - 4)
5023 // MODE.fp_round = (bit_table >> (table_index << 2)) & 0xf
5024 SDValue BitTable =
5026
5027 SDValue Four = DAG.getConstant(4, SL, MVT::i32);
5028 SDValue OffsetEnum = DAG.getNode(ISD::SUB, SL, MVT::i32, NewMode, Four);
5029 SDValue IndexVal =
5030 DAG.getNode(ISD::UMIN, SL, MVT::i32, NewMode, OffsetEnum);
5031
5032 SDValue Two = DAG.getConstant(2, SL, MVT::i32);
5033 SDValue RoundModeTimesNumBits =
5034 DAG.getNode(ISD::SHL, SL, MVT::i32, IndexVal, Two);
5035
5036 SDValue TableValue =
5037 DAG.getNode(ISD::SRL, SL, MVT::i64, BitTable, RoundModeTimesNumBits);
5038 SDValue TruncTable = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, TableValue);
5039
5040 // No need to mask out the high bits since the setreg will ignore them
5041 // anyway.
5042 NewMode = TruncTable;
5043 }
5044
5045 // Insert a readfirstlane in case the value is a VGPR. We could do this
5046 // earlier and keep more operations scalar, but that interferes with
5047 // combining the source.
5048 SDValue ReadFirstLaneID =
5049 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, SL, MVT::i32);
5050 NewMode = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
5051 ReadFirstLaneID, NewMode);
5052 }
5053
5054 // N.B. The setreg will be later folded into s_round_mode on supported
5055 // targets.
5056 SDValue IntrinID =
5057 DAG.getTargetConstant(Intrinsic::amdgcn_s_setreg, SL, MVT::i32);
5058 uint32_t BothRoundHwReg =
5060 SDValue RoundBothImm = DAG.getTargetConstant(BothRoundHwReg, SL, MVT::i32);
5061
5062 SDValue SetReg =
5063 DAG.getNode(ISD::INTRINSIC_VOID, SL, Op->getVTList(), Op.getOperand(0),
5064 IntrinID, RoundBothImm, NewMode);
5065
5066 return SetReg;
5067}
5068
5070 unsigned AS = cast<MemSDNode>(Op)->getAddressSpace();
5071 if (AS == AMDGPUAS::BUFFER_RESOURCE)
5072 return Op.getOperand(0);
5074 return SDValue();
5075
5076 // I$ prefetch
5077 if (!Subtarget->hasSafeSmemPrefetch() && !Op.getConstantOperandVal(4))
5078 return SDValue();
5079
5080 return Op;
5081}
5082
5083// Work around DAG legality rules only based on the result type.
5085 bool IsStrict = Op.getOpcode() == ISD::STRICT_FP_EXTEND;
5086 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
5087 EVT SrcVT = Src.getValueType();
5088
5089 if (SrcVT.getScalarType() != MVT::bf16)
5090 return Op;
5091
5092 SDLoc SL(Op);
5093 SDValue BitCast =
5094 DAG.getNode(ISD::BITCAST, SL, SrcVT.changeTypeToInteger(), Src);
5095
5096 EVT DstVT = Op.getValueType();
5097 if (IsStrict)
5098 llvm_unreachable("Need STRICT_BF16_TO_FP");
5099
5100 return DAG.getNode(ISD::BF16_TO_FP, SL, DstVT, BitCast);
5101}
5102
5104 SDLoc SL(Op);
5105 if (Op.getValueType() != MVT::i64)
5106 return Op;
5107
5108 uint32_t ModeHwReg =
5110 SDValue ModeHwRegImm = DAG.getTargetConstant(ModeHwReg, SL, MVT::i32);
5111 uint32_t TrapHwReg =
5113 SDValue TrapHwRegImm = DAG.getTargetConstant(TrapHwReg, SL, MVT::i32);
5114
5115 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::Other);
5116 SDValue IntrinID =
5117 DAG.getTargetConstant(Intrinsic::amdgcn_s_getreg, SL, MVT::i32);
5118 SDValue GetModeReg = DAG.getNode(ISD::INTRINSIC_W_CHAIN, SL, VTList,
5119 Op.getOperand(0), IntrinID, ModeHwRegImm);
5120 SDValue GetTrapReg = DAG.getNode(ISD::INTRINSIC_W_CHAIN, SL, VTList,
5121 Op.getOperand(0), IntrinID, TrapHwRegImm);
5122 SDValue TokenReg =
5123 DAG.getNode(ISD::TokenFactor, SL, MVT::Other, GetModeReg.getValue(1),
5124 GetTrapReg.getValue(1));
5125
5126 SDValue CvtPtr =
5127 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, GetModeReg, GetTrapReg);
5128 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5129
5130 return DAG.getMergeValues({Result, TokenReg}, SL);
5131}
5132
5134 SDLoc SL(Op);
5135 if (Op.getOperand(1).getValueType() != MVT::i64)
5136 return Op;
5137
5138 SDValue Input = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op.getOperand(1));
5139 SDValue NewModeReg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Input,
5140 DAG.getConstant(0, SL, MVT::i32));
5141 SDValue NewTrapReg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Input,
5142 DAG.getConstant(1, SL, MVT::i32));
5143
5144 SDValue ReadFirstLaneID =
5145 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, SL, MVT::i32);
5146 NewModeReg = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
5147 ReadFirstLaneID, NewModeReg);
5148 NewTrapReg = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
5149 ReadFirstLaneID, NewTrapReg);
5150
5151 unsigned ModeHwReg =
5153 SDValue ModeHwRegImm = DAG.getTargetConstant(ModeHwReg, SL, MVT::i32);
5154 unsigned TrapHwReg =
5156 SDValue TrapHwRegImm = DAG.getTargetConstant(TrapHwReg, SL, MVT::i32);
5157
5158 SDValue IntrinID =
5159 DAG.getTargetConstant(Intrinsic::amdgcn_s_setreg, SL, MVT::i32);
5160 SDValue SetModeReg =
5161 DAG.getNode(ISD::INTRINSIC_VOID, SL, MVT::Other, Op.getOperand(0),
5162 IntrinID, ModeHwRegImm, NewModeReg);
5163 SDValue SetTrapReg =
5164 DAG.getNode(ISD::INTRINSIC_VOID, SL, MVT::Other, Op.getOperand(0),
5165 IntrinID, TrapHwRegImm, NewTrapReg);
5166 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, SetTrapReg, SetModeReg);
5167}
5168
5170 const MachineFunction &MF) const {
5171 Register Reg =
5173 .Case("m0", AMDGPU::M0)
5174 .Case("exec", AMDGPU::EXEC)
5175 .Case("exec_lo", AMDGPU::EXEC_LO)
5176 .Case("exec_hi", AMDGPU::EXEC_HI)
5177 .Case("flat_scratch", AMDGPU::FLAT_SCR)
5178 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
5179 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
5180 .Case("src_flat_scratch_base", AMDGPU::SRC_FLAT_SCRATCH_BASE)
5181 .Case("src_flat_scratch_base_lo", AMDGPU::SRC_FLAT_SCRATCH_BASE_LO)
5182 .Case("src_flat_scratch_base_hi", AMDGPU::SRC_FLAT_SCRATCH_BASE_HI)
5183 .Default(Register());
5184 if (!Reg)
5185 return Reg;
5186
5187 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
5188 if (!Subtarget->hasFlatScrRegister() &&
5189 TRI->regsOverlap(Reg, AMDGPU::FLAT_SCR))
5190 return Register();
5191
5192 if (!Subtarget->hasGloballyAddressableScratch() &&
5193 TRI->regsOverlap(Reg, AMDGPU::SRC_FLAT_SCRATCH_BASE))
5194 return Register();
5195
5196 switch (Reg) {
5197 case AMDGPU::M0:
5198 case AMDGPU::EXEC_LO:
5199 case AMDGPU::EXEC_HI:
5200 case AMDGPU::FLAT_SCR_LO:
5201 case AMDGPU::FLAT_SCR_HI:
5202 case AMDGPU::SRC_FLAT_SCRATCH_BASE_LO:
5203 case AMDGPU::SRC_FLAT_SCRATCH_BASE_HI:
5204 if (VT.getSizeInBits() == 32)
5205 return Reg;
5206 break;
5207 case AMDGPU::EXEC:
5208 case AMDGPU::FLAT_SCR:
5209 case AMDGPU::SRC_FLAT_SCRATCH_BASE:
5210 if (VT.getSizeInBits() == 64)
5211 return Reg;
5212 break;
5213 default:
5214 llvm_unreachable("missing register type checking");
5215 }
5216
5218 Twine("invalid type for register \"" + StringRef(RegName) + "\"."));
5219}
5220
5221// If kill is not the last instruction, split the block so kill is always a
5222// proper terminator.
5225 MachineBasicBlock *BB) const {
5226 MachineBasicBlock *SplitBB = BB->splitAt(MI, /*UpdateLiveIns=*/true);
5228 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
5229 return SplitBB;
5230}
5231
5232// Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
5233// \p MI will be the only instruction in the loop body block. Otherwise, it will
5234// be the first instruction in the remainder block.
5235//
5236/// \returns { LoopBody, Remainder }
5237static std::pair<MachineBasicBlock *, MachineBasicBlock *>
5239 MachineFunction *MF = MBB.getParent();
5241
5242 // To insert the loop we need to split the block. Move everything after this
5243 // point to a new block, and insert a new empty block between the two.
5245 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
5247 ++MBBI;
5248
5249 MF->insert(MBBI, LoopBB);
5250 MF->insert(MBBI, RemainderBB);
5251
5252 LoopBB->addSuccessor(LoopBB);
5253 LoopBB->addSuccessor(RemainderBB);
5254
5255 // Move the rest of the block into a new block.
5256 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
5257
5258 if (InstInLoop) {
5259 auto Next = std::next(I);
5260
5261 // Move instruction to loop body.
5262 LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
5263
5264 // Move the rest of the block.
5265 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
5266 } else {
5267 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
5268 }
5269
5270 MBB.addSuccessor(LoopBB);
5271
5272 return std::pair(LoopBB, RemainderBB);
5273}
5274
5275/// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
5277 MachineBasicBlock *MBB = MI.getParent();
5279 auto I = MI.getIterator();
5280 auto E = std::next(I);
5281
5282 // clang-format off
5283 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
5284 .addImm(0);
5285 // clang-format on
5286
5287 MIBundleBuilder Bundler(*MBB, I, E);
5288 finalizeBundle(*MBB, Bundler.begin());
5289}
5290
5293 MachineBasicBlock *BB) const {
5294 const DebugLoc &DL = MI.getDebugLoc();
5295
5297
5299
5300 // Apparently kill flags are only valid if the def is in the same block?
5301 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
5302 Src->setIsKill(false);
5303
5304 auto [LoopBB, RemainderBB] = splitBlockForLoop(MI, *BB, true);
5305
5306 MachineBasicBlock::iterator I = LoopBB->end();
5307
5308 const unsigned EncodedReg = AMDGPU::Hwreg::HwregEncoding::encode(
5310
5311 // Clear TRAP_STS.MEM_VIOL
5312 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
5313 .addImm(0)
5314 .addImm(EncodedReg);
5315
5317
5318 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5319
5320 // Load and check TRAP_STS.MEM_VIOL
5321 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
5322 .addImm(EncodedReg);
5323
5324 // clang-format off
5325 // FIXME: Do we need to use an isel pseudo that may clobber scc?
5326 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
5327 .addReg(Reg)
5328 .addImm(0);
5329 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
5330 .addMBB(LoopBB);
5331 // clang-format on
5332
5333 return RemainderBB;
5334}
5335
5336// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
5337// wavefront. If the value is uniform and just happens to be in a VGPR, this
5338// will only do one iteration. In the worst case, this will loop 64 times.
5339//
5340// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
5343 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
5344 const DebugLoc &DL, const MachineOperand &Idx,
5345 unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
5346 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
5347 Register &SGPRIdxReg) {
5348
5349 MachineFunction *MF = OrigBB.getParent();
5350 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5351 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5354
5355 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
5356 Register PhiExec = MRI.createVirtualRegister(BoolRC);
5357 Register NewExec = MRI.createVirtualRegister(BoolRC);
5358 Register CurrentIdxReg =
5359 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5360 Register CondReg = MRI.createVirtualRegister(BoolRC);
5361
5362 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
5363 .addReg(InitReg)
5364 .addMBB(&OrigBB)
5365 .addReg(ResultReg)
5366 .addMBB(&LoopBB);
5367
5368 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
5369 .addReg(InitSaveExecReg)
5370 .addMBB(&OrigBB)
5371 .addReg(NewExec)
5372 .addMBB(&LoopBB);
5373
5374 // Read the next variant <- also loop target.
5375 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
5376 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
5377
5378 // Compare the just read M0 value to all possible Idx values.
5379 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
5380 .addReg(CurrentIdxReg)
5381 .addReg(Idx.getReg(), {}, Idx.getSubReg());
5382
5383 // Update EXEC, save the original EXEC value to VCC.
5384 BuildMI(LoopBB, I, DL, TII->get(LMC.AndSaveExecOpc), NewExec)
5385 .addReg(CondReg)
5386 .setOperandDead(3); // Dead scc
5387
5388 MRI.setSimpleHint(NewExec, CondReg);
5389
5390 if (UseGPRIdxMode) {
5391 if (Offset == 0) {
5392 SGPRIdxReg = CurrentIdxReg;
5393 } else {
5394 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5395 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
5396 .addReg(CurrentIdxReg)
5397 .addImm(Offset)
5398 .setOperandDead(3); // Dead scc
5399 }
5400 } else {
5401 // Move index from VCC into M0
5402 if (Offset == 0) {
5403 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::COPY), AMDGPU::M0)
5404 .addReg(CurrentIdxReg);
5405 } else {
5406 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
5407 .addReg(CurrentIdxReg)
5408 .addImm(Offset)
5409 .setOperandDead(3); // Dead scc
5410 }
5411 }
5412
5413 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
5415 BuildMI(LoopBB, I, DL, TII->get(LMC.XorTermOpc), LMC.ExecReg)
5416 .addReg(LMC.ExecReg)
5417 .addReg(NewExec)
5418 .setOperandDead(3); // Dead scc
5419
5420 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
5421 // s_cbranch_scc0?
5422
5423 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
5424 // clang-format off
5425 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
5426 .addMBB(&LoopBB);
5427 // clang-format on
5428
5429 return InsertPt->getIterator();
5430}
5431
5432// This has slightly sub-optimal regalloc when the source vector is killed by
5433// the read. The register allocator does not understand that the kill is
5434// per-workitem, so is kept alive for the whole loop so we end up not re-using a
5435// subregister from it, using 1 more VGPR than necessary. This was saved when
5436// this was expanded after register allocation.
5439 unsigned InitResultReg, unsigned PhiReg, int Offset,
5440 bool UseGPRIdxMode, Register &SGPRIdxReg) {
5441 MachineFunction *MF = MBB.getParent();
5442 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5443 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5445 const DebugLoc &DL = MI.getDebugLoc();
5447
5448 const auto *BoolXExecRC = TRI->getWaveMaskRegClass();
5449 Register DstReg = MI.getOperand(0).getReg();
5450 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5451 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
5453
5454 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
5455
5456 // Save the EXEC mask
5457 // clang-format off
5458 BuildMI(MBB, I, DL, TII->get(LMC.MovOpc), SaveExec)
5459 .addReg(LMC.ExecReg);
5460 // clang-format on
5461
5462 auto [LoopBB, RemainderBB] = splitBlockForLoop(MI, MBB, false);
5463
5464 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5465
5466 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
5467 InitResultReg, DstReg, PhiReg, TmpExec,
5468 Offset, UseGPRIdxMode, SGPRIdxReg);
5469
5470 MachineBasicBlock *LandingPad = MF->CreateMachineBasicBlock();
5472 ++MBBI;
5473 MF->insert(MBBI, LandingPad);
5474 LoopBB->removeSuccessor(RemainderBB);
5475 LandingPad->addSuccessor(RemainderBB);
5476 LoopBB->addSuccessor(LandingPad);
5477 MachineBasicBlock::iterator First = LandingPad->begin();
5478 // clang-format off
5479 BuildMI(*LandingPad, First, DL, TII->get(LMC.MovOpc), LMC.ExecReg)
5480 .addReg(SaveExec);
5481 // clang-format on
5482
5483 return InsPt;
5484}
5485
5486// Returns subreg index, offset
5487static std::pair<unsigned, int>
5489 const TargetRegisterClass *SuperRC, unsigned VecReg,
5490 int Offset) {
5491 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
5492
5493 // Skip out of bounds offsets, or else we would end up using an undefined
5494 // register.
5495 if (Offset >= NumElts || Offset < 0)
5496 return std::pair(AMDGPU::sub0, Offset);
5497
5498 return std::pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
5499}
5500
5503 int Offset) {
5504 MachineBasicBlock *MBB = MI.getParent();
5505 const DebugLoc &DL = MI.getDebugLoc();
5507
5508 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5509
5510 assert(Idx->getReg() != AMDGPU::NoRegister);
5511
5512 if (Offset == 0) {
5513 // clang-format off
5514 BuildMI(*MBB, I, DL, TII->get(AMDGPU::COPY), AMDGPU::M0)
5515 .add(*Idx);
5516 // clang-format on
5517 } else {
5518 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
5519 .add(*Idx)
5520 .addImm(Offset)
5521 .setOperandDead(3); // Dead scc
5522 }
5523}
5524
5527 int Offset) {
5528 MachineBasicBlock *MBB = MI.getParent();
5529 const DebugLoc &DL = MI.getDebugLoc();
5531
5532 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5533
5534 if (Offset == 0)
5535 return Idx->getReg();
5536
5537 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5538 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
5539 .add(*Idx)
5540 .addImm(Offset)
5541 .setOperandDead(3); // Dead scc
5542 return Tmp;
5543}
5544
5547 const GCNSubtarget &ST) {
5548 const SIInstrInfo *TII = ST.getInstrInfo();
5549 const SIRegisterInfo &TRI = TII->getRegisterInfo();
5550 MachineFunction *MF = MBB.getParent();
5552
5553 Register Dst = MI.getOperand(0).getReg();
5554 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5555 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
5556 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
5557
5558 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
5559 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
5560
5561 unsigned SubReg;
5562 std::tie(SubReg, Offset) =
5563 computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
5564
5565 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
5566
5567 // Check for a SGPR index.
5568 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
5570 const DebugLoc &DL = MI.getDebugLoc();
5571
5572 if (UseGPRIdxMode) {
5573 // TODO: Look at the uses to avoid the copy. This may require rescheduling
5574 // to avoid interfering with other uses, so probably requires a new
5575 // optimization pass.
5577
5578 const MCInstrDesc &GPRIDXDesc =
5579 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
5580 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
5581 .addReg(SrcReg)
5582 .addReg(Idx)
5583 .addImm(SubReg);
5584 } else {
5586
5587 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
5588 .addReg(SrcReg, {}, SubReg)
5589 .addReg(SrcReg, RegState::Implicit);
5590 }
5591
5592 MI.eraseFromParent();
5593
5594 return &MBB;
5595 }
5596
5597 // Control flow needs to be inserted if indexing with a VGPR.
5598 const DebugLoc &DL = MI.getDebugLoc();
5600
5601 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5602 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5603
5604 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
5605
5606 Register SGPRIdxReg;
5607 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
5608 UseGPRIdxMode, SGPRIdxReg);
5609
5610 MachineBasicBlock *LoopBB = InsPt->getParent();
5611
5612 if (UseGPRIdxMode) {
5613 const MCInstrDesc &GPRIDXDesc =
5614 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
5615
5616 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
5617 .addReg(SrcReg)
5618 .addReg(SGPRIdxReg)
5619 .addImm(SubReg);
5620 } else {
5621 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
5622 .addReg(SrcReg, {}, SubReg)
5623 .addReg(SrcReg, RegState::Implicit);
5624 }
5625
5626 MI.eraseFromParent();
5627
5628 return LoopBB;
5629}
5630
5633 const GCNSubtarget &ST) {
5634 const SIInstrInfo *TII = ST.getInstrInfo();
5635 const SIRegisterInfo &TRI = TII->getRegisterInfo();
5636 MachineFunction *MF = MBB.getParent();
5638
5639 Register Dst = MI.getOperand(0).getReg();
5640 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
5641 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5642 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
5643 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
5644 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
5645 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
5646
5647 // This can be an immediate, but will be folded later.
5648 assert(Val->getReg());
5649
5650 unsigned SubReg;
5651 std::tie(SubReg, Offset) =
5652 computeIndirectRegAndOffset(TRI, VecRC, SrcVec->getReg(), Offset);
5653 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
5654
5655 if (Idx->getReg() == AMDGPU::NoRegister) {
5657 const DebugLoc &DL = MI.getDebugLoc();
5658
5659 assert(Offset == 0);
5660
5661 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
5662 .add(*SrcVec)
5663 .add(*Val)
5664 .addImm(SubReg);
5665
5666 MI.eraseFromParent();
5667 return &MBB;
5668 }
5669
5670 // Check for a SGPR index.
5671 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
5673 const DebugLoc &DL = MI.getDebugLoc();
5674
5675 if (UseGPRIdxMode) {
5677
5678 const MCInstrDesc &GPRIDXDesc =
5679 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
5680 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
5681 .addReg(SrcVec->getReg())
5682 .add(*Val)
5683 .addReg(Idx)
5684 .addImm(SubReg);
5685 } else {
5687
5688 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
5689 TRI.getRegSizeInBits(*VecRC), 32, false);
5690 BuildMI(MBB, I, DL, MovRelDesc, Dst)
5691 .addReg(SrcVec->getReg())
5692 .add(*Val)
5693 .addImm(SubReg);
5694 }
5695 MI.eraseFromParent();
5696 return &MBB;
5697 }
5698
5699 // Control flow needs to be inserted if indexing with a VGPR.
5700 const DebugLoc &DL = MI.getDebugLoc();
5701
5702 Register PhiReg = MRI.createVirtualRegister(VecRC);
5703
5704 Register SGPRIdxReg;
5705 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
5706 UseGPRIdxMode, SGPRIdxReg);
5707 MachineBasicBlock *LoopBB = InsPt->getParent();
5708
5709 if (UseGPRIdxMode) {
5710 const MCInstrDesc &GPRIDXDesc =
5711 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
5712
5713 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
5714 .addReg(PhiReg)
5715 .add(*Val)
5716 .addReg(SGPRIdxReg)
5717 .addImm(SubReg);
5718 } else {
5719 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
5720 TRI.getRegSizeInBits(*VecRC), 32, false);
5721 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
5722 .addReg(PhiReg)
5723 .add(*Val)
5724 .addImm(SubReg);
5725 }
5726
5727 MI.eraseFromParent();
5728 return LoopBB;
5729}
5730
5732 MachineBasicBlock *BB) {
5733 // For targets older than GFX12, we emit a sequence of 32-bit operations.
5734 // For GFX12, we emit s_add_u64 and s_sub_u64.
5735 MachineFunction *MF = BB->getParent();
5736 const SIInstrInfo *TII = MF->getSubtarget<GCNSubtarget>().getInstrInfo();
5737 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5739 const DebugLoc &DL = MI.getDebugLoc();
5740 MachineOperand &Dest = MI.getOperand(0);
5741 MachineOperand &Src0 = MI.getOperand(1);
5742 MachineOperand &Src1 = MI.getOperand(2);
5743 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
5744 if (ST.hasScalarAddSub64()) {
5745 // FIXME: If scc is used, this deletes the def
5746 unsigned Opc = IsAdd ? AMDGPU::S_ADD_U64 : AMDGPU::S_SUB_U64;
5747 // clang-format off
5748 BuildMI(*BB, MI, DL, TII->get(Opc), Dest.getReg())
5749 .add(Src0)
5750 .add(Src1);
5751 // clang-format on
5752 } else {
5753 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5754 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
5755
5756 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
5757 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
5758
5759 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
5760 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
5761 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
5762 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
5763
5764 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
5765 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
5766 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
5767 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
5768
5769 const MachineOperand &ImpDefSCC = MI.getOperand(3);
5770 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
5771
5772 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
5773 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
5774 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
5775 auto Hi = BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
5776 .add(Src0Sub1)
5777 .add(Src1Sub1);
5778 if (ImpDefSCC.isDead())
5779 Hi.setOperandDead(3);
5780 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
5781 .addReg(DestSub0)
5782 .addImm(AMDGPU::sub0)
5783 .addReg(DestSub1)
5784 .addImm(AMDGPU::sub1);
5785 }
5786 MI.eraseFromParent();
5787 return BB;
5788}
5789
5791 MachineFunction *MF = BB->getParent();
5792 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5793 const SIInstrInfo *TII = ST.getInstrInfo();
5794 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5796 const DebugLoc &DL = MI.getDebugLoc();
5797 Register Dst = MI.getOperand(0).getReg();
5798 const MachineOperand &Src0 = MI.getOperand(1);
5799 const MachineOperand &Src1 = MI.getOperand(2);
5800 Register SrcCond = MI.getOperand(3).getReg();
5801
5802 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5803 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5804 const TargetRegisterClass *CondRC = TRI->getWaveMaskRegClass();
5805 Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
5806
5807 int Src0Idx =
5808 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
5809 int Src1Idx =
5810 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src1);
5811 const TargetRegisterClass *Src0RC =
5812 TRI->getAllocatableClass(TII->getRegClass(MI.getDesc(), Src0Idx));
5813 const TargetRegisterClass *Src1RC =
5814 TRI->getAllocatableClass(TII->getRegClass(MI.getDesc(), Src1Idx));
5815
5816 const TargetRegisterClass *Src0SubRC =
5817 TRI->getSubRegisterClass(Src0RC, AMDGPU::sub0);
5818 const TargetRegisterClass *Src1SubRC =
5819 TRI->getSubRegisterClass(Src1RC, AMDGPU::sub1);
5820
5821 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
5822 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
5823 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
5824 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
5825
5826 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
5827 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
5828 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
5829 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
5830
5831 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy).addReg(SrcCond);
5832 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
5833 .addImm(0)
5834 .add(Src0Sub0)
5835 .addImm(0)
5836 .add(Src1Sub0)
5837 .addReg(SrcCondCopy);
5838
5839 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
5840 .addImm(0)
5841 .add(Src0Sub1)
5842 .addImm(0)
5843 .add(Src1Sub1)
5844 .addReg(SrcCondCopy);
5845
5846 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
5847 .addReg(DstLo)
5848 .addImm(AMDGPU::sub0)
5849 .addReg(DstHi)
5850 .addImm(AMDGPU::sub1);
5851 MI.eraseFromParent();
5852}
5853
5855 switch (Opc) {
5856 case AMDGPU::S_MIN_U32:
5857 return std::numeric_limits<uint32_t>::max();
5858 case AMDGPU::S_MIN_I32:
5859 return std::numeric_limits<int32_t>::max();
5860 case AMDGPU::S_MAX_U32:
5861 return std::numeric_limits<uint32_t>::min();
5862 case AMDGPU::S_MAX_I32:
5863 return std::numeric_limits<int32_t>::min();
5864 case AMDGPU::V_ADD_F32_e64: // -0.0
5865 return 0x80000000;
5866 case AMDGPU::V_SUB_F32_e64: // +0.0
5867 return 0x0;
5868 case AMDGPU::S_ADD_I32:
5869 case AMDGPU::S_SUB_I32:
5870 case AMDGPU::S_OR_B32:
5871 case AMDGPU::S_XOR_B32:
5872 return std::numeric_limits<uint32_t>::min();
5873 case AMDGPU::S_AND_B32:
5874 return std::numeric_limits<uint32_t>::max();
5875 case AMDGPU::V_MIN_F32_e64:
5876 case AMDGPU::V_MAX_F32_e64:
5877 return 0x7fc00000; // qNAN
5878 case AMDGPU::V_CMP_LT_U64_e64: // umin.u64
5879 return std::numeric_limits<uint64_t>::max();
5880 case AMDGPU::V_CMP_LT_I64_e64: // min.i64
5881 return std::numeric_limits<int64_t>::max();
5882 case AMDGPU::V_CMP_GT_U64_e64: // umax.u64
5883 return std::numeric_limits<uint64_t>::min();
5884 case AMDGPU::V_CMP_GT_I64_e64: // max.i64
5885 return std::numeric_limits<int64_t>::min();
5886 case AMDGPU::V_MIN_F64_e64:
5887 case AMDGPU::V_MAX_F64_e64:
5888 case AMDGPU::V_MIN_NUM_F64_e64:
5889 case AMDGPU::V_MAX_NUM_F64_e64:
5890 return 0x7FF8000000000000; // qNAN
5891 case AMDGPU::S_ADD_U64_PSEUDO:
5892 case AMDGPU::S_SUB_U64_PSEUDO:
5893 case AMDGPU::S_OR_B64:
5894 case AMDGPU::S_XOR_B64:
5895 return std::numeric_limits<uint64_t>::min();
5896 case AMDGPU::S_AND_B64:
5897 return std::numeric_limits<uint64_t>::max();
5898 case AMDGPU::V_ADD_F64_e64:
5899 case AMDGPU::V_ADD_F64_pseudo_e64:
5900 return 0x8000000000000000; // -0.0
5901 default:
5902 llvm_unreachable("Unexpected opcode in getIdentityValueForWaveReduction");
5903 }
5904}
5905
5906static bool is32bitWaveReduceOperation(unsigned Opc) {
5907 return Opc == AMDGPU::S_MIN_U32 || Opc == AMDGPU::S_MIN_I32 ||
5908 Opc == AMDGPU::S_MAX_U32 || Opc == AMDGPU::S_MAX_I32 ||
5909 Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32 ||
5910 Opc == AMDGPU::S_AND_B32 || Opc == AMDGPU::S_OR_B32 ||
5911 Opc == AMDGPU::S_XOR_B32 || Opc == AMDGPU::V_MIN_F32_e64 ||
5912 Opc == AMDGPU::V_MAX_F32_e64 || Opc == AMDGPU::V_ADD_F32_e64 ||
5913 Opc == AMDGPU::V_SUB_F32_e64;
5914}
5915
5917 return Opc == AMDGPU::V_MIN_F32_e64 || Opc == AMDGPU::V_MAX_F32_e64 ||
5918 Opc == AMDGPU::V_ADD_F32_e64 || Opc == AMDGPU::V_SUB_F32_e64 ||
5919 Opc == AMDGPU::V_MIN_F64_e64 || Opc == AMDGPU::V_MAX_F64_e64 ||
5920 Opc == AMDGPU::V_MIN_NUM_F64_e64 || Opc == AMDGPU::V_MAX_NUM_F64_e64 ||
5921 Opc == AMDGPU::V_ADD_F64_e64 || Opc == AMDGPU::V_ADD_F64_pseudo_e64;
5922}
5923
5924static std::tuple<unsigned, unsigned>
5926 unsigned DPPOpc;
5927 switch (Opc) {
5928 case AMDGPU::S_MIN_U32:
5929 DPPOpc = AMDGPU::V_MIN_U32_dpp;
5930 break;
5931 case AMDGPU::S_MIN_I32:
5932 DPPOpc = AMDGPU::V_MIN_I32_dpp;
5933 break;
5934 case AMDGPU::S_MAX_U32:
5935 DPPOpc = AMDGPU::V_MAX_U32_dpp;
5936 break;
5937 case AMDGPU::S_MAX_I32:
5938 DPPOpc = AMDGPU::V_MAX_I32_dpp;
5939 break;
5940 case AMDGPU::S_ADD_I32:
5941 case AMDGPU::S_SUB_I32:
5942 DPPOpc = ST.hasAddNoCarryInsts() ? AMDGPU::V_ADD_U32_dpp
5943 : AMDGPU::V_ADD_CO_U32_dpp;
5944 break;
5945 case AMDGPU::S_AND_B32:
5946 DPPOpc = AMDGPU::V_AND_B32_dpp;
5947 break;
5948 case AMDGPU::S_OR_B32:
5949 DPPOpc = AMDGPU::V_OR_B32_dpp;
5950 break;
5951 case AMDGPU::S_XOR_B32:
5952 DPPOpc = AMDGPU::V_XOR_B32_dpp;
5953 break;
5954 case AMDGPU::V_ADD_F32_e64:
5955 case AMDGPU::V_SUB_F32_e64:
5956 DPPOpc = AMDGPU::V_ADD_F32_dpp;
5957 break;
5958 case AMDGPU::V_MIN_F32_e64:
5959 DPPOpc = AMDGPU::V_MIN_F32_dpp;
5960 break;
5961 case AMDGPU::V_MAX_F32_e64:
5962 DPPOpc = AMDGPU::V_MAX_F32_dpp;
5963 break;
5964 case AMDGPU::V_CMP_LT_U64_e64: // umin.u64
5965 case AMDGPU::V_CMP_LT_I64_e64: // min.i64
5966 case AMDGPU::V_CMP_GT_U64_e64: // umax.u64
5967 case AMDGPU::V_CMP_GT_I64_e64: // max.i64
5968 case AMDGPU::S_ADD_U64_PSEUDO:
5969 case AMDGPU::S_SUB_U64_PSEUDO:
5970 case AMDGPU::S_AND_B64:
5971 case AMDGPU::S_OR_B64:
5972 case AMDGPU::S_XOR_B64:
5973 case AMDGPU::V_MIN_NUM_F64_e64:
5974 case AMDGPU::V_MIN_F64_e64:
5975 case AMDGPU::V_MAX_NUM_F64_e64:
5976 case AMDGPU::V_MAX_F64_e64:
5977 case AMDGPU::V_ADD_F64_pseudo_e64:
5978 case AMDGPU::V_ADD_F64_e64:
5979 DPPOpc = AMDGPU::V_MOV_B64_DPP_PSEUDO;
5980 break;
5981 default:
5982 llvm_unreachable("unhandled lane op");
5983 }
5984 unsigned ClampOpc = Opc;
5985 if (Opc == AMDGPU::V_SUB_F32_e64)
5986 ClampOpc = AMDGPU::V_ADD_F32_e64;
5987 if (!ST.getInstrInfo()->isVALU(Opc, /*AllowLDSDMA=*/false)) {
5988 if (Opc == AMDGPU::S_SUB_I32)
5989 ClampOpc = AMDGPU::S_ADD_I32;
5990 if (Opc == AMDGPU::S_ADD_U64_PSEUDO || Opc == AMDGPU::S_SUB_U64_PSEUDO)
5991 ClampOpc = AMDGPU::V_ADD_CO_U32_e64;
5992 else if (Opc == AMDGPU::S_AND_B64)
5993 ClampOpc = AMDGPU::V_AND_B32_e64;
5994 else if (Opc == AMDGPU::S_OR_B64)
5995 ClampOpc = AMDGPU::V_OR_B32_e64;
5996 else if (Opc == AMDGPU::S_XOR_B64)
5997 ClampOpc = AMDGPU::V_XOR_B32_e64;
5998 else
5999 ClampOpc = ST.getInstrInfo()->getVALUOp(ClampOpc);
6000 }
6001 return {DPPOpc, ClampOpc};
6002}
6003
6004static std::pair<Register, Register>
6006 const TargetRegisterClass *SrcRC, const GCNSubtarget &ST,
6008 const SIRegisterInfo *TRI = ST.getRegisterInfo();
6009 const SIInstrInfo *TII = ST.getInstrInfo();
6010 const TargetRegisterClass *SrcSubRC =
6011 TRI->getSubRegisterClass(SrcRC, AMDGPU::sub0);
6012 Register Op1L =
6013 TII->buildExtractSubReg(MI, MRI, Op, SrcRC, AMDGPU::sub0, SrcSubRC);
6014 Register Op1H =
6015 TII->buildExtractSubReg(MI, MRI, Op, SrcRC, AMDGPU::sub1, SrcSubRC);
6016 return {Op1L, Op1H};
6017}
6018
6021 const GCNSubtarget &ST,
6022 unsigned Opc) {
6024 const SIRegisterInfo *TRI = ST.getRegisterInfo();
6025 const DebugLoc &DL = MI.getDebugLoc();
6026 const SIInstrInfo *TII = ST.getInstrInfo();
6027
6028 // Reduction operations depend on whether the input operand is SGPR or VGPR.
6029 Register SrcReg = MI.getOperand(1).getReg();
6030 bool isSGPR = TRI->isSGPRClass(MRI.getRegClass(SrcReg));
6031 Register DstReg = MI.getOperand(0).getReg();
6032 unsigned Stratergy = static_cast<unsigned>(MI.getOperand(2).getImm());
6033 enum WAVE_REDUCE_STRATEGY : unsigned { DEFAULT = 0, ITERATIVE = 1, DPP = 2 };
6034 MachineBasicBlock *RetBB = nullptr;
6035 unsigned MIOpc = MI.getOpcode();
6036 auto BuildRegSequence = [&](MachineBasicBlock &BB,
6038 Register Src0, Register Src1) {
6039 auto RegSequence =
6040 BuildMI(BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dst)
6041 .addReg(Src0)
6042 .addImm(AMDGPU::sub0)
6043 .addReg(Src1)
6044 .addImm(AMDGPU::sub1);
6045 return RegSequence;
6046 };
6047 if (isSGPR) {
6048 switch (Opc) {
6049 case AMDGPU::S_MIN_U32:
6050 case AMDGPU::S_MIN_I32:
6051 case AMDGPU::V_MIN_F32_e64:
6052 case AMDGPU::S_MAX_U32:
6053 case AMDGPU::S_MAX_I32:
6054 case AMDGPU::V_MAX_F32_e64:
6055 case AMDGPU::S_AND_B32:
6056 case AMDGPU::S_OR_B32: {
6057 // Idempotent operations.
6058 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstReg).addReg(SrcReg);
6059 RetBB = &BB;
6060 break;
6061 }
6062 case AMDGPU::V_CMP_LT_U64_e64: // umin
6063 case AMDGPU::V_CMP_LT_I64_e64: // min
6064 case AMDGPU::V_CMP_GT_U64_e64: // umax
6065 case AMDGPU::V_CMP_GT_I64_e64: // max
6066 case AMDGPU::V_MIN_F64_e64:
6067 case AMDGPU::V_MIN_NUM_F64_e64:
6068 case AMDGPU::V_MAX_F64_e64:
6069 case AMDGPU::V_MAX_NUM_F64_e64:
6070 case AMDGPU::S_AND_B64:
6071 case AMDGPU::S_OR_B64: {
6072 // Idempotent operations.
6073 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B64), DstReg).addReg(SrcReg);
6074 RetBB = &BB;
6075 break;
6076 }
6077 case AMDGPU::S_XOR_B32:
6078 case AMDGPU::S_XOR_B64:
6079 case AMDGPU::S_ADD_I32:
6080 case AMDGPU::S_ADD_U64_PSEUDO:
6081 case AMDGPU::V_ADD_F32_e64:
6082 case AMDGPU::V_ADD_F64_e64:
6083 case AMDGPU::V_ADD_F64_pseudo_e64:
6084 case AMDGPU::S_SUB_I32:
6085 case AMDGPU::S_SUB_U64_PSEUDO:
6086 case AMDGPU::V_SUB_F32_e64: {
6087 const TargetRegisterClass *WaveMaskRegClass = TRI->getWaveMaskRegClass();
6088 const TargetRegisterClass *DstRegClass = MRI.getRegClass(DstReg);
6089 Register ExecMask = MRI.createVirtualRegister(WaveMaskRegClass);
6090 Register NumActiveLanes =
6091 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6092
6093 bool IsWave32 = ST.isWave32();
6094 unsigned MovOpc = IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
6095 MCRegister ExecReg = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
6096 unsigned BitCountOpc =
6097 IsWave32 ? AMDGPU::S_BCNT1_I32_B32 : AMDGPU::S_BCNT1_I32_B64;
6098
6099 BuildMI(BB, MI, DL, TII->get(MovOpc), ExecMask).addReg(ExecReg);
6100
6101 auto NewAccumulator =
6102 BuildMI(BB, MI, DL, TII->get(BitCountOpc), NumActiveLanes)
6103 .addReg(ExecMask)
6104 .setOperandDead(2); // Dead scc
6105
6106 switch (Opc) {
6107 case AMDGPU::S_XOR_B32:
6108 case AMDGPU::S_XOR_B64: {
6109 // Performing an XOR operation on a uniform value
6110 // depends on the parity of the number of active lanes.
6111 // For even parity, the result will be 0, for odd
6112 // parity the result will be the same as the input value.
6113 Register ParityRegister =
6114 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6115 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_AND_B32), ParityRegister)
6116 .addReg(NewAccumulator->getOperand(0).getReg())
6117 .addImm(1)
6118 .setOperandDead(3); // Dead scc
6119 // Check if Src is a known identity constant.
6120 if (TII->getImmOrMaterializedImm(MRI, SrcReg) == 1) {
6121 // 1 * parity(exec) = parity(exec)
6122 if (Opc == AMDGPU::S_XOR_B32) {
6123 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstReg)
6124 .addReg(ParityRegister);
6125 } else {
6126 Register DstHi =
6127 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6128 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstHi).addImm(0);
6129 BuildRegSequence(BB, MI, DstReg, ParityRegister, DstHi);
6130 }
6131 break;
6132 }
6133 if (Opc == AMDGPU::S_XOR_B32) {
6134 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DstReg)
6135 .addReg(SrcReg)
6136 .addReg(ParityRegister);
6137 } else {
6138 Register DestSub0 =
6139 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6140 Register DestSub1 =
6141 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6142 auto [Op1L, Op1H] = ExtractSubRegs(MI, MI.getOperand(1),
6143 MRI.getRegClass(SrcReg), ST, MRI);
6144 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DestSub0)
6145 .addReg(Op1L)
6146 .addReg(ParityRegister);
6147 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DestSub1)
6148 .addReg(Op1H)
6149 .addReg(ParityRegister);
6150 BuildRegSequence(BB, MI, DstReg, DestSub0, DestSub1);
6151 }
6152 break;
6153 }
6154 case AMDGPU::S_SUB_I32: {
6155 Register NegatedVal = MRI.createVirtualRegister(DstRegClass);
6156 // Take the negation of the source operand.
6157 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_SUB_I32), NegatedVal)
6158 .addImm(0)
6159 .addReg(SrcReg)
6160 .setOperandDead(3); // Dead scc
6161 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DstReg)
6162 .addReg(NegatedVal)
6163 .addReg(NewAccumulator->getOperand(0).getReg());
6164 break;
6165 }
6166 case AMDGPU::S_ADD_I32: {
6167 // Check if Src is a known identity constant.
6168 if (TII->getImmOrMaterializedImm(MRI, SrcReg) == 1) {
6169 // 1 * bitcount(exec) = bitcount(exec)
6170 BuildMI(BB, MI, DL, TII->get(AMDGPU::COPY), DstReg)
6171 .addReg(NewAccumulator->getOperand(0).getReg());
6172 break;
6173 }
6174 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DstReg)
6175 .addReg(SrcReg)
6176 .addReg(NewAccumulator->getOperand(0).getReg());
6177 break;
6178 }
6179 case AMDGPU::S_ADD_U64_PSEUDO:
6180 case AMDGPU::S_SUB_U64_PSEUDO: {
6181 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6182 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6183 Register Op1H_Op0L_Reg =
6184 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6185 Register Op1L_Op0H_Reg =
6186 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6187 Register CarryReg =
6188 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6189 Register AddReg = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6190 Register NegatedValLo =
6191 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6192 Register NegatedValHi =
6193 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6194 auto [Op1L, Op1H] = ExtractSubRegs(MI, MI.getOperand(1),
6195 MRI.getRegClass(SrcReg), ST, MRI);
6196 // Check if Src is a known identity constant.
6197 if (Opc == AMDGPU::S_ADD_U64_PSEUDO &&
6198 TII->getImmOrMaterializedImm(MRI, SrcReg) == 1) {
6199 // 1 * bitcount(exec) = bitcount(exec)
6200 Register DstHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6201 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstHi).addImm(0);
6202 BuildRegSequence(BB, MI, DstReg,
6203 NewAccumulator->getOperand(0).getReg(), DstHi);
6204 break;
6205 }
6206 if (Opc == AMDGPU::S_SUB_U64_PSEUDO) {
6207 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_SUB_I32), NegatedValLo)
6208 .addImm(0)
6209 .addReg(NewAccumulator->getOperand(0).getReg())
6210 .setOperandDead(3); // Dead scc
6211 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_ASHR_I32), NegatedValHi)
6212 .addReg(NegatedValLo)
6213 .addImm(31)
6214 .setOperandDead(3); // Dead scc
6215 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), Op1L_Op0H_Reg)
6216 .addReg(Op1L)
6217 .addReg(NegatedValHi);
6218 }
6219 Register LowOpcode = Opc == AMDGPU::S_SUB_U64_PSEUDO
6220 ? NegatedValLo
6221 : NewAccumulator->getOperand(0).getReg();
6222 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DestSub0)
6223 .addReg(Op1L)
6224 .addReg(LowOpcode);
6225 if (ST.hasScalarMulHiInsts()) {
6226 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_HI_U32), CarryReg)
6227 .addReg(Op1L)
6228 .addReg(LowOpcode);
6229 } else {
6230 Register VCarryReg =
6231 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6232 Register LowOpVGPR =
6233 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6234 BuildMI(BB, MI, DL, TII->get(AMDGPU::COPY), LowOpVGPR)
6235 .addReg(LowOpcode);
6236 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_MUL_HI_U32_e64), VCarryReg)
6237 .addReg(Op1L)
6238 .addReg(LowOpVGPR);
6239 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CarryReg)
6240 .addReg(VCarryReg);
6241 }
6242 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), Op1H_Op0L_Reg)
6243 .addReg(Op1H)
6244 .addReg(LowOpcode);
6245
6246 Register HiVal = Opc == AMDGPU::S_SUB_U64_PSEUDO ? AddReg : DestSub1;
6247 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_ADD_U32), HiVal)
6248 .addReg(CarryReg)
6249 .addReg(Op1H_Op0L_Reg)
6250 .setOperandDead(3); // Dead scc
6251
6252 if (Opc == AMDGPU::S_SUB_U64_PSEUDO) {
6253 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_ADD_U32), DestSub1)
6254 .addReg(HiVal)
6255 .addReg(Op1L_Op0H_Reg)
6256 .setOperandDead(3); // Dead scc
6257 }
6258 BuildRegSequence(BB, MI, DstReg, DestSub0, DestSub1);
6259 break;
6260 }
6261 case AMDGPU::V_ADD_F32_e64:
6262 case AMDGPU::V_ADD_F64_e64:
6263 case AMDGPU::V_ADD_F64_pseudo_e64:
6264 case AMDGPU::V_SUB_F32_e64: {
6265 bool is32BitOpc = is32bitWaveReduceOperation(Opc);
6266 const TargetRegisterClass *VregRC = TII->getRegClass(TII->get(Opc), 0);
6267 Register ActiveLanesVreg = MRI.createVirtualRegister(VregRC);
6268 Register DstVreg = MRI.createVirtualRegister(VregRC);
6269 // Get number of active lanes as a float val.
6270 BuildMI(BB, MI, DL,
6271 TII->get(is32BitOpc ? AMDGPU::V_CVT_F32_I32_e64
6272 : AMDGPU::V_CVT_F64_I32_e64),
6273 ActiveLanesVreg)
6274 .addReg(NewAccumulator->getOperand(0).getReg())
6275 .addImm(0) // clamp
6276 .addImm(0); // output-modifier
6277
6278 // Take negation of input for SUB reduction
6279 unsigned srcMod = (MIOpc == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F32 ||
6280 MIOpc == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64)
6283 unsigned MulOpc = is32BitOpc ? AMDGPU::V_MUL_F32_e64
6284 : ST.getGeneration() >= AMDGPUSubtarget::GFX12
6285 ? AMDGPU::V_MUL_F64_pseudo_e64
6286 : AMDGPU::V_MUL_F64_e64;
6287 auto DestVregInst = BuildMI(BB, MI, DL, TII->get(MulOpc),
6288 DstVreg)
6289 .addImm(srcMod) // src0 modifier
6290 .addReg(SrcReg)
6291 .addImm(SISrcMods::NONE) // src1 modifier
6292 .addReg(ActiveLanesVreg)
6293 .addImm(SISrcMods::NONE) // clamp
6294 .addImm(SISrcMods::NONE); // output-mod
6295 if (is32BitOpc) {
6296 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
6297 .addReg(DstVreg);
6298 } else {
6299 Register LaneValueLoReg =
6300 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6301 Register LaneValueHiReg =
6302 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6303 auto [Op1L, Op1H] =
6304 ExtractSubRegs(MI, DestVregInst->getOperand(0), VregRC, ST, MRI);
6305 // lane value input should be in an sgpr
6306 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
6307 LaneValueLoReg)
6308 .addReg(Op1L);
6309 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
6310 LaneValueHiReg)
6311 .addReg(Op1H);
6312 NewAccumulator =
6313 BuildRegSequence(BB, MI, DstReg, LaneValueLoReg, LaneValueHiReg);
6314 }
6315 }
6316 }
6317 RetBB = &BB;
6318 }
6319 }
6320 } else {
6322 Register SrcReg = MI.getOperand(1).getReg();
6323 bool is32BitOpc = is32bitWaveReduceOperation(Opc);
6325 bool NeedsMovDPP = !is32BitOpc;
6326 // Create virtual registers required for lowering.
6327 const TargetRegisterClass *WaveMaskRegClass = TRI->getWaveMaskRegClass();
6328 const TargetRegisterClass *DstRegClass = MRI.getRegClass(DstReg);
6329 const TargetRegisterClass *SrcRegClass = MRI.getRegClass(SrcReg);
6330 bool IsWave32 = ST.isWave32();
6331 unsigned MovOpcForExec = IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
6332 unsigned ExecReg = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
6333 if (Stratergy == WAVE_REDUCE_STRATEGY::ITERATIVE ||
6334 !ST.hasDPP()) { // If target doesn't support DPP operations, default to
6335 // iterative stratergy
6336
6337 // To reduce the VGPR using iterative approach, we need to iterate
6338 // over all the active lanes. Lowering consists of ComputeLoop,
6339 // which iterate over only active lanes. We use copy of EXEC register
6340 // as induction variable and every active lane modifies it using bitset0
6341 // so that we will get the next active lane for next iteration.
6342
6343 // Create Control flow for loop
6344 // Split MI's Machine Basic block into For loop
6345 auto [ComputeLoop, ComputeEnd] = splitBlockForLoop(MI, BB, true);
6346
6347 Register LoopIterator = MRI.createVirtualRegister(WaveMaskRegClass);
6348 Register IdentityValReg = MRI.createVirtualRegister(DstRegClass);
6349 Register AccumulatorReg = MRI.createVirtualRegister(DstRegClass);
6350 Register ActiveBitsReg = MRI.createVirtualRegister(WaveMaskRegClass);
6351 Register NewActiveBitsReg = MRI.createVirtualRegister(WaveMaskRegClass);
6352 Register FF1Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6353 Register LaneValueReg = MRI.createVirtualRegister(DstRegClass);
6354
6355 // Create initial values of induction variable from Exec, Accumulator and
6356 // insert branch instr to newly created ComputeBlock
6357 BuildMI(BB, I, DL, TII->get(MovOpcForExec), LoopIterator).addReg(ExecReg);
6358 uint64_t IdentityValue =
6359 MI.getOpcode() == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64
6360 ? 0x0 // +0.0 for double sub reduction
6362 BuildMI(BB, I, DL,
6363 TII->get(is32BitOpc ? AMDGPU::S_MOV_B32
6364 : AMDGPU::S_MOV_B64_IMM_PSEUDO),
6365 IdentityValReg)
6366 .addImm(IdentityValue);
6367 // clang-format off
6368 BuildMI(BB, I, DL, TII->get(AMDGPU::S_BRANCH))
6369 .addMBB(ComputeLoop);
6370 // clang-format on
6371
6372 // Start constructing ComputeLoop
6373 I = ComputeLoop->begin();
6374 auto Accumulator =
6375 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::PHI), AccumulatorReg)
6376 .addReg(IdentityValReg)
6377 .addMBB(&BB);
6378 auto ActiveBits =
6379 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::PHI), ActiveBitsReg)
6380 .addReg(LoopIterator)
6381 .addMBB(&BB);
6382
6383 I = ComputeLoop->end();
6384 MachineInstr *NewAccumulator;
6385 // Perform the computations
6386 unsigned SFFOpc =
6387 IsWave32 ? AMDGPU::S_FF1_I32_B32 : AMDGPU::S_FF1_I32_B64;
6388 BuildMI(*ComputeLoop, I, DL, TII->get(SFFOpc), FF1Reg)
6389 .addReg(ActiveBitsReg);
6390 if (is32BitOpc) {
6391 Register OpDstReg = DstReg;
6392 bool hasSrc0Modifier = AMDGPU::getNamedOperandIdx(
6393 Opc, AMDGPU::OpName::src0_modifiers) != -1;
6394 bool hasSrc1Modifier = AMDGPU::getNamedOperandIdx(
6395 Opc, AMDGPU::OpName::src1_modifiers) != -1;
6396 bool hasClamp =
6397 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp) != -1;
6398 bool hasOpSel =
6399 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel) != -1;
6400 bool hasOMod =
6401 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod) != -1;
6402 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::V_READLANE_B32),
6403 LaneValueReg)
6404 .addReg(SrcReg)
6405 .addReg(FF1Reg);
6406 if (ST.getInstrInfo()->isVALU(Opc, /*AllowLDSDMA=*/false)) {
6407 // Get the Lane Value in VGPR to avoid the Constant Bus Restriction
6408 Register LaneValVgpr = MRI.createVirtualRegister(SrcRegClass);
6409 Register VgprResultReg = MRI.createVirtualRegister(SrcRegClass);
6410 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::COPY), LaneValVgpr)
6411 .addReg(LaneValueReg);
6412 OpDstReg = VgprResultReg;
6413 LaneValueReg = LaneValVgpr;
6414 }
6415 auto OpInstr = BuildMI(*ComputeLoop, I, DL, TII->get(Opc), OpDstReg);
6416 if (hasSrc0Modifier)
6417 OpInstr.addImm(SISrcMods::NONE); // src0 modifier
6418 OpInstr.addReg(AccumulatorReg); // src0
6419 if (hasSrc1Modifier)
6420 OpInstr.addImm(SISrcMods::NONE); // src1 modifier
6421 OpInstr.addReg(LaneValueReg); // src1
6422 if (hasClamp)
6423 OpInstr.addImm(0); // clamp
6424 if (hasOpSel)
6425 OpInstr.addImm(0); // opsel
6426 if (hasOMod)
6427 OpInstr.addImm(0); // omod
6428 if (TII->isSALU(Opc))
6429 OpInstr.setOperandDead(3); // Dead scc
6430 if (ST.getInstrInfo()->isVALU(Opc, /*AllowLDSDMA=*/false)) {
6431 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
6432 DstReg)
6433 .addReg(OpDstReg);
6434 }
6435 } else {
6436 Register LaneValueLoReg =
6437 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6438 Register LaneValueHiReg =
6439 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6440 Register LaneValReg =
6441 MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
6442 auto [Op1L, Op1H] = ExtractSubRegs(MI, MI.getOperand(1),
6443 MRI.getRegClass(SrcReg), ST, MRI);
6444 // lane value input should be in an sgpr
6445 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::V_READLANE_B32),
6446 LaneValueLoReg)
6447 .addReg(Op1L)
6448 .addReg(FF1Reg);
6449 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::V_READLANE_B32),
6450 LaneValueHiReg)
6451 .addReg(Op1H)
6452 .addReg(FF1Reg);
6453 auto LaneValue = BuildRegSequence(*ComputeLoop, I, LaneValReg,
6454 LaneValueLoReg, LaneValueHiReg);
6455 switch (Opc) {
6456 case AMDGPU::S_OR_B64:
6457 case AMDGPU::S_AND_B64:
6458 case AMDGPU::S_XOR_B64: {
6459 NewAccumulator = BuildMI(*ComputeLoop, I, DL, TII->get(Opc), DstReg)
6460 .addReg(Accumulator->getOperand(0).getReg())
6461 .addReg(LaneValue->getOperand(0).getReg())
6462 .setOperandDead(3); // Dead scc
6463 break;
6464 }
6465 case AMDGPU::V_CMP_GT_I64_e64:
6466 case AMDGPU::V_CMP_GT_U64_e64:
6467 case AMDGPU::V_CMP_LT_I64_e64:
6468 case AMDGPU::V_CMP_LT_U64_e64: {
6469 Register LaneMaskReg = MRI.createVirtualRegister(WaveMaskRegClass);
6470 Register ComparisonResultReg =
6471 MRI.createVirtualRegister(WaveMaskRegClass);
6472 int SrcIdx =
6473 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src);
6474 const TargetRegisterClass *VregClass =
6475 TRI->getAllocatableClass(TII->getRegClass(MI.getDesc(), SrcIdx));
6476 Register AccumulatorVReg = MRI.createVirtualRegister(VregClass);
6477 auto [SrcReg0Sub0, SrcReg0Sub1] = ExtractSubRegs(
6478 MI, Accumulator->getOperand(0), VregClass, ST, MRI);
6479 BuildRegSequence(*ComputeLoop, I, AccumulatorVReg, SrcReg0Sub0,
6480 SrcReg0Sub1);
6481 BuildMI(*ComputeLoop, I, DL, TII->get(Opc), LaneMaskReg)
6482 .addReg(LaneValue->getOperand(0).getReg())
6483 .addReg(AccumulatorVReg);
6484
6485 unsigned AndOpc = IsWave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
6486 BuildMI(*ComputeLoop, I, DL, TII->get(AndOpc), ComparisonResultReg)
6487 .addReg(LaneMaskReg)
6488 .addReg(ActiveBitsReg);
6489
6490 NewAccumulator = BuildMI(*ComputeLoop, I, DL,
6491 TII->get(AMDGPU::S_CSELECT_B64), DstReg)
6492 .addReg(LaneValue->getOperand(0).getReg())
6493 .addReg(Accumulator->getOperand(0).getReg());
6494 break;
6495 }
6496 case AMDGPU::V_MIN_F64_e64:
6497 case AMDGPU::V_MIN_NUM_F64_e64:
6498 case AMDGPU::V_MAX_F64_e64:
6499 case AMDGPU::V_MAX_NUM_F64_e64:
6500 case AMDGPU::V_ADD_F64_e64:
6501 case AMDGPU::V_ADD_F64_pseudo_e64: {
6502 int SrcIdx =
6503 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src);
6504 const TargetRegisterClass *VregRC =
6505 TRI->getAllocatableClass(TII->getRegClass(MI.getDesc(), SrcIdx));
6506 Register AccumulatorVReg = MRI.createVirtualRegister(VregRC);
6507 Register DstVreg = MRI.createVirtualRegister(VregRC);
6508 Register LaneValLo =
6509 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6510 Register LaneValHi =
6511 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6512 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::COPY), AccumulatorVReg)
6513 .addReg(Accumulator->getOperand(0).getReg());
6514 unsigned Modifier =
6515 MI.getOpcode() == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64
6518 auto DstVregInst =
6519 BuildMI(*ComputeLoop, I, DL, TII->get(Opc), DstVreg)
6520 .addImm(Modifier) // src0 modifiers
6521 .addReg(LaneValue->getOperand(0).getReg())
6522 .addImm(SISrcMods::NONE) // src1 modifiers
6523 .addReg(AccumulatorVReg)
6524 .addImm(SISrcMods::NONE) // clamp
6525 .addImm(SISrcMods::NONE); // omod
6526 auto ReadLaneLo =
6527 BuildMI(*ComputeLoop, I, DL,
6528 TII->get(AMDGPU::V_READFIRSTLANE_B32), LaneValLo);
6529 auto ReadLaneHi =
6530 BuildMI(*ComputeLoop, I, DL,
6531 TII->get(AMDGPU::V_READFIRSTLANE_B32), LaneValHi);
6532 MachineBasicBlock::iterator Iters = *ReadLaneLo;
6533 auto [Op1L, Op1H] = ExtractSubRegs(*Iters, DstVregInst->getOperand(0),
6534 VregRC, ST, MRI);
6535 ReadLaneLo.addReg(Op1L);
6536 ReadLaneHi.addReg(Op1H);
6537 NewAccumulator =
6538 BuildRegSequence(*ComputeLoop, I, DstReg, LaneValLo, LaneValHi);
6539 break;
6540 }
6541 case AMDGPU::S_ADD_U64_PSEUDO:
6542 case AMDGPU::S_SUB_U64_PSEUDO: {
6543 NewAccumulator = BuildMI(*ComputeLoop, I, DL, TII->get(Opc), DstReg)
6544 .addReg(Accumulator->getOperand(0).getReg())
6545 .addReg(LaneValue->getOperand(0).getReg())
6546 .setOperandDead(3); // Dead scc
6547 ComputeLoop =
6548 expand64BitScalarArithmetic(*NewAccumulator, ComputeLoop);
6549 break;
6550 }
6551 }
6552 }
6553 // Manipulate the iterator to get the next active lane
6554 unsigned BITSETOpc =
6555 IsWave32 ? AMDGPU::S_BITSET0_B32 : AMDGPU::S_BITSET0_B64;
6556 BuildMI(*ComputeLoop, I, DL, TII->get(BITSETOpc), NewActiveBitsReg)
6557 .addReg(FF1Reg)
6558 .addReg(ActiveBitsReg);
6559
6560 // Add phi nodes
6561 Accumulator.addReg(DstReg).addMBB(ComputeLoop);
6562 ActiveBits.addReg(NewActiveBitsReg).addMBB(ComputeLoop);
6563
6564 // Creating branching
6565 MachineInstrBuilder SetSCCInstr;
6566 if (!ST.hasScalarCompareEq64()) {
6567 // For targets <= gfx7, use an S_OR_B32/B64 instruction to set SCC.
6568 Register LaneMaskReg = MRI.createVirtualRegister(WaveMaskRegClass);
6569 unsigned CMPOpc = IsWave32 ? AMDGPU::S_OR_B32 : AMDGPU::S_OR_B64;
6570 SetSCCInstr =
6571 BuildMI(*ComputeLoop, I, DL, TII->get(CMPOpc), LaneMaskReg);
6572 } else {
6573 unsigned CMPOpc =
6574 IsWave32 ? AMDGPU::S_CMP_LG_U32 : AMDGPU::S_CMP_LG_U64;
6575 SetSCCInstr = BuildMI(*ComputeLoop, I, DL, TII->get(CMPOpc));
6576 }
6577 SetSCCInstr.addReg(NewActiveBitsReg);
6578 if (ST.hasScalarCompareEq64())
6579 SetSCCInstr.addImm(0);
6580 else
6581 SetSCCInstr.addReg(NewActiveBitsReg);
6582 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
6583 .addMBB(ComputeLoop);
6584
6585 RetBB = ComputeEnd;
6586 } else {
6587 assert(ST.hasDPP() && "Sub Target does not support DPP Operations");
6588 MachineBasicBlock *CurrBB = &BB;
6589 Register SrcWithIdentity = MRI.createVirtualRegister(SrcRegClass);
6590 Register IdentityVGPR = MRI.createVirtualRegister(SrcRegClass);
6591 Register IdentitySGPR = MRI.createVirtualRegister(DstRegClass);
6592 Register DPPRowShr1 = MRI.createVirtualRegister(SrcRegClass);
6593 Register DPPRowShr2 = MRI.createVirtualRegister(SrcRegClass);
6594 Register DPPRowShr4 = MRI.createVirtualRegister(SrcRegClass);
6595 Register DPPRowShr8 = MRI.createVirtualRegister(SrcRegClass);
6596 Register RowBcast15 = MRI.createVirtualRegister(SrcRegClass);
6597 Register ReducedValSGPR = MRI.createVirtualRegister(DstRegClass);
6598 Register NegatedReducedVal = MRI.createVirtualRegister(DstRegClass);
6599 Register RowBcast31 = MRI.createVirtualRegister(SrcRegClass);
6600 Register UndefExec = MRI.createVirtualRegister(WaveMaskRegClass);
6601 Register FinalDPPResult;
6602 MachineInstr *SrcWithIdentityInstr;
6603 MachineInstr *LastBcastInstr;
6604 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), UndefExec);
6605
6607 BuildMI(*CurrBB, MI, DL,
6608 TII->get(is32BitOpc ? AMDGPU::S_MOV_B32
6609 : AMDGPU::S_MOV_B64_IMM_PSEUDO),
6610 IdentitySGPR)
6611 .addImm(IdentityValue);
6612 auto IdentityCopyInstr =
6613 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::COPY), IdentityVGPR)
6614 .addReg(IdentitySGPR);
6615 unsigned DPPOpc, ClampOpc;
6616 std::tie(DPPOpc, ClampOpc) = getDPPOpcForWaveReduction(Opc, ST);
6617 auto BuildSetInactiveInstr = [&](Register Dst, Register Src0,
6618 Register Src1) {
6619 return BuildMI(BB, MI, DL, TII->get(AMDGPU::V_SET_INACTIVE_B32),
6620 Dst)
6621 .addImm(0) // src0 modifiers
6622 .addReg(Src0) // src0
6623 .addImm(0) // src1 modifiers
6624 .addReg(Src1) // identity value for inactive lanes
6625 .addReg(UndefExec); // bool i1
6626 };
6627 auto BuildDPPMachineInstr = [&](Register Dst, Register Src,
6628 unsigned DPPCtrl) {
6629 auto DPPInstr =
6630 BuildMI(*CurrBB, MI, DL, TII->get(DPPOpc), Dst).addReg(Src); // old
6631 if (isFPOp && !NeedsMovDPP)
6632 DPPInstr.addImm(SISrcMods::NONE); // src0 modifier
6633 DPPInstr.addReg(Src); // src0
6634 if (isFPOp && !NeedsMovDPP)
6635 DPPInstr.addImm(SISrcMods::NONE); // src1 modifier
6636 if (!NeedsMovDPP)
6637 DPPInstr.addReg(Src); // src1
6638 if (AMDGPU::getNamedOperandIdx(DPPOpc, AMDGPU::OpName::clamp) >= 0)
6639 DPPInstr.addImm(0); // clamp
6640 DPPInstr
6641 .addImm(DPPCtrl) // dpp-ctrl
6642 .addImm(0xf) // row-mask
6643 .addImm(0xf) // bank-mask
6644 .addImm(0); // bound-control
6645 };
6646 auto BuildClampInstr = [&](Register Dst, Register Src0, Register Src1,
6647 bool isAddSub = false,
6648 bool needsCarryIn = false,
6649 Register CarryIn = Register()) {
6650 unsigned InstrOpc = ClampOpc;
6651 Register CarryOutReg = MRI.createVirtualRegister(WaveMaskRegClass);
6652 if (needsCarryIn)
6653 InstrOpc = AMDGPU::V_ADDC_U32_e64;
6654 auto ClampInstr = BuildMI(*CurrBB, MI, DL, TII->get(InstrOpc), Dst);
6655 if (isFPOp)
6656 ClampInstr.addImm(SISrcMods::NONE); // src0 mod
6657 if (isAddSub) {
6658 if (needsCarryIn)
6659 ClampInstr.addReg(CarryOutReg,
6661 RegState::Dead); // killed carry-out reg
6662 else
6663 ClampInstr.addReg(CarryOutReg, RegState::Define); // carry-out reg
6664 }
6665 ClampInstr.addReg(Src0); // src0
6666 if (isFPOp)
6667 ClampInstr.addImm(SISrcMods::NONE); // src1 mod
6668 ClampInstr.addReg(Src1); // src1
6669 if (needsCarryIn)
6670 ClampInstr.addReg(CarryIn); // carry-in reg
6671 if (AMDGPU::getNamedOperandIdx(InstrOpc, AMDGPU::OpName::clamp) >= 0)
6672 ClampInstr.addImm(0); // clamp
6673 if (isFPOp)
6674 ClampInstr.addImm(0); // omod
6675 LastBcastInstr = ClampInstr;
6676 return CarryOutReg;
6677 };
6678 auto BuildPostDPPInstr = [&](Register Src0, Register Src1) {
6679 bool isAddSubOpc =
6680 Opc == AMDGPU::S_ADD_U64_PSEUDO || Opc == AMDGPU::S_SUB_U64_PSEUDO;
6681 bool isBitWiseOpc = Opc == AMDGPU::S_AND_B64 ||
6682 Opc == AMDGPU::S_OR_B64 || Opc == AMDGPU::S_XOR_B64;
6683 Register ReturnReg = MRI.createVirtualRegister(SrcRegClass);
6684 if (isAddSubOpc || isBitWiseOpc) {
6685 Register ResLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6686 Register ResHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6687 MachineOperand Src0Operand =
6688 MachineOperand::CreateReg(Src0, /*isDef=*/false);
6689 MachineOperand Src1Operand =
6690 MachineOperand::CreateReg(Src1, /*isDef=*/false);
6691 auto [Src0Lo, Src0Hi] =
6692 ExtractSubRegs(MI, Src0Operand, SrcRegClass, ST, MRI);
6693 auto [Src1Lo, Src1Hi] =
6694 ExtractSubRegs(MI, Src1Operand, SrcRegClass, ST, MRI);
6695 Register CarryReg = BuildClampInstr(
6696 ResLo, Src0Lo, Src1Lo, isAddSubOpc, /*needsCarryIn*/ false);
6697 BuildClampInstr(ResHi, Src0Hi, Src1Hi, isAddSubOpc,
6698 /*needsCarryIn*/ isAddSubOpc, CarryReg);
6699 BuildRegSequence(*CurrBB, MI, ReturnReg, ResLo, ResHi);
6700 } else {
6701 if (isFPOp) {
6702 BuildMI(*CurrBB, MI, DL, TII->get(Opc), ReturnReg)
6703 .addImm(SISrcMods::NONE) // src0 modifiers
6704 .addReg(Src0)
6705 .addImm(SISrcMods::NONE) // src1 modifiers
6706 .addReg(Src1)
6707 .addImm(SISrcMods::NONE) // clamp
6708 .addImm(SISrcMods::NONE); // omod
6709 } else {
6710 Register CmpMaskReg = MRI.createVirtualRegister(WaveMaskRegClass);
6711 BuildMI(*CurrBB, MI, DL, TII->get(Opc), CmpMaskReg)
6712 .addReg(Src0) // src0
6713 .addReg(Src1); // src1
6714 LastBcastInstr =
6715 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B64_PSEUDO),
6716 ReturnReg)
6717 .addReg(Src1) // src0
6718 .addReg(Src0) // src1
6719 .addReg(CmpMaskReg); // src2
6720 expand64BitV_CNDMASK(*LastBcastInstr, CurrBB);
6721 }
6722 }
6723 return ReturnReg;
6724 };
6725
6726 // Set inactive lanes to the identity value.
6727 if (is32BitOpc) {
6728 SrcWithIdentityInstr =
6729 BuildSetInactiveInstr(SrcWithIdentity, SrcReg, IdentityVGPR);
6730 } else {
6731 Register SrcWithIdentitylo =
6732 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6733 Register SrcWithIdentityhi =
6734 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6735 auto [Reg0Sub0, Reg0Sub1] = ExtractSubRegs(
6736 MI, IdentityCopyInstr->getOperand(0), SrcRegClass, ST, MRI);
6737 auto [SrcReg0Sub0, SrcReg0Sub1] =
6738 ExtractSubRegs(MI, MI.getOperand(1), SrcRegClass, ST, MRI);
6739 MachineInstr *SetInactiveLoInstr =
6740 BuildSetInactiveInstr(SrcWithIdentitylo, SrcReg0Sub0, Reg0Sub0);
6741 MachineInstr *SetInactiveHiInstr =
6742 BuildSetInactiveInstr(SrcWithIdentityhi, SrcReg0Sub1, Reg0Sub1);
6743 SrcWithIdentityInstr =
6744 BuildRegSequence(*CurrBB, MI, SrcWithIdentity,
6745 SetInactiveLoInstr->getOperand(0).getReg(),
6746 SetInactiveHiInstr->getOperand(0).getReg());
6747 }
6748 // DPP reduction
6749 Register SrcWithIdentityReg =
6750 SrcWithIdentityInstr->getOperand(0).getReg();
6751 BuildDPPMachineInstr(DPPRowShr1, SrcWithIdentityReg,
6753 if (NeedsMovDPP)
6754 DPPRowShr1 = BuildPostDPPInstr(SrcWithIdentityReg, DPPRowShr1);
6755
6756 BuildDPPMachineInstr(DPPRowShr2, DPPRowShr1,
6758 if (NeedsMovDPP)
6759 DPPRowShr2 = BuildPostDPPInstr(DPPRowShr1, DPPRowShr2);
6760
6761 BuildDPPMachineInstr(DPPRowShr4, DPPRowShr2,
6763 if (NeedsMovDPP)
6764 DPPRowShr4 = BuildPostDPPInstr(DPPRowShr2, DPPRowShr4);
6765
6766 BuildDPPMachineInstr(DPPRowShr8, DPPRowShr4,
6768 if (NeedsMovDPP)
6769 DPPRowShr8 = BuildPostDPPInstr(DPPRowShr4, DPPRowShr8);
6770
6771 if (ST.hasDPPBroadcasts()) {
6772 BuildDPPMachineInstr(RowBcast15, DPPRowShr8, AMDGPU::DPP::BCAST15);
6773 if (NeedsMovDPP)
6774 RowBcast15 = BuildPostDPPInstr(DPPRowShr8, RowBcast15);
6775 } else {
6776 // magic constant: 0x1E0
6777 // To Set BIT_MODE : bit 15 = 0
6778 // XOR mask : bit [14:10] = 0
6779 // OR mask : bit [9:5] = 15
6780 // AND mask : bit [4:0] = 0
6781 if (is32BitOpc) {
6782 Register SwizzledValue =
6783 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6784 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_SWIZZLE_B32),
6785 SwizzledValue)
6786 .addReg(DPPRowShr8) // addr
6787 .addImm(0x1E0) // swizzle offset (i16)
6788 .addImm(0x0); // gds (i1)
6789 BuildClampInstr(RowBcast15, DPPRowShr8, SwizzledValue);
6790 } else {
6791 Register SwizzledValuelo =
6792 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6793 Register SwizzledValuehi =
6794 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6795 Register SwizzledValue64 = MRI.createVirtualRegister(SrcRegClass);
6796 MachineOperand DPPRowShr8Op =
6797 MachineOperand::CreateReg(DPPRowShr8, /*isDef=*/false);
6798 auto [Op1L, Op1H] =
6799 ExtractSubRegs(MI, DPPRowShr8Op, SrcRegClass, ST, MRI);
6800 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_SWIZZLE_B32),
6801 SwizzledValuelo)
6802 .addReg(Op1L) // addr
6803 .addImm(0x1E0) // swizzle offset (i16)
6804 .addImm(0x0); // gds (i1)
6805 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_SWIZZLE_B32),
6806 SwizzledValuehi)
6807 .addReg(Op1H) // addr
6808 .addImm(0x1E0) // swizzle offset (i16)
6809 .addImm(0x0); // gds (i1)
6810 BuildRegSequence(*CurrBB, MI, SwizzledValue64, SwizzledValuelo,
6811 SwizzledValuehi);
6812 if (NeedsMovDPP)
6813 RowBcast15 = BuildPostDPPInstr(DPPRowShr8, SwizzledValue64);
6814 else
6815 BuildClampInstr(RowBcast15, DPPRowShr8, SwizzledValue64);
6816 }
6817 }
6818 FinalDPPResult = RowBcast15;
6819 if (!IsWave32) {
6820 if (ST.hasDPPBroadcasts()) {
6821 BuildDPPMachineInstr(RowBcast31, RowBcast15, AMDGPU::DPP::BCAST31);
6822 if (NeedsMovDPP)
6823 RowBcast31 = BuildPostDPPInstr(RowBcast15, RowBcast31);
6824 } else {
6825 Register ShiftedThreadID =
6826 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6827 Register PermuteByteOffset =
6828 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6829 Register PermutedValue = MRI.createVirtualRegister(SrcRegClass);
6830 Register Lane32Offset =
6831 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6832 Register WordSizeConst =
6833 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6834 Register ThreadIDRegLo =
6835 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6836 Register ThreadIDReg =
6837 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6838 // Get the thread ID.
6839 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_MBCNT_LO_U32_B32_e64),
6840 ThreadIDRegLo)
6841 .addImm(-1)
6842 .addImm(0);
6843 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_MBCNT_HI_U32_B32_e64),
6844 ThreadIDReg)
6845 .addImm(-1)
6846 .addReg(ThreadIDRegLo);
6847 // shift each lane over by 32 positions, so value in 31st lane is
6848 // present in 63rd lane.
6849 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::S_MOV_B32), Lane32Offset)
6850 .addImm(0x20);
6851 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_ADD_U32_e64),
6852 ShiftedThreadID)
6853 .addReg(ThreadIDReg)
6854 .addReg(Lane32Offset)
6855 .addImm(0); // clamp
6856 // multiply by reg size.
6857 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::S_MOV_B32), WordSizeConst)
6858 .addImm(0x4);
6859 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_MUL_LO_U32_e64),
6860 PermuteByteOffset)
6861 .addReg(WordSizeConst)
6862 .addReg(ShiftedThreadID);
6863 // Permute the lanes
6864 if (is32BitOpc) {
6865 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_PERMUTE_B32),
6866 PermutedValue)
6867 .addReg(PermuteByteOffset) // addr
6868 .addReg(RowBcast15) // data
6869 .addImm(0); // offset
6870 } else {
6871 Register PermutedValuelo =
6872 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6873 Register PermutedValuehi =
6874 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6875 MachineOperand RowBcast15Op =
6876 MachineOperand::CreateReg(RowBcast15, /*isDef=*/false);
6877 auto [RowBcast15Lo, RowBcast15Hi] =
6878 ExtractSubRegs(MI, RowBcast15Op, SrcRegClass, ST, MRI);
6879 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_PERMUTE_B32),
6880 PermutedValuelo)
6881 .addReg(PermuteByteOffset) // addr
6882 .addReg(RowBcast15Lo) // swizzle offset (i16)
6883 .addImm(0x0); // gds (i1)
6884 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_PERMUTE_B32),
6885 PermutedValuehi)
6886 .addReg(PermuteByteOffset) // addr
6887 .addReg(RowBcast15Hi) // swizzle offset (i16)
6888 .addImm(0x0); // gds (i1)
6889 BuildRegSequence(*CurrBB, MI, PermutedValue, PermutedValuelo,
6890 PermutedValuehi);
6891 }
6892 if (NeedsMovDPP)
6893 RowBcast31 = BuildPostDPPInstr(RowBcast15, PermutedValue);
6894 else
6895 BuildClampInstr(RowBcast31, RowBcast15, PermutedValue);
6896 }
6897 FinalDPPResult = RowBcast31;
6898 }
6899 if (MIOpc == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F32 ||
6900 MIOpc == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64) {
6901 Register NegatedValVGPR = MRI.createVirtualRegister(SrcRegClass);
6902 // Opc for f32 reduction is V_SUB_F32.
6903 // For f64, there is no equivalent V_SUB_F64 opcode, so use
6904 // V_ADD_F64/V_ADD_F64_pseudo, and negate the second operand.
6905 BuildMI(*CurrBB, MI, DL, TII->get(Opc),
6906 NegatedValVGPR)
6907 .addImm(SISrcMods::NONE) // src0 mods
6908 .addReg(IdentityVGPR) // src0
6909 .addImm(is32BitOpc ? SISrcMods::NONE : SISrcMods::NEG) // src1 mods
6910 .addReg(IsWave32 ? RowBcast15 : RowBcast31) // src1
6911 .addImm(SISrcMods::NONE) // clamp
6912 .addImm(SISrcMods::NONE); // omod
6913 FinalDPPResult = NegatedValVGPR;
6914 }
6915 // The final reduced value is in the last lane.
6916 if (is32BitOpc) {
6917 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_READLANE_B32),
6918 ReducedValSGPR)
6919 .addReg(FinalDPPResult)
6920 .addImm(ST.getWavefrontSize() - 1);
6921 } else {
6922 Register LaneValueLoReg =
6923 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6924 Register LaneValueHiReg =
6925 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6926 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
6927 MachineOperand FinalDPPResultOperand =
6928 MachineOperand::CreateReg(FinalDPPResult, /*isDef=*/false);
6929 auto [Op1L, Op1H] =
6930 ExtractSubRegs(MI, FinalDPPResultOperand, SrcRC, ST, MRI);
6931 // lane value input should be in an sgpr
6932 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_READLANE_B32),
6933 LaneValueLoReg)
6934 .addReg(Op1L)
6935 .addImm(ST.getWavefrontSize() - 1);
6936 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_READLANE_B32),
6937 LaneValueHiReg)
6938 .addReg(Op1H)
6939 .addImm(ST.getWavefrontSize() - 1);
6940 BuildRegSequence(*CurrBB, MI, ReducedValSGPR, LaneValueLoReg,
6941 LaneValueHiReg);
6942 }
6943 if (Opc == AMDGPU::S_SUB_I32) {
6944 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::S_SUB_I32), NegatedReducedVal)
6945 .addImm(0)
6946 .addReg(ReducedValSGPR)
6947 .setOperandDead(3); // Dead scc
6948 } else if (Opc == AMDGPU::S_SUB_U64_PSEUDO) {
6949 auto NegatedValInstr =
6950 BuildMI(*CurrBB, MI, DL, TII->get(Opc), NegatedReducedVal)
6951 .addImm(0)
6952 .addReg(ReducedValSGPR)
6953 .setOperandDead(3); // Dead scc
6954 CurrBB = expand64BitScalarArithmetic(*NegatedValInstr, CurrBB);
6955 }
6956 // Mark the final result as a whole-wave-mode calculation.
6957 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::STRICT_WWM), DstReg)
6958 .addReg(Opc == AMDGPU::S_SUB_I32 || Opc == AMDGPU::S_SUB_U64_PSEUDO
6959 ? NegatedReducedVal
6960 : ReducedValSGPR);
6961 RetBB = CurrBB;
6962 }
6963 }
6964 MI.eraseFromParent();
6965 return RetBB;
6966}
6967
6970 MachineBasicBlock *BB) const {
6971 MachineFunction *MF = BB->getParent();
6973 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
6975 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
6977 const DebugLoc &DL = MI.getDebugLoc();
6978
6979 switch (MI.getOpcode()) {
6980 case AMDGPU::WAVE_REDUCE_UMIN_PSEUDO_U32:
6981 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MIN_U32);
6982 case AMDGPU::WAVE_REDUCE_UMIN_PSEUDO_U64:
6983 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_CMP_LT_U64_e64);
6984 case AMDGPU::WAVE_REDUCE_MIN_PSEUDO_I32:
6985 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MIN_I32);
6986 case AMDGPU::WAVE_REDUCE_MIN_PSEUDO_I64:
6987 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_CMP_LT_I64_e64);
6988 case AMDGPU::WAVE_REDUCE_FMIN_PSEUDO_F32:
6989 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_MIN_F32_e64);
6990 case AMDGPU::WAVE_REDUCE_FMIN_PSEUDO_F64:
6991 return lowerWaveReduce(MI, *BB, *getSubtarget(),
6992 ST.getGeneration() >= AMDGPUSubtarget::GFX12
6993 ? AMDGPU::V_MIN_NUM_F64_e64
6994 : AMDGPU::V_MIN_F64_e64);
6995 case AMDGPU::WAVE_REDUCE_UMAX_PSEUDO_U32:
6996 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MAX_U32);
6997 case AMDGPU::WAVE_REDUCE_UMAX_PSEUDO_U64:
6998 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_CMP_GT_U64_e64);
6999 case AMDGPU::WAVE_REDUCE_MAX_PSEUDO_I32:
7000 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MAX_I32);
7001 case AMDGPU::WAVE_REDUCE_MAX_PSEUDO_I64:
7002 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_CMP_GT_I64_e64);
7003 case AMDGPU::WAVE_REDUCE_FMAX_PSEUDO_F32:
7004 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_MAX_F32_e64);
7005 case AMDGPU::WAVE_REDUCE_FMAX_PSEUDO_F64:
7006 return lowerWaveReduce(MI, *BB, *getSubtarget(),
7007 ST.getGeneration() >= AMDGPUSubtarget::GFX12
7008 ? AMDGPU::V_MAX_NUM_F64_e64
7009 : AMDGPU::V_MAX_F64_e64);
7010 case AMDGPU::WAVE_REDUCE_ADD_PSEUDO_I32:
7011 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_ADD_I32);
7012 case AMDGPU::WAVE_REDUCE_ADD_PSEUDO_U64:
7013 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_ADD_U64_PSEUDO);
7014 case AMDGPU::WAVE_REDUCE_FADD_PSEUDO_F32:
7015 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_ADD_F32_e64);
7016 case AMDGPU::WAVE_REDUCE_FADD_PSEUDO_F64:
7017 return lowerWaveReduce(MI, *BB, *getSubtarget(),
7018 ST.getGeneration() >= AMDGPUSubtarget::GFX12
7019 ? AMDGPU::V_ADD_F64_pseudo_e64
7020 : AMDGPU::V_ADD_F64_e64);
7021 case AMDGPU::WAVE_REDUCE_SUB_PSEUDO_I32:
7022 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_SUB_I32);
7023 case AMDGPU::WAVE_REDUCE_SUB_PSEUDO_U64:
7024 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_SUB_U64_PSEUDO);
7025 case AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F32:
7026 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_SUB_F32_e64);
7027 case AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64:
7028 // There is no S/V_SUB_F64 opcode. Double type subtraction is expanded as
7029 // fadd + neg, by setting the NEG bit in the instruction.
7030 return lowerWaveReduce(MI, *BB, *getSubtarget(),
7031 ST.getGeneration() >= AMDGPUSubtarget::GFX12
7032 ? AMDGPU::V_ADD_F64_pseudo_e64
7033 : AMDGPU::V_ADD_F64_e64);
7034 case AMDGPU::WAVE_REDUCE_AND_PSEUDO_B32:
7035 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_AND_B32);
7036 case AMDGPU::WAVE_REDUCE_AND_PSEUDO_B64:
7037 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_AND_B64);
7038 case AMDGPU::WAVE_REDUCE_OR_PSEUDO_B32:
7039 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_OR_B32);
7040 case AMDGPU::WAVE_REDUCE_OR_PSEUDO_B64:
7041 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_OR_B64);
7042 case AMDGPU::WAVE_REDUCE_XOR_PSEUDO_B32:
7043 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_XOR_B32);
7044 case AMDGPU::WAVE_REDUCE_XOR_PSEUDO_B64:
7045 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_XOR_B64);
7046 case AMDGPU::S_UADDO_PSEUDO:
7047 case AMDGPU::S_USUBO_PSEUDO: {
7048 MachineOperand &Dest0 = MI.getOperand(0);
7049 MachineOperand &Dest1 = MI.getOperand(1);
7050 MachineOperand &Src0 = MI.getOperand(2);
7051 MachineOperand &Src1 = MI.getOperand(3);
7052
7053 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
7054 ? AMDGPU::S_ADD_U32
7055 : AMDGPU::S_SUB_U32;
7056 // clang-format off
7057 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg())
7058 .add(Src0)
7059 .add(Src1);
7060 // clang-format on
7061
7062 unsigned SelOpc =
7063 Subtarget->isWave64() ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
7064 BuildMI(*BB, MI, DL, TII->get(SelOpc), Dest1.getReg()).addImm(-1).addImm(0);
7065
7066 MI.eraseFromParent();
7067 return BB;
7068 }
7069 case AMDGPU::S_ADD_U64_PSEUDO:
7070 case AMDGPU::S_SUB_U64_PSEUDO: {
7071 return expand64BitScalarArithmetic(MI, BB);
7072 }
7073 case AMDGPU::V_ADD_U64_PSEUDO:
7074 case AMDGPU::V_SUB_U64_PSEUDO: {
7075 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
7076
7077 MachineOperand &Dest = MI.getOperand(0);
7078 MachineOperand &Src0 = MI.getOperand(1);
7079 MachineOperand &Src1 = MI.getOperand(2);
7080
7081 if (ST.hasAddSubU64Insts()) {
7082 auto I = BuildMI(*BB, MI, DL,
7083 TII->get(IsAdd ? AMDGPU::V_ADD_U64_e64
7084 : AMDGPU::V_SUB_U64_e64),
7085 Dest.getReg())
7086 .add(Src0)
7087 .add(Src1)
7088 .addImm(0); // clamp
7089 TII->legalizeOperands(*I);
7090 MI.eraseFromParent();
7091 return BB;
7092 }
7093
7094 if (IsAdd && ST.hasLshlAddU64Inst()) {
7095 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
7096 Dest.getReg())
7097 .add(Src0)
7098 .addImm(0)
7099 .add(Src1);
7100 TII->legalizeOperands(*Add);
7101 MI.eraseFromParent();
7102 return BB;
7103 }
7104
7105 const auto *CarryRC = TRI->getWaveMaskRegClass();
7106
7107 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7108 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7109
7110 Register CarryReg = MRI.createVirtualRegister(CarryRC);
7111 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
7112
7113 const TargetRegisterClass *Src0RC = Src0.isReg()
7114 ? MRI.getRegClass(Src0.getReg())
7115 : &AMDGPU::VReg_64RegClass;
7116 const TargetRegisterClass *Src1RC = Src1.isReg()
7117 ? MRI.getRegClass(Src1.getReg())
7118 : &AMDGPU::VReg_64RegClass;
7119
7120 const TargetRegisterClass *Src0SubRC =
7121 TRI->getSubRegisterClass(Src0RC, AMDGPU::sub0);
7122 const TargetRegisterClass *Src1SubRC =
7123 TRI->getSubRegisterClass(Src1RC, AMDGPU::sub1);
7124
7125 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
7126 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
7127 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
7128 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
7129
7130 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
7131 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
7132 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
7133 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
7134
7135 unsigned LoOpc =
7136 IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
7137 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
7138 .addReg(CarryReg, RegState::Define)
7139 .add(SrcReg0Sub0)
7140 .add(SrcReg1Sub0)
7141 .addImm(0); // clamp bit
7142
7143 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
7144 MachineInstr *HiHalf =
7145 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
7146 .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
7147 .add(SrcReg0Sub1)
7148 .add(SrcReg1Sub1)
7149 .addReg(CarryReg)
7150 .addImm(0); // clamp bit
7151
7152 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
7153 .addReg(DestSub0)
7154 .addImm(AMDGPU::sub0)
7155 .addReg(DestSub1)
7156 .addImm(AMDGPU::sub1);
7157 TII->legalizeOperands(*LoHalf);
7158 TII->legalizeOperands(*HiHalf);
7159 MI.eraseFromParent();
7160 return BB;
7161 }
7162 case AMDGPU::S_ADD_CO_PSEUDO:
7163 case AMDGPU::S_SUB_CO_PSEUDO: {
7164 // This pseudo has a chance to be selected
7165 // only from uniform add/subcarry node. All the VGPR operands
7166 // therefore assumed to be splat vectors.
7168 MachineOperand &Dest = MI.getOperand(0);
7169 MachineOperand &CarryDest = MI.getOperand(1);
7170 MachineOperand &Src0 = MI.getOperand(2);
7171 MachineOperand &Src1 = MI.getOperand(3);
7172 MachineOperand &Src2 = MI.getOperand(4);
7173 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
7174 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7175 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
7176 .addReg(Src0.getReg());
7177 Src0.setReg(RegOp0);
7178 }
7179 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
7180 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7181 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
7182 .addReg(Src1.getReg());
7183 Src1.setReg(RegOp1);
7184 }
7185 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7186 if (TRI->isVectorRegister(MRI, Src2.getReg())) {
7187 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
7188 .addReg(Src2.getReg());
7189 Src2.setReg(RegOp2);
7190 }
7191
7192 if (ST.isWave64()) {
7193 if (ST.hasScalarCompareEq64()) {
7194 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
7195 .addReg(Src2.getReg())
7196 .addImm(0);
7197 } else {
7198 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
7199 const TargetRegisterClass *SubRC =
7200 TRI->getSubRegisterClass(Src2RC, AMDGPU::sub0);
7201 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
7202 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
7203 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
7204 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
7205 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7206
7207 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
7208 .add(Src2Sub0)
7209 .add(Src2Sub1);
7210
7211 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
7212 .addReg(Src2_32)
7213 .addImm(0);
7214 }
7215 } else {
7216 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
7217 .addReg(Src2.getReg())
7218 .addImm(0);
7219 }
7220
7221 unsigned Opc = MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO
7222 ? AMDGPU::S_ADDC_U32
7223 : AMDGPU::S_SUBB_U32;
7224
7225 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
7226
7227 unsigned SelOpc =
7228 ST.isWave64() ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
7229
7230 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
7231 .addImm(-1)
7232 .addImm(0);
7233
7234 MI.eraseFromParent();
7235 return BB;
7236 }
7237 case AMDGPU::SI_INIT_M0: {
7238 MachineOperand &M0Init = MI.getOperand(0);
7239 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
7240 TII->get(M0Init.isReg() ? AMDGPU::COPY : AMDGPU::S_MOV_B32),
7241 AMDGPU::M0)
7242 .add(M0Init);
7243 MI.eraseFromParent();
7244 return BB;
7245 }
7246 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM: {
7247 // Set SCC to true, in case the barrier instruction gets converted to a NOP.
7248 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
7249 TII->get(AMDGPU::S_CMP_EQ_U32))
7250 .addImm(0)
7251 .addImm(0);
7252 return BB;
7253 }
7254 case AMDGPU::GET_GROUPSTATICSIZE: {
7255 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
7256 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
7257 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
7258 .add(MI.getOperand(0))
7259 .addImm(MFI->getLDSSize());
7260 MI.eraseFromParent();
7261 return BB;
7262 }
7263 case AMDGPU::GET_SHADERCYCLESHILO: {
7264 assert(MF->getSubtarget<GCNSubtarget>().hasShaderCyclesHiLoRegisters());
7265 // The algorithm is:
7266 //
7267 // hi1 = getreg(SHADER_CYCLES_HI)
7268 // lo1 = getreg(SHADER_CYCLES_LO)
7269 // hi2 = getreg(SHADER_CYCLES_HI)
7270 //
7271 // If hi1 == hi2 then there was no overflow and the result is hi2:lo1.
7272 // Otherwise there was overflow and the result is hi2:0. In both cases the
7273 // result should represent the actual time at some point during the sequence
7274 // of three getregs.
7275 using namespace AMDGPU::Hwreg;
7276 Register RegHi1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7277 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_GETREG_B32), RegHi1)
7278 .addImm(HwregEncoding::encode(ID_SHADER_CYCLES_HI, 0, 32));
7279 Register RegLo1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7280 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_GETREG_B32), RegLo1)
7281 .addImm(HwregEncoding::encode(ID_SHADER_CYCLES, 0, 32));
7282 Register RegHi2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7283 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_GETREG_B32), RegHi2)
7284 .addImm(HwregEncoding::encode(ID_SHADER_CYCLES_HI, 0, 32));
7285 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CMP_EQ_U32))
7286 .addReg(RegHi1)
7287 .addReg(RegHi2);
7288 Register RegLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7289 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B32), RegLo)
7290 .addReg(RegLo1)
7291 .addImm(0);
7292 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE))
7293 .add(MI.getOperand(0))
7294 .addReg(RegLo)
7295 .addImm(AMDGPU::sub0)
7296 .addReg(RegHi2)
7297 .addImm(AMDGPU::sub1);
7298 MI.eraseFromParent();
7299 return BB;
7300 }
7301 case AMDGPU::SI_INDIRECT_SRC_V1:
7302 case AMDGPU::SI_INDIRECT_SRC_V2:
7303 case AMDGPU::SI_INDIRECT_SRC_V3:
7304 case AMDGPU::SI_INDIRECT_SRC_V4:
7305 case AMDGPU::SI_INDIRECT_SRC_V5:
7306 case AMDGPU::SI_INDIRECT_SRC_V6:
7307 case AMDGPU::SI_INDIRECT_SRC_V7:
7308 case AMDGPU::SI_INDIRECT_SRC_V8:
7309 case AMDGPU::SI_INDIRECT_SRC_V9:
7310 case AMDGPU::SI_INDIRECT_SRC_V10:
7311 case AMDGPU::SI_INDIRECT_SRC_V11:
7312 case AMDGPU::SI_INDIRECT_SRC_V12:
7313 case AMDGPU::SI_INDIRECT_SRC_V16:
7314 case AMDGPU::SI_INDIRECT_SRC_V32:
7315 return emitIndirectSrc(MI, *BB, *getSubtarget());
7316 case AMDGPU::SI_INDIRECT_DST_V1:
7317 case AMDGPU::SI_INDIRECT_DST_V2:
7318 case AMDGPU::SI_INDIRECT_DST_V3:
7319 case AMDGPU::SI_INDIRECT_DST_V4:
7320 case AMDGPU::SI_INDIRECT_DST_V5:
7321 case AMDGPU::SI_INDIRECT_DST_V6:
7322 case AMDGPU::SI_INDIRECT_DST_V7:
7323 case AMDGPU::SI_INDIRECT_DST_V8:
7324 case AMDGPU::SI_INDIRECT_DST_V9:
7325 case AMDGPU::SI_INDIRECT_DST_V10:
7326 case AMDGPU::SI_INDIRECT_DST_V11:
7327 case AMDGPU::SI_INDIRECT_DST_V12:
7328 case AMDGPU::SI_INDIRECT_DST_V16:
7329 case AMDGPU::SI_INDIRECT_DST_V32:
7330 return emitIndirectDst(MI, *BB, *getSubtarget());
7331 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
7332 case AMDGPU::SI_KILL_I1_PSEUDO:
7333 return splitKillBlock(MI, BB);
7334 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
7336 return BB;
7337 }
7338 case AMDGPU::SI_BR_UNDEF: {
7339 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
7340 .add(MI.getOperand(0));
7341 Br->getOperand(1).setIsUndef(); // read undef SCC
7342 MI.eraseFromParent();
7343 return BB;
7344 }
7345 case AMDGPU::ADJCALLSTACKUP:
7346 case AMDGPU::ADJCALLSTACKDOWN: {
7348 MachineInstrBuilder MIB(*MF, &MI);
7349 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
7350 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
7351 return BB;
7352 }
7353 case AMDGPU::SI_CALL_ISEL: {
7354 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
7355
7357 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL))
7358 .addDef(ReturnAddrReg, RegState::Dead);
7359
7360 for (const MachineOperand &MO : MI.operands())
7361 MIB.add(MO);
7362
7363 MIB.cloneMemRefs(MI);
7364 MIB.setMIFlags(MI.getFlags());
7365 MI.eraseFromParent();
7366 return BB;
7367 }
7368 case AMDGPU::V_ADDC_U32_e32:
7369 case AMDGPU::V_SUBB_U32_e32:
7370 case AMDGPU::V_SUBBREV_U32_e32:
7371 // These instructions have an implicit use of vcc which counts towards the
7372 // constant bus limit.
7373 TII->legalizeOperands(MI);
7374 return BB;
7375 case AMDGPU::DS_GWS_INIT:
7376 case AMDGPU::DS_GWS_SEMA_BR:
7377 case AMDGPU::DS_GWS_BARRIER:
7378 case AMDGPU::DS_GWS_SEMA_V:
7379 case AMDGPU::DS_GWS_SEMA_P:
7380 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
7381 // A s_waitcnt 0 is required to be the instruction immediately following.
7382 if (getSubtarget()->hasGWSAutoReplay()) {
7384 return BB;
7385 }
7386
7387 return emitGWSMemViolTestLoop(MI, BB);
7388 case AMDGPU::S_SETREG_B32: {
7389 // Try to optimize cases that only set the denormal mode or rounding mode.
7390 //
7391 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
7392 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
7393 // instead.
7394 //
7395 // FIXME: This could be predicates on the immediate, but tablegen doesn't
7396 // allow you to have a no side effect instruction in the output of a
7397 // sideeffecting pattern.
7398 auto [ID, Offset, Width] =
7399 AMDGPU::Hwreg::HwregEncoding::decode(MI.getOperand(1).getImm());
7400 if (ID != AMDGPU::Hwreg::ID_MODE)
7401 return BB;
7402
7403 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
7404 const unsigned SetMask = WidthMask << Offset;
7405
7406 if (getSubtarget()->hasDenormModeInst()) {
7407 unsigned SetDenormOp = 0;
7408 unsigned SetRoundOp = 0;
7409
7410 // The dedicated instructions can only set the whole denorm or round mode
7411 // at once, not a subset of bits in either.
7412 if (SetMask ==
7414 // If this fully sets both the round and denorm mode, emit the two
7415 // dedicated instructions for these.
7416 SetRoundOp = AMDGPU::S_ROUND_MODE;
7417 SetDenormOp = AMDGPU::S_DENORM_MODE;
7418 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
7419 SetRoundOp = AMDGPU::S_ROUND_MODE;
7420 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
7421 SetDenormOp = AMDGPU::S_DENORM_MODE;
7422 }
7423
7424 if (SetRoundOp || SetDenormOp) {
7425 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
7426 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
7427 unsigned ImmVal = Def->getOperand(1).getImm();
7428 if (SetRoundOp) {
7429 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
7430 .addImm(ImmVal & 0xf);
7431
7432 // If we also have the denorm mode, get just the denorm mode bits.
7433 ImmVal >>= 4;
7434 }
7435
7436 if (SetDenormOp) {
7437 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
7438 .addImm(ImmVal & 0xf);
7439 }
7440
7441 MI.eraseFromParent();
7442 return BB;
7443 }
7444 }
7445 }
7446
7447 // If only FP bits are touched, used the no side effects pseudo.
7448 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
7449 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
7450 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
7451
7452 return BB;
7453 }
7454 case AMDGPU::S_INVERSE_BALLOT_U32:
7455 case AMDGPU::S_INVERSE_BALLOT_U64:
7456 // These opcodes only exist to let SIFixSGPRCopies insert a readfirstlane if
7457 // necessary. After that they are equivalent to a COPY.
7458 MI.setDesc(TII->get(AMDGPU::COPY));
7459 return BB;
7460 case AMDGPU::ENDPGM_TRAP: {
7461 if (BB->succ_empty() && std::next(MI.getIterator()) == BB->end()) {
7462 MI.setDesc(TII->get(AMDGPU::S_ENDPGM));
7463 MI.addOperand(MachineOperand::CreateImm(0));
7464 return BB;
7465 }
7466
7467 // We need a block split to make the real endpgm a terminator. We also don't
7468 // want to break phis in successor blocks, so we can't just delete to the
7469 // end of the block.
7470
7471 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
7473 MF->push_back(TrapBB);
7474 // clang-format off
7475 BuildMI(*TrapBB, TrapBB->end(), DL, TII->get(AMDGPU::S_ENDPGM))
7476 .addImm(0);
7477 BuildMI(*BB, &MI, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
7478 .addMBB(TrapBB);
7479 // clang-format on
7480
7481 BB->addSuccessor(TrapBB);
7482 MI.eraseFromParent();
7483 return SplitBB;
7484 }
7485 case AMDGPU::SIMULATED_TRAP: {
7486 assert(Subtarget->hasPrivEnabledTrap2NopBug());
7487 MachineBasicBlock *SplitBB =
7488 TII->insertSimulatedTrap(MRI, *BB, MI, MI.getDebugLoc());
7489 MI.eraseFromParent();
7490 return SplitBB;
7491 }
7492 case AMDGPU::SI_TCRETURN_GFX_WholeWave:
7493 case AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN: {
7495
7496 // During ISel, it's difficult to propagate the original EXEC mask to use as
7497 // an input to SI_WHOLE_WAVE_FUNC_RETURN. Set it up here instead.
7498 MachineInstr *Setup = TII->getWholeWaveFunctionSetup(*BB->getParent());
7499 assert(Setup && "Couldn't find SI_SETUP_WHOLE_WAVE_FUNC");
7500 Register OriginalExec = Setup->getOperand(0).getReg();
7501 MI.getOperand(0).setReg(OriginalExec);
7502 return BB;
7503 }
7504 case AMDGPU::V_DOT2_F32_F16:
7505 case AMDGPU::V_DOT2_F32_BF16: {
7506 // Hint RA to assign dst and src2 the same physical register.
7507 // For targets without VOP2, but with VOPD, variant of the instruction this
7508 // is one of the conditions to attempt converting VOP3P to VOPD.
7509 MRI.setSimpleHint(MI.getOperand(0).getReg(), MI.getOperand(6).getReg());
7510 return BB;
7511 }
7512 case AMDGPU::SCHED_BARRIER:
7513 case AMDGPU::SCHED_GROUP_BARRIER:
7514 MI.getOperand(0).setImm(MI.getOperand(0).getImm() &
7515 static_cast<unsigned>(AMDGPU::SchedGroupMask::ALL));
7516 return BB;
7517 default:
7518 if (TII->isImage(MI) || TII->isMUBUF(MI)) {
7519 if (!MI.mayStore())
7521 return BB;
7522 }
7524 }
7525}
7526
7528 // This currently forces unfolding various combinations of fsub into fma with
7529 // free fneg'd operands. As long as we have fast FMA (controlled by
7530 // isFMAFasterThanFMulAndFAdd), we should perform these.
7531
7532 // When fma is quarter rate, for f64 where add / sub are at best half rate,
7533 // most of these combines appear to be cycle neutral but save on instruction
7534 // count / code size.
7535 return true;
7536}
7537
7539
7541 EVT VT) const {
7542 if (!VT.isVector()) {
7543 return MVT::i1;
7544 }
7545 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
7546}
7547
7549 // TODO: Should i16 be used always if legal? For now it would force VALU
7550 // shifts.
7551 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
7552}
7553
7555 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
7556 ? Ty.changeElementSize(16)
7557 : Ty.changeElementSize(32);
7558}
7559
7560// Answering this is somewhat tricky and depends on the specific device which
7561// have different rates for fma or all f64 operations.
7562//
7563// v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
7564// regardless of which device (although the number of cycles differs between
7565// devices), so it is always profitable for f64.
7566//
7567// v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
7568// only on full rate devices. Normally, we should prefer selecting v_mad_f32
7569// which we can always do even without fused FP ops since it returns the same
7570// result as the separate operations and since it is always full
7571// rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
7572// however does not support denormals, so we do report fma as faster if we have
7573// a fast fma device and require denormals.
7574//
7576 DenormalFPEnv FPEnv) const {
7577 VT = VT.getScalarType();
7578 if (!VT.isSimple())
7579 return false;
7580
7581 switch (VT.getSimpleVT().SimpleTy) {
7582 case MVT::f32: {
7583 // If mad is not available this depends only on if f32 fma is full rate.
7584 if (!Subtarget->hasMadMacF32Insts())
7585 return Subtarget->hasFastFMAF32();
7586
7587 // Otherwise f32 mad is always full rate and returns the same result as
7588 // the separate operations so should be preferred over fma.
7589 // However does not support denormals.
7591 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
7592
7593 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
7594 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
7595 }
7596 case MVT::f64:
7597 return true;
7598 case MVT::f16:
7599 case MVT::bf16:
7600 return Subtarget->has16BitInsts() &&
7602 default:
7603 break;
7604 }
7605
7606 return false;
7607}
7608
7613
7615 Type *Ty) const {
7617 getValueType(F.getDataLayout(), Ty, /*AllowUnknown=*/true),
7618 F.getDenormalFPEnv());
7619}
7620
7622 LLT Ty) const {
7623 switch (Ty.getScalarSizeInBits()) {
7624 case 16:
7625 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
7626 case 32:
7627 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
7628 case 64:
7629 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
7630 default:
7631 break;
7632 }
7633
7634 return false;
7635}
7636
7638 // TODO: Check future ftz flag
7639 // v_mad_f32/v_mac_f32 do not support denormals.
7640 if (VT == MVT::f32)
7641 return Subtarget->hasMadMacF32Insts() &&
7643 if (VT == MVT::f16)
7644 return Subtarget->hasMadF16() &&
7646
7647 return false;
7648}
7649
7651 if (!Ty.isScalar())
7652 return false;
7653
7654 DenormalFPEnv FPEnv = getDenormalFPEnv(*MI.getMF());
7655 if (Ty.getScalarSizeInBits() == 16)
7656 return isFMADLegal(MVT::f16, FPEnv);
7657 if (Ty.getScalarSizeInBits() == 32)
7658 return isFMADLegal(MVT::f32, FPEnv);
7659
7660 return false;
7661}
7662
7664 const SDNode *N) const {
7665 return isFMADLegal(N->getValueType(0),
7667}
7668
7670 return isFMADLegal(getValueType(F.getDataLayout(), Ty->getScalarType(),
7671 /*AllowUnknown=*/true),
7672 F.getDenormalFPEnv());
7673}
7674
7675//===----------------------------------------------------------------------===//
7676// Custom DAG Lowering Operations
7677//===----------------------------------------------------------------------===//
7678
7679// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
7680// wider vector type is legal.
7682 SelectionDAG &DAG) const {
7683 unsigned Opc = Op.getOpcode();
7684 EVT VT = Op.getValueType();
7686
7687 auto [Lo, Hi] = DAG.SplitVectorOperand(Op.getNode(), 0);
7688 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
7689
7690 SDLoc SL(Op);
7691
7692 // Forward any trailing scalar operands unchanged to both halves.
7693 SmallVector<SDValue, 2> LoOps = {Lo};
7694 SmallVector<SDValue, 2> HiOps = {Hi};
7695 auto TrailingOps = drop_begin(Op->ops());
7696 LoOps.append(TrailingOps.begin(), TrailingOps.end());
7697 HiOps.append(TrailingOps.begin(), TrailingOps.end());
7698
7699 SDValue OpLo = DAG.getNode(Opc, SL, LoVT, LoOps, Op->getFlags());
7700 SDValue OpHi = DAG.getNode(Opc, SL, HiVT, HiOps, Op->getFlags());
7701
7702 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
7703}
7704
7705// Enable lowering of ROTR for vxi32 types. This is a workaround for a
7706// regression whereby extra unnecessary instructions were added to codegen
7707// for rotr operations, casued by legalising v2i32 or. This resulted in extra
7708// instructions to extract the result from the vector.
7710 [[maybe_unused]] EVT VT = Op.getValueType();
7711
7712 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v8i32 ||
7713 VT == MVT::v16i32) &&
7714 "Unexpected ValueType.");
7715
7716 return DAG.UnrollVectorOp(Op.getNode());
7717}
7718
7719// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
7720// wider vector type is legal.
7722 SelectionDAG &DAG) const {
7723 unsigned Opc = Op.getOpcode();
7724 EVT VT = Op.getValueType();
7726
7727 auto [Lo0, Hi0] = DAG.SplitVectorOperand(Op.getNode(), 0);
7728 auto [Lo1, Hi1] = DAG.SplitVectorOperand(Op.getNode(), 1);
7729
7730 SDLoc SL(Op);
7731
7732 SDValue OpLo =
7733 DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Op->getFlags());
7734 SDValue OpHi =
7735 DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Op->getFlags());
7736
7737 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
7738}
7739
7741 SelectionDAG &DAG) const {
7742 unsigned Opc = Op.getOpcode();
7743 EVT VT = Op.getValueType();
7745
7746 SDValue Op0 = Op.getOperand(0);
7747 SDValue Lo0, Hi0;
7748 if (Op0.getValueType().isVector())
7749 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
7750 else
7751 Lo0 = Hi0 = DAG.getFreeze(Op0);
7752
7753 auto [Lo1, Hi1] = DAG.SplitVectorOperand(Op.getNode(), 1);
7754 auto [Lo2, Hi2] = DAG.SplitVectorOperand(Op.getNode(), 2);
7755
7756 SDLoc SL(Op);
7757 auto ResVT = DAG.GetSplitDestVTs(VT);
7758
7759 SDValue OpLo =
7760 DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, Op->getFlags());
7761 SDValue OpHi =
7762 DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, Op->getFlags());
7763
7764 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
7765}
7766
7768 switch (Op.getOpcode()) {
7769 default:
7771 case ISD::BRCOND:
7772 return LowerBRCOND(Op, DAG);
7773 case ISD::RETURNADDR:
7774 return LowerRETURNADDR(Op, DAG);
7775 case ISD::FrameIndex:
7776 return lowerFrameIndex(Op, DAG);
7777 case ISD::SPONENTRY:
7778 return LowerSPONENTRY(Op, DAG);
7779 case ISD::LOAD: {
7780 SDValue Result = LowerLOAD(Op, DAG);
7781 assert((!Result.getNode() || Result.getNode()->getNumValues() == 2) &&
7782 "Load should return a value and a chain");
7783 return Result;
7784 }
7785 case ISD::FSQRT: {
7786 EVT VT = Op.getValueType();
7787 if (VT == MVT::f32)
7788 return lowerFSQRTF32(Op, DAG);
7789 if (VT == MVT::f64)
7790 return lowerFSQRTF64(Op, DAG);
7791 return SDValue();
7792 }
7793 case ISD::FSIN:
7794 case ISD::FCOS:
7795 return LowerTrig(Op, DAG);
7796 case ISD::SELECT:
7797 return LowerSELECT(Op, DAG);
7798 case ISD::FDIV:
7799 return LowerFDIV(Op, DAG);
7800 case ISD::FFREXP:
7801 return LowerFFREXP(Op, DAG);
7803 return LowerATOMIC_CMP_SWAP(Op, DAG);
7804 case ISD::STORE:
7805 return LowerSTORE(Op, DAG);
7806 case ISD::GlobalAddress: {
7809 return LowerGlobalAddress(MFI, Op, DAG);
7810 }
7811 case ISD::BlockAddress:
7812 return LowerBlockAddress(Op, DAG);
7814 return LowerExternalSymbol(Op, DAG);
7816 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7818 return LowerCONVERT_FROM_ARBITRARY_FP(Op, DAG);
7820 return LowerCONVERT_TO_ARBITRARY_FP(Op, DAG);
7822 return LowerINTRINSIC_W_CHAIN(Op, DAG);
7824 return LowerINTRINSIC_VOID(Op, DAG);
7825 case ISD::ADDRSPACECAST:
7826 return lowerADDRSPACECAST(Op, DAG);
7828 return lowerINSERT_SUBVECTOR(Op, DAG);
7830 return lowerINSERT_VECTOR_ELT(Op, DAG);
7832 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
7834 return lowerVECTOR_SHUFFLE(Op, DAG);
7836 return lowerSCALAR_TO_VECTOR(Op, DAG);
7837 case ISD::BUILD_VECTOR:
7838 return lowerBUILD_VECTOR(Op, DAG);
7839 case ISD::FP_ROUND:
7841 return lowerFP_ROUND(Op, DAG);
7842 case ISD::TRAP:
7843 return lowerTRAP(Op, DAG);
7844 case ISD::DEBUGTRAP:
7845 return lowerDEBUGTRAP(Op, DAG);
7846 case ISD::ABS:
7847 case ISD::FABS:
7848 case ISD::FNEG:
7849 case ISD::FCANONICALIZE:
7850 case ISD::BSWAP:
7851 return splitUnaryVectorOp(Op, DAG);
7854 if (Op.getValueType().isVector() && Op.getValueType() != MVT::v2i16 &&
7855 Op.getOperand(0).getValueType().getScalarType() == MVT::f32)
7856 return splitUnaryVectorOp(Op, DAG);
7857 return LowerFP_TO_INT_SAT(Op, DAG);
7858 case ISD::FSUB:
7859 if (Op.getValueType() == MVT::bf16) {
7860 // Custom expansion:
7861 // fsub bf16 %a, %b -> fadd v2bf16(widen %a), fneg v2bf16(widen %b)
7862 // Then extract back to bf16.
7863 //
7864 // We create fneg on v2bf16 (not bf16) so the instruction selector can
7865 // fold the negation into the packed add's neg_lo/neg_hi modifiers,
7866 // generating a single v_pk_add_bf16 instruction. If we negate bf16 first,
7867 // it becomes a separate v_xor instruction before widening.
7868 SDLoc DL(Op);
7869 SDValue Op0 = Op.getOperand(0);
7870 SDValue Op1 = Op.getOperand(1);
7871
7872 // Widen both operands to v2bf16
7873 SDValue Vec0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2bf16, Op0);
7874 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2bf16, Op1);
7875
7876 // Create FNEG v2bf16 for the second operand
7877 SDValue NegVec1 = DAG.getNode(ISD::FNEG, DL, MVT::v2bf16, Vec1);
7878
7879 // Perform FADD v2bf16
7880 SDValue Result = DAG.getNode(ISD::FADD, DL, MVT::v2bf16, Vec0, NegVec1);
7881
7882 // Extract element 0 back to bf16
7883 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::bf16, Result,
7884 DAG.getConstant(0, DL, MVT::i32));
7885 }
7886 return SDValue();
7887 case ISD::FMINNUM:
7888 case ISD::FMAXNUM:
7889 return lowerFMINNUM_FMAXNUM(Op, DAG);
7890 case ISD::FMINIMUMNUM:
7891 case ISD::FMAXIMUMNUM:
7892 return lowerFMINIMUMNUM_FMAXIMUMNUM(Op, DAG);
7893 case ISD::FLDEXP:
7894 case ISD::STRICT_FLDEXP:
7895 return lowerFLDEXP(Op, DAG);
7896 case ISD::FMA:
7897 return splitTernaryVectorOp(Op, DAG);
7898 case ISD::FP_TO_SINT:
7899 case ISD::FP_TO_UINT:
7900 if (Subtarget->hasVCvtPkIU16F32() && Op.getValueType() == MVT::i16 &&
7901 Op.getOperand(0).getValueType() == MVT::f32) {
7902 // Make f32->i16 legal so we can select V_CVT_PK_[IU]16_F32.
7903 return Op;
7904 }
7905 return LowerFP_TO_INT(Op, DAG);
7906 case ISD::SHL:
7907 case ISD::SRA:
7908 case ISD::SRL:
7909 case ISD::ADD:
7910 case ISD::SUB:
7911 case ISD::SMIN:
7912 case ISD::SMAX:
7913 case ISD::UMIN:
7914 case ISD::UMAX:
7915 case ISD::FMINNUM_IEEE:
7916 case ISD::FMAXNUM_IEEE:
7917 case ISD::FMINIMUM:
7918 case ISD::FMAXIMUM:
7919 case ISD::UADDSAT:
7920 case ISD::USUBSAT:
7921 case ISD::SADDSAT:
7922 case ISD::SSUBSAT:
7923 case ISD::FADD:
7924 case ISD::FMUL:
7925 return splitBinaryVectorOp(Op, DAG);
7926 case ISD::FCOPYSIGN:
7927 return lowerFCOPYSIGN(Op, DAG);
7928 case ISD::MUL:
7929 return lowerMUL(Op, DAG);
7930 case ISD::SMULO:
7931 case ISD::UMULO:
7932 return lowerXMULO(Op, DAG);
7933 case ISD::SMUL_LOHI:
7934 case ISD::UMUL_LOHI:
7935 return lowerXMUL_LOHI(Op, DAG);
7937 return LowerDYNAMIC_STACKALLOC(Op, DAG);
7938 case ISD::STACKSAVE:
7939 return LowerSTACKSAVE(Op, DAG);
7940 case ISD::GET_ROUNDING:
7941 return lowerGET_ROUNDING(Op, DAG);
7942 case ISD::SET_ROUNDING:
7943 return lowerSET_ROUNDING(Op, DAG);
7944 case ISD::PREFETCH:
7945 return lowerPREFETCH(Op, DAG);
7946 case ISD::FP_EXTEND:
7948 return lowerFP_EXTEND(Op, DAG);
7949 case ISD::GET_FPENV:
7950 return lowerGET_FPENV(Op, DAG);
7951 case ISD::SET_FPENV:
7952 return lowerSET_FPENV(Op, DAG);
7953 case ISD::ROTR:
7954 return lowerROTR(Op, DAG);
7955 case ISD::INLINEASM:
7956 return LowerINLINEASM(Op, DAG);
7957 }
7958 return SDValue();
7959}
7960
7961// TFE results are dword granular: value dwords followed by one status dword.
7962static std::pair<SDValue, SDValue>
7964 LLVMContext &C = *DAG.getContext();
7965 unsigned NumValueDWords = divideCeil(VT.getSizeInBits(), 32);
7967 DAG.getVectorIdxConstant(NumValueDWords, DL));
7968 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
7969 SDValue ValueDWords =
7970 NumValueDWords == 1
7971 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op, ZeroIdx)
7973 EVT::getVectorVT(C, MVT::i32, NumValueDWords), Op,
7974 ZeroIdx);
7975 if (!VT.isVector() && VT.getSizeInBits() < 32)
7976 ValueDWords =
7977 DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), ValueDWords);
7978 return {DAG.getNode(ISD::BITCAST, DL, VT, ValueDWords), Status};
7979}
7980
7981// Used for D16: Casts the result of an instruction into the right vector,
7982// packs values if loads return unpacked values.
7984 const SDLoc &DL, SelectionDAG &DAG,
7985 bool Unpacked) {
7986 if (!LoadVT.isVector())
7987 return Result;
7988
7989 // Cast back to the original packed type or to a larger type that is a
7990 // multiple of 32 bit for D16. Widening the return type is a required for
7991 // legalization.
7992 EVT FittingLoadVT = LoadVT;
7993 if ((LoadVT.getVectorNumElements() % 2) == 1) {
7994 FittingLoadVT =
7996 LoadVT.getVectorNumElements() + 1);
7997 }
7998
7999 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
8000 // Truncate to v2i16/v4i16.
8001 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
8002
8003 // Workaround legalizer not scalarizing truncate after vector op
8004 // legalization but not creating intermediate vector trunc.
8006 DAG.ExtractVectorElements(Result, Elts);
8007 for (SDValue &Elt : Elts)
8008 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
8009
8010 // Pad illegal v1i16/v3fi6 to v4i16
8011 if ((LoadVT.getVectorNumElements() % 2) == 1)
8012 Elts.push_back(DAG.getPOISON(MVT::i16));
8013
8014 Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
8015
8016 // Bitcast to original type (v2f16/v4f16).
8017 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
8018 }
8019
8020 // Cast back to the original packed type.
8021 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
8022}
8023
8024SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, MemSDNode *M,
8025 SelectionDAG &DAG,
8027 bool IsIntrinsic) const {
8028 SDLoc DL(M);
8029
8030 bool IsTFE = M->getNumValues() == 3;
8031 bool Unpacked = Subtarget->hasUnpackedD16VMem();
8032 EVT LoadVT = M->getValueType(0);
8033
8034 EVT EquivLoadVT = LoadVT;
8035 if (LoadVT.isVector()) {
8036 if (Unpacked) {
8037 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8038 LoadVT.getVectorNumElements());
8039 } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
8040 // Widen v3f16 to legal type
8041 EquivLoadVT =
8043 LoadVT.getVectorNumElements() + 1);
8044 }
8045 }
8046
8047 if (IsTFE) {
8048 unsigned NumValueDWords = divideCeil(EquivLoadVT.getSizeInBits(), 32);
8049 EVT LoadDWordsVT =
8050 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumValueDWords + 1);
8051 SDVTList VTList = DAG.getVTList(LoadDWordsVT, MVT::Other);
8053 Opcode, DL, VTList, Ops, M->getMemoryVT(), M->getMemOperand());
8054 auto [Value, Status] = splitTFEValueAndStatus(Load, EquivLoadVT, DL, DAG);
8055 SDValue Adjusted =
8056 adjustLoadValueTypeImpl(Value, LoadVT, DL, DAG, Unpacked);
8057 return DAG.getMergeValues({Adjusted, Status, Load.getValue(1)}, DL);
8058 }
8059
8060 // Change from v4f16/v2f16 to EquivLoadVT.
8061 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
8062
8064 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, VTList, Ops,
8065 M->getMemoryVT(), M->getMemOperand());
8066
8067 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
8068
8069 return DAG.getMergeValues({Adjusted, Load.getValue(1)}, DL);
8070}
8071
8072SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
8073 SelectionDAG &DAG,
8074 ArrayRef<SDValue> Ops) const {
8075 SDLoc DL(M);
8076 EVT LoadVT = M->getValueType(0);
8077 EVT EltType = LoadVT.getScalarType();
8078 EVT IntVT = LoadVT.changeTypeToInteger();
8079
8080 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8081
8082 if (IsFormat && !IsD16 && EltType.getSizeInBits() < 32) {
8083 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
8085 "unsupported sub-dword format buffer load", DL.getDebugLoc()));
8086 return DAG.getMergeValues({DAG.getPOISON(LoadVT), M->getOperand(0)}, DL);
8087 }
8088
8089 assert(M->getNumValues() == 2 || M->getNumValues() == 3);
8090 bool IsTFE = M->getNumValues() == 3;
8091
8092 if (IsD16 && IsTFE && !Subtarget->hasBufferTFEFormatD16()) {
8093 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
8095 "TFE D16 format buffer load is not supported on this GPU",
8096 DL.getDebugLoc()));
8097 return DAG.getErrorMergeValues({M->value_begin(), M->value_end()},
8098 M->getOperand(0), DL);
8099 }
8100
8101 unsigned Opc = IsD16 ? (IsTFE ? AMDGPUISD::BUFFER_LOAD_FORMAT_D16_TFE
8102 : AMDGPUISD::BUFFER_LOAD_FORMAT_D16)
8103 : IsFormat ? (IsTFE ? AMDGPUISD::BUFFER_LOAD_FORMAT_TFE
8104 : AMDGPUISD::BUFFER_LOAD_FORMAT)
8105 : IsTFE ? AMDGPUISD::BUFFER_LOAD_TFE
8106 : AMDGPUISD::BUFFER_LOAD;
8107
8108 if (IsD16)
8109 return adjustLoadValueType(Opc, M, DAG, Ops);
8110
8111 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
8112 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
8113 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M->getMemOperand(),
8114 IsTFE);
8115
8116 if (isTypeLegal(LoadVT)) {
8117 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
8118 M->getMemOperand(), DAG);
8119 }
8120
8121 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
8122 SDVTList VTList = IsTFE ? DAG.getVTList(CastVT, MVT::i32, MVT::Other)
8123 : DAG.getVTList(CastVT, MVT::Other);
8124 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
8125 M->getMemOperand(), DAG);
8126 SDValue Data = DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode);
8127 if (IsTFE)
8128 return DAG.getMergeValues({Data, MemNode.getValue(1), MemNode.getValue(2)},
8129 DL);
8130 return DAG.getMergeValues({Data, MemNode.getValue(1)}, DL);
8131}
8132
8134 SelectionDAG &DAG) {
8135 EVT VT = N->getValueType(0);
8136 SDValue Src = N->getOperand(1);
8137 SDLoc SL(N);
8138
8139 if (Src.getOpcode() == ISD::SETCC) {
8140 SDValue Op0 = Src.getOperand(0);
8141 SDValue Op1 = Src.getOperand(1);
8142 // Need to expand bfloat to float for comparison (setcc).
8143 if (Op0.getValueType() == MVT::bf16) {
8144 Op0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Op0);
8145 Op1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Op1);
8146 }
8147 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
8148 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Op0, Op1, Src.getOperand(2));
8149 }
8150 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
8151 // (ballot 0) -> 0
8152 if (Arg->isZero())
8153 return DAG.getConstant(0, SL, VT);
8154
8155 // (ballot 1) -> EXEC/EXEC_LO
8156 if (Arg->isOne()) {
8157 Register Exec;
8158 if (VT.getScalarSizeInBits() == 32)
8159 Exec = AMDGPU::EXEC_LO;
8160 else if (VT.getScalarSizeInBits() == 64)
8161 Exec = AMDGPU::EXEC;
8162 else
8163 return SDValue();
8164
8165 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
8166 }
8167 }
8168
8169 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
8170 // ISD::SETNE)
8171 return DAG.getNode(
8172 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
8173 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
8174}
8175
8177 Intrinsic::ID IntrinsicID) {
8178 bool Signed = IntrinsicID == Intrinsic::amdgcn_sbfe;
8179 SDLoc DL(Op);
8180 EVT VT = Op.getValueType();
8181 SDValue Src = Op.getOperand(1);
8182 SDValue Offset = Op.getOperand(2);
8183 SDValue Width = Op.getOperand(3);
8184
8185 if (VT != MVT::i32) {
8188 Twine(Intrinsic::getBaseName(IntrinsicID)) + " only supports i32",
8189 DL.getDebugLoc()));
8190 return DAG.getPOISON(VT);
8191 }
8192
8193 return DAG.getNode(Signed ? AMDGPUISD::BFE_I32 : AMDGPUISD::BFE_U32, DL, VT,
8194 Src, Offset, Width);
8195}
8196
8198 EVT VT);
8199
8201 SelectionDAG &DAG) {
8202 EVT VT = N->getValueType(0);
8203 unsigned ValSize = VT.getSizeInBits();
8204 unsigned IID = N->getConstantOperandVal(0);
8205 bool IsPermLane16 = IID == Intrinsic::amdgcn_permlane16 ||
8206 IID == Intrinsic::amdgcn_permlanex16;
8207 bool IsSetInactive = IID == Intrinsic::amdgcn_set_inactive ||
8208 IID == Intrinsic::amdgcn_set_inactive_chain_arg;
8209 bool IsPermlaneShuffle = IID == Intrinsic::amdgcn_permlane_bcast ||
8210 IID == Intrinsic::amdgcn_permlane_up ||
8211 IID == Intrinsic::amdgcn_permlane_down ||
8212 IID == Intrinsic::amdgcn_permlane_xor;
8213 SDLoc SL(N);
8214 MVT IntVT = MVT::getIntegerVT(ValSize);
8215 const GCNSubtarget *ST = TLI.getSubtarget();
8216
8217 unsigned SplitSize = 32;
8218 if (IID == Intrinsic::amdgcn_update_dpp && (ValSize % 64 == 0) &&
8219 ST->hasDPALU_DPP() &&
8220 AMDGPU::isLegalDPALU_DPPControl(*ST, N->getConstantOperandVal(3)))
8221 SplitSize = 64;
8222
8223 auto createLaneOp = [&DAG, &SL, N, IID](SDValue Src0, SDValue Src1,
8224 SDValue Src2, MVT ValT) -> SDValue {
8226 switch (IID) {
8227 case Intrinsic::amdgcn_permlane16:
8228 case Intrinsic::amdgcn_permlanex16:
8229 case Intrinsic::amdgcn_update_dpp:
8230 Operands.push_back(N->getOperand(6));
8231 Operands.push_back(N->getOperand(5));
8232 Operands.push_back(N->getOperand(4));
8233 [[fallthrough]];
8234 case Intrinsic::amdgcn_writelane:
8235 case Intrinsic::amdgcn_permlane_bcast:
8236 case Intrinsic::amdgcn_permlane_up:
8237 case Intrinsic::amdgcn_permlane_down:
8238 case Intrinsic::amdgcn_permlane_xor:
8239 Operands.push_back(Src2);
8240 [[fallthrough]];
8241 case Intrinsic::amdgcn_readlane:
8242 case Intrinsic::amdgcn_set_inactive:
8243 case Intrinsic::amdgcn_set_inactive_chain_arg:
8244 case Intrinsic::amdgcn_mov_dpp8:
8245 Operands.push_back(Src1);
8246 [[fallthrough]];
8247 case Intrinsic::amdgcn_readfirstlane:
8248 case Intrinsic::amdgcn_permlane64:
8249 Operands.push_back(Src0);
8250 break;
8251 default:
8252 llvm_unreachable("unhandled lane op");
8253 }
8254
8255 Operands.push_back(DAG.getTargetConstant(IID, SL, MVT::i32));
8256 std::reverse(Operands.begin(), Operands.end());
8257
8258 if (SDNode *GL = N->getGluedNode()) {
8259 assert(GL->getOpcode() == ISD::CONVERGENCECTRL_GLUE);
8260 GL = GL->getOperand(0).getNode();
8261 Operands.push_back(DAG.getNode(ISD::CONVERGENCECTRL_GLUE, SL, MVT::Glue,
8262 SDValue(GL, 0)));
8263 }
8264
8265 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, ValT, Operands);
8266 };
8267
8268 SDValue Src0 = N->getOperand(1);
8269 SDValue Src1, Src2;
8270 if (IID == Intrinsic::amdgcn_readlane || IID == Intrinsic::amdgcn_writelane ||
8271 IID == Intrinsic::amdgcn_mov_dpp8 ||
8272 IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16 ||
8273 IsPermlaneShuffle) {
8274 Src1 = N->getOperand(2);
8275 if (IID == Intrinsic::amdgcn_writelane ||
8276 IID == Intrinsic::amdgcn_update_dpp || IsPermLane16 ||
8277 IsPermlaneShuffle)
8278 Src2 = N->getOperand(3);
8279 }
8280
8281 if (ValSize == SplitSize) {
8282 // Already legal
8283 return SDValue();
8284 }
8285
8286 if (ValSize < 32) {
8287 bool IsFloat = VT.isFloatingPoint();
8288 Src0 = DAG.getAnyExtOrTrunc(IsFloat ? DAG.getBitcast(IntVT, Src0) : Src0,
8289 SL, MVT::i32);
8290
8291 if (IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16) {
8292 Src1 = DAG.getAnyExtOrTrunc(IsFloat ? DAG.getBitcast(IntVT, Src1) : Src1,
8293 SL, MVT::i32);
8294 }
8295
8296 if (IID == Intrinsic::amdgcn_writelane) {
8297 Src2 = DAG.getAnyExtOrTrunc(IsFloat ? DAG.getBitcast(IntVT, Src2) : Src2,
8298 SL, MVT::i32);
8299 }
8300
8301 SDValue LaneOp = createLaneOp(Src0, Src1, Src2, MVT::i32);
8302 SDValue Trunc = DAG.getAnyExtOrTrunc(LaneOp, SL, IntVT);
8303 return IsFloat ? DAG.getBitcast(VT, Trunc) : Trunc;
8304 }
8305
8306 if (ValSize % SplitSize != 0)
8307 return SDValue();
8308
8309 auto unrollLaneOp = [&DAG, &SL](SDNode *N) -> SDValue {
8310 EVT VT = N->getValueType(0);
8311 unsigned NE = VT.getVectorNumElements();
8312 EVT EltVT = VT.getVectorElementType();
8314 unsigned NumOperands = N->getNumOperands();
8315 SmallVector<SDValue, 4> Operands(NumOperands);
8316 SDNode *GL = N->getGluedNode();
8317
8318 // only handle convergencectrl_glue
8320
8321 for (unsigned i = 0; i != NE; ++i) {
8322 for (unsigned j = 0, e = GL ? NumOperands - 1 : NumOperands; j != e;
8323 ++j) {
8324 SDValue Operand = N->getOperand(j);
8325 EVT OperandVT = Operand.getValueType();
8326 if (OperandVT.isVector()) {
8327 // A vector operand; extract a single element.
8328 EVT OperandEltVT = OperandVT.getVectorElementType();
8329 Operands[j] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, OperandEltVT,
8330 Operand, DAG.getVectorIdxConstant(i, SL));
8331 } else {
8332 // A scalar operand; just use it as is.
8333 Operands[j] = Operand;
8334 }
8335 }
8336
8337 if (GL)
8338 Operands[NumOperands - 1] =
8339 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, SL, MVT::Glue,
8340 SDValue(GL->getOperand(0).getNode(), 0));
8341
8342 Scalars.push_back(DAG.getNode(N->getOpcode(), SL, EltVT, Operands));
8343 }
8344
8345 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NE);
8346 return DAG.getBuildVector(VecVT, SL, Scalars);
8347 };
8348
8349 if (VT.isVector()) {
8350 switch (MVT::SimpleValueType EltTy =
8352 case MVT::i32:
8353 case MVT::f32:
8354 if (SplitSize == 32) {
8355 SDValue LaneOp = createLaneOp(Src0, Src1, Src2, VT.getSimpleVT());
8356 return unrollLaneOp(LaneOp.getNode());
8357 }
8358 [[fallthrough]];
8359 case MVT::i16:
8360 case MVT::f16:
8361 case MVT::bf16: {
8362 unsigned SubVecNumElt =
8363 SplitSize / VT.getVectorElementType().getSizeInBits();
8364 MVT SubVecVT = MVT::getVectorVT(EltTy, SubVecNumElt);
8366 SDValue Src0SubVec, Src1SubVec, Src2SubVec;
8367 for (unsigned i = 0, EltIdx = 0; i < ValSize / SplitSize; i++) {
8368 Src0SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, SubVecVT, Src0,
8369 DAG.getConstant(EltIdx, SL, MVT::i32));
8370
8371 if (IID == Intrinsic::amdgcn_update_dpp || IsSetInactive ||
8372 IsPermLane16) {
8373 Src1SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, SubVecVT, Src1,
8374 DAG.getConstant(EltIdx, SL, MVT::i32));
8375
8376 Pieces.push_back(
8377 createLaneOp(Src0SubVec, Src1SubVec, Src2, SubVecVT));
8378 } else if (IID == Intrinsic::amdgcn_writelane) {
8379 Src2SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, SubVecVT, Src2,
8380 DAG.getConstant(EltIdx, SL, MVT::i32));
8381 Pieces.push_back(
8382 createLaneOp(Src0SubVec, Src1, Src2SubVec, SubVecVT));
8383 } else {
8384 Pieces.push_back(createLaneOp(Src0SubVec, Src1, Src2, SubVecVT));
8385 }
8386
8387 EltIdx += SubVecNumElt;
8388 }
8389 return DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, Pieces);
8390 }
8391 default:
8392 // Handle all other cases by bitcasting to i32 vectors
8393 break;
8394 }
8395 }
8396
8397 MVT VecVT =
8398 MVT::getVectorVT(MVT::getIntegerVT(SplitSize), ValSize / SplitSize);
8399 Src0 = DAG.getBitcast(VecVT, Src0);
8400
8401 if (IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16)
8402 Src1 = DAG.getBitcast(VecVT, Src1);
8403
8404 if (IID == Intrinsic::amdgcn_writelane)
8405 Src2 = DAG.getBitcast(VecVT, Src2);
8406
8407 SDValue LaneOp = createLaneOp(Src0, Src1, Src2, VecVT);
8408 SDValue UnrolledLaneOp = unrollLaneOp(LaneOp.getNode());
8409 return DAG.getBitcast(VT, UnrolledLaneOp);
8410}
8411
8413 SelectionDAG &DAG) {
8414 EVT VT = N->getValueType(0);
8415
8416 if (VT.getSizeInBits() != 32)
8417 return SDValue();
8418
8419 SDLoc SL(N);
8420
8421 SDValue Value = N->getOperand(1);
8422 SDValue Index = N->getOperand(2);
8423
8424 // ds_bpermute requires index to be multiplied by 4
8425 SDValue ShiftAmount = DAG.getShiftAmountConstant(2, MVT::i32, SL);
8426 SDValue ShiftedIndex =
8427 DAG.getNode(ISD::SHL, SL, Index.getValueType(), Index, ShiftAmount);
8428
8429 // Intrinsics will require i32 to operate on
8430 SDValue ValueI32 = DAG.getBitcast(MVT::i32, Value);
8431
8432 auto MakeIntrinsic = [&DAG, &SL](unsigned IID, MVT RetVT,
8433 SmallVector<SDValue> IntrinArgs) -> SDValue {
8435 Operands[0] = DAG.getTargetConstant(IID, SL, MVT::i32);
8436 Operands.append(IntrinArgs);
8437 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, RetVT, Operands);
8438 };
8439
8440 // If we can bpermute across the whole wave, then just do that
8441 if (TLI.getSubtarget()->supportsWaveWideBPermute()) {
8442 SDValue BPermute = MakeIntrinsic(Intrinsic::amdgcn_ds_bpermute, MVT::i32,
8443 {ShiftedIndex, ValueI32});
8444 return DAG.getBitcast(VT, BPermute);
8445 }
8446
8447 assert(TLI.getSubtarget()->isWave64());
8448
8449 // Otherwise, we need to make use of whole wave mode
8450 SDValue PoisonVal = DAG.getPOISON(ValueI32->getValueType(0));
8451
8452 // Set inactive lanes to poison
8453 SDValue WWMValue = MakeIntrinsic(Intrinsic::amdgcn_set_inactive, MVT::i32,
8454 {ValueI32, PoisonVal});
8455 SDValue WWMIndex = MakeIntrinsic(Intrinsic::amdgcn_set_inactive, MVT::i32,
8456 {ShiftedIndex, PoisonVal});
8457
8458 SDValue Swapped =
8459 MakeIntrinsic(Intrinsic::amdgcn_permlane64, MVT::i32, {WWMValue});
8460
8461 // Get permutation of each half, then we'll select which one to use
8462 SDValue BPermSameHalf = MakeIntrinsic(Intrinsic::amdgcn_ds_bpermute, MVT::i32,
8463 {WWMIndex, WWMValue});
8464 SDValue BPermOtherHalf = MakeIntrinsic(Intrinsic::amdgcn_ds_bpermute,
8465 MVT::i32, {WWMIndex, Swapped});
8466 SDValue BPermOtherHalfWWM =
8467 MakeIntrinsic(Intrinsic::amdgcn_wwm, MVT::i32, {BPermOtherHalf});
8468
8469 // Select which side to take the permute from
8470 SDValue ThreadIDMask = DAG.getAllOnesConstant(SL, MVT::i32);
8471 // We can get away with only using mbcnt_lo here since we're only
8472 // trying to detect which side of 32 each lane is on, and mbcnt_lo
8473 // returns 32 for lanes 32-63.
8474 SDValue ThreadID =
8475 MakeIntrinsic(Intrinsic::amdgcn_mbcnt_lo, MVT::i32,
8476 {ThreadIDMask, DAG.getTargetConstant(0, SL, MVT::i32)});
8477
8478 SDValue SameOrOtherHalf =
8479 DAG.getNode(ISD::AND, SL, MVT::i32,
8480 DAG.getNode(ISD::XOR, SL, MVT::i32, ThreadID, Index),
8481 DAG.getTargetConstant(32, SL, MVT::i32));
8482 SDValue UseSameHalf =
8483 DAG.getSetCC(SL, MVT::i1, SameOrOtherHalf,
8484 DAG.getConstant(0, SL, MVT::i32), ISD::SETEQ);
8485 SDValue Result = DAG.getSelect(SL, MVT::i32, UseSameHalf, BPermSameHalf,
8486 BPermOtherHalfWWM);
8487 return DAG.getBitcast(VT, Result);
8488}
8489
8492 SelectionDAG &DAG) const {
8493 switch (N->getOpcode()) {
8495 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
8496 Results.push_back(Res);
8497 return;
8498 }
8500 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
8501 Results.push_back(Res);
8502 return;
8503 }
8505 if (SDValue Res = LowerCONVERT_TO_ARBITRARY_FP(SDValue(N, 0), DAG))
8506 Results.push_back(Res);
8507 return;
8508 }
8510 unsigned IID = N->getConstantOperandVal(0);
8511 switch (IID) {
8512 case Intrinsic::amdgcn_wave_reduce_min:
8513 case Intrinsic::amdgcn_wave_reduce_umin:
8514 case Intrinsic::amdgcn_wave_reduce_max:
8515 case Intrinsic::amdgcn_wave_reduce_umax:
8516 case Intrinsic::amdgcn_wave_reduce_add:
8517 case Intrinsic::amdgcn_wave_reduce_sub:
8518 case Intrinsic::amdgcn_wave_reduce_and:
8519 case Intrinsic::amdgcn_wave_reduce_or:
8520 case Intrinsic::amdgcn_wave_reduce_xor: {
8521 EVT VT = N->getValueType(0);
8522 if (isTypeLegal(VT))
8523 return;
8524 SDLoc SL(N);
8525 bool NeedsSignExt = IID == Intrinsic::amdgcn_wave_reduce_min ||
8526 IID == Intrinsic::amdgcn_wave_reduce_max ||
8527 IID == Intrinsic::amdgcn_wave_reduce_add ||
8528 IID == Intrinsic::amdgcn_wave_reduce_sub;
8529 unsigned ExtOpc = NeedsSignExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8530 SDValue ExtSrc = DAG.getNode(ExtOpc, SL, MVT::i32, N->getOperand(1));
8531 SDValue Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
8532 N->getOperand(0), ExtSrc, N->getOperand(2));
8533 Results.push_back(DAG.getNode(ISD::TRUNCATE, SL, VT, Result));
8534 return;
8535 }
8536 case Intrinsic::amdgcn_make_buffer_rsrc:
8537 Results.push_back(lowerPointerAsRsrcIntrin(N, DAG));
8538 return;
8539 case Intrinsic::amdgcn_cvt_pkrtz: {
8540 SDValue Src0 = N->getOperand(1);
8541 SDValue Src1 = N->getOperand(2);
8542 SDLoc SL(N);
8543 SDValue Cvt =
8544 DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, Src0, Src1);
8545 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
8546 return;
8547 }
8548 case Intrinsic::amdgcn_cvt_pknorm_i16:
8549 case Intrinsic::amdgcn_cvt_pknorm_u16:
8550 case Intrinsic::amdgcn_cvt_pk_i16:
8551 case Intrinsic::amdgcn_cvt_pk_u16: {
8552 SDValue Src0 = N->getOperand(1);
8553 SDValue Src1 = N->getOperand(2);
8554 SDLoc SL(N);
8555 unsigned Opcode;
8556
8557 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
8558 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
8559 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
8560 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
8561 else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
8562 Opcode = AMDGPUISD::CVT_PK_I16_I32;
8563 else
8564 Opcode = AMDGPUISD::CVT_PK_U16_U32;
8565
8566 EVT VT = N->getValueType(0);
8567 if (isTypeLegal(VT))
8568 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
8569 else {
8570 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
8571 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
8572 }
8573 return;
8574 }
8575 case Intrinsic::amdgcn_s_buffer_load: {
8576 SDValue Op = SDValue(N, 0);
8577 EVT VT = Op.getValueType();
8578 Results.push_back(lowerSBuffer(VT, VT, SDLoc(Op), DAG.getEntryNode(),
8579 Op.getOperand(1), Op.getOperand(2),
8580 Op.getOperand(3), DAG));
8581 return;
8582 }
8583 case Intrinsic::amdgcn_dead: {
8584 for (unsigned I = 0, E = N->getNumValues(); I < E; ++I)
8585 Results.push_back(DAG.getPOISON(N->getValueType(I)));
8586 return;
8587 }
8588 }
8589 break;
8590 }
8592 if (N->getConstantOperandVal(1) != Intrinsic::amdgcn_ptr_s_buffer_load &&
8593 N->getValueType(0).isSimple() &&
8594 SBufferLoadDiagnosticVTs[N->getSimpleValueType(0).SimpleTy])
8595 break;
8596 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
8597 if (Res.getOpcode() == ISD::MERGE_VALUES) {
8598 // FIXME: Hacky
8599 for (unsigned I = 0; I < Res.getNumOperands(); I++) {
8600 Results.push_back(Res.getOperand(I));
8601 }
8602 } else {
8603 for (unsigned I = 0; I < N->getNumValues(); ++I)
8604 Results.push_back(Res.getValue(I));
8605 }
8606 return;
8607 }
8608
8609 break;
8610 }
8611 case ISD::SELECT: {
8612 SDLoc SL(N);
8613 EVT VT = N->getValueType(0);
8614 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
8615 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
8616 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
8617
8618 EVT SelectVT = NewVT;
8619 if (NewVT.bitsLT(MVT::i32)) {
8620 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
8621 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
8622 SelectVT = MVT::i32;
8623 }
8624
8625 SDValue NewSelect =
8626 DAG.getNode(ISD::SELECT, SL, SelectVT, N->getOperand(0), LHS, RHS);
8627
8628 if (NewVT != SelectVT)
8629 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
8630 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
8631 return;
8632 }
8633 case ISD::FNEG: {
8634 if (N->getValueType(0) != MVT::v2f16)
8635 break;
8636
8637 SDLoc SL(N);
8638 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
8639
8640 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, BC,
8641 DAG.getConstant(0x80008000, SL, MVT::i32));
8642 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
8643 return;
8644 }
8645 case ISD::FABS: {
8646 if (N->getValueType(0) != MVT::v2f16)
8647 break;
8648
8649 SDLoc SL(N);
8650 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
8651
8652 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, BC,
8653 DAG.getConstant(0x7fff7fff, SL, MVT::i32));
8654 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
8655 return;
8656 }
8657 case ISD::FSQRT: {
8658 if (N->getValueType(0) != MVT::f16)
8659 break;
8660 Results.push_back(lowerFSQRTF16(SDValue(N, 0), DAG));
8661 break;
8662 }
8663 default:
8665 break;
8666 }
8667}
8668
8669/// Helper function for LowerBRCOND
8670static SDNode *findUser(SDValue Value, unsigned Opcode) {
8671
8672 for (SDUse &U : Value->uses()) {
8673 if (U.get() != Value)
8674 continue;
8675
8676 if (U.getUser()->getOpcode() == Opcode)
8677 return U.getUser();
8678 }
8679 return nullptr;
8680}
8681
8682unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
8683 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8684 switch (Intr->getConstantOperandVal(1)) {
8685 case Intrinsic::amdgcn_if:
8686 return AMDGPUISD::IF;
8687 case Intrinsic::amdgcn_else:
8688 return AMDGPUISD::ELSE;
8689 case Intrinsic::amdgcn_loop:
8690 return AMDGPUISD::LOOP;
8691 case Intrinsic::amdgcn_end_cf:
8692 llvm_unreachable("should not occur");
8693 default:
8694 return 0;
8695 }
8696 }
8697
8698 // break, if_break, else_break are all only used as inputs to loop, not
8699 // directly as branch conditions.
8700 return 0;
8701}
8702
8709
8711 if (Subtarget->isAmdPalOS() || Subtarget->isMesa3DOS())
8712 return false;
8713
8714 // FIXME: Either avoid relying on address space here or change the default
8715 // address space for functions to avoid the explicit check.
8716 return (GV->getValueType()->isFunctionTy() ||
8719}
8720
8722 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
8723}
8724
8726 if (!GV->hasExternalLinkage())
8727 return true;
8728
8729 // With object linking, external LDS declarations need relocations so the
8730 // linker can assign their offsets.
8732 if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
8733 if (GVar->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
8734 GVar->getAddressSpace() == AMDGPUAS::BARRIER) {
8735 assert(GVar->isDeclaration() &&
8736 "AS 3 & 13 GVs should be declaration here "
8737 "when object linking is enabled");
8738 return false;
8739 }
8740 }
8741 }
8742
8743 const auto OS = getTargetMachine().getTargetTriple().getOS();
8744 return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
8745}
8746
8747/// This transforms the control flow intrinsics to get the branch destination as
8748/// last parameter, also switches branch target with BR if the need arise
8749SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, SelectionDAG &DAG) const {
8750 SDLoc DL(BRCOND);
8751
8752 SDNode *Intr = BRCOND.getOperand(1).getNode();
8753 SDValue Target = BRCOND.getOperand(2);
8754 SDNode *BR = nullptr;
8755 SDNode *SetCC = nullptr;
8756
8757 switch (Intr->getOpcode()) {
8758 case ISD::SETCC: {
8759 // As long as we negate the condition everything is fine
8760 SetCC = Intr;
8761 Intr = SetCC->getOperand(0).getNode();
8762 break;
8763 }
8764 case ISD::XOR: {
8765 // Similar to SETCC, if we have (xor c, -1), we will be fine.
8766 SDValue LHS = Intr->getOperand(0);
8767 SDValue RHS = Intr->getOperand(1);
8768 if (auto *C = dyn_cast<ConstantSDNode>(RHS); C && C->getZExtValue()) {
8769 Intr = LHS.getNode();
8770 break;
8771 }
8772 [[fallthrough]];
8773 }
8774 default: {
8775 // Get the target from BR if we don't negate the condition
8776 BR = findUser(BRCOND, ISD::BR);
8777 assert(BR && "brcond missing unconditional branch user");
8778 Target = BR->getOperand(1);
8779 }
8780 }
8781
8782 unsigned CFNode = isCFIntrinsic(Intr);
8783 if (CFNode == 0) {
8784 // This is a uniform branch so we don't need to legalize.
8785 return BRCOND;
8786 }
8787
8788 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
8790
8791 assert(!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
8792 SetCC->getOperandCondCode(2) == ISD::SETNE));
8793
8794 // operands of the new intrinsic call
8796 if (HaveChain)
8797 Ops.push_back(BRCOND.getOperand(0));
8798
8799 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
8800 Ops.push_back(Target);
8801
8802 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
8803
8804 // build the new intrinsic call
8805 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
8806
8807 if (!HaveChain) {
8808 SDValue Ops[] = {SDValue(Result, 0), BRCOND.getOperand(0)};
8809
8811 }
8812
8813 if (BR) {
8814 // Give the branch instruction our target
8815 SDValue Ops[] = {BR->getOperand(0), BRCOND.getOperand(2)};
8816 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
8817 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
8818 }
8819
8820 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
8821
8822 // Copy the intrinsic results to registers
8823 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
8824 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
8825 if (!CopyToReg)
8826 continue;
8827
8828 Chain = DAG.getCopyToReg(Chain, DL, CopyToReg->getOperand(1),
8829 SDValue(Result, i - 1), SDValue());
8830
8831 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
8832 }
8833
8834 // Remove the old intrinsic from the chain
8835 DAG.ReplaceAllUsesOfValueWith(SDValue(Intr, Intr->getNumValues() - 1),
8836 Intr->getOperand(0));
8837
8838 return Chain;
8839}
8840
8841SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
8842 MVT VT = Op.getSimpleValueType();
8843 SDLoc DL(Op);
8844 // Checking the depth
8845 if (Op.getConstantOperandVal(0) != 0)
8846 return DAG.getConstant(0, DL, VT);
8847
8849 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8850 // Check for kernel and shader functions
8851 if (Info->isEntryFunction())
8852 return DAG.getConstant(0, DL, VT);
8853
8854 MachineFrameInfo &MFI = MF.getFrameInfo();
8855 // There is a call to @llvm.returnaddress in this function
8856 MFI.setReturnAddressIsTaken(true);
8857
8858 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
8859 // Get the return address reg and mark it as an implicit live-in
8860 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF),
8861 getRegClassFor(VT, Op.getNode()->isDivergent()));
8862
8863 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
8864}
8865
8866SDValue SITargetLowering::LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const {
8868 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8869
8870 // For functions that set up their own stack, select the GET_STACK_BASE
8871 // pseudo.
8872 if (MFI->isBottomOfStack())
8873 return Op;
8874
8875 // For everything else, create a dummy stack object.
8876 int FI = MF.getFrameInfo().CreateFixedObject(1, 0, /*IsImmutable=*/false);
8877 return DAG.getFrameIndex(FI, Op.getValueType());
8878}
8879
8880SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, SDValue Op,
8881 const SDLoc &DL, EVT VT) const {
8882 return Op.getValueType().bitsLE(VT)
8883 ? DAG.getNode(ISD::FP_EXTEND, DL, VT, Op)
8884 : DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
8885 DAG.getTargetConstant(0, DL, MVT::i32));
8886}
8887
8888SDValue SITargetLowering::splitFP_ROUNDVectorOp(SDValue Op,
8889 SelectionDAG &DAG) const {
8890 EVT DstVT = Op.getValueType();
8891 unsigned NumElts = DstVT.getVectorNumElements();
8892 assert(NumElts > 2 && isPowerOf2_32(NumElts));
8893
8894 auto [Lo, Hi] = DAG.SplitVectorOperand(Op.getNode(), 0);
8895
8896 SDLoc DL(Op);
8897 unsigned Opc = Op.getOpcode();
8898 SDValue Flags = Op.getOperand(1);
8899 EVT HalfDstVT =
8900 EVT::getVectorVT(*DAG.getContext(), DstVT.getScalarType(), NumElts / 2);
8901 SDValue OpLo = DAG.getNode(Opc, DL, HalfDstVT, Lo, Flags);
8902 SDValue OpHi = DAG.getNode(Opc, DL, HalfDstVT, Hi, Flags);
8903
8904 return DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, OpLo, OpHi);
8905}
8906
8907SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
8908 bool IsStrict = Op->isStrictFPOpcode();
8909 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8910 EVT SrcVT = Src.getValueType();
8911 EVT DstVT = Op.getValueType();
8912
8913 if (DstVT.isVectorOf(MVT::f16)) {
8914 assert(Subtarget->hasCvtPkF16F32Inst() && "support v_cvt_pk_f16_f32");
8915 if (SrcVT.getScalarType() != MVT::f32)
8916 return SDValue();
8917 return SrcVT == MVT::v2f32 ? Op : splitFP_ROUNDVectorOp(Op, DAG);
8918 }
8919
8920 if (SrcVT.getScalarType() != MVT::f64)
8921 return Op;
8922
8923 SDLoc DL(Op);
8924 if (DstVT == MVT::f16) {
8925 // TODO: Handle strictfp
8926 if (Op.getOpcode() != ISD::FP_ROUND)
8927 return Op;
8928
8929 if (!Subtarget->has16BitInsts()) {
8930 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
8931 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
8932 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
8933 }
8934 if (Op->getFlags().hasApproximateFuncs()) {
8935 SDValue Flags = Op.getOperand(1);
8936 SDValue Src32 = DAG.getNode(ISD::FP_ROUND, DL, MVT::f32, Src, Flags);
8937 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Src32, Flags);
8938 }
8939 SDValue FpToFp16 = LowerF64ToF16Safe(Src, DL, DAG);
8940 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
8941 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
8942 }
8943
8944 assert(DstVT.getScalarType() == MVT::bf16 &&
8945 "custom lower FP_ROUND for f16 or bf16");
8946 assert(Subtarget->hasBF16ConversionInsts() && "f32 -> bf16 is legal");
8947
8948 // Round-inexact-to-odd f64 to f32, then do the final rounding using the
8949 // hardware f32 -> bf16 instruction.
8950 EVT F32VT = SrcVT.changeElementType(*DAG.getContext(), MVT::f32);
8951 SDValue Rod = expandRoundInexactToOdd(F32VT, Src, DL, DAG);
8952 if (IsStrict) {
8953 return DAG.getNode(
8954 ISD::STRICT_FP_ROUND, DL, {DstVT, MVT::Other},
8955 {Op.getOperand(0), Rod, DAG.getTargetConstant(0, DL, MVT::i32)});
8956 }
8957 return DAG.getNode(ISD::FP_ROUND, DL, DstVT, Rod,
8958 DAG.getTargetConstant(0, DL, MVT::i32));
8959}
8960
8961SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
8962 SelectionDAG &DAG) const {
8963 EVT VT = Op.getValueType();
8964 const MachineFunction &MF = DAG.getMachineFunction();
8965 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8966 bool IsIEEEMode = Info->getMode().IEEE;
8967
8968 // FIXME: Assert during selection that this is only selected for
8969 // ieee_mode. Currently a combine can produce the ieee version for non-ieee
8970 // mode functions, but this happens to be OK since it's only done in cases
8971 // where there is known no sNaN.
8972 if (IsIEEEMode && !Subtarget->hasIEEEMinimumMaximumInsts())
8973 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
8974
8975 if (VT == MVT::v4f16 || VT == MVT::v8f16 || VT == MVT::v16f16 ||
8976 VT == MVT::v32f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16 ||
8977 VT == MVT::v16bf16 || VT == MVT::v32bf16 || VT == MVT::v4f64 ||
8978 VT == MVT::v8f64 || VT == MVT::v16f64 || VT == MVT::v32f64)
8979 return splitBinaryVectorOp(Op, DAG);
8980 return Op;
8981}
8982
8983SDValue
8984SITargetLowering::lowerFMINIMUMNUM_FMAXIMUMNUM(SDValue Op,
8985 SelectionDAG &DAG) const {
8986 EVT VT = Op.getValueType();
8987 const MachineFunction &MF = DAG.getMachineFunction();
8988 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8989 bool IsIEEEMode = Info->getMode().IEEE;
8990
8991 if (IsIEEEMode && !Subtarget->hasIEEEMinimumMaximumInsts())
8992 return expandFMINIMUMNUM_FMAXIMUMNUM(Op.getNode(), DAG);
8993
8994 if (VT == MVT::v4f16 || VT == MVT::v8f16 || VT == MVT::v16f16 ||
8995 VT == MVT::v32f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16 ||
8996 VT == MVT::v16bf16 || VT == MVT::v32bf16 || VT == MVT::v4f64 ||
8997 VT == MVT::v8f64 || VT == MVT::v16f64 || VT == MVT::v32f64)
8998 return splitBinaryVectorOp(Op, DAG);
8999 return Op;
9000}
9001
9002SDValue SITargetLowering::lowerFLDEXP(SDValue Op, SelectionDAG &DAG) const {
9003 bool IsStrict = Op.getOpcode() == ISD::STRICT_FLDEXP;
9004 EVT VT = Op.getValueType();
9005 assert(VT == MVT::f16);
9006
9007 SDValue Exp = Op.getOperand(IsStrict ? 2 : 1);
9008 EVT ExpVT = Exp.getValueType();
9009 if (ExpVT == MVT::i16)
9010 return Op;
9011
9012 SDLoc DL(Op);
9013
9014 // Correct the exponent type for f16 to i16.
9015 // Clamp the range of the exponent to the instruction's range.
9016
9017 // TODO: This should be a generic narrowing legalization, and can easily be
9018 // for GlobalISel.
9019
9020 SDValue MinExp = DAG.getSignedConstant(minIntN(16), DL, ExpVT);
9021 SDValue ClampMin = DAG.getNode(ISD::SMAX, DL, ExpVT, Exp, MinExp);
9022
9023 SDValue MaxExp = DAG.getSignedConstant(maxIntN(16), DL, ExpVT);
9024 SDValue Clamp = DAG.getNode(ISD::SMIN, DL, ExpVT, ClampMin, MaxExp);
9025
9026 SDValue TruncExp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Clamp);
9027
9028 if (IsStrict) {
9029 return DAG.getNode(ISD::STRICT_FLDEXP, DL, {VT, MVT::Other},
9030 {Op.getOperand(0), Op.getOperand(1), TruncExp});
9031 }
9032
9033 return DAG.getNode(ISD::FLDEXP, DL, VT, Op.getOperand(0), TruncExp);
9034}
9035
9037 switch (Op->getOpcode()) {
9038 case ISD::ABS:
9039 case ISD::SRA:
9040 case ISD::SMIN:
9041 case ISD::SMAX:
9042 return ISD::SIGN_EXTEND;
9043 case ISD::SRL:
9044 case ISD::UMIN:
9045 case ISD::UMAX:
9046 case ISD::USUBSAT:
9047 case ISD::UADDSAT:
9048 return ISD::ZERO_EXTEND;
9049 case ISD::ADD:
9050 case ISD::SUB:
9051 case ISD::AND:
9052 case ISD::OR:
9053 case ISD::XOR:
9054 case ISD::SHL:
9055 case ISD::SELECT:
9056 case ISD::MUL:
9057 // operation result won't be influenced by garbage high bits.
9058 // TODO: are all of those cases correct, and are there more?
9059 return ISD::ANY_EXTEND;
9060 case ISD::SETCC: {
9061 ISD::CondCode CC = Op.getOperandCondCode(2);
9063 }
9064 default:
9065 llvm_unreachable("unexpected opcode!");
9066 }
9067}
9068
9069SDValue
9070SITargetLowering::promoteUniformUnaryOpToI32(SDValue Op,
9071 DAGCombinerInfo &DCI) const {
9072 EVT OpTy = Op.getValueType();
9073 SelectionDAG &DAG = DCI.DAG;
9074 EVT ExtTy = OpTy.changeElementType(*DAG.getContext(), MVT::i32);
9075
9076 if (isNarrowingProfitable(Op.getNode(), ExtTy, OpTy))
9077 return SDValue();
9078
9079 SDLoc DL(Op);
9080 SDValue Input = Op.getOperand(0);
9081 const unsigned ExtOp = getExtOpcodeForPromotedOp(Op);
9082 Input = DAG.getNode(ExtOp, DL, ExtTy, Input);
9083
9084 SDValue NewVal = DAG.getNode(Op.getOpcode(), DL, ExtTy, Input);
9085
9086 return DAG.getNode(ISD::TRUNCATE, DL, OpTy, NewVal);
9087}
9088
9089SDValue SITargetLowering::promoteUniformOpToI32(SDValue Op,
9090 DAGCombinerInfo &DCI) const {
9091 const unsigned Opc = Op.getOpcode();
9092 assert(Opc == ISD::ADD || Opc == ISD::SUB || Opc == ISD::SHL ||
9093 Opc == ISD::SRL || Opc == ISD::SRA || Opc == ISD::AND ||
9094 Opc == ISD::OR || Opc == ISD::XOR || Opc == ISD::MUL ||
9095 Opc == ISD::SETCC || Opc == ISD::SELECT || Opc == ISD::SMIN ||
9096 Opc == ISD::SMAX || Opc == ISD::UMIN || Opc == ISD::UMAX ||
9097 Opc == ISD::USUBSAT || Opc == ISD::UADDSAT);
9098
9099 EVT OpTy = (Opc != ISD::SETCC) ? Op.getValueType()
9100 : Op->getOperand(0).getValueType();
9101 auto &DAG = DCI.DAG;
9102 auto ExtTy = OpTy.changeElementType(*DAG.getContext(), MVT::i32);
9103
9104 if (DCI.isBeforeLegalizeOps() ||
9105 isNarrowingProfitable(Op.getNode(), ExtTy, OpTy))
9106 return SDValue();
9107
9108 SDLoc DL(Op);
9109 SDValue LHS;
9110 SDValue RHS;
9111 if (Opc == ISD::SELECT) {
9112 LHS = Op->getOperand(1);
9113 RHS = Op->getOperand(2);
9114 } else {
9115 LHS = Op->getOperand(0);
9116 RHS = Op->getOperand(1);
9117 }
9118
9119 const unsigned ExtOp = getExtOpcodeForPromotedOp(Op);
9120 LHS = DAG.getNode(ExtOp, DL, ExtTy, {LHS});
9121
9122 // Special case: for shifts, the RHS always needs a zext.
9123 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
9124 RHS = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtTy, {RHS});
9125 else
9126 RHS = DAG.getNode(ExtOp, DL, ExtTy, {RHS});
9127
9128 // setcc always return i1/i1 vec so no need to truncate after.
9129 if (Opc == ISD::SETCC) {
9130 ISD::CondCode CC = Op.getOperandCondCode(2);
9131 return DAG.getSetCC(DL, Op.getValueType(), LHS, RHS, CC);
9132 }
9133
9134 // For other ops, we extend the operation's return type as well so we need to
9135 // truncate back to the original type.
9136 SDValue NewVal;
9137 if (Opc == ISD::SELECT)
9138 NewVal = DAG.getNode(ISD::SELECT, DL, ExtTy, {Op->getOperand(0), LHS, RHS});
9139 else if (Opc == ISD::UADDSAT) {
9140 SDValue Sum = DAG.getNode(ISD::ADD, DL, ExtTy, LHS, RHS);
9141 SDValue MaxVal = DAG.getConstant(
9142 APInt::getMaxValue(OpTy.getScalarSizeInBits()).zext(32), DL, ExtTy);
9143 NewVal = DAG.getNode(ISD::UMIN, DL, ExtTy, Sum, MaxVal);
9144 } else
9145 NewVal = DAG.getNode(Opc, DL, ExtTy, {LHS, RHS});
9146
9147 return DAG.getZExtOrTrunc(NewVal, DL, OpTy);
9148}
9149
9150SDValue SITargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9151 SDValue Mag = Op.getOperand(0);
9152 EVT MagVT = Mag.getValueType();
9153
9154 if (MagVT.getVectorNumElements() > 2)
9155 return splitBinaryVectorOp(Op, DAG);
9156
9157 SDValue Sign = Op.getOperand(1);
9158 EVT SignVT = Sign.getValueType();
9159
9160 if (MagVT == SignVT)
9161 return Op;
9162
9163 // fcopysign v2f16:mag, v2f32:sign ->
9164 // fcopysign v2f16:mag,
9165 // bitcast (trunc (srl (bitcast sign to v2i32), 16) to v2i16)
9166
9167 SDLoc SL(Op);
9168 SDValue SignAsInt32 = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Sign);
9169 SDValue ShiftAmt = DAG.getShiftAmountConstant(16, MVT::v2i32, SL);
9170 SDValue SignShifted =
9171 DAG.getNode(ISD::SRL, SL, MVT::v2i32, SignAsInt32, ShiftAmt);
9172 SDValue SignAsInt16 = DAG.getNode(ISD::TRUNCATE, SL, MVT::v2i16, SignShifted);
9173
9174 SDValue SignAsHalf16 = DAG.getNode(ISD::BITCAST, SL, MagVT, SignAsInt16);
9175
9176 return DAG.getNode(ISD::FCOPYSIGN, SL, MagVT, Mag, SignAsHalf16);
9177}
9178
9179// Custom lowering for vector multiplications and s_mul_u64.
9180SDValue SITargetLowering::lowerMUL(SDValue Op, SelectionDAG &DAG) const {
9181 EVT VT = Op.getValueType();
9182
9183 // Split vector operands.
9184 if (VT.isVector())
9185 return splitBinaryVectorOp(Op, DAG);
9186
9187 assert(VT == MVT::i64 && "The following code is a special for s_mul_u64");
9188
9189 // There are four ways to lower s_mul_u64:
9190 //
9191 // 1. If all the operands are uniform, then we lower it as it is.
9192 //
9193 // 2. If the operands are divergent, then we have to split s_mul_u64 in 32-bit
9194 // multiplications because there is not a vector equivalent of s_mul_u64.
9195 //
9196 // 3. If the cost model decides that it is more efficient to use vector
9197 // registers, then we have to split s_mul_u64 in 32-bit multiplications.
9198 // This happens in splitScalarSMULU64() in SIInstrInfo.cpp .
9199 //
9200 // 4. If the cost model decides to use vector registers and both of the
9201 // operands are zero-extended/sign-extended from 32-bits, then we split the
9202 // s_mul_u64 in two 32-bit multiplications. The problem is that it is not
9203 // possible to check if the operands are zero-extended or sign-extended in
9204 // SIInstrInfo.cpp. For this reason, here, we replace s_mul_u64 with
9205 // s_mul_u64_u32_pseudo if both operands are zero-extended and we replace
9206 // s_mul_u64 with s_mul_i64_i32_pseudo if both operands are sign-extended.
9207 // If the cost model decides that we have to use vector registers, then
9208 // splitScalarSMulPseudo() (in SIInstrInfo.cpp) split s_mul_u64_u32/
9209 // s_mul_i64_i32_pseudo in two vector multiplications. If the cost model
9210 // decides that we should use scalar registers, then s_mul_u64_u32_pseudo/
9211 // s_mul_i64_i32_pseudo is lowered as s_mul_u64 in expandPostRAPseudo() in
9212 // SIInstrInfo.cpp .
9213
9214 if (Op->isDivergent())
9215 return SDValue();
9216
9217 SDValue Op0 = Op.getOperand(0);
9218 SDValue Op1 = Op.getOperand(1);
9219 // If all the operands are zero-enteted to 32-bits, then we replace s_mul_u64
9220 // with s_mul_u64_u32_pseudo. If all the operands are sign-extended to
9221 // 32-bits, then we replace s_mul_u64 with s_mul_i64_i32_pseudo.
9222 KnownBits Op0KnownBits = DAG.computeKnownBits(Op0);
9223 unsigned Op0LeadingZeros = Op0KnownBits.countMinLeadingZeros();
9224 KnownBits Op1KnownBits = DAG.computeKnownBits(Op1);
9225 unsigned Op1LeadingZeros = Op1KnownBits.countMinLeadingZeros();
9226 SDLoc SL(Op);
9227 if (Op0LeadingZeros >= 32 && Op1LeadingZeros >= 32)
9228 return SDValue(
9229 DAG.getMachineNode(AMDGPU::S_MUL_U64_U32_PSEUDO, SL, VT, Op0, Op1), 0);
9230 unsigned Op0SignBits = DAG.ComputeNumSignBits(Op0);
9231 unsigned Op1SignBits = DAG.ComputeNumSignBits(Op1);
9232 if (Op0SignBits >= 33 && Op1SignBits >= 33)
9233 return SDValue(
9234 DAG.getMachineNode(AMDGPU::S_MUL_I64_I32_PSEUDO, SL, VT, Op0, Op1), 0);
9235 // If all the operands are uniform, then we lower s_mul_u64 as it is.
9236 return Op;
9237}
9238
9239SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
9240 EVT VT = Op.getValueType();
9241 SDLoc SL(Op);
9242 SDValue LHS = Op.getOperand(0);
9243 SDValue RHS = Op.getOperand(1);
9244 bool isSigned = Op.getOpcode() == ISD::SMULO;
9245
9246 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
9247 const APInt &C = RHSC->getAPIntValue();
9248 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
9249 if (C.isPowerOf2()) {
9250 // smulo(x, signed_min) is same as umulo(x, signed_min).
9251 bool UseArithShift = isSigned && !C.isMinSignedValue();
9252 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
9253 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
9254 SDValue Overflow =
9255 DAG.getSetCC(SL, MVT::i1,
9256 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, SL, VT,
9257 Result, ShiftAmt),
9258 LHS, ISD::SETNE);
9259 return DAG.getMergeValues({Result, Overflow}, SL);
9260 }
9261 }
9262
9263 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
9264 SDValue Top =
9265 DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, SL, VT, LHS, RHS);
9266
9268 ? DAG.getNode(ISD::SRA, SL, VT, Result,
9269 DAG.getConstant(VT.getScalarSizeInBits() - 1,
9270 SL, MVT::i32))
9271 : DAG.getConstant(0, SL, VT);
9272 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
9273
9274 return DAG.getMergeValues({Result, Overflow}, SL);
9275}
9276
9277SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
9278 if (Op->isDivergent()) {
9279 // Select to V_MAD_[IU]64_[IU]32.
9280 return Op;
9281 }
9282 if (Subtarget->hasSMulHi()) {
9283 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
9284 return SDValue();
9285 }
9286 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
9287 // calculate the high part, so we might as well do the whole thing with
9288 // V_MAD_[IU]64_[IU]32.
9289 return Op;
9290}
9291
9292SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
9293 if (!Subtarget->hasTrapHandler() ||
9294 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
9295 return lowerTrapEndpgm(Op, DAG);
9296
9297 return Subtarget->supportsGetDoorbellID() ? lowerTrapHsa(Op, DAG)
9298 : lowerTrapHsaQueuePtr(Op, DAG);
9299}
9300
9301SDValue SITargetLowering::lowerTrapEndpgm(SDValue Op, SelectionDAG &DAG) const {
9302 SDLoc SL(Op);
9303 SDValue Chain = Op.getOperand(0);
9304 return DAG.getNode(AMDGPUISD::ENDPGM_TRAP, SL, MVT::Other, Chain);
9305}
9306
9307SDValue
9308SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
9309 const SDLoc &DL, Align Alignment,
9310 ImplicitParameter Param) const {
9313 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
9314 MachinePointerInfo PtrInfo =
9316 return DAG.getLoad(
9317 VT, DL, DAG.getEntryNode(), Ptr, PtrInfo.getWithOffset(Offset), Alignment,
9319}
9320
9321SDValue SITargetLowering::lowerTrapHsaQueuePtr(SDValue Op,
9322 SelectionDAG &DAG) const {
9323 SDLoc SL(Op);
9324 SDValue Chain = Op.getOperand(0);
9325
9326 SDValue QueuePtr;
9327 // For code object version 5, QueuePtr is passed through implicit kernarg.
9328 const Module *M = DAG.getMachineFunction().getFunction().getParent();
9330 QueuePtr =
9331 loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
9332 } else {
9334 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9335 Register UserSGPR = Info->getQueuePtrUserSGPR();
9336
9337 if (UserSGPR == AMDGPU::NoRegister) {
9338 // We probably are in a function incorrectly marked with
9339 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
9340 // trap, so just use a null pointer.
9341 QueuePtr = DAG.getConstant(0, SL, MVT::i64);
9342 } else {
9343 QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
9344 MVT::i64);
9345 }
9346 }
9347
9348 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
9349 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, QueuePtr, SDValue());
9350
9352 SDValue Ops[] = {ToReg, DAG.getTargetConstant(TrapID, SL, MVT::i16), SGPR01,
9353 ToReg.getValue(1)};
9354 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
9355}
9356
9357SDValue SITargetLowering::lowerTrapHsa(SDValue Op, SelectionDAG &DAG) const {
9358 SDLoc SL(Op);
9359 SDValue Chain = Op.getOperand(0);
9360
9361 // We need to simulate the 's_trap 2' instruction on targets that run in
9362 // PRIV=1 (where it is treated as a nop).
9363 if (Subtarget->hasPrivEnabledTrap2NopBug())
9364 return DAG.getNode(AMDGPUISD::SIMULATED_TRAP, SL, MVT::Other, Chain);
9365
9367 SDValue Ops[] = {Chain, DAG.getTargetConstant(TrapID, SL, MVT::i16)};
9368 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
9369}
9370
9371SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
9372 SDLoc SL(Op);
9373 SDValue Chain = Op.getOperand(0);
9375
9376 if (!Subtarget->hasTrapHandler() ||
9377 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
9378 LLVMContext &Ctx = MF.getFunction().getContext();
9379 Ctx.diagnose(DiagnosticInfoUnsupported(MF.getFunction(),
9380 "debugtrap handler not supported",
9381 Op.getDebugLoc(), DS_Warning));
9382 return Chain;
9383 }
9384
9385 uint64_t TrapID =
9387 SDValue Ops[] = {Chain, DAG.getTargetConstant(TrapID, SL, MVT::i16)};
9388 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
9389}
9390
9391/// When a divergent value (in VGPR) is passed to an inline asm with an SGPR
9392/// constraint ('s'), we need to insert v_readfirstlane to move the value from
9393/// VGPR to SGPR. This is done by modifying the CopyToReg nodes in the glue
9394/// chain that feed into the INLINEASM node.
9395SDValue SITargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
9396 unsigned NumOps = Op.getNumOperands();
9397
9398 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
9399 SmallSet<Register, 8> SGPRInputRegs;
9400
9401 unsigned NumVals = 0;
9402 for (unsigned I = InlineAsm::Op_FirstOperand; I < NumOps - 1;
9403 I += 1 + NumVals) {
9404 const InlineAsm::Flag Flags(Op.getConstantOperandVal(I));
9405 NumVals = Flags.getNumOperandRegisters();
9406
9407 unsigned RCID;
9408 bool IsSGPRInput = Flags.getKind() == InlineAsm::Kind::RegUse &&
9409 NumVals > 0 && Flags.hasRegClassConstraint(RCID) &&
9410 TRI->isSGPRClass(TRI->getRegClass(RCID));
9411
9412 for (unsigned J = 0; J < NumVals; ++J) {
9413 SDValue Val = Op.getOperand(I + 1 + J);
9414 if (const RegisterSDNode *RegNode =
9416 Register Reg = RegNode->getReg();
9417 if (IsSGPRInput || (Reg.isPhysical() && TRI->isSGPRPhysReg(Reg)))
9418 SGPRInputRegs.insert(Reg);
9419 }
9420 }
9421 }
9422
9423 if (SGPRInputRegs.empty())
9424 return Op;
9425
9426 // Walk the glue chain and insert readfirstlane for divergent SGPR inputs.
9427 SDLoc DL(Op);
9428 SDNode *N = Op.getOperand(NumOps - 1).getNode();
9429
9430 while (N && N->getOpcode() == ISD::CopyToReg) {
9431 Register Reg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
9432 SDValue SrcVal = N->getOperand(2);
9433
9434 // Insert readfirstlane if copying a divergent value to an SGPR input.
9435 if (SrcVal->isDivergent() && SGPRInputRegs.count(Reg)) {
9436 SDValue ReadFirstLaneID =
9437 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
9438 SDValue ReadFirstLane =
9440 ReadFirstLaneID, SrcVal);
9441
9442 SmallVector<SDValue, 4> Ops = {N->getOperand(0), N->getOperand(1),
9443 ReadFirstLane};
9444 if (N->getNumOperands() > 3)
9445 Ops.push_back(N->getOperand(3)); // Glue input
9446
9447 DAG.UpdateNodeOperands(N, Ops);
9448 }
9449
9450 // Follow glue chain to next CopyToReg.
9451 SDNode *Next = nullptr;
9452 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I) {
9453 if (N->getOperand(I).getValueType() == MVT::Glue) {
9454 Next = N->getOperand(I).getNode();
9455 break;
9456 }
9457 }
9458 N = Next;
9459 }
9460
9461 return Op;
9462}
9463
9464SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
9465 SelectionDAG &DAG) const {
9466 unsigned BaseAS = AS;
9467 unsigned SANum = AMDGPU::getSyntheticApertureNumber(AS);
9469 BaseAS = AMDGPUAS::LOCAL_ADDRESS;
9470
9471 SDValue Aperture = getBaseSegmentAperture(BaseAS, DL, DAG);
9472
9473 if (SANum != AMDGPU::SyntheticAperture::None) {
9474 SDValue Tag = DAG.getConstant(SANum, DL, MVT::i32);
9475 return DAG.getNode(ISD::OR, DL, MVT::i32, Aperture, Tag);
9476 }
9477
9478 return Aperture;
9479}
9480
9481SDValue SITargetLowering::getBaseSegmentAperture(unsigned AS, const SDLoc &DL,
9482 SelectionDAG &DAG) const {
9483 const bool IsLDS = (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::BARRIER);
9484
9485 if (Subtarget->hasApertureRegs()) {
9486 const unsigned ApertureRegNo =
9487 IsLDS ? AMDGPU::SRC_SHARED_BASE : AMDGPU::SRC_PRIVATE_BASE;
9488 assert((ApertureRegNo != AMDGPU::SRC_PRIVATE_BASE ||
9489 !Subtarget->hasGloballyAddressableScratch()) &&
9490 "Cannot use src_private_base with globally addressable scratch!");
9491 // Note: this feature (register) is broken. When used as a 32-bit operand,
9492 // it returns a wrong value (all zeroes?). The real value is in the upper 32
9493 // bits.
9494 //
9495 // To work around the issue, emit a 64 bit copy from this register
9496 // then extract the high bits. Note that this shouldn't even result in a
9497 // shift being emitted and simply become a pair of registers (e.g.):
9498 // s_mov_b64 s[6:7], src_shared_base
9499 // v_mov_b32_e32 v1, s7
9500 SDValue Copy =
9501 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ApertureRegNo, MVT::v2i32);
9502 return DAG.getExtractVectorElt(DL, MVT::i32, Copy, 1);
9503 }
9504
9505 // For code object version 5, private_base and shared_base are passed through
9506 // implicit kernargs.
9507 const Module *M = DAG.getMachineFunction().getFunction().getParent();
9510 return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
9511 }
9512
9514 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9515 Register UserSGPR = Info->getQueuePtrUserSGPR();
9516 if (UserSGPR == AMDGPU::NoRegister) {
9517 // We probably are in a function incorrectly marked with
9518 // amdgpu-no-queue-ptr. This is undefined.
9519 return DAG.getPOISON(MVT::i32);
9520 }
9521
9522 SDValue QueuePtr =
9523 CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
9524
9525 // Offset into amd_queue_t for group_segment_aperture_base_hi /
9526 // private_segment_aperture_base_hi.
9527 uint32_t StructOffset = IsLDS ? 0x40 : 0x44;
9528
9529 SDValue Ptr =
9530 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::getFixed(StructOffset));
9531
9532 // TODO: Use custom target PseudoSourceValue.
9533 // TODO: We should use the value from the IR intrinsic call, but it might not
9534 // be available and how do we get it?
9535 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
9536 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
9537 commonAlignment(Align(64), StructOffset),
9540}
9541
9542/// Return true if the value is a known valid address, such that a null check is
9543/// not necessary.
9545 const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
9547 return true;
9548
9549 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
9550 return ConstVal->getSExtValue() != AMDGPU::getNullPointerValue(AddrSpace);
9551
9552 // TODO: Search through arithmetic, handle arguments and loads
9553 // marked nonnull.
9554 return false;
9555}
9556
9557SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
9558 SelectionDAG &DAG) const {
9559 SDLoc SL(Op);
9560
9561 const AMDGPUTargetMachine &TM =
9562 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
9563
9564 const auto *ASC = cast<AddrSpaceCastSDNode>(Op);
9565 unsigned SrcAS = ASC->getSrcAddressSpace();
9566 SDValue Src = ASC->getOperand(0);
9567 unsigned DestAS = ASC->getDestAddressSpace();
9568 bool IsNonNull = ASC->getFlags().hasNonNull();
9569
9570 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
9571
9572 // flat -> local/private/barrier/vgpr
9573 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
9574 if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
9575 DestAS == AMDGPUAS::PRIVATE_ADDRESS || DestAS == AMDGPUAS::BARRIER ||
9576 DestAS == AMDGPUAS::VGPR) {
9577 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
9578
9579 if (DestAS == AMDGPUAS::PRIVATE_ADDRESS &&
9580 Subtarget->hasGloballyAddressableScratch()) {
9581 // flat -> private with globally addressable scratch: subtract
9582 // src_flat_scratch_base_lo.
9583 SDValue FlatScratchBaseLo(
9584 DAG.getMachineNode(
9585 AMDGPU::S_MOV_B32, SL, MVT::i32,
9586 DAG.getRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE_LO, MVT::i32)),
9587 0);
9588 Ptr = DAG.getNode(ISD::SUB, SL, MVT::i32, Ptr, FlatScratchBaseLo);
9589 }
9590
9591 if (IsNonNull || isKnownNonNull(Src, DAG, TM, SrcAS))
9592 return Ptr;
9593
9594 unsigned NullVal = AMDGPU::getNullPointerValue(DestAS);
9595 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
9596 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
9597
9598 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
9599 SegmentNullPtr);
9600 }
9601 }
9602
9603 // local/private/barrier/vgpr -> flat
9604 if (DestAS == AMDGPUAS::FLAT_ADDRESS) {
9605 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
9606 SrcAS == AMDGPUAS::PRIVATE_ADDRESS || SrcAS == AMDGPUAS::BARRIER ||
9607 SrcAS == AMDGPUAS::VGPR) {
9608 SDValue CvtPtr;
9609 if (SrcAS == AMDGPUAS::PRIVATE_ADDRESS &&
9610 Subtarget->hasGloballyAddressableScratch()) {
9611 // For wave32: Addr = (TID[4:0] << 52) + FLAT_SCRATCH_BASE + privateAddr
9612 // For wave64: Addr = (TID[5:0] << 51) + FLAT_SCRATCH_BASE + privateAddr
9613 SDValue AllOnes = DAG.getSignedTargetConstant(-1, SL, MVT::i32);
9614 SDValue ThreadID = DAG.getConstant(0, SL, MVT::i32);
9615 ThreadID = DAG.getNode(
9616 ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
9617 DAG.getTargetConstant(Intrinsic::amdgcn_mbcnt_lo, SL, MVT::i32),
9618 AllOnes, ThreadID);
9619 if (Subtarget->isWave64())
9620 ThreadID = DAG.getNode(
9621 ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
9622 DAG.getTargetConstant(Intrinsic::amdgcn_mbcnt_hi, SL, MVT::i32),
9623 AllOnes, ThreadID);
9624 SDValue ShAmt = DAG.getShiftAmountConstant(
9625 57 - 32 - Subtarget->getWavefrontSizeLog2(), MVT::i32, SL);
9626 SDValue SrcHi = DAG.getNode(ISD::SHL, SL, MVT::i32, ThreadID, ShAmt);
9627 CvtPtr = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, SrcHi);
9628 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
9629 // Accessing src_flat_scratch_base_lo as a 64-bit operand gives the full
9630 // 64-bit hi:lo value.
9631 SDValue FlatScratchBase = {
9632 DAG.getMachineNode(
9633 AMDGPU::S_MOV_B64, SL, MVT::i64,
9634 DAG.getRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE, MVT::i64)),
9635 0};
9636 CvtPtr = DAG.getNode(ISD::ADD, SL, MVT::i64, CvtPtr, FlatScratchBase);
9637 } else {
9638 SDValue Aperture = getSegmentAperture(SrcAS, SL, DAG);
9639
9640 CvtPtr = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
9641 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
9642 }
9643
9644 if (IsNonNull || isKnownNonNull(Src, DAG, TM, SrcAS))
9645 return CvtPtr;
9646
9647 unsigned NullVal = AMDGPU::getNullPointerValue(SrcAS);
9648 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
9649
9650 SDValue NonNull =
9651 DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
9652
9653 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
9654 FlatNullPtr);
9655 }
9656 }
9657
9658 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
9659 Op.getValueType() == MVT::i64) {
9660 const SIMachineFunctionInfo *Info =
9661 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
9662 if (Info->get32BitAddressHighBits() == 0)
9663 return DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i64, Src);
9664
9665 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
9666 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
9667 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9668 }
9669
9670 if (DestAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
9671 Src.getValueType() == MVT::i64)
9672 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
9673
9674 // global <-> flat are no-ops and never emitted.
9675
9676 // Invalid casts are poison.
9677 return DAG.getPOISON(Op->getValueType(0));
9678}
9679
9680// This lowers an INSERT_SUBVECTOR by extracting the individual elements from
9681// the small vector and inserting them into the big vector. That is better than
9682// the default expansion of doing it via a stack slot. Even though the use of
9683// the stack slot would be optimized away afterwards, the stack slot itself
9684// remains.
9685SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
9686 SelectionDAG &DAG) const {
9687 SDValue Vec = Op.getOperand(0);
9688 SDValue Ins = Op.getOperand(1);
9689 SDValue Idx = Op.getOperand(2);
9690 EVT VecVT = Vec.getValueType();
9691 EVT InsVT = Ins.getValueType();
9692 EVT EltVT = VecVT.getVectorElementType();
9693 unsigned InsNumElts = InsVT.getVectorNumElements();
9694 unsigned IdxVal = Idx->getAsZExtVal();
9695 SDLoc SL(Op);
9696
9697 if (EltVT.getScalarSizeInBits() == 16 && IdxVal % 2 == 0) {
9698 // Insert 32-bit registers at a time.
9699 assert(InsNumElts % 2 == 0 && "expect legal vector types");
9700
9701 unsigned VecNumElts = VecVT.getVectorNumElements();
9702 EVT NewVecVT =
9703 EVT::getVectorVT(*DAG.getContext(), MVT::i32, VecNumElts / 2);
9704 EVT NewInsVT = InsNumElts == 2 ? MVT::i32
9706 MVT::i32, InsNumElts / 2);
9707
9708 Vec = DAG.getNode(ISD::BITCAST, SL, NewVecVT, Vec);
9709 Ins = DAG.getNode(ISD::BITCAST, SL, NewInsVT, Ins);
9710
9711 for (unsigned I = 0; I != InsNumElts / 2; ++I) {
9712 SDValue Elt;
9713 if (InsNumElts == 2) {
9714 Elt = Ins;
9715 } else {
9716 Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Ins,
9717 DAG.getConstant(I, SL, MVT::i32));
9718 }
9719 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NewVecVT, Vec, Elt,
9720 DAG.getConstant(IdxVal / 2 + I, SL, MVT::i32));
9721 }
9722
9723 return DAG.getNode(ISD::BITCAST, SL, VecVT, Vec);
9724 }
9725
9726 for (unsigned I = 0; I != InsNumElts; ++I) {
9727 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
9728 DAG.getConstant(I, SL, MVT::i32));
9729 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
9730 DAG.getConstant(IdxVal + I, SL, MVT::i32));
9731 }
9732 return Vec;
9733}
9734
9735SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
9736 SelectionDAG &DAG) const {
9737 SDValue Vec = Op.getOperand(0);
9738 SDValue InsVal = Op.getOperand(1);
9739 SDValue Idx = Op.getOperand(2);
9740 EVT VecVT = Vec.getValueType();
9741 EVT EltVT = VecVT.getVectorElementType();
9742 unsigned VecSize = VecVT.getSizeInBits();
9743 unsigned EltSize = EltVT.getSizeInBits();
9744 SDLoc SL(Op);
9745
9746 // Specially handle the case of v4i16 with static indexing.
9747 unsigned NumElts = VecVT.getVectorNumElements();
9748 auto *KIdx = dyn_cast<ConstantSDNode>(Idx);
9749 if (NumElts == 4 && EltSize == 16 && KIdx) {
9750 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
9751
9752 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
9753 DAG.getConstant(0, SL, MVT::i32));
9754 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
9755 DAG.getConstant(1, SL, MVT::i32));
9756
9757 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
9758 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
9759
9760 unsigned Idx = KIdx->getZExtValue();
9761 bool InsertLo = Idx < 2;
9762 SDValue InsHalf = DAG.getNode(
9763 ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, InsertLo ? LoVec : HiVec,
9764 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
9765 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
9766
9767 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
9768
9769 SDValue Concat =
9770 InsertLo ? DAG.getBuildVector(MVT::v2i32, SL, {InsHalf, HiHalf})
9771 : DAG.getBuildVector(MVT::v2i32, SL, {LoHalf, InsHalf});
9772
9773 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
9774 }
9775
9776 // Static indexing does not lower to stack access, and hence there is no need
9777 // for special custom lowering to avoid stack access.
9778 if (isa<ConstantSDNode>(Idx))
9779 return SDValue();
9780
9781 // Avoid stack access for dynamic indexing by custom lowering to
9782 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
9783 // Vectors wider than 64 bits do this on each 64-bit piece.
9784 assert(isPowerOf2_32(EltSize));
9785 unsigned PieceSize = std::min(VecSize, 64u);
9786 unsigned NumPieces = VecSize / PieceSize;
9787 unsigned EltsPerPiece = PieceSize / EltSize;
9788 MVT IntVT = MVT::getIntegerVT(PieceSize);
9789 EVT PieceVT = EVT::getVectorVT(*DAG.getContext(), EltVT, EltsPerPiece);
9790
9791 // Convert vector index to bit-index within its piece and get the required
9792 // bit mask. Using the index within the piece keeps the shift below 64.
9793 SDValue PieceIdx = Idx;
9794 if (NumPieces > 1)
9795 PieceIdx = DAG.getNode(ISD::AND, SL, MVT::i32, Idx,
9796 DAG.getConstant(EltsPerPiece - 1, SL, MVT::i32));
9797 const auto EltMask = maskTrailingOnes<uint64_t>(EltSize);
9798 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
9799 SDValue ScaledIdx =
9800 DAG.getNode(ISD::SHL, SL, MVT::i32, PieceIdx, ScaleFactor);
9801 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
9802 DAG.getConstant(EltMask, SL, IntVT), ScaledIdx);
9803
9804 // 1. Create a congruent vector with the target value in each element.
9805 SDValue ExtVal =
9806 DAG.getBitcast(IntVT, DAG.getSplatBuildVector(PieceVT, SL, InsVal));
9807
9808 auto InsertIntoPiece = [&](SDValue Piece, SDValue Mask) {
9809 // 2. Mask off all other indices except the required index within (1).
9810 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, Mask, ExtVal);
9811
9812 // 3. Mask off the required index within the target vector.
9813 SDValue RHS =
9814 DAG.getNode(ISD::AND, SL, IntVT, DAG.getNOT(SL, Mask, IntVT), Piece);
9815
9816 // 4. Get (2) and (3) ORed into the target vector.
9817 return DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS, SDNodeFlags::Disjoint);
9818 };
9819
9820 if (NumPieces == 1)
9821 return DAG.getBitcast(VecVT,
9822 InsertIntoPiece(DAG.getBitcast(IntVT, Vec), BFM));
9823
9824 // 5. Apply (2)-(4) to each 64-bit piece, with the mask cleared in every
9825 // piece except the one that holds the index, and rebuild the vector.
9826 MVT PiecesVT = MVT::getVectorVT(IntVT, NumPieces);
9827 SDValue BCVec = DAG.getBitcast(PiecesVT, Vec);
9828 SDValue PieceNo =
9829 DAG.getNode(ISD::SRL, SL, MVT::i32, Idx,
9830 DAG.getConstant(Log2_32(EltsPerPiece), SL, MVT::i32));
9831 SDValue Zero = DAG.getConstant(0, SL, IntVT);
9833 Pieces.reserve(NumPieces);
9834 for (unsigned I = 0; I != NumPieces; ++I) {
9835 SDValue CurPieceNo = DAG.getConstant(I, SL, MVT::i32);
9836 SDValue Piece =
9837 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, IntVT, BCVec, CurPieceNo);
9838 SDValue Mask =
9839 DAG.getSelectCC(SL, PieceNo, CurPieceNo, BFM, Zero, ISD::SETEQ);
9840 Pieces.push_back(InsertIntoPiece(Piece, Mask));
9841 }
9842
9843 return DAG.getBitcast(VecVT, DAG.getBuildVector(PiecesVT, SL, Pieces));
9844}
9845
9846SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
9847 SelectionDAG &DAG) const {
9848 SDLoc SL(Op);
9849
9850 EVT ResultVT = Op.getValueType();
9851 SDValue Vec = Op.getOperand(0);
9852 SDValue Idx = Op.getOperand(1);
9853 EVT VecVT = Vec.getValueType();
9854 unsigned VecSize = VecVT.getSizeInBits();
9855 EVT EltVT = VecVT.getVectorElementType();
9856
9857 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
9858
9859 // Make sure we do any optimizations that will make it easier to fold
9860 // source modifiers before obscuring it with bit operations.
9861
9862 // XXX - Why doesn't this get called when vector_shuffle is expanded?
9863 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
9864 return Combined;
9865
9866 if (VecSize == 128 || VecSize == 256 || VecSize == 512) {
9867 SDValue Lo, Hi;
9868 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VecVT);
9869
9870 if (VecSize == 128) {
9871 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
9872 Lo = DAG.getBitcast(LoVT,
9873 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
9874 DAG.getConstant(0, SL, MVT::i32)));
9875 Hi = DAG.getBitcast(HiVT,
9876 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
9877 DAG.getConstant(1, SL, MVT::i32)));
9878 } else if (VecSize == 256) {
9879 SDValue V2 = DAG.getBitcast(MVT::v4i64, Vec);
9880 SDValue Parts[4];
9881 for (unsigned P = 0; P < 4; ++P) {
9882 Parts[P] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
9883 DAG.getConstant(P, SL, MVT::i32));
9884 }
9885
9886 Lo = DAG.getBitcast(LoVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
9887 Parts[0], Parts[1]));
9888 Hi = DAG.getBitcast(HiVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
9889 Parts[2], Parts[3]));
9890 } else {
9891 assert(VecSize == 512);
9892
9893 SDValue V2 = DAG.getBitcast(MVT::v8i64, Vec);
9894 SDValue Parts[8];
9895 for (unsigned P = 0; P < 8; ++P) {
9896 Parts[P] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
9897 DAG.getConstant(P, SL, MVT::i32));
9898 }
9899
9900 Lo = DAG.getBitcast(LoVT,
9901 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v4i64,
9902 Parts[0], Parts[1], Parts[2], Parts[3]));
9903 Hi = DAG.getBitcast(HiVT,
9904 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v4i64,
9905 Parts[4], Parts[5], Parts[6], Parts[7]));
9906 }
9907
9908 EVT IdxVT = Idx.getValueType();
9909 unsigned NElem = VecVT.getVectorNumElements();
9910 assert(isPowerOf2_32(NElem));
9911 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
9912 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
9913 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
9914 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
9915 }
9916
9917 assert(VecSize <= 64);
9918
9919 MVT IntVT = MVT::getIntegerVT(VecSize);
9920
9921 // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly.
9922 SDValue VecBC = peekThroughBitcasts(Vec);
9923 if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9924 SDValue Src = VecBC.getOperand(0);
9925 Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src);
9926 Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT);
9927 }
9928
9929 unsigned EltSize = EltVT.getSizeInBits();
9930 assert(isPowerOf2_32(EltSize));
9931
9932 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
9933
9934 // Convert vector index to bit-index (* EltSize)
9935 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
9936
9937 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
9938 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
9939
9940 if (ResultVT == MVT::f16 || ResultVT == MVT::bf16) {
9941 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
9942 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
9943 }
9944
9945 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
9946}
9947
9948static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
9949 assert(Elt % 2 == 0);
9950 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
9951}
9952
9953static bool elementPairIsOddToEven(ArrayRef<int> Mask, int Elt) {
9954 assert(Elt % 2 == 0);
9955 return Mask[Elt] >= 0 && Mask[Elt + 1] >= 0 && (Mask[Elt] & 1) &&
9956 !(Mask[Elt + 1] & 1);
9957}
9958
9959SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
9960 SelectionDAG &DAG) const {
9961 SDLoc SL(Op);
9962 EVT ResultVT = Op.getValueType();
9963 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
9964 MVT EltVT = ResultVT.getVectorElementType().getSimpleVT();
9965 const int NewSrcNumElts = 2;
9966 MVT PackVT = MVT::getVectorVT(EltVT, NewSrcNumElts);
9967 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
9968
9969 // Break up the shuffle into registers sized pieces.
9970 //
9971 // We're trying to form sub-shuffles that the register allocation pipeline
9972 // won't be able to figure out, like how to use v_pk_mov_b32 to do a register
9973 // blend or 16-bit op_sel. It should be able to figure out how to reassemble a
9974 // pair of copies into a consecutive register copy, so use the ordinary
9975 // extract_vector_elt lowering unless we can use the shuffle.
9976 //
9977 // TODO: This is a bit of hack, and we should probably always use
9978 // extract_subvector for the largest possible subvector we can (or at least
9979 // use it for PackVT aligned pieces). However we have worse support for
9980 // combines on them don't directly treat extract_subvector / insert_subvector
9981 // as legal. The DAG scheduler also ends up doing a worse job with the
9982 // extract_subvectors.
9983 const bool ShouldUseConsecutiveExtract = EltVT.getSizeInBits() == 16;
9984
9985 // vector_shuffle <0,1,6,7> lhs, rhs
9986 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
9987 //
9988 // vector_shuffle <6,7,2,3> lhs, rhs
9989 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
9990 //
9991 // vector_shuffle <6,7,0,1> lhs, rhs
9992 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
9993
9994 // Avoid scalarizing when both halves are reading from consecutive elements.
9995
9996 // If we're treating 2 element shuffles as legal, also create odd-to-even
9997 // shuffles of neighboring pairs.
9998 //
9999 // vector_shuffle <3,2,7,6> lhs, rhs
10000 // -> concat_vectors vector_shuffle <1, 0> (extract_subvector lhs, 0)
10001 // vector_shuffle <1, 0> (extract_subvector rhs, 2)
10002
10004 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
10005 if (ShouldUseConsecutiveExtract &&
10007 const int Idx = SVN->getMaskElt(I);
10008 int VecIdx = Idx < SrcNumElts ? 0 : 1;
10009 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
10010 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, PackVT,
10011 SVN->getOperand(VecIdx),
10012 DAG.getConstant(EltIdx, SL, MVT::i32));
10013 Pieces.push_back(SubVec);
10014 } else if (elementPairIsOddToEven(SVN->getMask(), I) &&
10016 int Idx0 = SVN->getMaskElt(I);
10017 int Idx1 = SVN->getMaskElt(I + 1);
10018
10019 SDValue SrcOp0 = SVN->getOperand(0);
10020 SDValue SrcOp1 = SrcOp0;
10021 if (Idx0 >= SrcNumElts) {
10022 SrcOp0 = SVN->getOperand(1);
10023 Idx0 -= SrcNumElts;
10024 }
10025
10026 if (Idx1 >= SrcNumElts) {
10027 SrcOp1 = SVN->getOperand(1);
10028 Idx1 -= SrcNumElts;
10029 }
10030
10031 int AlignedIdx0 = Idx0 & ~(NewSrcNumElts - 1);
10032 int AlignedIdx1 = Idx1 & ~(NewSrcNumElts - 1);
10033
10034 // Extract nearest even aligned piece.
10035 SDValue SubVec0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, PackVT, SrcOp0,
10036 DAG.getConstant(AlignedIdx0, SL, MVT::i32));
10037 SDValue SubVec1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, PackVT, SrcOp1,
10038 DAG.getConstant(AlignedIdx1, SL, MVT::i32));
10039
10040 int NewMaskIdx0 = Idx0 - AlignedIdx0;
10041 int NewMaskIdx1 = Idx1 - AlignedIdx1;
10042
10043 SDValue Result0 = SubVec0;
10044 SDValue Result1 = SubVec0;
10045
10046 if (SubVec0 != SubVec1) {
10047 NewMaskIdx1 += NewSrcNumElts;
10048 Result1 = SubVec1;
10049 } else {
10050 Result1 = DAG.getPOISON(PackVT);
10051 }
10052
10053 SDValue Shuf = DAG.getVectorShuffle(PackVT, SL, Result0, Result1,
10054 {NewMaskIdx0, NewMaskIdx1});
10055 Pieces.push_back(Shuf);
10056 } else {
10057 const int Idx0 = SVN->getMaskElt(I);
10058 const int Idx1 = SVN->getMaskElt(I + 1);
10059 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
10060 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
10061 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
10062 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
10063
10064 SDValue Vec0 = SVN->getOperand(VecIdx0);
10065 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec0,
10066 DAG.getSignedConstant(EltIdx0, SL, MVT::i32));
10067
10068 SDValue Vec1 = SVN->getOperand(VecIdx1);
10069 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec1,
10070 DAG.getSignedConstant(EltIdx1, SL, MVT::i32));
10071 Pieces.push_back(DAG.getBuildVector(PackVT, SL, {Elt0, Elt1}));
10072 }
10073 }
10074
10075 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
10076}
10077
10078SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
10079 SelectionDAG &DAG) const {
10080 SDValue SVal = Op.getOperand(0);
10081 EVT ResultVT = Op.getValueType();
10082 EVT SValVT = SVal.getValueType();
10083 SDValue UndefVal = DAG.getPOISON(SValVT);
10084 SDLoc SL(Op);
10085
10087 VElts.push_back(SVal);
10088 for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I)
10089 VElts.push_back(UndefVal);
10090
10091 return DAG.getBuildVector(ResultVT, SL, VElts);
10092}
10093
10094SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
10095 SelectionDAG &DAG) const {
10096 SDLoc SL(Op);
10097 EVT VT = Op.getValueType();
10098
10099 if (VT == MVT::v2f16 || VT == MVT::v2i16 || VT == MVT::v2bf16) {
10100 assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
10101
10102 SDValue Lo = Op.getOperand(0);
10103 SDValue Hi = Op.getOperand(1);
10104
10105 // Avoid adding defined bits with the zero_extend.
10106 if (Hi.isUndef()) {
10107 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
10108 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
10109 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
10110 }
10111
10112 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
10113 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
10114
10115 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
10116 DAG.getConstant(16, SL, MVT::i32));
10117 if (Lo.isUndef())
10118 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
10119
10120 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
10121 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
10122
10123 SDValue Or =
10124 DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi, SDNodeFlags::Disjoint);
10125 return DAG.getNode(ISD::BITCAST, SL, VT, Or);
10126 }
10127
10128 // Split into 2-element chunks.
10129 const unsigned NumParts = VT.getVectorNumElements() / 2;
10130 EVT PartVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
10131 MVT PartIntVT = MVT::getIntegerVT(PartVT.getSizeInBits());
10132
10134 for (unsigned P = 0; P < NumParts; ++P) {
10135 SDValue Vec = DAG.getBuildVector(
10136 PartVT, SL, {Op.getOperand(P * 2), Op.getOperand(P * 2 + 1)});
10137 Casts.push_back(DAG.getNode(ISD::BITCAST, SL, PartIntVT, Vec));
10138 }
10139
10140 SDValue Blend =
10141 DAG.getBuildVector(MVT::getVectorVT(PartIntVT, NumParts), SL, Casts);
10142 return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
10143}
10144
10146 const GlobalAddressSDNode *GA) const {
10147 // Named barriers have fixed, non-relocated LDS addresses, so a constant
10148 // offset into an array of them can be folded into the address.
10150 const auto *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
10151 return GV && AMDGPU::isNamedBarrier(*GV);
10152 }
10153
10154 // OSes that use ELF REL relocations (instead of RELA) can only store a
10155 // 32-bit addend in the instruction, so it is not safe to allow offset folding
10156 // which can create arbitrary 64-bit addends. (This is only a problem for
10157 // R_AMDGPU_*32_HI relocations since other relocation types are unaffected by
10158 // the high 32 bits of the addend.)
10159 //
10160 // This should be kept in sync with how HasRelocationAddend is initialized in
10161 // the constructor of ELFAMDGPUAsmBackend.
10162 if (!Subtarget->isAmdHsaOS())
10163 return false;
10164
10165 // We can fold offsets for anything that doesn't require a GOT relocation.
10166 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
10170}
10171
10172static SDValue
10174 const SDLoc &DL, int64_t Offset, EVT PtrVT,
10175 unsigned GAFlags = SIInstrInfo::MO_NONE) {
10176 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
10177 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
10178 // lowered to the following code sequence:
10179 //
10180 // For constant address space:
10181 // s_getpc_b64 s[0:1]
10182 // s_add_u32 s0, s0, $symbol
10183 // s_addc_u32 s1, s1, 0
10184 //
10185 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
10186 // a fixup or relocation is emitted to replace $symbol with a literal
10187 // constant, which is a pc-relative offset from the encoding of the $symbol
10188 // operand to the global variable.
10189 //
10190 // For global address space:
10191 // s_getpc_b64 s[0:1]
10192 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
10193 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
10194 //
10195 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
10196 // fixups or relocations are emitted to replace $symbol@*@lo and
10197 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
10198 // which is a 64-bit pc-relative offset from the encoding of the $symbol
10199 // operand to the global variable.
10200 if (((const GCNSubtarget &)DAG.getSubtarget()).has64BitLiterals()) {
10201 assert(GAFlags != SIInstrInfo::MO_NONE);
10202
10203 SDValue Ptr =
10204 DAG.getTargetGlobalAddress(GV, DL, MVT::i64, Offset, GAFlags + 2);
10205 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET64, DL, PtrVT, Ptr);
10206 }
10207
10208 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset, GAFlags);
10209 SDValue PtrHi;
10210 if (GAFlags == SIInstrInfo::MO_NONE)
10211 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
10212 else
10213 PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset, GAFlags + 1);
10214 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
10215}
10216
10217SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunctionInfo *MFI,
10218 SDValue Op,
10219 SelectionDAG &DAG) const {
10220 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
10221 SDLoc DL(GSD);
10222 EVT PtrVT = Op.getValueType();
10223
10224 const GlobalValue *GV = GSD->getGlobal();
10225 const unsigned AS = GSD->getAddressSpace();
10226 if (((AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::BARRIER) &&
10229 if (AS == AMDGPUAS::LOCAL_ADDRESS && GV->hasExternalLinkage()) {
10230 const GlobalVariable &GVar = *cast<GlobalVariable>(GV);
10231 // HIP uses an unsized array `extern __shared__ T s[]` or similar
10232 // zero-sized type in other languages to declare the dynamic shared
10233 // memory which size is not known at the compile time. They will be
10234 // allocated by the runtime and placed directly after the static
10235 // allocated ones. They all share the same offset.
10236 if (GVar.getGlobalSize(GVar.getDataLayout()) == 0) {
10237 assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
10238 // Adjust alignment for that dynamic shared memory array.
10240 MFI->setDynLDSAlign(F, GVar);
10241 MFI->setUsesDynamicLDS(true);
10242 return SDValue(
10243 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
10244 }
10245 }
10247 }
10248
10249 if (AS == AMDGPUAS::BARRIER) {
10250 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
10252 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0);
10253 }
10254
10255 if (AS == AMDGPUAS::LOCAL_ADDRESS) {
10256 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
10258 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
10259 }
10260
10261 if (Subtarget->isAmdPalOS() || Subtarget->isMesa3DOS()) {
10262 if (Subtarget->has64BitLiterals()) {
10264 GV, DL, MVT::i64, GSD->getOffset(), SIInstrInfo::MO_ABS64);
10265 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Addr),
10266 0);
10267 }
10268
10269 SDValue AddrLo = DAG.getTargetGlobalAddress(
10270 GV, DL, MVT::i32, GSD->getOffset(), SIInstrInfo::MO_ABS32_LO);
10271 AddrLo = {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, AddrLo), 0};
10272
10273 SDValue AddrHi = DAG.getTargetGlobalAddress(
10274 GV, DL, MVT::i32, GSD->getOffset(), SIInstrInfo::MO_ABS32_HI);
10275 AddrHi = {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, AddrHi), 0};
10276
10277 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, AddrLo, AddrHi);
10278 }
10279
10280 if (shouldEmitFixup(GV))
10281 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
10282
10283 if (shouldEmitPCReloc(GV))
10284 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
10286
10287 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
10289 PointerType *PtrTy =
10291 const DataLayout &DataLayout = DAG.getDataLayout();
10292 Align Alignment = DataLayout.getABITypeAlign(PtrTy);
10293 MachinePointerInfo PtrInfo =
10295
10296 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
10299}
10300
10301// An alloca in the VGPR ("as memory") address space has no registers to live
10302// in, so its stack offset must not be taken for a register address. Every
10303// other frame index keeps its default lowering.
10304SDValue SITargetLowering::lowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
10306 int FI = cast<FrameIndexSDNode>(Op)->getIndex();
10307 const AllocaInst *Alloca = MF.getFrameInfo().getObjectAllocation(FI);
10308 if (!Alloca || Alloca->getAddressSpace() != AMDGPUAS::VGPR)
10309 return SDValue();
10310
10311 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
10312 MF.getFunction(),
10313 "unsupported alloca in VGPR 'as memory' address space (13)",
10314 Alloca->getDebugLoc()));
10315 return DAG.getPOISON(MVT::i32);
10316}
10317
10318SDValue SITargetLowering::LowerExternalSymbol(SDValue Op,
10319 SelectionDAG &DAG) const {
10320 // TODO: Handle this. It should be mostly the same as LowerGlobalAddress.
10321 const Function &Fn = DAG.getMachineFunction().getFunction();
10322 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
10323 Fn, "unsupported external symbol", Op.getDebugLoc()));
10324 return DAG.getPOISON(Op.getValueType());
10325}
10326
10328 const SDLoc &DL, SDValue V) const {
10329 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
10330 // the destination register.
10331 //
10332 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
10333 // so we will end up with redundant moves to m0.
10334 //
10335 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
10336
10337 // A Null SDValue creates a glue result.
10338 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
10339 V, Chain);
10340 return SDValue(M0, 0);
10341}
10342
10343SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, SDValue Op,
10344 MVT VT,
10345 unsigned Offset) const {
10346 SDLoc SL(Op);
10347 SDValue Param = lowerKernargMemParameter(
10348 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
10349 // The local size values will have the hi 16-bits as zero.
10350 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
10351 DAG.getValueType(VT));
10352}
10353
10355 EVT VT) {
10358 "non-hsa intrinsic with hsa target", DL.getDebugLoc()));
10359 return DAG.getPOISON(VT);
10360}
10361
10363 EVT VT) {
10366 "intrinsic not supported on subtarget", DL.getDebugLoc()));
10367 return DAG.getPOISON(VT);
10368}
10369
10371 ArrayRef<SDValue> Elts) {
10372 assert(!Elts.empty());
10373 MVT Type;
10374 unsigned NumElts = Elts.size();
10375
10376 if (NumElts <= 12) {
10377 Type = MVT::getVectorVT(MVT::f32, NumElts);
10378 } else {
10379 assert(Elts.size() <= 16);
10380 Type = MVT::v16f32;
10381 NumElts = 16;
10382 }
10383
10384 SmallVector<SDValue, 16> VecElts(NumElts);
10385 for (unsigned i = 0; i < Elts.size(); ++i) {
10386 SDValue Elt = Elts[i];
10387 if (Elt.getValueType() != MVT::f32)
10388 Elt = DAG.getBitcast(MVT::f32, Elt);
10389 VecElts[i] = Elt;
10390 }
10391 for (unsigned i = Elts.size(); i < NumElts; ++i)
10392 VecElts[i] = DAG.getPOISON(MVT::f32);
10393
10394 if (NumElts == 1)
10395 return VecElts[0];
10396 return DAG.getBuildVector(Type, DL, VecElts);
10397}
10398
10399static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
10400 SDValue Src, int ExtraElts) {
10401 EVT SrcVT = Src.getValueType();
10402
10404
10405 if (SrcVT.isVector())
10406 DAG.ExtractVectorElements(Src, Elts);
10407 else
10408 Elts.push_back(Src);
10409
10410 SDValue Undef = DAG.getPOISON(SrcVT.getScalarType());
10411 while (ExtraElts--)
10412 Elts.push_back(Undef);
10413
10414 return DAG.getBuildVector(CastVT, DL, Elts);
10415}
10416
10417// Re-construct the required return value for a image load intrinsic.
10418// This is more complicated due to the optional use TexFailCtrl which means the
10419// required return type is an aggregate
10421 ArrayRef<EVT> ResultTypes, bool IsTexFail,
10422 bool Unpacked, bool IsD16, int DMaskPop,
10423 int NumVDataDwords, bool IsAtomicPacked16Bit,
10424 const SDLoc &DL) {
10425 // Determine the required return type. This is the same regardless of
10426 // IsTexFail flag
10427 EVT ReqRetVT = ResultTypes[0];
10428 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
10429 int NumDataDwords = ((IsD16 && !Unpacked) || IsAtomicPacked16Bit)
10430 ? (ReqRetNumElts + 1) / 2
10431 : ReqRetNumElts;
10432
10433 int MaskPopDwords = (!IsD16 || Unpacked) ? DMaskPop : (DMaskPop + 1) / 2;
10434
10435 MVT DataDwordVT =
10436 NumDataDwords == 1 ? MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
10437
10438 MVT MaskPopVT =
10439 MaskPopDwords == 1 ? MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
10440
10441 SDValue Data(Result, 0);
10442 SDValue TexFail;
10443
10444 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
10445 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
10446 if (MaskPopVT.isVector()) {
10447 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
10448 SDValue(Result, 0), ZeroIdx);
10449 } else {
10450 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
10451 SDValue(Result, 0), ZeroIdx);
10452 }
10453 }
10454
10455 if (DataDwordVT.isVector() && !IsAtomicPacked16Bit)
10456 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
10457 NumDataDwords - MaskPopDwords);
10458
10459 if (IsD16)
10460 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
10461
10462 EVT LegalReqRetVT = ReqRetVT;
10463 if (!ReqRetVT.isVector()) {
10464 if (!Data.getValueType().isInteger())
10465 Data = DAG.getNode(ISD::BITCAST, DL,
10466 Data.getValueType().changeTypeToInteger(), Data);
10467 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
10468 } else {
10469 // We need to widen the return vector to a legal type
10470 if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
10471 ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
10472 LegalReqRetVT =
10474 ReqRetVT.getVectorNumElements() + 1);
10475 }
10476 }
10477 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
10478
10479 if (IsTexFail) {
10480 TexFail =
10481 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
10482 DAG.getConstant(MaskPopDwords, DL, MVT::i32));
10483
10484 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
10485 }
10486
10487 if (Result->getNumValues() == 1)
10488 return Data;
10489
10490 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
10491}
10492
10493static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
10494 SDValue *LWE, bool &IsTexFail) {
10495 auto *TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
10496
10497 uint64_t Value = TexFailCtrlConst->getZExtValue();
10498 if (Value) {
10499 IsTexFail = true;
10500 }
10501
10502 SDLoc DL(TexFailCtrlConst);
10503 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
10504 Value &= ~(uint64_t)0x1;
10505 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
10506 Value &= ~(uint64_t)0x2;
10507
10508 return Value == 0;
10509}
10510
10512 MVT PackVectorVT,
10513 SmallVectorImpl<SDValue> &PackedAddrs,
10514 unsigned DimIdx, unsigned EndIdx,
10515 unsigned NumGradients) {
10516 SDLoc DL(Op);
10517 for (unsigned I = DimIdx; I < EndIdx; I++) {
10518 SDValue Addr = Op.getOperand(I);
10519
10520 // Gradients are packed with undef for each coordinate.
10521 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
10522 // 1D: undef,dx/dh; undef,dx/dv
10523 // 2D: dy/dh,dx/dh; dy/dv,dx/dv
10524 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
10525 if (((I + 1) >= EndIdx) ||
10526 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
10527 I == DimIdx + NumGradients - 1))) {
10528 if (Addr.getValueType() != MVT::i16)
10529 Addr = DAG.getBitcast(MVT::i16, Addr);
10530 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
10531 } else {
10532 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
10533 I++;
10534 }
10535 Addr = DAG.getBitcast(MVT::f32, Addr);
10536 PackedAddrs.push_back(Addr);
10537 }
10538}
10539
10540/// Emit a DiagnosticInfoUnsupported for an unsupported image intrinsic and
10541/// return poison values of \p ResultTypes, preserving the chain if present.
10543 ArrayRef<EVT> ResultTypes,
10544 const SDLoc &DL, const Twine &Msg) {
10546 DAG.getMachineFunction().getFunction(), Msg, DL.getDebugLoc()));
10547 return DAG.getErrorMergeValues(ResultTypes, Op.getOperand(0), DL);
10548}
10549
10550SDValue SITargetLowering::lowerImage(SDValue Op,
10552 SelectionDAG &DAG, bool WithChain) const {
10553 SDLoc DL(Op);
10555 const GCNSubtarget *ST = &MF.getSubtarget<GCNSubtarget>();
10556 unsigned IntrOpcode = Intr->BaseOpcode;
10557 // For image atomic: use no-return opcode if result is unused.
10558 if (Intr->AtomicNoRetBaseOpcode != Intr->BaseOpcode &&
10559 !Op.getNode()->hasAnyUseOfValue(0))
10560 IntrOpcode = Intr->AtomicNoRetBaseOpcode;
10561 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
10563 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
10564 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
10565 bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
10566 bool IsGFX12Plus = AMDGPU::isGFX12Plus(*Subtarget);
10567 bool IsGFX13 = AMDGPU::isGFX13(*Subtarget);
10568
10569 SmallVector<EVT, 3> ResultTypes(Op->values());
10570 SmallVector<EVT, 3> OrigResultTypes(Op->values());
10571 if (BaseOpcode->NoReturn && BaseOpcode->Atomic)
10572 ResultTypes.erase(&ResultTypes[0]);
10573
10574 bool IsD16 = false;
10575 bool IsG16 = false;
10576 bool IsA16 = false;
10577 SDValue VData;
10578 int NumVDataDwords = 0;
10579 bool AdjustRetType = false;
10580 bool IsAtomicPacked16Bit = false;
10581
10582 // Offset of intrinsic arguments
10583 const unsigned ArgOffset = WithChain ? 2 : 1;
10584
10585 unsigned DMask;
10586 unsigned DMaskLanes = 0;
10587
10588 if (BaseOpcode->Atomic) {
10589 VData = Op.getOperand(2);
10590
10591 IsAtomicPacked16Bit =
10592 (IntrOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_F16 ||
10593 IntrOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_F16_NORTN ||
10594 IntrOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_BF16 ||
10595 IntrOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_BF16_NORTN);
10596
10597 if (!IsAtomicPacked16Bit && VData.getValueSizeInBits() != 32 &&
10598 VData.getValueSizeInBits() != 64) {
10599 return diagnoseUnsupportedImage(DAG, Op, OrigResultTypes, DL,
10600 "unsupported image atomic data type");
10601 }
10602
10603 bool Is64Bit = VData.getValueSizeInBits() == 64;
10604 if (BaseOpcode->AtomicX2) {
10605 SDValue VData2 = Op.getOperand(3);
10606 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
10607 {VData, VData2});
10608 if (Is64Bit)
10609 VData = DAG.getBitcast(MVT::v4i32, VData);
10610
10611 if (!BaseOpcode->NoReturn)
10612 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
10613
10614 DMask = Is64Bit ? 0xf : 0x3;
10615 NumVDataDwords = Is64Bit ? 4 : 2;
10616 } else {
10617 DMask = Is64Bit ? 0x3 : 0x1;
10618 NumVDataDwords = Is64Bit ? 2 : 1;
10619 }
10620 } else {
10621 DMask = Op->getConstantOperandVal(ArgOffset + Intr->DMaskIndex);
10622 DMaskLanes = BaseOpcode->Gather4 ? 4 : llvm::popcount(DMask);
10623
10624 if (BaseOpcode->Store) {
10625 VData = Op.getOperand(2);
10626
10627 MVT StoreVT = VData.getSimpleValueType();
10628 MVT StoreScalarVT = StoreVT.getScalarType();
10629 if (StoreScalarVT != MVT::f16 && StoreScalarVT.getSizeInBits() != 32 &&
10630 StoreScalarVT.getSizeInBits() != 64) {
10631 return diagnoseUnsupportedImage(DAG, Op, OrigResultTypes, DL,
10632 "unsupported image store data type");
10633 }
10634 if (StoreScalarVT == MVT::f16) {
10635 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
10636 return Op; // D16 is unsupported for this instruction
10637
10638 IsD16 = true;
10639 VData = handleD16VData(VData, DAG, true);
10640 }
10641
10642 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
10643 } else if (!BaseOpcode->NoReturn) {
10644 // Work out the num dwords based on the dmask popcount and underlying type
10645 // and whether packing is supported.
10646 MVT LoadVT = ResultTypes[0].getSimpleVT();
10647 MVT LoadScalarVT = LoadVT.getScalarType();
10648 if (LoadScalarVT != MVT::f16 && LoadScalarVT.getSizeInBits() != 32 &&
10649 LoadScalarVT.getSizeInBits() != 64) {
10650 return diagnoseUnsupportedImage(DAG, Op, OrigResultTypes, DL,
10651 "unsupported image load data type");
10652 }
10653 if (LoadScalarVT == MVT::f16) {
10654 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
10655 return Op; // D16 is unsupported for this instruction
10656
10657 IsD16 = true;
10658 }
10659
10660 // Confirm that the return type is large enough for the dmask specified
10661 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
10662 (!LoadVT.isVector() && DMaskLanes > 1))
10663 return Op;
10664
10665 // The sq block of gfx8 and gfx9 do not estimate register use correctly
10666 // for d16 image_gather4, image_gather4_l, and image_gather4_lz
10667 // instructions.
10668 if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
10669 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
10670 NumVDataDwords = (DMaskLanes + 1) / 2;
10671 else
10672 NumVDataDwords = DMaskLanes;
10673
10674 AdjustRetType = true;
10675 }
10676 }
10677
10678 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
10680
10681 // Check for 16 bit addresses or derivatives and pack if true.
10682 MVT VAddrVT =
10683 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
10684 MVT VAddrScalarVT = VAddrVT.getScalarType();
10685 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
10686 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
10687
10688 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
10689 VAddrScalarVT = VAddrVT.getScalarType();
10690 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
10691 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
10692
10693 // Push back extra arguments.
10694 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
10695 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
10696 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
10697 // Special handling of bias when A16 is on. Bias is of type half but
10698 // occupies full 32-bit.
10699 SDValue Bias = DAG.getBuildVector(
10700 MVT::v2f16, DL,
10701 {Op.getOperand(ArgOffset + I), DAG.getPOISON(MVT::f16)});
10702 VAddrs.push_back(Bias);
10703 } else {
10704 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
10705 "Bias needs to be converted to 16 bit in A16 mode");
10706 VAddrs.push_back(Op.getOperand(ArgOffset + I));
10707 }
10708 }
10709
10710 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
10711 // 16 bit gradients are supported, but are tied to the A16 control
10712 // so both gradients and addresses must be 16 bit
10713 LLVM_DEBUG(
10714 dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
10715 "require 16 bit args for both gradients and addresses");
10716 return Op;
10717 }
10718
10719 if (IsA16) {
10720 if (!ST->hasA16()) {
10721 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
10722 "support 16 bit addresses\n");
10723 return Op;
10724 }
10725 }
10726
10727 // We've dealt with incorrect input so we know that if IsA16, IsG16
10728 // are set then we have to compress/pack operands (either address,
10729 // gradient or both)
10730 // In the case where a16 and gradients are tied (no G16 support) then we
10731 // have already verified that both IsA16 and IsG16 are true
10732 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
10733 // Activate g16
10734 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
10736 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
10737 }
10738
10739 // Add gradients (packed or unpacked)
10740 if (IsG16) {
10741 // Pack the gradients
10742 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
10743 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
10744 ArgOffset + Intr->GradientStart,
10745 ArgOffset + Intr->CoordStart, Intr->NumGradients);
10746 } else {
10747 for (unsigned I = ArgOffset + Intr->GradientStart;
10748 I < ArgOffset + Intr->CoordStart; I++)
10749 VAddrs.push_back(Op.getOperand(I));
10750 }
10751
10752 // Add addresses (packed or unpacked)
10753 if (IsA16) {
10754 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
10755 ArgOffset + Intr->CoordStart, VAddrEnd,
10756 0 /* No gradients */);
10757 } else {
10758 // Add uncompressed address
10759 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
10760 VAddrs.push_back(Op.getOperand(I));
10761 }
10762
10763 // If the register allocator cannot place the address registers contiguously
10764 // without introducing moves, then using the non-sequential address encoding
10765 // is always preferable, since it saves VALU instructions and is usually a
10766 // wash in terms of code size or even better.
10767 //
10768 // However, we currently have no way of hinting to the register allocator that
10769 // MIMG addresses should be placed contiguously when it is possible to do so,
10770 // so force non-NSA for the common 2-address case as a heuristic.
10771 //
10772 // SIShrinkInstructions will convert NSA encodings to non-NSA after register
10773 // allocation when possible.
10774 //
10775 // Partial NSA is allowed on GFX11+ where the final register is a contiguous
10776 // set of the remaining addresses.
10777 const unsigned NSAMaxSize = ST->getNSAMaxSize(BaseOpcode->Sampler);
10778 const bool HasPartialNSAEncoding = ST->hasPartialNSAEncoding();
10779 const bool UseNSA = ST->hasNSAEncoding() &&
10780 VAddrs.size() >= ST->getNSAThreshold(MF) &&
10781 (VAddrs.size() <= NSAMaxSize || HasPartialNSAEncoding);
10782 const bool UsePartialNSA =
10783 UseNSA && HasPartialNSAEncoding && VAddrs.size() > NSAMaxSize;
10784
10785 SDValue VAddr;
10786 if (UsePartialNSA) {
10787 VAddr = getBuildDwordsVector(DAG, DL,
10788 ArrayRef(VAddrs).drop_front(NSAMaxSize - 1));
10789 } else if (!UseNSA) {
10790 VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
10791 }
10792
10793 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
10794 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
10795 SDValue Unorm;
10796 if (!BaseOpcode->Sampler) {
10797 Unorm = True;
10798 } else {
10799 uint64_t UnormConst =
10800 Op.getConstantOperandVal(ArgOffset + Intr->UnormIndex);
10801
10802 Unorm = UnormConst ? True : False;
10803 }
10804
10805 SDValue TFE;
10806 SDValue LWE;
10807 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
10808 bool IsTexFail = false;
10809 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
10810 return Op;
10811
10812 if (IsTexFail) {
10813 if (!DMaskLanes) {
10814 // Expecting to get an error flag since TFC is on - and dmask is 0
10815 // Force dmask to be at least 1 otherwise the instruction will fail
10816 DMask = 0x1;
10817 DMaskLanes = 1;
10818 NumVDataDwords = 1;
10819 }
10820 NumVDataDwords += 1;
10821 AdjustRetType = true;
10822 }
10823
10824 // Has something earlier tagged that the return type needs adjusting
10825 // This happens if the instruction is a load or has set TexFailCtrl flags
10826 if (AdjustRetType) {
10827 // NumVDataDwords reflects the true number of dwords required in the return
10828 // type
10829 if (DMaskLanes == 0 && !BaseOpcode->Store) {
10830 // This is a no-op load. This can be eliminated
10831 SDValue Undef = DAG.getPOISON(Op.getValueType());
10832 if (isa<MemSDNode>(Op))
10833 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
10834 return Undef;
10835 }
10836
10837 EVT NewVT = NumVDataDwords > 1 ? EVT::getVectorVT(*DAG.getContext(),
10838 MVT::i32, NumVDataDwords)
10839 : MVT::i32;
10840
10841 ResultTypes[0] = NewVT;
10842 if (ResultTypes.size() == 3) {
10843 // Original result was aggregate type used for TexFailCtrl results
10844 // The actual instruction returns as a vector type which has now been
10845 // created. Remove the aggregate result.
10846 ResultTypes.erase(&ResultTypes[1]);
10847 }
10848 }
10849
10850 unsigned CPol = Op.getConstantOperandVal(ArgOffset + Intr->CachePolicyIndex);
10851 // Keep GLC only when the atomic's result is actually used.
10852 if (BaseOpcode->Atomic && !BaseOpcode->NoReturn)
10854 if (CPol & ~((IsGFX12Plus ? AMDGPU::CPol::ALL : AMDGPU::CPol::ALL_pregfx12) |
10856 return Op;
10857
10859 if (BaseOpcode->Store || BaseOpcode->Atomic)
10860 Ops.push_back(VData); // vdata
10861 if (UsePartialNSA) {
10862 append_range(Ops, ArrayRef(VAddrs).take_front(NSAMaxSize - 1));
10863 Ops.push_back(VAddr);
10864 } else if (UseNSA)
10865 append_range(Ops, VAddrs);
10866 else
10867 Ops.push_back(VAddr);
10868 SDValue Rsrc = Op.getOperand(ArgOffset + Intr->RsrcIndex);
10869 EVT RsrcVT = Rsrc.getValueType();
10870 bool IndexedRsrc = IsGFX13 && RsrcVT == MVT::i32;
10871 if (RsrcVT != MVT::v4i32 && RsrcVT != MVT::v8i32 && !IndexedRsrc)
10872 return Op;
10873 Ops.push_back(Rsrc);
10874 bool IsSampIndexed = false;
10875 if (BaseOpcode->Sampler) {
10876 SDValue Samp = Op.getOperand(ArgOffset + Intr->SampIndex);
10877 EVT SampVT = Samp.getValueType();
10878 IsSampIndexed = IsGFX13 && SampVT == MVT::i32;
10879 if (SampVT != MVT::v4i32 && !IsSampIndexed)
10880 return Op;
10881 Ops.push_back(Samp);
10882 }
10883 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
10884 if (IsGFX10Plus)
10885 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
10886 if (!IsGFX12Plus || BaseOpcode->Sampler || BaseOpcode->MSAA)
10887 Ops.push_back(Unorm);
10888 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
10889 Ops.push_back(IsA16 && // r128, a16 for gfx9
10890 ST->hasFeature(AMDGPU::FeatureR128A16)
10891 ? True
10892 : False);
10893 if (IsGFX10Plus)
10894 Ops.push_back(IsA16 ? True : False);
10895
10896 if (!Subtarget->hasGFX90AInsts())
10897 Ops.push_back(TFE); // tfe
10898 else if (TFE->getAsZExtVal()) {
10899 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
10901 "TFE is not supported on this GPU", DL.getDebugLoc()));
10902 }
10903
10904 if (!IsGFX12Plus || BaseOpcode->Sampler || BaseOpcode->MSAA)
10905 Ops.push_back(LWE); // lwe
10906 if (!IsGFX10Plus)
10907 Ops.push_back(DimInfo->DA ? True : False);
10908 if (BaseOpcode->HasD16)
10909 Ops.push_back(IsD16 ? True : False);
10910 if (isa<MemSDNode>(Op))
10911 Ops.push_back(Op.getOperand(0)); // chain
10912
10913 int NumVAddrDwords =
10914 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
10915 int Opcode = -1;
10916
10917 if (IsGFX13) {
10918 Opcode =
10919 AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx13, NumVDataDwords,
10920 NumVAddrDwords, IndexedRsrc, IsSampIndexed);
10921 } else if (IsGFX12Plus) {
10922 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx12,
10923 NumVDataDwords, NumVAddrDwords);
10924 } else if (IsGFX11Plus) {
10925 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
10926 UseNSA ? AMDGPU::MIMGEncGfx11NSA
10927 : AMDGPU::MIMGEncGfx11Default,
10928 NumVDataDwords, NumVAddrDwords);
10929 } else if (IsGFX10Plus) {
10930 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
10931 UseNSA ? AMDGPU::MIMGEncGfx10NSA
10932 : AMDGPU::MIMGEncGfx10Default,
10933 NumVDataDwords, NumVAddrDwords);
10934 } else {
10935 if (Subtarget->hasGFX90AInsts()) {
10936 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
10937 NumVDataDwords, NumVAddrDwords);
10938 if (Opcode == -1) {
10940 DAG, Op, OrigResultTypes, DL,
10941 "requested image instruction is not supported on this GPU");
10942 }
10943 }
10944 if (Opcode == -1 &&
10945 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
10946 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
10947 NumVDataDwords, NumVAddrDwords);
10948 if (Opcode == -1)
10949 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
10950 NumVDataDwords, NumVAddrDwords);
10951 }
10952 if (Opcode == -1)
10953 return Op;
10954
10955 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
10956 if (auto *MemOp = dyn_cast<MemSDNode>(Op)) {
10957 MachineMemOperand *MemRef = MemOp->getMemOperand();
10958 DAG.setNodeMemRefs(NewNode, {MemRef});
10959 }
10960
10961 if (BaseOpcode->NoReturn) {
10962 if (BaseOpcode->Atomic)
10963 return DAG.getMergeValues(
10964 {DAG.getPOISON(OrigResultTypes[0]), SDValue(NewNode, 0)}, DL);
10965
10966 return SDValue(NewNode, 0);
10967 }
10968
10969 if (BaseOpcode->AtomicX2) {
10971 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
10972 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
10973 }
10974
10975 return constructRetValue(DAG, NewNode, OrigResultTypes, IsTexFail,
10976 Subtarget->hasUnpackedD16VMem(), IsD16, DMaskLanes,
10977 NumVDataDwords, IsAtomicPacked16Bit, DL);
10978}
10979
10980SDValue SITargetLowering::lowerSBuffer(EVT VT, EVT MemVT, SDLoc DL,
10981 SDValue Chain, SDValue Rsrc,
10982 SDValue Offset, SDValue CachePolicy,
10983 SelectionDAG &DAG,
10984 MachineMemOperand *MMO) const {
10986 bool HasChainResult = MMO != nullptr;
10987
10988 // SBUFFER_LOAD only produces values that fill whole SGPRs, apart from the
10989 // subword loads below.
10990 bool IsSubwordLoad = (MemVT == MVT::i8 || MemVT == MVT::i16) &&
10991 Subtarget->hasScalarSubwordLoads();
10992 if ((!isTypeLegal(VT) || VT.getSizeInBits() % 32 != 0) && !IsSubwordLoad) {
10993 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
10994 MF.getFunction(), "unsupported s_buffer_load result type",
10995 DL.getDebugLoc()));
10996 EVT ResultTypes[] = {VT, MVT::Other};
10997 return DAG.getErrorMergeValues(
10998 ArrayRef(ResultTypes, HasChainResult ? 2 : 1), Chain, DL);
10999 }
11000
11001 if (!HasChainResult) {
11002 const DataLayout &DataLayout = DAG.getDataLayout();
11004 DataLayout.getABITypeAlign(MemVT.getTypeForEVT(*DAG.getContext()));
11005
11006 MMO = MF.getMachineMemOperand(MachinePointerInfo(),
11010 MemVT.getStoreSize(), Alignment);
11011 }
11012
11013 if (!Offset->isDivergent()) {
11014 SDValue Ops[] = {Chain, Rsrc, Offset, CachePolicy};
11015
11016 // Lower llvm.amdgcn.*s.buffer.load.{i,u}N intrinsics. First, generate
11017 // s_buffer_load_u* for signed and unsigned load instructions. Next, DAG
11018 // combiner tries to merge the s_buffer_load_uN with a sext instruction
11019 // (performSignExtendInRegCombine()) and it replaces s_buffer_load_uN with
11020 // s_buffer_load_iN.
11021 auto HandleScalarSubwordLoads = [&](unsigned Opcode) -> SDValue {
11022 SDValue BufferLoad = DAG.getMemIntrinsicNode(
11023 Opcode, DL, DAG.getVTList(MVT::i32, MVT::Other), Ops, MemVT, MMO);
11024 SDValue LoadVal = DAG.getAnyExtOrTrunc(
11025 DAG.getNode(ISD::TRUNCATE, DL, MemVT, BufferLoad), DL, VT);
11026 if (HasChainResult)
11027 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
11028 return LoadVal;
11029 };
11030 if (MemVT == MVT::i8 && Subtarget->hasScalarSubwordLoads())
11031 return HandleScalarSubwordLoads(AMDGPUISD::SBUFFER_LOAD_UBYTE);
11032
11033 if (MemVT == MVT::i16 && Subtarget->hasScalarSubwordLoads())
11034 return HandleScalarSubwordLoads(AMDGPUISD::SBUFFER_LOAD_USHORT);
11035
11036 // Widen vec3 load to vec4. Only 32-bit elements have a vec4 pattern.
11037 if (VT.isVector() && VT.getVectorNumElements() == 3 &&
11038 VT.getVectorElementType().getSizeInBits() == 32 &&
11039 !Subtarget->hasScalarDwordx3Loads()) {
11040 EVT WidenedVT =
11042 auto WidenedOp = DAG.getMemIntrinsicNode(
11043 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT, MVT::Other),
11044 Ops, WidenedVT,
11045 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
11046 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
11047 DAG.getVectorIdxConstant(0, DL));
11048 if (HasChainResult)
11049 return DAG.getMergeValues({Subvector, WidenedOp.getValue(1)}, DL);
11050 return Subvector;
11051 }
11052
11053 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
11054 DAG.getVTList(VT, MVT::Other), Ops, MemVT,
11055 MMO);
11056 }
11057
11058 // We have a divergent offset. Emit a MUBUF buffer load instead. We can
11059 // assume that the buffer is unswizzled.
11060 SDValue Ops[] = {
11061 Chain, // Chain
11062 Rsrc, // rsrc
11063 DAG.getConstant(0, DL, MVT::i32), // vindex
11064 {}, // voffset
11065 {}, // soffset
11066 {}, // offset
11067 CachePolicy, // cachepolicy
11068 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
11069 };
11070 if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
11071 Subtarget->hasScalarSubwordLoads()) {
11072 setBufferOffsets(Offset, DAG, &Ops[3], Align(4));
11073 SDValue Load = handleByteShortBufferLoads(DAG, MemVT, DL, Ops, MMO);
11074 SDValue LoadVal = DAG.getAnyExtOrTrunc(Load.getOperand(0), DL, VT);
11075 if (HasChainResult)
11076 return DAG.getMergeValues({LoadVal, Load.getOperand(1)}, DL);
11077 return LoadVal;
11078 }
11079
11081 unsigned NumLoads = 1;
11082 MVT LoadVT = VT.getSimpleVT();
11083 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
11084 assert((LoadVT.getScalarType() == MVT::i32 ||
11085 LoadVT.getScalarType() == MVT::f32));
11086
11087 if (NumElts == 8 || NumElts == 16) {
11088 NumLoads = NumElts / 4;
11089 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
11090 }
11091
11092 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Other});
11093
11094 // Use the alignment to ensure that the required offsets will fit into the
11095 // immediate offsets.
11096 setBufferOffsets(Offset, DAG, &Ops[3],
11097 NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
11098
11099 uint64_t InstOffset = Ops[5]->getAsZExtVal();
11100 unsigned LoadSize = LoadVT.getStoreSize();
11101 for (unsigned i = 0; i < NumLoads; ++i) {
11102 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
11103 MachineMemOperand *LoadMMO = MF.getMachineMemOperand(MMO, 16 * i, LoadSize);
11104 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
11105 LoadVT, LoadMMO, DAG));
11106 }
11107
11108 if (NumElts == 8 || NumElts == 16) {
11109 SDValue LoadVal = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
11110 if (HasChainResult) {
11111 SmallVector<SDValue, 4> LoadChains;
11112 for (SDValue Load : Loads)
11113 LoadChains.push_back(Load.getValue(1));
11114 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, LoadChains);
11115 return DAG.getMergeValues({LoadVal, Chain}, DL);
11116 }
11117 return LoadVal;
11118 }
11119
11120 return Loads[0];
11121}
11122
11123SDValue SITargetLowering::lowerWaveID(SelectionDAG &DAG, SDValue Op) const {
11124 // With architected SGPRs, waveIDinGroup is in TTMP8[29:25].
11125 if (!Subtarget->hasArchitectedSGPRs())
11126 return {};
11127 SDLoc SL(Op);
11128 MVT VT = MVT::i32;
11129 SDValue TTMP8 = DAG.getCopyFromReg(DAG.getEntryNode(), SL, AMDGPU::TTMP8, VT);
11130 return DAG.getNode(AMDGPUISD::BFE_U32, SL, VT, TTMP8,
11131 DAG.getConstant(25, SL, VT), DAG.getConstant(5, SL, VT));
11132}
11133
11134SDValue SITargetLowering::lowerConstHwRegRead(SelectionDAG &DAG, SDValue Op,
11135 AMDGPU::Hwreg::Id HwReg,
11136 unsigned LowBit,
11137 unsigned Width) const {
11138 SDLoc SL(Op);
11139 using namespace AMDGPU::Hwreg;
11140 return {DAG.getMachineNode(
11141 AMDGPU::S_GETREG_B32_const, SL, MVT::i32,
11142 DAG.getTargetConstant(HwregEncoding::encode(HwReg, LowBit, Width),
11143 SL, MVT::i32)),
11144 0};
11145}
11146
11147SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op,
11148 unsigned Dim,
11149 const ArgDescriptor &Arg) const {
11150 SDLoc SL(Op);
11152 unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim);
11153 if (MaxID == 0)
11154 return DAG.getConstant(0, SL, MVT::i32);
11155
11156 // It's undefined behavior if a function marked with the amdgpu-no-*
11157 // attributes uses the corresponding intrinsic.
11158 if (!Arg)
11159 return DAG.getPOISON(Op->getValueType(0));
11160
11161 SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
11162 SDLoc(DAG.getEntryNode()), Arg);
11163
11164 // Don't bother inserting AssertZext for packed IDs since we're emitting the
11165 // masking operations anyway.
11166 //
11167 // TODO: We could assert the top bit is 0 for the source copy.
11168 if (Arg.isMasked())
11169 return Val;
11170
11171 // Preserve the known bits after expansion to a copy.
11172 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_width(MaxID));
11173 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val,
11174 DAG.getValueType(SmallVT));
11175}
11176
11177SDValue SITargetLowering::lowerFromFP8(SDValue Op, bool IsBF8,
11178 SelectionDAG &DAG) const {
11179 SDLoc SL(Op);
11180 SDValue Src = Op.getOperand(0);
11181 EVT DstVT = Op.getValueType();
11182 bool IsF16 = DstVT.getVectorElementType() == MVT::f16;
11183 assert((!IsF16 || Subtarget->hasFP8F16ConversionInsts()) &&
11184 "fp8/bf8 -> f16 conversion requires FP8F16ConversionInsts");
11185
11186 unsigned Opc;
11187 if (IsF16)
11188 Opc = IsBF8 ? AMDGPUISD::CVT_PK_F16_BF8 : AMDGPUISD::CVT_PK_F16_FP8;
11189 else
11190 Opc = IsBF8 ? AMDGPUISD::CVT_PK_F32_BF8 : AMDGPUISD::CVT_PK_F32_FP8;
11191
11192 // Pack the two i8 lanes into the integer type the packed HW node reads. The
11193 // f16 form takes i16 and the f32 form takes i32. v2i8 bitcasts to i16
11194 // directly and the f32 node reads the low half of an any-extended i32.
11195 EVT PackedVT =
11197 SDValue AsI16 = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11198 SDValue Packed = DAG.getAnyExtOrTrunc(AsI16, SL, PackedVT);
11199 return DAG.getNode(Opc, SL, DstVT, Packed);
11200}
11201
11202SDValue
11203SITargetLowering::LowerCONVERT_FROM_ARBITRARY_FP(SDValue Op,
11204 SelectionDAG &DAG) const {
11205 // Handle the OCP FP8 formats (E4M3FN, E5M2) and unsigned E5M3 on subtargets
11206 // with matching HW conversions. Other formats use the generic expansion.
11207 APFloatBase::Semantics FPSemantic =
11208 static_cast<APFloatBase::Semantics>(Op.getConstantOperandVal(1));
11209 const bool IsFP8 = FPSemantic == APFloatBase::S_Float8E4M3FN;
11210 const bool IsBF8 = FPSemantic == APFloatBase::S_Float8E5M2;
11211 const bool IsE5M3 = FPSemantic == APFloatBase::S_Float8E5M3FNU;
11212 const bool HasE5M3ConversionInsts =
11213 Subtarget->hasFP8ConversionInsts() && Subtarget->hasFP8E5M3Insts();
11214 const bool IsSupported = IsFP8 || IsBF8 || (IsE5M3 && HasE5M3ConversionInsts);
11215 if (!IsSupported)
11216 return SDValue();
11217
11218 EVT DstVT = Op.getValueType();
11219 // The custom action for a v2i8 source also reaches half conversions on
11220 // targets which only have FP8-to-f32 instructions.
11221 if (DstVT.getScalarType() == MVT::f16 &&
11222 !Subtarget->hasFP8F16ConversionInsts())
11223 return SDValue();
11224
11225 if (IsE5M3) {
11226 if (DstVT.getScalarType() != MVT::f32)
11227 return SDValue();
11228
11229 SDLoc SL(Op);
11230 SDValue Src = Op.getOperand(0);
11231 assert((!DstVT.isVector() || DstVT == MVT::v2f32) &&
11232 "only the v2f32 vector result is custom lowered");
11233
11234 if (DstVT.isVector())
11235 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11236 Src = DAG.getAnyExtOrTrunc(Src, SL, MVT::i32);
11237
11238 auto ConvertByte = [&](unsigned ByteSel) {
11239 return DAG.getNode(AMDGPUISD::CVT_F32_FP8_E5M3, SL, MVT::f32, Src,
11240 DAG.getTargetConstant(ByteSel, SL, MVT::i32));
11241 };
11242
11243 if (!DstVT.isVector())
11244 return ConvertByte(0);
11245 return DAG.getBuildVector(DstVT, SL, {ConvertByte(0), ConvertByte(1)});
11246 }
11247
11248 if (!DstVT.isVector()) {
11249 SDValue Src = Op.getOperand(0);
11250 if (Src.getValueType() != MVT::i32) {
11251 SDLoc SL(Op);
11252 SDValue SrcI32 = DAG.getAnyExtOrTrunc(Src, SL, MVT::i32);
11253 return DAG.getNode(ISD::CONVERT_FROM_ARBITRARY_FP, SL, DstVT, SrcI32,
11254 Op.getOperand(1));
11255 }
11256 return Op;
11257 }
11258
11259 EVT EltVT = DstVT.getVectorElementType();
11260 if (EltVT == MVT::f16 || EltVT == MVT::f32)
11261 return lowerFromFP8(Op, IsBF8, DAG);
11262 return SDValue();
11263}
11264
11265SDValue SITargetLowering::lowerToFP8(SDValue Op, bool IsBF8, bool IsE5M3,
11266 SelectionDAG &DAG) const {
11267 SDLoc SL(Op);
11268 SDValue Src = Op.getOperand(0);
11269 EVT ResVT = Op.getValueType();
11270 bool IsF16 = Src.getValueType().getScalarType() == MVT::f16;
11271 assert((!IsF16 || Subtarget->hasF16FP8ConversionInsts()) &&
11272 "f16 -> fp8/bf8 conversion requires F16FP8ConversionInsts");
11273 assert((!ResVT.isVector() || ResVT == MVT::v2i8) &&
11274 "only the v2i8 vector result is custom lowered");
11275
11276 if (IsF16) {
11277 unsigned Opc =
11278 IsBF8 ? AMDGPUISD::CVT_PK_BF8_F16 : AMDGPUISD::CVT_PK_FP8_F16;
11279 SDValue Bytes = DAG.getNode(Opc, SL, MVT::i16, Src);
11280 return DAG.getNode(ISD::BITCAST, SL, ResVT, Bytes);
11281 }
11282
11283 unsigned Opc = IsBF8 ? AMDGPUISD::CVT_PK_BF8_F32
11284 : IsE5M3 ? AMDGPUISD::CVT_PK_FP8_F32_E5M3
11285 : AMDGPUISD::CVT_PK_FP8_F32;
11286 SDValue PoisonI32 = DAG.getPOISON(MVT::i32);
11287 SDValue WordSel = DAG.getTargetConstant(0, SL, MVT::i1);
11288
11289 if (!ResVT.isVector()) {
11290 // Convert one lane, the second is unused. Feed it the same source so the
11291 // instruction does not read an undefined register.
11292 SDValue Packed =
11293 DAG.getNode(Opc, SL, MVT::i32, Src, Src, PoisonI32, WordSel);
11294 return DAG.getAnyExtOrTrunc(Packed, SL, ResVT);
11295 }
11296
11297 SDValue A = DAG.getExtractVectorElt(SL, MVT::f32, Src, 0);
11298 SDValue B = DAG.getExtractVectorElt(SL, MVT::f32, Src, 1);
11299 SDValue Packed = DAG.getNode(Opc, SL, MVT::i32, A, B, PoisonI32, WordSel);
11300 SDValue Bytes = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Packed);
11301 return DAG.getNode(ISD::BITCAST, SL, ResVT, Bytes);
11302}
11303
11304SDValue
11305SITargetLowering::LowerCONVERT_TO_ARBITRARY_FP(SDValue Op,
11306 SelectionDAG &DAG) const {
11307 // The OCP FP8 formats (E4M3FN, E5M2) and unsigned E5M3 map to HW conversions
11308 // on subtargets that support them. Everything else uses generic expansion.
11310 static_cast<APFloatBase::Semantics>(Op.getConstantOperandVal(1));
11311 const bool IsFP8 = Sem == APFloatBase::S_Float8E4M3FN;
11312 const bool IsBF8 = Sem == APFloatBase::S_Float8E5M2;
11313 const bool IsE5M3 = Sem == APFloatBase::S_Float8E5M3FNU;
11314 const bool HasE5M3ConversionInsts =
11315 Subtarget->hasFP8ConversionInsts() && Subtarget->hasFP8E5M3Insts();
11316 const bool IsSupported = IsFP8 || IsBF8 || (IsE5M3 && HasE5M3ConversionInsts);
11317 if (!IsSupported)
11318 return SDValue();
11319
11320 // The HW conversions only support nearest-even. The OCP conversions do not
11321 // saturate. The unsigned E5M3 conversion always clamps out-of-range inputs,
11322 // which also refines the non-saturating form where those inputs are poison.
11323 if (static_cast<RoundingMode>(Op.getConstantOperandVal(2)) !=
11325 return SDValue();
11326 if (!IsE5M3 && Op.getConstantOperandVal(3) != 0)
11327 return SDValue();
11328
11329 EVT SrcEltVT = Op.getOperand(0).getValueType().getScalarType();
11330 // The f32 form is built here rather than by a tablegen pattern because the
11331 // HW result is i32 while the node result is i16 after the i8 promotion.
11332 if (SrcEltVT == MVT::f32)
11333 return lowerToFP8(Op, IsBF8, IsE5M3, DAG);
11334 if (!IsE5M3 && SrcEltVT == MVT::f16 &&
11335 Subtarget->hasF16FP8ConversionInsts()) {
11336 // A scalar conversion is selected from the generic node by tablegen, only
11337 // the illegal v2i8 result type needs lowering here.
11338 if (!Op.getValueType().isVector())
11339 return Op;
11340 return lowerToFP8(Op, IsBF8, false, DAG);
11341 }
11342 return SDValue();
11343}
11344
11345SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
11346 SelectionDAG &DAG) const {
11348 auto *MFI = MF.getInfo<SIMachineFunctionInfo>();
11349
11350 EVT VT = Op.getValueType();
11351 SDLoc DL(Op);
11352 unsigned IntrinsicID = Op.getConstantOperandVal(0);
11353
11354 // TODO: Should this propagate fast-math-flags?
11355
11356 switch (IntrinsicID) {
11357 case Intrinsic::amdgcn_wave_reduce_min:
11358 case Intrinsic::amdgcn_wave_reduce_umin:
11359 case Intrinsic::amdgcn_wave_reduce_fmin:
11360 case Intrinsic::amdgcn_wave_reduce_max:
11361 case Intrinsic::amdgcn_wave_reduce_umax:
11362 case Intrinsic::amdgcn_wave_reduce_fmax:
11363 case Intrinsic::amdgcn_wave_reduce_add:
11364 case Intrinsic::amdgcn_wave_reduce_fadd:
11365 case Intrinsic::amdgcn_wave_reduce_sub:
11366 case Intrinsic::amdgcn_wave_reduce_fsub:
11367 case Intrinsic::amdgcn_wave_reduce_and:
11368 case Intrinsic::amdgcn_wave_reduce_or:
11369 case Intrinsic::amdgcn_wave_reduce_xor: {
11370 EVT SrcVT = Op.getOperand(1).getValueType();
11371 if (SrcVT.getFixedSizeInBits() == 16) {
11372 bool IsFPOp = SrcVT.isFloatingPoint();
11373 bool NeedsSignExt = IntrinsicID == Intrinsic::amdgcn_wave_reduce_min ||
11374 IntrinsicID == Intrinsic::amdgcn_wave_reduce_max ||
11375 IntrinsicID == Intrinsic::amdgcn_wave_reduce_add ||
11376 IntrinsicID == Intrinsic::amdgcn_wave_reduce_sub;
11377 unsigned ExtOpc = IsFPOp ? ISD::FP_EXTEND
11378 : NeedsSignExt ? ISD::SIGN_EXTEND
11380 auto SrcType = IsFPOp ? MVT::f16 : MVT::i16;
11381 auto ExtType = IsFPOp ? MVT::f32 : MVT::i32;
11382 SDValue ExtendedSrc = DAG.getNode(ExtOpc, DL, ExtType, Op.getOperand(1));
11383 SDValue Strategy = Op.getOperand(2);
11385 Op.getOperand(0), ExtendedSrc, Strategy);
11386 if (IsFPOp)
11387 return DAG.getNode(ISD::FP_ROUND, DL, SrcType, Result,
11388 DAG.getTargetConstant(1, DL, MVT::i32));
11389 else
11390 return DAG.getNode(ISD::TRUNCATE, DL, SrcType, Result);
11391 }
11392 return SDValue();
11393 }
11394 case Intrinsic::amdgcn_implicit_buffer_ptr: {
11395 if (!MFI->getUserSGPRInfo().hasImplicitBufferPtr()) {
11396 const char *Error =
11397 Subtarget->hasArchitectedFlatScratch()
11398 ? "intrinsic not supported on subtarget"
11399 : !Subtarget->isMesa3DOS()
11400 ? "intrinsic not supported for OS"
11401 : "intrinsic not supported for calling convention";
11402 DAG.getContext()->diagnose(
11403 DiagnosticInfoUnsupported(MF.getFunction(), Error, DL.getDebugLoc()));
11404 return DAG.getPOISON(VT);
11405 }
11406
11407 return getPreloadedValue(DAG, *MFI, VT,
11409 }
11410 case Intrinsic::amdgcn_dispatch_ptr:
11411 case Intrinsic::amdgcn_queue_ptr: {
11412 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
11413 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
11414 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
11415 DL.getDebugLoc()));
11416 return DAG.getPOISON(VT);
11417 }
11418
11419 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr
11422 return getPreloadedValue(DAG, *MFI, VT, RegID);
11423 }
11424 case Intrinsic::amdgcn_implicitarg_ptr: {
11425 if (MFI->isEntryFunction())
11426 return getImplicitArgPtr(DAG, DL);
11427 return getPreloadedValue(DAG, *MFI, VT,
11429 }
11430 case Intrinsic::amdgcn_kernarg_segment_ptr: {
11431 if (!AMDGPU::isKernel(MF.getFunction())) {
11432 // This only makes sense to call in a kernel, so just lower to null.
11433 return DAG.getConstant(0, DL, VT);
11434 }
11435
11436 return getPreloadedValue(DAG, *MFI, VT,
11438 }
11439 case Intrinsic::amdgcn_dispatch_id: {
11440 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
11441 }
11442 case Intrinsic::amdgcn_rcp:
11443 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
11444 case Intrinsic::amdgcn_rsq:
11445 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
11446 case Intrinsic::amdgcn_rsq_legacy:
11447 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
11448 return emitRemovedIntrinsicError(DAG, DL, VT);
11449 return SDValue();
11450 case Intrinsic::amdgcn_rcp_legacy:
11451 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
11452 return emitRemovedIntrinsicError(DAG, DL, VT);
11453 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
11454 case Intrinsic::amdgcn_fma_legacy:
11455 case Intrinsic::amdgcn_sudot4:
11456 case Intrinsic::amdgcn_sudot8:
11457 case Intrinsic::amdgcn_tanh:
11458 return SDValue();
11459 case Intrinsic::amdgcn_rsq_clamp: {
11460 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
11461 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
11462
11463 Type *Type = VT.getTypeForEVT(*DAG.getContext());
11464 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
11465 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
11466
11467 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
11468 SDValue Tmp =
11469 DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, DAG.getConstantFP(Max, DL, VT));
11470 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
11471 DAG.getConstantFP(Min, DL, VT));
11472 }
11473 case Intrinsic::r600_read_ngroups_x:
11474 if (Subtarget->isAmdHsaOS())
11475 return emitNonHSAIntrinsicError(DAG, DL, VT);
11476
11477 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
11479 false);
11480 case Intrinsic::r600_read_ngroups_y:
11481 if (Subtarget->isAmdHsaOS())
11482 return emitNonHSAIntrinsicError(DAG, DL, VT);
11483
11484 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
11486 false);
11487 case Intrinsic::r600_read_ngroups_z:
11488 if (Subtarget->isAmdHsaOS())
11489 return emitNonHSAIntrinsicError(DAG, DL, VT);
11490
11491 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
11493 false);
11494 case Intrinsic::r600_read_local_size_x:
11495 if (Subtarget->isAmdHsaOS())
11496 return emitNonHSAIntrinsicError(DAG, DL, VT);
11497
11498 return lowerImplicitZextParam(DAG, Op, MVT::i16,
11500 case Intrinsic::r600_read_local_size_y:
11501 if (Subtarget->isAmdHsaOS())
11502 return emitNonHSAIntrinsicError(DAG, DL, VT);
11503
11504 return lowerImplicitZextParam(DAG, Op, MVT::i16,
11506 case Intrinsic::r600_read_local_size_z:
11507 if (Subtarget->isAmdHsaOS())
11508 return emitNonHSAIntrinsicError(DAG, DL, VT);
11509
11510 return lowerImplicitZextParam(DAG, Op, MVT::i16,
11512 case Intrinsic::amdgcn_workgroup_id_x:
11513 return lowerWorkGroupId(DAG, *MFI, VT,
11517 case Intrinsic::amdgcn_workgroup_id_y:
11518 return lowerWorkGroupId(DAG, *MFI, VT,
11522 case Intrinsic::amdgcn_workgroup_id_z:
11523 return lowerWorkGroupId(DAG, *MFI, VT,
11527 case Intrinsic::amdgcn_cluster_id_x:
11528 return Subtarget->hasClusters()
11529 ? getPreloadedValue(DAG, *MFI, VT,
11531 : DAG.getPOISON(VT);
11532 case Intrinsic::amdgcn_cluster_id_y:
11533 return Subtarget->hasClusters()
11534 ? getPreloadedValue(DAG, *MFI, VT,
11536 : DAG.getPOISON(VT);
11537 case Intrinsic::amdgcn_cluster_id_z:
11538 return Subtarget->hasClusters()
11539 ? getPreloadedValue(DAG, *MFI, VT,
11541 : DAG.getPOISON(VT);
11542 case Intrinsic::amdgcn_cluster_workgroup_id_x:
11543 return lowerClusterWorkGroupValue(
11545 case Intrinsic::amdgcn_cluster_workgroup_id_y:
11546 return lowerClusterWorkGroupValue(
11548 case Intrinsic::amdgcn_cluster_workgroup_id_z:
11549 return lowerClusterWorkGroupValue(
11551 case Intrinsic::amdgcn_cluster_workgroup_flat_id:
11552 return Subtarget->hasClusters()
11553 ? lowerConstHwRegRead(DAG, Op, AMDGPU::Hwreg::ID_IB_STS2, 21, 4)
11554 : SDValue();
11555 case Intrinsic::amdgcn_cluster_workgroup_max_id_x:
11556 return lowerClusterWorkGroupValue(
11558 case Intrinsic::amdgcn_cluster_workgroup_max_id_y:
11559 return lowerClusterWorkGroupValue(
11561 case Intrinsic::amdgcn_cluster_workgroup_max_id_z:
11562 return lowerClusterWorkGroupValue(
11564 case Intrinsic::amdgcn_cluster_workgroup_max_flat_id:
11565 return lowerClusterWorkGroupValue(
11567 case Intrinsic::amdgcn_wave_id:
11568 return lowerWaveID(DAG, Op);
11569 case Intrinsic::amdgcn_lds_kernel_id: {
11570 if (MFI->isEntryFunction())
11571 return getLDSKernelId(DAG, DL);
11572 return getPreloadedValue(DAG, *MFI, VT,
11574 }
11575 case Intrinsic::amdgcn_workitem_id_x:
11576 return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX);
11577 case Intrinsic::amdgcn_workitem_id_y:
11578 return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY);
11579 case Intrinsic::amdgcn_workitem_id_z:
11580 return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ);
11581 case Intrinsic::amdgcn_wavefrontsize:
11582 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
11583 SDLoc(Op), MVT::i32);
11584 case Intrinsic::amdgcn_s_buffer_load: {
11585 unsigned CPol = Op.getConstantOperandVal(3);
11586 // s_buffer_load, because of how it's optimized, can't be volatile
11587 // so reject ones with the volatile bit set.
11588 if (CPol & ~((Subtarget->getGeneration() >= AMDGPUSubtarget::GFX12)
11591 return Op;
11592 return lowerSBuffer(VT, VT, DL, DAG.getEntryNode(), Op.getOperand(1),
11593 Op.getOperand(2), Op.getOperand(3), DAG);
11594 }
11595 case Intrinsic::amdgcn_fdiv_fast:
11596 return lowerFDIV_FAST(Op, DAG);
11597 case Intrinsic::amdgcn_sin:
11598 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
11599
11600 case Intrinsic::amdgcn_cos:
11601 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
11602
11603 case Intrinsic::amdgcn_mul_u24:
11604 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1),
11605 Op.getOperand(2));
11606 case Intrinsic::amdgcn_mul_i24:
11607 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1),
11608 Op.getOperand(2));
11609
11610 case Intrinsic::amdgcn_log_clamp: {
11611 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
11612 return SDValue();
11613
11614 return emitRemovedIntrinsicError(DAG, DL, VT);
11615 }
11616 case Intrinsic::amdgcn_fract:
11617 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
11618
11619 case Intrinsic::amdgcn_class: {
11620 SDValue Src = Op.getOperand(1);
11621 EVT SrcVT = Src.getValueType();
11622 bool IsLegal = SrcVT == MVT::f32 || SrcVT == MVT::f64 ||
11623 (SrcVT == MVT::f16 && Subtarget->has16BitInsts());
11624 if (!IsLegal) {
11625 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
11627 "llvm.amdgcn.class only supports f16, f32, and f64",
11628 DL.getDebugLoc()));
11629 return DAG.getPOISON(VT);
11630 }
11631 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, Src, Op.getOperand(2));
11632 }
11633 case Intrinsic::amdgcn_div_fmas:
11634 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, Op.getOperand(1),
11635 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
11636
11637 case Intrinsic::amdgcn_div_fixup:
11638 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, Op.getOperand(1),
11639 Op.getOperand(2), Op.getOperand(3));
11640
11641 case Intrinsic::amdgcn_div_scale: {
11642 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
11643
11644 // Translate to the operands expected by the machine instruction. The
11645 // first parameter must be the same as the first instruction.
11646 SDValue Numerator = Op.getOperand(1);
11647 SDValue Denominator = Op.getOperand(2);
11648
11649 // Note this order is opposite of the machine instruction's operations,
11650 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
11651 // intrinsic has the numerator as the first operand to match a normal
11652 // division operation.
11653
11654 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
11655
11656 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
11657 Denominator, Numerator);
11658 }
11659 case Intrinsic::amdgcn_ballot:
11660 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
11661 case Intrinsic::amdgcn_fmed3:
11662 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, Op.getOperand(1),
11663 Op.getOperand(2), Op.getOperand(3), Op->getFlags());
11664 case Intrinsic::amdgcn_fdot2:
11665 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, Op.getOperand(1),
11666 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
11667 case Intrinsic::amdgcn_fmul_legacy:
11668 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, Op.getOperand(1),
11669 Op.getOperand(2));
11670 case Intrinsic::amdgcn_sbfe:
11671 case Intrinsic::amdgcn_ubfe:
11672 return lowerBFEIntrinsic(Op, DAG, IntrinsicID);
11673 case Intrinsic::amdgcn_cvt_pkrtz:
11674 case Intrinsic::amdgcn_cvt_pknorm_i16:
11675 case Intrinsic::amdgcn_cvt_pknorm_u16:
11676 case Intrinsic::amdgcn_cvt_pk_i16:
11677 case Intrinsic::amdgcn_cvt_pk_u16: {
11678 // FIXME: Stop adding cast if v2f16/v2i16 are legal.
11679 EVT VT = Op.getValueType();
11680 unsigned Opcode;
11681
11682 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
11683 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
11684 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
11685 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
11686 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
11687 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
11688 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
11689 Opcode = AMDGPUISD::CVT_PK_I16_I32;
11690 else
11691 Opcode = AMDGPUISD::CVT_PK_U16_U32;
11692
11693 if (isTypeLegal(VT))
11694 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
11695
11696 SDValue Node =
11697 DAG.getNode(Opcode, DL, MVT::i32, Op.getOperand(1), Op.getOperand(2));
11698 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
11699 }
11700 case Intrinsic::amdgcn_fmad_ftz:
11701 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
11702 Op.getOperand(2), Op.getOperand(3));
11703
11704 case Intrinsic::amdgcn_if_break:
11705 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
11706 Op->getOperand(1), Op->getOperand(2)),
11707 0);
11708
11709 case Intrinsic::amdgcn_groupstaticsize: {
11711 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
11712 return Op;
11713
11714 const Module *M = MF.getFunction().getParent();
11715 const GlobalValue *GV =
11716 Intrinsic::getDeclarationIfExists(M, Intrinsic::amdgcn_groupstaticsize);
11717 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
11719 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
11720 }
11721 case Intrinsic::amdgcn_is_shared:
11722 case Intrinsic::amdgcn_is_private: {
11723 SDLoc SL(Op);
11724 SDValue SrcVec =
11725 DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
11726 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
11727 DAG.getConstant(1, SL, MVT::i32));
11728
11729 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared)
11731 : AMDGPUAS::PRIVATE_ADDRESS;
11732 if (AS == AMDGPUAS::PRIVATE_ADDRESS &&
11733 Subtarget->hasGloballyAddressableScratch()) {
11734 SDValue FlatScratchBaseHi(
11735 DAG.getMachineNode(
11736 AMDGPU::S_MOV_B32, DL, MVT::i32,
11737 DAG.getRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE_HI, MVT::i32)),
11738 0);
11739 // Test bits 63..58 against the aperture address.
11740 return DAG.getSetCC(
11741 SL, MVT::i1,
11742 DAG.getNode(ISD::XOR, SL, MVT::i32, SrcHi, FlatScratchBaseHi),
11743 DAG.getConstant(1u << 26, SL, MVT::i32), ISD::SETULT);
11744 }
11745
11746 SDValue Aperture = getSegmentAperture(AS, SL, DAG);
11747 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
11748 }
11749 case Intrinsic::amdgcn_perm:
11750 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
11751 Op.getOperand(2), Op.getOperand(3));
11752 case Intrinsic::amdgcn_reloc_constant: {
11753 Module *M = MF.getFunction().getParent();
11754 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
11755 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
11756 auto *RelocSymbol = cast<GlobalVariable>(
11757 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
11758 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
11760 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
11761 }
11762 case Intrinsic::amdgcn_swmmac_f16_16x16x32_f16:
11763 case Intrinsic::amdgcn_swmmac_bf16_16x16x32_bf16:
11764 case Intrinsic::amdgcn_swmmac_f32_16x16x32_bf16:
11765 case Intrinsic::amdgcn_swmmac_f32_16x16x32_f16:
11766 case Intrinsic::amdgcn_swmmac_f32_16x16x32_fp8_fp8:
11767 case Intrinsic::amdgcn_swmmac_f32_16x16x32_fp8_bf8:
11768 case Intrinsic::amdgcn_swmmac_f32_16x16x32_bf8_fp8:
11769 case Intrinsic::amdgcn_swmmac_f32_16x16x32_bf8_bf8: {
11770 if (Op.getOperand(4).getValueType() == MVT::i32)
11771 return SDValue();
11772
11773 SDLoc SL(Op);
11774 auto IndexKeyi32 = DAG.getAnyExtOrTrunc(Op.getOperand(4), SL, MVT::i32);
11775 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, Op.getValueType(),
11776 Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
11777 Op.getOperand(3), IndexKeyi32);
11778 }
11779 case Intrinsic::amdgcn_swmmac_f32_16x16x128_fp8_fp8:
11780 case Intrinsic::amdgcn_swmmac_f32_16x16x128_fp8_bf8:
11781 case Intrinsic::amdgcn_swmmac_f32_16x16x128_bf8_fp8:
11782 case Intrinsic::amdgcn_swmmac_f32_16x16x128_bf8_bf8:
11783 case Intrinsic::amdgcn_swmmac_f16_16x16x128_fp8_fp8:
11784 case Intrinsic::amdgcn_swmmac_f16_16x16x128_fp8_bf8:
11785 case Intrinsic::amdgcn_swmmac_f16_16x16x128_bf8_fp8:
11786 case Intrinsic::amdgcn_swmmac_f16_16x16x128_bf8_bf8: {
11787 if (Op.getOperand(4).getValueType() == MVT::i64)
11788 return SDValue();
11789
11790 SDLoc SL(Op);
11791 auto IndexKeyi64 =
11792 Op.getOperand(4).getValueType() == MVT::v2i32
11793 ? DAG.getBitcast(MVT::i64, Op.getOperand(4))
11794 : DAG.getAnyExtOrTrunc(Op.getOperand(4), SL, MVT::i64);
11795 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, Op.getValueType(),
11796 {Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
11797 Op.getOperand(3), IndexKeyi64, Op.getOperand(5),
11798 Op.getOperand(6)});
11799 }
11800 case Intrinsic::amdgcn_swmmac_f16_16x16x64_f16:
11801 case Intrinsic::amdgcn_swmmac_bf16_16x16x64_bf16:
11802 case Intrinsic::amdgcn_swmmac_f32_16x16x64_bf16:
11803 case Intrinsic::amdgcn_swmmac_bf16f32_16x16x64_bf16:
11804 case Intrinsic::amdgcn_swmmac_f32_16x16x64_f16:
11805 case Intrinsic::amdgcn_swmmac_i32_16x16x128_iu8: {
11806 EVT IndexKeyTy = IntrinsicID == Intrinsic::amdgcn_swmmac_i32_16x16x128_iu8
11807 ? MVT::i64
11808 : MVT::i32;
11809 if (Op.getOperand(6).getValueType() == IndexKeyTy)
11810 return SDValue();
11811
11812 SDLoc SL(Op);
11813 auto IndexKey =
11814 Op.getOperand(6).getValueType().isVector()
11815 ? DAG.getBitcast(IndexKeyTy, Op.getOperand(6))
11816 : DAG.getAnyExtOrTrunc(Op.getOperand(6), SL, IndexKeyTy);
11818 Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
11819 Op.getOperand(3), Op.getOperand(4), Op.getOperand(5),
11820 IndexKey, Op.getOperand(7), Op.getOperand(8)};
11821 if (IntrinsicID == Intrinsic::amdgcn_swmmac_i32_16x16x128_iu8)
11822 Args.push_back(Op.getOperand(9));
11823 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, Op.getValueType(), Args);
11824 }
11825 case Intrinsic::amdgcn_swmmac_i32_16x16x32_iu4:
11826 case Intrinsic::amdgcn_swmmac_i32_16x16x32_iu8:
11827 case Intrinsic::amdgcn_swmmac_i32_16x16x64_iu4: {
11828 if (Op.getOperand(6).getValueType() == MVT::i32)
11829 return SDValue();
11830
11831 SDLoc SL(Op);
11832 auto IndexKeyi32 = DAG.getAnyExtOrTrunc(Op.getOperand(6), SL, MVT::i32);
11833 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, Op.getValueType(),
11834 {Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
11835 Op.getOperand(3), Op.getOperand(4), Op.getOperand(5),
11836 IndexKeyi32, Op.getOperand(7)});
11837 }
11838 case Intrinsic::amdgcn_wmma_scale_f32_16x16x128_f8f6f4:
11839 case Intrinsic::amdgcn_wmma_scale16_f32_16x16x128_f8f6f4: {
11840 unsigned AFmt = (unsigned)Op.getConstantOperandVal(1);
11841 unsigned BFmt = (unsigned)Op.getConstantOperandVal(3);
11842 unsigned AScaleFmt = (unsigned)Op.getConstantOperandVal(8);
11843 unsigned BScaleFmt = (unsigned)Op.getConstantOperandVal(11);
11844 if (!AMDGPU::isValidWMMAScaleFmtCombination(AFmt, AScaleFmt, BFmt,
11845 BScaleFmt)) {
11847 "invalid matrix and scale format combination in wmma call");
11848 Op->print(errs());
11849 errs() << '\n';
11850 }
11851 return SDValue();
11852 }
11853 case Intrinsic::amdgcn_readlane:
11854 case Intrinsic::amdgcn_readfirstlane:
11855 case Intrinsic::amdgcn_writelane:
11856 case Intrinsic::amdgcn_permlane16:
11857 case Intrinsic::amdgcn_permlanex16:
11858 case Intrinsic::amdgcn_permlane64:
11859 case Intrinsic::amdgcn_set_inactive:
11860 case Intrinsic::amdgcn_set_inactive_chain_arg:
11861 case Intrinsic::amdgcn_mov_dpp8:
11862 case Intrinsic::amdgcn_update_dpp:
11863 case Intrinsic::amdgcn_permlane_bcast:
11864 case Intrinsic::amdgcn_permlane_up:
11865 case Intrinsic::amdgcn_permlane_down:
11866 case Intrinsic::amdgcn_permlane_xor:
11867 return lowerLaneOp(*this, Op.getNode(), DAG);
11868 case Intrinsic::amdgcn_dead: {
11870 for (const EVT ValTy : Op.getNode()->values())
11871 Poisons.push_back(DAG.getPOISON(ValTy));
11872 return DAG.getMergeValues(Poisons, SDLoc(Op));
11873 }
11874 case Intrinsic::amdgcn_wave_shuffle:
11875 return lowerWaveShuffle(*this, Op.getNode(), DAG);
11876 default:
11877 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
11879 return lowerImage(Op, ImageDimIntr, DAG, false);
11880
11881 return Op;
11882 }
11883}
11884
11885// On targets not supporting constant in soffset field, turn zero to
11886// SGPR_NULL to avoid generating an extra s_mov with zero.
11888 const GCNSubtarget *Subtarget) {
11889 if (Subtarget->hasRestrictedSOffset() && isNullConstant(SOffset))
11890 return DAG.getRegister(AMDGPU::SGPR_NULL, MVT::i32);
11891 return SOffset;
11892}
11893
11894// Lower the arguments of the buffer intrinsic \p Op into the operands of the
11895// corresponding AMDGPUISD buffer node: the chain, \p VData and the cmp operand
11896// if present, then rsrc, vindex, voffset, soffset, offset, [format,]
11897// cachepolicy and idxen.
11898SmallVector<SDValue, 10> SITargetLowering::getBufferIntrinsicOps(
11900 SDValue VData) const {
11901 SDLoc DL(Op);
11902 auto GetArg = [&](unsigned Arg) {
11903 return Op.getOperand(AMDGPU::getSDOperandIdx(Arg));
11904 };
11905
11906 SDValue Rsrc = bufferRsrcPtrToVector(GetArg(Info.RsrcArg), DAG);
11907 auto [VOffset, Offset] =
11908 splitBufferOffsets(GetArg(*Info.getVOffsetArg()), DAG);
11909 SDValue SOffset =
11910 selectSOffset(GetArg(*Info.getSOffsetArg()), DAG, Subtarget);
11911
11912 SmallVector<SDValue, 10> Ops = {Op.getOperand(0)}; // Chain
11913 if (VData)
11914 Ops.push_back(VData);
11915 if (std::optional<unsigned> CmpArg = Info.getCmpArg())
11916 Ops.push_back(GetArg(*CmpArg));
11917 Ops.push_back(Rsrc);
11918 std::optional<unsigned> VIndexArg = Info.getVIndexArg();
11919 Ops.push_back(VIndexArg ? GetArg(*VIndexArg)
11920 : DAG.getConstant(0, DL, MVT::i32)); // vindex
11921 Ops.push_back(VOffset);
11922 Ops.push_back(SOffset);
11923 Ops.push_back(Offset);
11924 if (std::optional<unsigned> FormatArg = Info.getFormatArg())
11925 Ops.push_back(GetArg(*FormatArg));
11926 Ops.push_back(GetArg(*Info.getAuxArg())); // cachepolicy, swizzled buffer
11927 Ops.push_back(
11928 DAG.getTargetConstant(VIndexArg.has_value(), DL, MVT::i1)); // idxen
11929 return Ops;
11930}
11931
11932SDValue SITargetLowering::lowerBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
11933 unsigned NewOpcode) const {
11934 SDLoc DL(Op);
11935 const AMDGPU::BufferIntrinsicInfo &Info =
11936 *AMDGPU::lookupBufferIntrinsic(Op.getConstantOperandVal(1));
11937
11938 SDValue VData = Op.getOperand(AMDGPU::getSDOperandIdx(*Info.getVDataArg()));
11939 if (VData.getValueSizeInBits() != 32 && VData.getValueSizeInBits() != 64) {
11940 SmallVector<EVT, 2> ResultTypes(Op->values());
11941 return diagnoseUnsupportedImage(DAG, Op, ResultTypes, DL,
11942 "unsupported buffer atomic data type");
11943 }
11944 SmallVector<SDValue, 10> Ops = getBufferIntrinsicOps(Op, Info, DAG, VData);
11945
11946 auto *M = cast<MemSDNode>(Op);
11947
11948 EVT MemVT = VData.getValueType();
11949 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
11950 M->getMemOperand());
11951}
11952
11953// Lower the buffer loads and the compare-and-swap atomics, which are all
11954// INTRINSIC_W_CHAIN nodes. Other atomics need an opcode for their operation,
11955// and so are handled by LowerINTRINSIC_W_CHAIN.
11956SDValue SITargetLowering::lowerBufferIntrinsicWithChain(
11958 SelectionDAG &DAG) const {
11959 SDLoc DL(Op);
11960 auto *M = cast<MemSDNode>(Op);
11961 auto GetArg = [&](unsigned Arg) {
11962 return Op.getOperand(AMDGPU::getSDOperandIdx(Arg));
11963 };
11964
11965 switch (Info.Kind) {
11966 case AMDGPU::BufferKindSLoad: {
11967 SDValue CachePolicy = GetArg(*Info.getAuxArg());
11968 if (CachePolicy->getAsZExtVal() &
11969 ~((Subtarget->getGeneration() >= AMDGPUSubtarget::GFX12)
11972 return Op;
11973
11974 return lowerSBuffer(
11975 Op.getValueType(), M->getMemoryVT(), DL, Op.getOperand(0),
11976 bufferRsrcPtrToVector(GetArg(Info.RsrcArg), DAG),
11977 GetArg(*Info.getSOffsetArg()), CachePolicy, DAG, M->getMemOperand());
11978 }
11979 case AMDGPU::BufferKindLoad:
11980 case AMDGPU::BufferKindAtomicLoad: {
11981 SmallVector<SDValue, 10> Ops = getBufferIntrinsicOps(Op, Info, DAG);
11982 if (!Info.isTyped())
11983 return lowerIntrinsicLoad(M, Info.isFormatFromRsrc(), DAG, Ops);
11984
11985 EVT LoadVT = Op.getValueType();
11986 if (LoadVT.getScalarSizeInBits() == 16)
11987 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, M, DAG,
11988 Ops);
11989 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
11990 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
11991 DAG);
11992 }
11993 case AMDGPU::BufferKindAtomicCmpSwap: {
11994 SDValue Src = GetArg(*Info.getVDataArg());
11995 if (Src.getValueSizeInBits() != 32 && Src.getValueSizeInBits() != 64) {
11996 SmallVector<EVT, 2> ResultTypes(Op->values());
11997 return diagnoseUnsupportedImage(DAG, Op, ResultTypes, DL,
11998 "unsupported buffer atomic data type");
11999 }
12000 SmallVector<SDValue, 10> Ops = getBufferIntrinsicOps(Op, Info, DAG, Src);
12001 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
12002 Op->getVTList(), Ops, Op.getValueType(),
12003 M->getMemOperand());
12004 }
12005 default:
12006 llvm_unreachable("not a buffer intrinsic with a chain and a result");
12007 }
12008}
12009
12011 SDLoc DL) {
12012 SDNode *N = Op.getNode();
12013 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
12014 unsigned NumOperands = N->getNumOperands();
12015 if (N->getOperand(NumOperands - 1) == Zero)
12016 return;
12018 Ops[NumOperands - 1] = Zero; // M0 = 0
12019 DAG.UpdateNodeOperands(N, Ops);
12020}
12021
12022// Try to resolve a named barrier object to a constant barrier ID.
12023// Named barrier IDs are encoded at bits [5:0] of a BARRIER address space
12024// address - other bits of that address are ignored as reserved.
12025static std::optional<uint32_t>
12027 std::optional<uint64_t> BarVal;
12028 if (auto *C = dyn_cast<ConstantSDNode>(BarOp)) {
12029 BarVal = C->getZExtValue();
12030 } else if (BarOp->isUndef()) {
12031 // Refine poison to the 0 barrier to turn things into noops, thus reducing
12032 // the risk of hitting an unallocated barrier.
12033 BarVal = 0;
12034 } else if (auto *GA = dyn_cast<GlobalAddressSDNode>(BarOp)) {
12035 const auto *GV = cast<GlobalVariable>(GA->getGlobal());
12036 if (AMDGPU::isNamedBarrier(*GV) &&
12040 // Record the use of the manualy-specified barrier address to make sure
12041 // this function has the right number of resources. This function is named
12042 // weird, and we're calling it here since we're skipping the GlobalAddress
12043 // lowering with this pattern match.
12044 BarVal = MFI->allocateBarrierGlobal(DAG.getDataLayout(), *GV) +
12045 GA->getOffset();
12046 }
12047 }
12048 if (BarVal)
12049 return *BarVal & 0x3F;
12050 return std::nullopt;
12051}
12052
12053SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
12054 SelectionDAG &DAG) const {
12055 unsigned IntrID = Op.getConstantOperandVal(1);
12056 SDLoc DL(Op);
12057
12058 if (const AMDGPU::BufferIntrinsicInfo *BufInfo =
12060 BufInfo && BufInfo->Kind != AMDGPU::BufferKindAtomicRMW)
12061 return lowerBufferIntrinsicWithChain(Op, *BufInfo, DAG);
12062
12063 switch (IntrID) {
12064 case Intrinsic::amdgcn_cluster_load_b32:
12065 case Intrinsic::amdgcn_cluster_load_b64:
12066 case Intrinsic::amdgcn_cluster_load_b128: {
12067 if (Subtarget->hasGFX1250_STRICT())
12069 return SDValue();
12070 }
12071 case Intrinsic::amdgcn_ds_ordered_add:
12072 case Intrinsic::amdgcn_ds_ordered_swap: {
12073 MemSDNode *M = cast<MemSDNode>(Op);
12074 SDValue Chain = M->getOperand(0);
12075 SDValue M0 = M->getOperand(2);
12076 SDValue Value = M->getOperand(3);
12077 unsigned IndexOperand = M->getConstantOperandVal(7);
12078 unsigned WaveRelease = M->getConstantOperandVal(8);
12079 unsigned WaveDone = M->getConstantOperandVal(9);
12080
12081 unsigned OrderedCountIndex = IndexOperand & 0x3f;
12082 IndexOperand &= ~0x3f;
12083 unsigned CountDw = 0;
12084
12085 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
12086 CountDw = (IndexOperand >> 24) & 0xf;
12087 IndexOperand &= ~(0xf << 24);
12088
12089 if (CountDw < 1 || CountDw > 4) {
12090 const Function &Fn = DAG.getMachineFunction().getFunction();
12091 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
12092 Fn, "ds_ordered_count: dword count must be between 1 and 4",
12093 DL.getDebugLoc()));
12094 CountDw = 1;
12095 }
12096 }
12097
12098 if (IndexOperand) {
12099 const Function &Fn = DAG.getMachineFunction().getFunction();
12100 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
12101 Fn, "ds_ordered_count: bad index operand", DL.getDebugLoc()));
12102 }
12103
12104 if (WaveDone && !WaveRelease) {
12105 // TODO: Move this to IR verifier
12106 const Function &Fn = DAG.getMachineFunction().getFunction();
12107 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
12108 Fn, "ds_ordered_count: wave_done requires wave_release",
12109 DL.getDebugLoc()));
12110 }
12111
12112 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
12113 unsigned ShaderType =
12115 unsigned Offset0 = OrderedCountIndex << 2;
12116 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (Instruction << 4);
12117
12118 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
12119 Offset1 |= (CountDw - 1) << 6;
12120
12121 if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX11)
12122 Offset1 |= ShaderType << 2;
12123
12124 unsigned Offset = Offset0 | (Offset1 << 8);
12125
12126 SDValue Ops[] = {
12127 Chain, Value, DAG.getTargetConstant(Offset, DL, MVT::i16),
12128 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
12129 };
12130 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
12131 M->getVTList(), Ops, M->getMemoryVT(),
12132 M->getMemOperand());
12133 }
12134 case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
12135 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fadd:
12136 case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
12137 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fadd:
12138 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
12139 case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
12140 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fmin:
12141 case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
12142 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fmin:
12143 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
12144 case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
12145 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fmax:
12146 case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
12147 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fmax:
12148 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
12149 case Intrinsic::amdgcn_raw_buffer_atomic_swap:
12150 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_swap:
12151 case Intrinsic::amdgcn_struct_buffer_atomic_swap:
12152 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_swap:
12153 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
12154 case Intrinsic::amdgcn_raw_buffer_atomic_add:
12155 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_add:
12156 case Intrinsic::amdgcn_struct_buffer_atomic_add:
12157 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_add:
12158 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
12159 case Intrinsic::amdgcn_raw_buffer_atomic_sub:
12160 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub:
12161 case Intrinsic::amdgcn_struct_buffer_atomic_sub:
12162 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub:
12163 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
12164 case Intrinsic::amdgcn_raw_buffer_atomic_smin:
12165 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smin:
12166 case Intrinsic::amdgcn_struct_buffer_atomic_smin:
12167 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smin:
12168 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
12169 case Intrinsic::amdgcn_raw_buffer_atomic_umin:
12170 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umin:
12171 case Intrinsic::amdgcn_struct_buffer_atomic_umin:
12172 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umin:
12173 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
12174 case Intrinsic::amdgcn_raw_buffer_atomic_smax:
12175 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smax:
12176 case Intrinsic::amdgcn_struct_buffer_atomic_smax:
12177 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smax:
12178 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
12179 case Intrinsic::amdgcn_raw_buffer_atomic_umax:
12180 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umax:
12181 case Intrinsic::amdgcn_struct_buffer_atomic_umax:
12182 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umax:
12183 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
12184 case Intrinsic::amdgcn_raw_buffer_atomic_and:
12185 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_and:
12186 case Intrinsic::amdgcn_struct_buffer_atomic_and:
12187 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_and:
12188 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
12189 case Intrinsic::amdgcn_raw_buffer_atomic_or:
12190 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_or:
12191 case Intrinsic::amdgcn_struct_buffer_atomic_or:
12192 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_or:
12193 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
12194 case Intrinsic::amdgcn_raw_buffer_atomic_xor:
12195 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_xor:
12196 case Intrinsic::amdgcn_struct_buffer_atomic_xor:
12197 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_xor:
12198 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
12199 case Intrinsic::amdgcn_raw_buffer_atomic_inc:
12200 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_inc:
12201 case Intrinsic::amdgcn_struct_buffer_atomic_inc:
12202 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_inc:
12203 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
12204 case Intrinsic::amdgcn_raw_buffer_atomic_dec:
12205 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_dec:
12206 case Intrinsic::amdgcn_struct_buffer_atomic_dec:
12207 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_dec:
12208 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
12209 case Intrinsic::amdgcn_raw_buffer_atomic_sub_clamp_u32:
12210 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub_clamp_u32:
12211 case Intrinsic::amdgcn_struct_buffer_atomic_sub_clamp_u32:
12212 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub_clamp_u32:
12213 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_CSUB);
12214 case Intrinsic::amdgcn_raw_buffer_atomic_cond_sub_u32:
12215 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_cond_sub_u32:
12216 case Intrinsic::amdgcn_struct_buffer_atomic_cond_sub_u32:
12217 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_cond_sub_u32:
12218 return lowerBufferAtomicIntrin(Op, DAG,
12219 AMDGPUISD::BUFFER_ATOMIC_COND_SUB_U32);
12220 case Intrinsic::amdgcn_image_bvh_dual_intersect_ray:
12221 case Intrinsic::amdgcn_image_bvh8_intersect_ray: {
12222 MemSDNode *M = cast<MemSDNode>(Op);
12223 SDValue NodePtr = M->getOperand(2);
12224 SDValue RayExtent = M->getOperand(3);
12225 SDValue InstanceMask = M->getOperand(4);
12226 SDValue RayOrigin = M->getOperand(5);
12227 SDValue RayDir = M->getOperand(6);
12228 SDValue Offsets = M->getOperand(7);
12229 SDValue TDescr = M->getOperand(8);
12230
12231 assert(NodePtr.getValueType() == MVT::i64);
12232 assert(RayDir.getValueType() == MVT::v3f32);
12233
12234 bool IsBVH8 = IntrID == Intrinsic::amdgcn_image_bvh8_intersect_ray;
12235 const unsigned NumVDataDwords = 10;
12236 const unsigned NumVAddrDwords = IsBVH8 ? 11 : 12;
12237 int Opcode = AMDGPU::getMIMGOpcode(
12238 IsBVH8 ? AMDGPU::IMAGE_BVH8_INTERSECT_RAY
12239 : AMDGPU::IMAGE_BVH_DUAL_INTERSECT_RAY,
12240 AMDGPU::MIMGEncGfx12, NumVDataDwords, NumVAddrDwords);
12241 assert(Opcode != -1);
12242
12244 Ops.push_back(NodePtr);
12245 Ops.push_back(DAG.getBuildVector(
12246 MVT::v2i32, DL,
12247 {DAG.getBitcast(MVT::i32, RayExtent),
12248 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, InstanceMask)}));
12249 Ops.push_back(RayOrigin);
12250 Ops.push_back(RayDir);
12251 Ops.push_back(Offsets);
12252 Ops.push_back(TDescr);
12253 Ops.push_back(M->getChain());
12254
12255 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
12256 MachineMemOperand *MemRef = M->getMemOperand();
12257 DAG.setNodeMemRefs(NewNode, {MemRef});
12258 return SDValue(NewNode, 0);
12259 }
12260 case Intrinsic::amdgcn_image_bvh_intersect_ray: {
12261 MemSDNode *M = cast<MemSDNode>(Op);
12262 SDValue NodePtr = M->getOperand(2);
12263 SDValue RayExtent = M->getOperand(3);
12264 SDValue RayOrigin = M->getOperand(4);
12265 SDValue RayDir = M->getOperand(5);
12266 SDValue RayInvDir = M->getOperand(6);
12267 SDValue TDescr = M->getOperand(7);
12268
12269 assert(NodePtr.getValueType() == MVT::i32 ||
12270 NodePtr.getValueType() == MVT::i64);
12271 assert(RayDir.getValueType() == MVT::v3f16 ||
12272 RayDir.getValueType() == MVT::v3f32);
12273
12274 const bool IsGFX11 = AMDGPU::isGFX11(*Subtarget);
12275 const bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
12276 const bool IsGFX12Plus = AMDGPU::isGFX12Plus(*Subtarget);
12277 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
12278 const bool Is64 = NodePtr.getValueType() == MVT::i64;
12279 const unsigned NumVDataDwords = 4;
12280 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
12281 const unsigned NumVAddrs = IsGFX11Plus ? (IsA16 ? 4 : 5) : NumVAddrDwords;
12282 const bool UseNSA = (Subtarget->hasNSAEncoding() &&
12283 NumVAddrs <= Subtarget->getNSAMaxSize()) ||
12284 IsGFX12Plus;
12285 const unsigned BaseOpcodes[2][2] = {
12286 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
12287 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
12288 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
12289 int Opcode;
12290 if (UseNSA) {
12291 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
12292 IsGFX12Plus ? AMDGPU::MIMGEncGfx12
12293 : IsGFX11 ? AMDGPU::MIMGEncGfx11NSA
12294 : AMDGPU::MIMGEncGfx10NSA,
12295 NumVDataDwords, NumVAddrDwords);
12296 } else {
12297 assert(!IsGFX12Plus);
12298 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
12299 IsGFX11 ? AMDGPU::MIMGEncGfx11Default
12300 : AMDGPU::MIMGEncGfx10Default,
12301 NumVDataDwords, NumVAddrDwords);
12302 }
12303 assert(Opcode != -1);
12304
12306
12307 auto packLanes = [&DAG, &Ops, &DL](SDValue Op, bool IsAligned) {
12309 DAG.ExtractVectorElements(Op, Lanes, 0, 3);
12310 if (Lanes[0].getValueSizeInBits() == 32) {
12311 for (unsigned I = 0; I < 3; ++I)
12312 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
12313 } else {
12314 if (IsAligned) {
12315 Ops.push_back(DAG.getBitcast(
12316 MVT::i32,
12317 DAG.getBuildVector(MVT::v2f16, DL, {Lanes[0], Lanes[1]})));
12318 Ops.push_back(Lanes[2]);
12319 } else {
12320 SDValue Elt0 = Ops.pop_back_val();
12321 Ops.push_back(DAG.getBitcast(
12322 MVT::i32, DAG.getBuildVector(MVT::v2f16, DL, {Elt0, Lanes[0]})));
12323 Ops.push_back(DAG.getBitcast(
12324 MVT::i32,
12325 DAG.getBuildVector(MVT::v2f16, DL, {Lanes[1], Lanes[2]})));
12326 }
12327 }
12328 };
12329
12330 if (UseNSA && IsGFX11Plus) {
12331 Ops.push_back(NodePtr);
12332 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
12333 Ops.push_back(RayOrigin);
12334 if (IsA16) {
12335 SmallVector<SDValue, 3> DirLanes, InvDirLanes, MergedLanes;
12336 DAG.ExtractVectorElements(RayDir, DirLanes, 0, 3);
12337 DAG.ExtractVectorElements(RayInvDir, InvDirLanes, 0, 3);
12338 for (unsigned I = 0; I < 3; ++I) {
12339 MergedLanes.push_back(DAG.getBitcast(
12340 MVT::i32, DAG.getBuildVector(MVT::v2f16, DL,
12341 {DirLanes[I], InvDirLanes[I]})));
12342 }
12343 Ops.push_back(DAG.getBuildVector(MVT::v3i32, DL, MergedLanes));
12344 } else {
12345 Ops.push_back(RayDir);
12346 Ops.push_back(RayInvDir);
12347 }
12348 } else {
12349 if (Is64)
12350 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0,
12351 2);
12352 else
12353 Ops.push_back(NodePtr);
12354
12355 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
12356 packLanes(RayOrigin, true);
12357 packLanes(RayDir, true);
12358 packLanes(RayInvDir, false);
12359 }
12360
12361 if (!UseNSA) {
12362 // Build a single vector containing all the operands so far prepared.
12363 if (NumVAddrDwords > 12) {
12364 SDValue Undef = DAG.getPOISON(MVT::i32);
12365 Ops.append(16 - Ops.size(), Undef);
12366 }
12367 assert(Ops.size() >= 8 && Ops.size() <= 12);
12368 SDValue MergedOps =
12369 DAG.getBuildVector(MVT::getVectorVT(MVT::i32, Ops.size()), DL, Ops);
12370 Ops.clear();
12371 Ops.push_back(MergedOps);
12372 }
12373
12374 Ops.push_back(TDescr);
12375 Ops.push_back(DAG.getTargetConstant(IsA16, DL, MVT::i1));
12376 Ops.push_back(M->getChain());
12377
12378 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
12379 MachineMemOperand *MemRef = M->getMemOperand();
12380 DAG.setNodeMemRefs(NewNode, {MemRef});
12381 return SDValue(NewNode, 0);
12382 }
12383 case Intrinsic::amdgcn_global_atomic_fmin_num:
12384 case Intrinsic::amdgcn_global_atomic_fmax_num:
12385 case Intrinsic::amdgcn_flat_atomic_fmin_num:
12386 case Intrinsic::amdgcn_flat_atomic_fmax_num: {
12387 MemSDNode *M = cast<MemSDNode>(Op);
12388 SDValue Ops[] = {
12389 M->getOperand(0), // Chain
12390 M->getOperand(2), // Ptr
12391 M->getOperand(3) // Value
12392 };
12393 unsigned Opcode = 0;
12394 switch (IntrID) {
12395 case Intrinsic::amdgcn_global_atomic_fmin_num:
12396 case Intrinsic::amdgcn_flat_atomic_fmin_num: {
12397 Opcode = ISD::ATOMIC_LOAD_FMIN;
12398 break;
12399 }
12400 case Intrinsic::amdgcn_global_atomic_fmax_num:
12401 case Intrinsic::amdgcn_flat_atomic_fmax_num: {
12402 Opcode = ISD::ATOMIC_LOAD_FMAX;
12403 break;
12404 }
12405 default:
12406 llvm_unreachable("unhandled atomic opcode");
12407 }
12408 return DAG.getAtomic(Opcode, SDLoc(Op), M->getMemoryVT(), M->getVTList(),
12409 Ops, M->getMemOperand());
12410 }
12411 case Intrinsic::amdgcn_s_alloc_vgpr: {
12412 SDValue NumVGPRs = Op.getOperand(2);
12413 if (!NumVGPRs->isDivergent())
12414 return Op;
12415
12416 SDValue ReadFirstLaneID =
12417 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
12418 NumVGPRs = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
12419 ReadFirstLaneID, NumVGPRs);
12420
12421 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, Op->getVTList(),
12422 Op.getOperand(0), Op.getOperand(1), NumVGPRs);
12423 }
12424 case Intrinsic::amdgcn_s_get_barrier_state:
12425 case Intrinsic::amdgcn_s_get_named_barrier_state: {
12426 SDValue Chain = Op->getOperand(0);
12428 unsigned Opc;
12429
12430 std::optional<uint32_t> BarID;
12431 if (IntrID == Intrinsic::amdgcn_s_get_named_barrier_state)
12432 BarID = getConstantNamedBarrierNumber(Op->getOperand(2), DAG);
12433 else if (auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(2)))
12434 BarID = C->getZExtValue();
12435
12436 if (BarID) {
12437 Opc = AMDGPU::S_GET_BARRIER_STATE_IMM;
12438 SDValue K = DAG.getTargetConstant(*BarID, DL, MVT::i32);
12439 Ops.push_back(K);
12440 Ops.push_back(Chain);
12441 } else {
12442 Opc = AMDGPU::S_GET_BARRIER_STATE_M0;
12443 if (IntrID == Intrinsic::amdgcn_s_get_named_barrier_state) {
12444 SDValue M0Val = DAG.getNode(ISD::AND, DL, MVT::i32, Op->getOperand(2),
12445 DAG.getConstant(0x3F, DL, MVT::i32));
12446 Ops.push_back(copyToM0(DAG, Chain, DL, M0Val).getValue(0));
12447 } else
12448 Ops.push_back(copyToM0(DAG, Chain, DL, Op->getOperand(2)).getValue(0));
12449 }
12450
12451 auto *NewMI = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
12452 return SDValue(NewMI, 0);
12453 }
12454 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
12455 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
12456 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B: {
12457 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
12458 SDValue Chain = Op->getOperand(0);
12459 SDValue Ptr = Op->getOperand(2);
12460 EVT VT = Op->getValueType(0);
12461 return DAG.getAtomicLoad(ISD::NON_EXTLOAD, DL, MII->getMemoryVT(), VT,
12462 Chain, Ptr, MII->getMemOperand());
12463 }
12464 case Intrinsic::amdgcn_av_load_b8:
12465 case Intrinsic::amdgcn_av_load_b16:
12466 case Intrinsic::amdgcn_av_load_b32:
12467 case Intrinsic::amdgcn_av_load_b64:
12468 case Intrinsic::amdgcn_av_load_b128: {
12469 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
12470 SDValue Chain = Op->getOperand(0);
12471 SDValue Ptr = Op->getOperand(2);
12472 EVT VT = Op->getValueType(0);
12473 // Lower to a regular ISD::LOAD. The MachineMemOperand carries Monotonic
12474 // ordering and syncscope so that SIMemoryLegalizer sets cache policy bits.
12475 // Address space filtering in the load_global/load_flat PatFrags selects
12476 // the correct GLOBAL vs FLAT instruction.
12477 return DAG.getLoad(VT, DL, Chain, Ptr, MII->getMemOperand());
12478 }
12479 case Intrinsic::amdgcn_flat_load_monitor_b32:
12480 case Intrinsic::amdgcn_flat_load_monitor_b64:
12481 case Intrinsic::amdgcn_flat_load_monitor_b128: {
12482 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
12483 SDValue Chain = Op->getOperand(0);
12484 SDValue Ptr = Op->getOperand(2);
12485 return DAG.getMemIntrinsicNode(AMDGPUISD::FLAT_LOAD_MONITOR, DL,
12486 Op->getVTList(), {Chain, Ptr},
12487 MII->getMemoryVT(), MII->getMemOperand());
12488 }
12489 case Intrinsic::amdgcn_global_load_monitor_b32:
12490 case Intrinsic::amdgcn_global_load_monitor_b64:
12491 case Intrinsic::amdgcn_global_load_monitor_b128: {
12492 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
12493 SDValue Chain = Op->getOperand(0);
12494 SDValue Ptr = Op->getOperand(2);
12495 return DAG.getMemIntrinsicNode(AMDGPUISD::GLOBAL_LOAD_MONITOR, DL,
12496 Op->getVTList(), {Chain, Ptr},
12497 MII->getMemoryVT(), MII->getMemOperand());
12498 }
12499 default:
12500
12501 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
12503 return lowerImage(Op, ImageDimIntr, DAG, true);
12504
12505 return SDValue();
12506 }
12507}
12508
12509// Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
12510// dwordx4 if on SI and handle TFE loads.
12511SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
12512 SDVTList VTList,
12513 ArrayRef<SDValue> Ops, EVT MemVT,
12514 MachineMemOperand *MMO,
12515 SelectionDAG &DAG) const {
12516 LLVMContext &C = *DAG.getContext();
12518 EVT VT = VTList.VTs[0];
12519
12520 assert(VTList.NumVTs == 2 || VTList.NumVTs == 3);
12521 bool IsTFE = VTList.NumVTs == 3;
12522 if (IsTFE) {
12523 unsigned NumValueDWords = divideCeil(VT.getSizeInBits(), 32);
12524 unsigned NumOpDWords = NumValueDWords + 1;
12525 EVT OpDWordsVT = EVT::getVectorVT(C, MVT::i32, NumOpDWords);
12526 SDVTList OpDWordsVTList = DAG.getVTList(OpDWordsVT, VTList.VTs[2]);
12527 MachineMemOperand *OpDWordsMMO =
12528 MF.getMachineMemOperand(MMO, 0, NumOpDWords * 4);
12529 SDValue Op = getMemIntrinsicNode(Opcode, DL, OpDWordsVTList, Ops,
12530 OpDWordsVT, OpDWordsMMO, DAG);
12531 auto [Value, Status] = splitTFEValueAndStatus(Op, VT, DL, DAG);
12532 return DAG.getMergeValues({Value, Status, SDValue(Op.getNode(), 1)}, DL);
12533 }
12534
12535 if (!Subtarget->hasDwordx3LoadStores() &&
12536 (VT == MVT::v3i32 || VT == MVT::v3f32)) {
12537 EVT WidenedVT = EVT::getVectorVT(C, VT.getVectorElementType(), 4);
12538 EVT WidenedMemVT = EVT::getVectorVT(C, MemVT.getVectorElementType(), 4);
12539 MachineMemOperand *WidenedMMO = MF.getMachineMemOperand(MMO, 0, 16);
12540 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
12541 SDValue Op = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
12542 WidenedMemVT, WidenedMMO);
12544 DAG.getVectorIdxConstant(0, DL));
12545 return DAG.getMergeValues({Value, SDValue(Op.getNode(), 1)}, DL);
12546 }
12547
12548 return DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops, MemVT, MMO);
12549}
12550
12551SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
12552 bool ImageStore) const {
12553 EVT StoreVT = VData.getValueType();
12554
12555 // No change for f16 and legal vector D16 types.
12556 if (!StoreVT.isVector())
12557 return VData;
12558
12559 SDLoc DL(VData);
12560 unsigned NumElements = StoreVT.getVectorNumElements();
12561
12562 if (Subtarget->hasUnpackedD16VMem()) {
12563 // We need to unpack the packed data to store.
12564 EVT IntStoreVT = StoreVT.changeTypeToInteger();
12565 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
12566
12567 EVT EquivStoreVT =
12568 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
12569 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
12570 return DAG.UnrollVectorOp(ZExt.getNode());
12571 }
12572
12573 // The sq block of gfx8.1 does not estimate register use correctly for d16
12574 // image store instructions. The data operand is computed as if it were not a
12575 // d16 image instruction.
12576 if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
12577 // Bitcast to i16
12578 EVT IntStoreVT = StoreVT.changeTypeToInteger();
12579 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
12580
12581 // Decompose into scalars
12583 DAG.ExtractVectorElements(IntVData, Elts);
12584
12585 // Group pairs of i16 into v2i16 and bitcast to i32
12586 SmallVector<SDValue, 4> PackedElts;
12587 for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
12588 SDValue Pair =
12589 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
12590 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
12591 PackedElts.push_back(IntPair);
12592 }
12593 if ((NumElements % 2) == 1) {
12594 // Handle v3i16
12595 unsigned I = Elts.size() / 2;
12596 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
12597 {Elts[I * 2], DAG.getPOISON(MVT::i16)});
12598 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
12599 PackedElts.push_back(IntPair);
12600 }
12601
12602 // Pad using UNDEF
12603 PackedElts.resize(Elts.size(), DAG.getPOISON(MVT::i32));
12604
12605 // Build final vector
12606 EVT VecVT =
12607 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
12608 return DAG.getBuildVector(VecVT, DL, PackedElts);
12609 }
12610
12611 if (NumElements == 3) {
12612 EVT IntStoreVT =
12614 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
12615
12616 EVT WidenedStoreVT = EVT::getVectorVT(
12617 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
12618 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
12619 WidenedStoreVT.getStoreSizeInBits());
12620 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
12621 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
12622 }
12623
12624 assert(isTypeLegal(StoreVT));
12625 return VData;
12626}
12627
12628static bool isAsyncLDSDMA(Intrinsic::ID Intr) {
12629 if (const AMDGPU::BufferIntrinsicInfo *BufInfo =
12631 return BufInfo->IsAsync;
12632 switch (Intr) {
12633 case Intrinsic::amdgcn_load_async_to_lds:
12634 case Intrinsic::amdgcn_global_load_async_lds:
12635 return true;
12636 }
12637 return false;
12638}
12639
12640// Lower the buffer stores, loads to LDS and prefetches, which are all
12641// INTRINSIC_VOID nodes.
12642SDValue SITargetLowering::lowerBufferIntrinsicVoid(
12644 SelectionDAG &DAG) const {
12645 SDLoc DL(Op);
12646 SDValue Chain = Op.getOperand(0);
12647 auto *M = cast<MemSDNode>(Op);
12648 auto GetArg = [&](unsigned Arg) {
12649 return Op.getOperand(AMDGPU::getSDOperandIdx(Arg));
12650 };
12651
12652 switch (Info.Kind) {
12653 case AMDGPU::BufferKindStore: {
12654 SDValue VData = GetArg(*Info.getVDataArg());
12655 EVT VDataVT = VData.getValueType();
12656 EVT EltType = VDataVT.getScalarType();
12657
12658 if (Info.isTyped()) {
12659 bool IsD16 = EltType.getSizeInBits() == 16;
12660 if (IsD16)
12661 VData = handleD16VData(VData, DAG);
12663 getBufferIntrinsicOps(Op, Info, DAG, VData);
12664 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16
12665 : AMDGPUISD::TBUFFER_STORE_FORMAT;
12666 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
12667 M->getMemoryVT(), M->getMemOperand());
12668 }
12669
12670 bool IsFormat = Info.isFormatFromRsrc();
12671 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
12672
12673 if (IsFormat && !IsD16 && EltType.getSizeInBits() < 32) {
12674 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
12676 "unsupported sub-dword format buffer store", DL.getDebugLoc()));
12677 return Chain;
12678 }
12679
12680 if (IsD16) {
12681 VData = handleD16VData(VData, DAG);
12682 VDataVT = VData.getValueType();
12683 }
12684
12685 if (!isTypeLegal(VDataVT)) {
12686 VData =
12687 DAG.getNode(ISD::BITCAST, DL,
12688 getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
12689 }
12690
12691 SmallVector<SDValue, 10> Ops = getBufferIntrinsicOps(Op, Info, DAG, VData);
12692 unsigned Opc =
12693 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
12694 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
12695
12696 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
12697 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
12698 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops.data(), M);
12699
12700 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
12701 M->getMemoryVT(), M->getMemOperand());
12702 }
12703 case AMDGPU::BufferKindLoadToLDS: {
12704 unsigned Opc;
12705 std::optional<unsigned> VIndexArg = Info.getVIndexArg();
12706 bool HasVIndex = VIndexArg.has_value();
12707 SDValue VOffset = GetArg(*Info.getVOffsetArg());
12708 bool HasVOffset = !isNullConstant(VOffset);
12709 unsigned Size = GetArg(*Info.getSizeArg())->getAsZExtVal();
12710
12711 switch (Size) {
12712 default:
12713 return SDValue();
12714 case 1:
12715 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN
12716 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN
12717 : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN
12718 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET;
12719 break;
12720 case 2:
12721 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN
12722 : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN
12723 : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN
12724 : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET;
12725 break;
12726 case 4:
12727 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN
12728 : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN
12729 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN
12730 : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET;
12731 break;
12732 case 12:
12733 if (!Subtarget->hasLDSLoadB96_B128())
12734 return SDValue();
12735 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX3_LDS_BOTHEN
12736 : AMDGPU::BUFFER_LOAD_DWORDX3_LDS_IDXEN
12737 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX3_LDS_OFFEN
12738 : AMDGPU::BUFFER_LOAD_DWORDX3_LDS_OFFSET;
12739 break;
12740 case 16:
12741 if (!Subtarget->hasLDSLoadB96_B128())
12742 return SDValue();
12743 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX4_LDS_BOTHEN
12744 : AMDGPU::BUFFER_LOAD_DWORDX4_LDS_IDXEN
12745 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX4_LDS_OFFEN
12746 : AMDGPU::BUFFER_LOAD_DWORDX4_LDS_OFFSET;
12747 break;
12748 }
12749
12750 SDValue M0Val = copyToM0(DAG, Chain, DL, GetArg(*Info.getLDSPtrArg()));
12751
12753
12754 if (HasVIndex && HasVOffset)
12755 Ops.push_back(
12756 DAG.getBuildVector(MVT::v2i32, DL, {GetArg(*VIndexArg), VOffset}));
12757 else if (HasVIndex)
12758 Ops.push_back(GetArg(*VIndexArg));
12759 else if (HasVOffset)
12760 Ops.push_back(VOffset);
12761
12762 SDValue Rsrc = bufferRsrcPtrToVector(GetArg(Info.RsrcArg), DAG);
12763 Ops.push_back(Rsrc);
12764 Ops.push_back(GetArg(*Info.getSOffsetArg()));
12765 Ops.push_back(GetArg(*Info.getImmOffsetArg()));
12766 bool IsGFX12Plus = AMDGPU::isGFX12Plus(*Subtarget);
12767 unsigned Aux = GetArg(*Info.getAuxArg())->getAsZExtVal();
12768 Ops.push_back(DAG.getTargetConstant(
12769 Aux & (IsGFX12Plus ? AMDGPU::CPol::ALL : AMDGPU::CPol::ALL_pregfx12),
12770 DL, MVT::i16)); // cpol
12771 Ops.push_back(DAG.getTargetConstant(
12772 Aux & (IsGFX12Plus ? AMDGPU::CPol::SWZ : AMDGPU::CPol::SWZ_pregfx12)
12773 ? 1
12774 : 0,
12775 DL, MVT::i8)); // swz
12776 Ops.push_back(DAG.getTargetConstant(Info.IsAsync, DL, MVT::i8)); // async
12777 Ops.push_back(M0Val.getValue(0)); // Chain
12778 Ops.push_back(M0Val.getValue(1)); // Glue
12779
12780 auto *Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops);
12781 DAG.setNodeMemRefs(Load, M->memoperands());
12782
12783 return SDValue(Load, 0);
12784 }
12785 case AMDGPU::BufferKindPrefetch: {
12786 SDValue Ops[] = {
12787 Chain,
12788 bufferRsrcPtrToVector(GetArg(Info.RsrcArg), DAG),
12789 GetArg(*Info.getSOffsetArg()), // soffset
12790 GetArg(*Info.getSizeArg()), // length
12791 };
12792
12793 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_PREFETCH_DATA, DL,
12794 Op->getVTList(), Ops, M->getMemoryVT(),
12795 M->getMemOperand());
12796 }
12797 default:
12798 llvm_unreachable("not a buffer intrinsic without a result");
12799 }
12800}
12801
12802SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
12803 SelectionDAG &DAG) const {
12804 SDLoc DL(Op);
12805 SDValue Chain = Op.getOperand(0);
12806 unsigned IntrinsicID = Op.getConstantOperandVal(1);
12807
12808 if (const AMDGPU::BufferIntrinsicInfo *BufInfo =
12809 AMDGPU::lookupBufferIntrinsic(IntrinsicID))
12810 return lowerBufferIntrinsicVoid(Op, *BufInfo, DAG);
12811
12812 switch (IntrinsicID) {
12813 case Intrinsic::amdgcn_cluster_load_async_to_lds_b8:
12814 case Intrinsic::amdgcn_cluster_load_async_to_lds_b32:
12815 case Intrinsic::amdgcn_cluster_load_async_to_lds_b64:
12816 case Intrinsic::amdgcn_cluster_load_async_to_lds_b128: {
12817 if (Subtarget->hasGFX1250_STRICT())
12819 return SDValue();
12820 }
12821 case Intrinsic::amdgcn_exp_compr: {
12822 SDValue Src0 = Op.getOperand(4);
12823 SDValue Src1 = Op.getOperand(5);
12824 // Hack around illegal type on SI by directly selecting it.
12825 if (isTypeLegal(Src0.getValueType()))
12826 return SDValue();
12827
12828 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
12829 SDValue Undef = DAG.getPOISON(MVT::f32);
12830 const SDValue Ops[] = {
12831 Op.getOperand(2), // tgt
12832 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
12833 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
12834 Undef, // src2
12835 Undef, // src3
12836 Op.getOperand(7), // vm
12837 DAG.getTargetConstant(1, DL, MVT::i1), // compr
12838 Op.getOperand(3), // en
12839 Op.getOperand(0) // Chain
12840 };
12841
12842 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
12843 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
12844 }
12845
12846 // Buffers are handled by LowerBufferFatPointers, and we're going to go
12847 // for "trust me" that the remaining cases are global pointers until
12848 // such time as we can put two mem operands on an intrinsic.
12849 case Intrinsic::amdgcn_load_to_lds:
12850 case Intrinsic::amdgcn_load_async_to_lds:
12851 case Intrinsic::amdgcn_global_load_lds:
12852 case Intrinsic::amdgcn_global_load_async_lds: {
12853 if (!Subtarget->hasVMemToLDSLoad())
12854 return SDValue();
12855
12856 unsigned Opc;
12857 unsigned Size = Op->getConstantOperandVal(4);
12858 switch (Size) {
12859 default:
12860 return SDValue();
12861 case 1:
12862 Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE;
12863 break;
12864 case 2:
12865 Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT;
12866 break;
12867 case 4:
12868 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD;
12869 break;
12870 case 12:
12871 if (!Subtarget->hasLDSLoadB96_B128())
12872 return SDValue();
12873 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORDX3;
12874 break;
12875 case 16:
12876 if (!Subtarget->hasLDSLoadB96_B128())
12877 return SDValue();
12878 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORDX4;
12879 break;
12880 }
12881
12882 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
12883
12885
12886 SDValue Addr = Op.getOperand(2); // Global ptr
12887 SDValue VOffset;
12888 // Try to split SAddr and VOffset. Global and LDS pointers share the same
12889 // immediate offset, so we cannot use a regular SelectGlobalSAddr().
12890 if (Addr->isDivergent() && Addr->isAnyAdd()) {
12891 SDValue LHS = Addr.getOperand(0);
12892 SDValue RHS = Addr.getOperand(1);
12893
12894 if (LHS->isDivergent())
12895 std::swap(LHS, RHS);
12896
12897 if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND &&
12898 RHS.getOperand(0).getValueType() == MVT::i32) {
12899 // add (i64 sgpr), (zero_extend (i32 vgpr))
12900 Addr = LHS;
12901 VOffset = RHS.getOperand(0);
12902 }
12903 }
12904
12905 Ops.push_back(Addr);
12906 if (!Addr->isDivergent()) {
12908 if (!VOffset)
12909 VOffset =
12910 SDValue(DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32,
12911 DAG.getTargetConstant(0, DL, MVT::i32)),
12912 0);
12913 Ops.push_back(VOffset);
12914 }
12915
12916 Ops.push_back(Op.getOperand(5)); // Offset
12917
12918 unsigned Aux = Op.getConstantOperandVal(6);
12919 Ops.push_back(DAG.getTargetConstant(Aux & ~AMDGPU::CPol::VIRTUAL_BITS, DL,
12920 MVT::i32)); // CPol
12921 Ops.push_back(
12922 DAG.getTargetConstant(isAsyncLDSDMA(IntrinsicID), DL, MVT::i8));
12923
12924 Ops.push_back(M0Val.getValue(0)); // Chain
12925 Ops.push_back(M0Val.getValue(1)); // Glue
12926
12927 auto *M = cast<MemSDNode>(Op);
12928 auto *Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
12929 DAG.setNodeMemRefs(Load, M->memoperands());
12930
12931 return SDValue(Load, 0);
12932 }
12933 case Intrinsic::amdgcn_end_cf:
12934 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
12935 Op->getOperand(2), Chain),
12936 0);
12937 case Intrinsic::amdgcn_s_barrier_signal_var: {
12938 // Member count of 0 means to re-use a previous member count,
12939 // which, if the named barrier is statically chosen, means we can use
12940 // the immarg form. Otherwisee, fall through to constructiong M0 as for
12941 // s_barrier_init.
12942 SDValue CntOp = Op->getOperand(3);
12943 auto *CntC = dyn_cast<ConstantSDNode>(CntOp);
12944 if (CntC && CntC->isZero()) {
12945 SDValue Chain = Op->getOperand(0);
12946 SDValue BarOp = Op->getOperand(2);
12947
12948 if (auto BarID = getConstantNamedBarrierNumber(BarOp, DAG)) {
12949 std::array<SDValue, 2> Ops = {
12950 DAG.getTargetConstant(*BarID, DL, MVT::i32), Chain};
12951 auto *NewMI = DAG.getMachineNode(AMDGPU::S_BARRIER_SIGNAL_IMM, DL,
12952 Op->getVTList(), Ops);
12953 return SDValue(NewMI, 0);
12954 }
12955 }
12956 [[fallthrough]];
12957 }
12958 case Intrinsic::amdgcn_s_barrier_init: {
12959 // these two intrinsics have two operands: barrier pointer and member count
12960 SDValue Chain = Op->getOperand(0);
12962 SDValue BarOp = Op->getOperand(2);
12963 SDValue CntOp = Op->getOperand(3);
12964 SDValue M0Val;
12965 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_s_barrier_init
12966 ? AMDGPU::S_BARRIER_INIT_M0
12967 : AMDGPU::S_BARRIER_SIGNAL_M0;
12968 // extract the BarrierID from bits 0-5 of BarOp
12969 SDValue BarID = DAG.getNode(ISD::AND, DL, MVT::i32, BarOp,
12970 DAG.getConstant(0x3F, DL, MVT::i32));
12971 // Member count should be put into M0[ShAmt:+CntMask width]
12972 // Barrier ID should be put into M0[5:0]
12973 unsigned CntMask = AMDGPU::getBarrierMemberCountBitMask(
12974 AMDGPU::getIsaVersion(Subtarget->getCPU()));
12975 SDValue MemberCnt = DAG.getNode(ISD::AND, DL, MVT::i32, CntOp,
12976 DAG.getConstant(CntMask, DL, MVT::i32));
12977 constexpr unsigned ShAmt = 16;
12978 M0Val = DAG.getNode(ISD::SHL, DL, MVT::i32, MemberCnt,
12979 DAG.getShiftAmountConstant(ShAmt, MVT::i32, DL));
12980
12981 M0Val = DAG.getNode(ISD::OR, DL, MVT::i32, M0Val, BarID);
12982
12983 Ops.push_back(copyToM0(DAG, Chain, DL, M0Val).getValue(0));
12984
12985 auto *NewMI = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
12986 return SDValue(NewMI, 0);
12987 }
12988 case Intrinsic::amdgcn_s_wakeup_barrier: {
12989 if (!Subtarget->hasSWakeupBarrier())
12990 return SDValue();
12991 [[fallthrough]];
12992 }
12993 case Intrinsic::amdgcn_s_barrier_join: {
12994 // these three intrinsics have one operand: barrier pointer
12995 SDValue Chain = Op->getOperand(0);
12997 SDValue BarOp = Op->getOperand(2);
12998 unsigned Opc;
12999
13000 if (auto BarID = getConstantNamedBarrierNumber(BarOp, DAG)) {
13001 switch (IntrinsicID) {
13002 default:
13003 return SDValue();
13004 case Intrinsic::amdgcn_s_barrier_join:
13005 Opc = AMDGPU::S_BARRIER_JOIN_IMM;
13006 break;
13007 case Intrinsic::amdgcn_s_wakeup_barrier:
13008 Opc = AMDGPU::S_WAKEUP_BARRIER_IMM;
13009 break;
13010 }
13011 SDValue K = DAG.getTargetConstant(*BarID, DL, MVT::i32);
13012 Ops.push_back(K);
13013 Ops.push_back(Chain);
13014 } else {
13015 switch (IntrinsicID) {
13016 default:
13017 return SDValue();
13018 case Intrinsic::amdgcn_s_barrier_join:
13019 Opc = AMDGPU::S_BARRIER_JOIN_M0;
13020 break;
13021 case Intrinsic::amdgcn_s_wakeup_barrier:
13022 Opc = AMDGPU::S_WAKEUP_BARRIER_M0;
13023 break;
13024 }
13025 // extract the BarrierID from bits 0-5 of BarOp, copy to M0[5:0]
13026 SDValue M0Val = DAG.getNode(ISD::AND, DL, MVT::i32, BarOp,
13027 DAG.getConstant(0x3F, DL, MVT::i32));
13028 Ops.push_back(copyToM0(DAG, Chain, DL, M0Val).getValue(0));
13029 }
13030
13031 auto *NewMI = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
13032 return SDValue(NewMI, 0);
13033 }
13034 case Intrinsic::amdgcn_s_prefetch_data:
13035 case Intrinsic::amdgcn_s_prefetch_inst: {
13036 // For non-global address space preserve the chain and remove the call.
13038 return Op.getOperand(0);
13039 return Op;
13040 }
13041 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
13042 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
13043 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B: {
13044 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
13045 SDValue Chain = Op->getOperand(0);
13046 SDValue Ptr = Op->getOperand(2);
13047 SDValue Val = Op->getOperand(3);
13048 return DAG.getAtomic(ISD::ATOMIC_STORE, DL, MII->getMemoryVT(), Chain, Val,
13049 Ptr, MII->getMemOperand());
13050 }
13051 case Intrinsic::amdgcn_av_store_b8:
13052 case Intrinsic::amdgcn_av_store_b16:
13053 case Intrinsic::amdgcn_av_store_b32:
13054 case Intrinsic::amdgcn_av_store_b64:
13055 case Intrinsic::amdgcn_av_store_b128: {
13056 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
13057 SDValue Chain = Op->getOperand(0);
13058 SDValue Ptr = Op->getOperand(2);
13059 SDValue Val = Op->getOperand(3);
13060 return DAG.getStore(Chain, DL, Val, Ptr, MII->getMemOperand());
13061 }
13062 default: {
13063 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
13065 return lowerImage(Op, ImageDimIntr, DAG, true);
13066
13067 return Op;
13068 }
13069 }
13070}
13071
13072// Return whether the operation has NoUnsignedWrap property.
13073static bool isNoUnsignedWrap(SDValue Addr) {
13074 return (Addr.getOpcode() == ISD::ADD &&
13075 Addr->getFlags().hasNoUnsignedWrap()) ||
13076 Addr->getOpcode() == ISD::OR;
13077}
13078
13080 EVT PtrVT) const {
13081 return PtrVT == MVT::i64;
13082}
13083
13085 EVT PtrVT) const {
13086 return true;
13087}
13088
13089// The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
13090// offset (the offset that is included in bounds checking and swizzling, to be
13091// split between the instruction's voffset and immoffset fields) and soffset
13092// (the offset that is excluded from bounds checking and swizzling, to go in
13093// the instruction's soffset field). This function takes the first kind of
13094// offset and figures out how to split it between voffset and immoffset.
13095std::pair<SDValue, SDValue>
13096SITargetLowering::splitBufferOffsets(SDValue Offset, SelectionDAG &DAG) const {
13097 SDLoc DL(Offset);
13098 const unsigned MaxImm = SIInstrInfo::getMaxMUBUFImmOffset(*Subtarget);
13099 SDValue N0 = Offset;
13100 ConstantSDNode *C1 = nullptr;
13101
13102 if ((C1 = dyn_cast<ConstantSDNode>(N0)))
13103 N0 = SDValue();
13104 else if (DAG.isBaseWithConstantOffset(N0)) {
13105 // On GFX1250+, voffset and immoffset are zero-extended from 32 bits before
13106 // being added, so we can only safely match a 32-bit addition with no
13107 // unsigned overflow.
13108 bool CheckNUW = Subtarget->hasGFX1250Insts();
13109 if (!CheckNUW || isNoUnsignedWrap(N0)) {
13111 N0 = N0.getOperand(0);
13112 }
13113 }
13114
13115 if (C1) {
13116 unsigned ImmOffset = C1->getZExtValue();
13117 // If the immediate value is too big for the immoffset field, put only bits
13118 // that would normally fit in the immoffset field. The remaining value that
13119 // is copied/added for the voffset field is a large power of 2, and it
13120 // stands more chance of being CSEd with the copy/add for another similar
13121 // load/store.
13122 // However, do not do that rounding down if that is a negative
13123 // number, as it appears to be illegal to have a negative offset in the
13124 // vgpr, even if adding the immediate offset makes it positive.
13125 unsigned Overflow = ImmOffset & ~MaxImm;
13126 ImmOffset -= Overflow;
13127 if ((int32_t)Overflow < 0) {
13128 Overflow += ImmOffset;
13129 ImmOffset = 0;
13130 }
13131 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
13132 if (Overflow) {
13133 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
13134 if (!N0)
13135 N0 = OverflowVal;
13136 else {
13137 SDValue Ops[] = {N0, OverflowVal};
13138 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
13139 }
13140 }
13141 }
13142 if (!N0)
13143 N0 = DAG.getConstant(0, DL, MVT::i32);
13144 if (!C1)
13145 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
13146 return {N0, SDValue(C1, 0)};
13147}
13148
13149// Analyze a combined offset from an amdgcn_s_buffer_load intrinsic and store
13150// the three offsets (voffset, soffset and instoffset) into the SDValue[3] array
13151// pointed to by Offsets.
13152void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
13153 SelectionDAG &DAG, SDValue *Offsets,
13154 Align Alignment) const {
13155 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
13156 SDLoc DL(CombinedOffset);
13157 if (auto *C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
13158 uint32_t Imm = C->getZExtValue();
13159 uint32_t SOffset, ImmOffset;
13160 if (TII->splitMUBUFOffset(Imm, SOffset, ImmOffset, Alignment)) {
13161 Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
13162 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
13163 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
13164 return;
13165 }
13166 }
13167 if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
13168 // On GFX1250+, voffset and immoffset are zero-extended from 32 bits before
13169 // being added, so we can only safely match a 32-bit addition with no
13170 // unsigned overflow.
13171 bool CheckNUW = Subtarget->hasGFX1250Insts();
13172 SDValue N0 = CombinedOffset.getOperand(0);
13173 SDValue N1 = CombinedOffset.getOperand(1);
13174 uint32_t SOffset, ImmOffset;
13175 int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
13176 if (Offset >= 0 && (!CheckNUW || isNoUnsignedWrap(CombinedOffset)) &&
13177 TII->splitMUBUFOffset(Offset, SOffset, ImmOffset, Alignment)) {
13178 Offsets[0] = N0;
13179 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
13180 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
13181 return;
13182 }
13183 }
13184
13185 SDValue SOffsetZero = Subtarget->hasRestrictedSOffset()
13186 ? DAG.getRegister(AMDGPU::SGPR_NULL, MVT::i32)
13187 : DAG.getConstant(0, DL, MVT::i32);
13188
13189 Offsets[0] = CombinedOffset;
13190 Offsets[1] = SOffsetZero;
13191 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
13192}
13193
13194SDValue SITargetLowering::bufferRsrcPtrToVector(SDValue MaybePointer,
13195 SelectionDAG &DAG) const {
13196 if (!MaybePointer.getValueType().isScalarInteger())
13197 return MaybePointer;
13198
13199 SDValue Rsrc = DAG.getBitcast(MVT::v4i32, MaybePointer);
13200 return Rsrc;
13201}
13202
13203// Wrap a global or flat pointer into a buffer intrinsic using the flags
13204// specified in the intrinsic.
13205SDValue SITargetLowering::lowerPointerAsRsrcIntrin(SDNode *Op,
13206 SelectionDAG &DAG) const {
13207 SDLoc Loc(Op);
13208
13209 SDValue Pointer = Op->getOperand(1);
13210 SDValue Stride = Op->getOperand(2);
13211 SDValue NumRecords = Op->getOperand(3);
13212 SDValue Flags = Op->getOperand(4);
13213
13214 SDValue ExtStride = DAG.getAnyExtOrTrunc(Stride, Loc, MVT::i32);
13215 SDValue Rsrc;
13216
13217 if (Subtarget->getBufferResourceNumRecordsWidth() == 45) {
13218 NumRecords = DAG.getZExtOrTrunc(NumRecords, Loc, MVT::i64);
13219 NumRecords = DAG.getNode(ISD::AND, Loc, MVT::i64, NumRecords,
13220 DAG.getConstant((1ULL << 45) - 1, Loc, MVT::i64));
13221 SDValue Zero = DAG.getConstant(0, Loc, MVT::i32);
13222 // Build the lower 64-bit value, which has a 57-bit base and the lower 7-bit
13223 // num_records.
13224 SDValue ExtPointer = DAG.getAnyExtOrTrunc(Pointer, Loc, MVT::i64);
13225 SDValue NumRecordsLHS =
13226 DAG.getNode(ISD::SHL, Loc, MVT::i64, NumRecords,
13227 DAG.getShiftAmountConstant(57, MVT::i32, Loc));
13228 SDValue LowHalf =
13229 DAG.getNode(ISD::OR, Loc, MVT::i64, ExtPointer, NumRecordsLHS);
13230
13231 // Build the higher 64-bit value, which has the higher 38-bit num_records,
13232 // 6-bit zero (omit), 16-bit stride and scale and 4-bit flag.
13233 SDValue NumRecordsRHS =
13234 DAG.getNode(ISD::SRL, Loc, MVT::i64, NumRecords,
13235 DAG.getShiftAmountConstant(7, MVT::i32, Loc));
13236 SDValue ShiftedStride =
13237 DAG.getNode(ISD::SHL, Loc, MVT::i32, ExtStride,
13238 DAG.getShiftAmountConstant(12, MVT::i32, Loc));
13239 SDValue ExtShiftedStrideVec =
13240 DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v2i32, Zero, ShiftedStride);
13241 SDValue ExtShiftedStride =
13242 DAG.getNode(ISD::BITCAST, Loc, MVT::i64, ExtShiftedStrideVec);
13243 SDValue ShiftedFlags =
13244 DAG.getNode(ISD::SHL, Loc, MVT::i32, Flags,
13245 DAG.getShiftAmountConstant(28, MVT::i32, Loc));
13246 SDValue ExtShiftedFlagsVec =
13247 DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v2i32, Zero, ShiftedFlags);
13248 SDValue ExtShiftedFlags =
13249 DAG.getNode(ISD::BITCAST, Loc, MVT::i64, ExtShiftedFlagsVec);
13250 SDValue CombinedFields =
13251 DAG.getNode(ISD::OR, Loc, MVT::i64, NumRecordsRHS, ExtShiftedStride);
13252 SDValue HighHalf =
13253 DAG.getNode(ISD::OR, Loc, MVT::i64, CombinedFields, ExtShiftedFlags);
13254
13255 Rsrc = DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v2i64, LowHalf, HighHalf);
13256 } else {
13257 NumRecords = DAG.getZExtOrTrunc(NumRecords, Loc, MVT::i32);
13258 auto [LowHalf, HighHalf] =
13259 DAG.SplitScalar(Pointer, Loc, MVT::i32, MVT::i32);
13260 SDValue Mask = DAG.getConstant(0x0000ffff, Loc, MVT::i32);
13261 SDValue Masked = DAG.getNode(ISD::AND, Loc, MVT::i32, HighHalf, Mask);
13262 SDValue ShiftedStride =
13263 DAG.getNode(ISD::SHL, Loc, MVT::i32, ExtStride,
13264 DAG.getShiftAmountConstant(16, MVT::i32, Loc));
13265 SDValue NewHighHalf =
13266 DAG.getNode(ISD::OR, Loc, MVT::i32, Masked, ShiftedStride);
13267
13268 Rsrc = DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v4i32, LowHalf, NewHighHalf,
13269 NumRecords, Flags);
13270 }
13271
13272 SDValue RsrcPtr = DAG.getNode(ISD::BITCAST, Loc, MVT::i128, Rsrc);
13273 return RsrcPtr;
13274}
13275
13276// Handle 8 bit and 16 bit buffer loads
13277SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
13278 EVT LoadVT, SDLoc DL,
13280 MachineMemOperand *MMO,
13281 bool IsTFE) const {
13282 EVT IntVT = LoadVT.changeTypeToInteger();
13283
13284 if (IsTFE) {
13285 unsigned Opc = (LoadVT.getScalarType() == MVT::i8)
13286 ? AMDGPUISD::BUFFER_LOAD_UBYTE_TFE
13287 : AMDGPUISD::BUFFER_LOAD_USHORT_TFE;
13289 MachineMemOperand *OpMMO = MF.getMachineMemOperand(MMO, 0, 8);
13290 SDVTList VTs = DAG.getVTList(MVT::v2i32, MVT::Other);
13291 SDValue Op = getMemIntrinsicNode(Opc, DL, VTs, Ops, MVT::v2i32, OpMMO, DAG);
13292 SDValue Status = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op,
13293 DAG.getConstant(1, DL, MVT::i32));
13294 SDValue Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op,
13295 DAG.getConstant(0, DL, MVT::i32));
13296 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, IntVT, Data);
13297 SDValue Value = DAG.getNode(ISD::BITCAST, DL, LoadVT, Trunc);
13298 return DAG.getMergeValues({Value, Status, SDValue(Op.getNode(), 1)}, DL);
13299 }
13300
13301 unsigned Opc = LoadVT.getScalarType() == MVT::i8
13302 ? AMDGPUISD::BUFFER_LOAD_UBYTE
13303 : AMDGPUISD::BUFFER_LOAD_USHORT;
13304
13305 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
13306 SDValue BufferLoad =
13307 DAG.getMemIntrinsicNode(Opc, DL, ResList, Ops, IntVT, MMO);
13308 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
13309 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
13310
13311 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
13312}
13313
13314// Handle 8 bit and 16 bit buffer stores
13315SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
13316 EVT VDataType, SDLoc DL,
13317 SDValue Ops[],
13318 MemSDNode *M) const {
13319 if (VDataType == MVT::f16 || VDataType == MVT::bf16)
13320 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
13321
13322 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
13323 Ops[1] = BufferStoreExt;
13324 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE
13325 : AMDGPUISD::BUFFER_STORE_SHORT;
13326 ArrayRef<SDValue> OpsRef = ArrayRef(&Ops[0], 9);
13327 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
13328 M->getMemOperand());
13329}
13330
13332 SDValue Op, const SDLoc &SL, EVT VT) {
13333 if (VT.bitsLT(Op.getValueType()))
13334 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
13335
13336 switch (ExtType) {
13337 case ISD::SEXTLOAD:
13338 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
13339 case ISD::ZEXTLOAD:
13340 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
13341 case ISD::EXTLOAD:
13342 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
13343 case ISD::NON_EXTLOAD:
13344 return Op;
13345 }
13346
13347 llvm_unreachable("invalid ext type");
13348}
13349
13350// Try to turn 8 and 16-bit scalar loads into SMEM eligible 32-bit loads.
13351// TODO: Skip this on GFX12 which does have scalar sub-dword loads.
13352SDValue SITargetLowering::widenLoad(LoadSDNode *Ld,
13353 DAGCombinerInfo &DCI) const {
13354 SelectionDAG &DAG = DCI.DAG;
13355 if (Ld->getAlign() < Align(4) || Ld->isDivergent())
13356 return SDValue();
13357
13358 // FIXME: Constant loads should all be marked invariant.
13359 unsigned AS = Ld->getAddressSpace();
13360 if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
13362 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
13363 return SDValue();
13364
13365 // Don't do this early, since it may interfere with adjacent load merging for
13366 // illegal types. We can avoid losing alignment information for exotic types
13367 // pre-legalize.
13368 EVT MemVT = Ld->getMemoryVT();
13369 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
13370 MemVT.getSizeInBits() >= 32)
13371 return SDValue();
13372
13373 SDLoc SL(Ld);
13374
13375 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
13376 "unexpected vector extload");
13377
13378 // TODO: Drop only high part of range.
13379 SDValue Ptr = Ld->getBasePtr();
13380 SDValue NewLoad = DAG.getLoad(
13381 ISD::UNINDEXED, ISD::NON_EXTLOAD, MVT::i32, SL, Ld->getChain(), Ptr,
13382 Ld->getOffset(), Ld->getPointerInfo(), MVT::i32, Ld->getAlign(),
13383 Ld->getMemOperand()->getFlags(), Ld->getAAInfo()); // Drop ranges
13384
13385 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
13386 if (MemVT.isFloatingPoint()) {
13387 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
13388 "unexpected fp extload");
13389 TruncVT = MemVT.changeTypeToInteger();
13390 }
13391
13392 SDValue Cvt = NewLoad;
13393 if (Ld->getExtensionType() == ISD::SEXTLOAD) {
13394 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
13395 DAG.getValueType(TruncVT));
13396 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
13397 Ld->getExtensionType() == ISD::NON_EXTLOAD) {
13398 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
13399 } else {
13400 assert(Ld->getExtensionType() == ISD::EXTLOAD);
13401 }
13402
13403 EVT VT = Ld->getValueType(0);
13404 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
13405
13406 DCI.AddToWorklist(Cvt.getNode());
13407
13408 // We may need to handle exotic cases, such as i16->i64 extloads, so insert
13409 // the appropriate extension from the 32-bit load.
13410 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
13411 DCI.AddToWorklist(Cvt.getNode());
13412
13413 // Handle conversion back to floating point if necessary.
13414 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
13415
13416 return DAG.getMergeValues({Cvt, NewLoad.getValue(1)}, SL);
13417}
13418
13420 const SIMachineFunctionInfo &Info) {
13421 // TODO: Should check if the address can definitely not access stack.
13422 if (Info.isEntryFunction())
13423 return Info.getUserSGPRInfo().hasFlatScratchInit();
13424 return true;
13425}
13426
13427// Lower a VGPR ("as memory") load or store to a REG_LOAD / REG_STORE node
13428// carrying the dword index. TODO: sub-dword accesses.
13429SDValue SITargetLowering::lowerLoadStoreVGPR(SDValue Op,
13430 SelectionDAG &DAG) const {
13431 SDLoc DL(Op);
13432 MemSDNode *MemOp = cast<MemSDNode>(Op);
13433 EVT MemVT = MemOp->getMemoryVT();
13434 unsigned BitWidth = MemVT.getSizeInBits();
13435
13436 // Each caller replaces the node, so this is diagnosed once.
13437 auto reportUnsupported = [&]() -> SDValue {
13438 const Function &F = DAG.getMachineFunction().getFunction();
13439 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
13440 F,
13441 "unsupported access of VGPR 'as memory' address space (13); only "
13442 "dword-aligned whole-dword loads and stores are implemented",
13443 DL.getDebugLoc()));
13444 SmallVector<EVT, 2> ResultTypes(Op->values());
13445 return DAG.getErrorMergeValues(ResultTypes, MemOp->getChain(), DL);
13446 };
13447
13448 if (BitWidth < 32)
13449 return reportUnsupported();
13450
13451 // The index is the pointer >> 2, so an under-aligned access would silently
13452 // reach the containing dword rather than the bytes asked for.
13453 if (MemOp->getAlign() < Align(4))
13454 return reportUnsupported();
13455 auto *Store = dyn_cast<StoreSDNode>(MemOp);
13456 if (Store && Store->isTruncatingStore())
13457 return reportUnsupported();
13458 // Only a width some VGPR tuple has is looked up. A whole-dword access of any
13459 // other width is done as one of <N x i32>, which type legalization splits.
13460 auto *Load = dyn_cast<LoadSDNode>(MemOp);
13461 if (!Subtarget->getRegisterInfo()->getVGPRClassForBitWidth(BitWidth) ||
13463 if (BitWidth % 32 != 0)
13464 return reportUnsupported();
13465 EVT ViewVT = getEquivalentMemType(*DAG.getContext(), MemVT);
13466 if (Store) {
13467 if (MemVT == ViewVT)
13468 return SDValue();
13469 return DAG.getStore(Store->getChain(), DL,
13470 DAG.getBitcast(ViewVT, Store->getValue()),
13471 Store->getBasePtr(), Store->getMemOperand());
13472 }
13473 if (MemVT == ViewVT && Load->getExtensionType() == ISD::NON_EXTLOAD)
13474 return SDValue();
13475 // The range is for the elements of MemVT, not for dwords.
13476 Load->getMemOperand()->clearRanges();
13477 SDValue NewLoad = DAG.getLoad(ViewVT, DL, Load->getChain(),
13478 Load->getBasePtr(), Load->getMemOperand());
13479 SDValue Value = getLoadExtOrTrunc(DAG, Load->getExtensionType(),
13480 DAG.getBitcast(MemVT, NewLoad), DL,
13481 Load->getValueType(0));
13482 return DAG.getMergeValues({Value, NewLoad.getValue(1)}, DL);
13483 }
13484
13485 SDValue Chain = MemOp->getChain();
13486 SDValue Index = DAG.getNode(ISD::SRL, DL, MVT::i32, MemOp->getBasePtr(),
13487 DAG.getConstant(2, DL, MVT::i32));
13488
13489 // View as i32 / <N x i32> when the memory type is not register legal.
13490 EVT RegVT = MemVT;
13491 if (!isTypeLegal(RegVT)) {
13492 unsigned NumDwords = BitWidth / 32;
13493 RegVT = NumDwords == 1
13494 ? EVT(MVT::i32)
13495 : EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumDwords);
13496 }
13497
13498 if (Store) {
13499 SDValue Value = DAG.getBitcast(RegVT, Store->getValue());
13500 return DAG.getMemIntrinsicNode(
13501 AMDGPUISD::REG_STORE, DL, DAG.getVTList(MVT::Other),
13502 {Chain, Value, Index}, MemVT, Store->getMemOperand());
13503 }
13504
13505 SDValue NewLoad = DAG.getMemIntrinsicNode(
13506 AMDGPUISD::REG_LOAD, DL, DAG.getVTList(RegVT, MVT::Other), {Chain, Index},
13507 MemVT, Load->getMemOperand());
13508 SDValue Value = DAG.getBitcast(MemVT, NewLoad);
13509 // The combiner folds an extension of a whole-dword load into the load.
13510 Value = getLoadExtOrTrunc(DAG, Load->getExtensionType(), Value, DL,
13511 Load->getValueType(0));
13512 if (Value == NewLoad)
13513 return NewLoad;
13514 return DAG.getMergeValues({Value, NewLoad.getValue(1)}, DL);
13515}
13516
13517SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
13518 SDLoc DL(Op);
13519 LoadSDNode *Load = cast<LoadSDNode>(Op);
13520 assert(Load->getExtensionType() == ISD::NON_EXTLOAD &&
13521 "Unexpected custom extending load!");
13522 EVT MemVT = Load->getMemoryVT();
13523 MachineMemOperand *MMO = Load->getMemOperand();
13524
13525 if (MemVT.getSizeInBits() < 32) {
13526 // Legalize uniform 16-bit loads to i16 = trunc (zextload i16->i32)
13527 // to match subword load patterns.
13528 // Only do this for loads that can use scalar subword load instructions.
13529 if (!MemVT.isVector() && MemVT.getSizeInBits() == 16 &&
13530 isTypeLegal(MemVT) && Subtarget->hasScalarSubwordLoads() &&
13532 SDValue Chain = Load->getChain();
13533 SDValue BasePtr = Load->getBasePtr();
13534
13535 // Load as i16 and zero-extend to i32 (matches S_LOAD_U16 behavior)
13536 SDValue NewLD = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
13537 BasePtr, MVT::i16, MMO);
13538
13539 // Truncate back to i16
13540 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, NewLD);
13541
13542 // For f16/bf16, bitcast from i16 to the original fp type
13543 SDValue Result = (MemVT == MVT::i16)
13544 ? Trunc
13545 : DAG.getNode(ISD::BITCAST, DL, MemVT, Trunc);
13546
13547 SDValue Ops[] = {Result, NewLD.getValue(1)};
13548 return DAG.getMergeValues(Ops, DL);
13549 }
13550
13551 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
13552 return SDValue();
13553
13554 // FIXME: Copied from PPC
13555 // First, load into 32 bits, then truncate to 1 bit.
13556
13557 SDValue Chain = Load->getChain();
13558 SDValue BasePtr = Load->getBasePtr();
13559
13560 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
13561
13562 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, BasePtr,
13563 RealMemVT, MMO);
13564
13565 if (!MemVT.isVector()) {
13566 SDValue Ops[] = {DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
13567 NewLD.getValue(1)};
13568
13569 return DAG.getMergeValues(Ops, DL);
13570 }
13571
13573 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
13574 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
13575 DAG.getConstant(I, DL, MVT::i32));
13576
13577 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
13578 }
13579
13580 SDValue Ops[] = {DAG.getBuildVector(MemVT, DL, Elts), NewLD.getValue(1)};
13581
13582 return DAG.getMergeValues(Ops, DL);
13583 }
13584
13585 assert(MemVT.isVector() &&
13586 Op.getValueType().getVectorElementType() == MVT::i32 &&
13587 "Custom lowering for non-i32 vectors hasn't been implemented.");
13588
13589 Align Alignment = Load->getAlign();
13590 unsigned AS = Load->getAddressSpace();
13591 if (Subtarget->hasLDSMisalignedBugInWGPMode() &&
13592 AS == AMDGPUAS::FLAT_ADDRESS &&
13593 Alignment.value() < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
13594 return SplitVectorLoad(Op, DAG);
13595 }
13596
13598 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
13599 // If there is a possibility that flat instruction access scratch memory
13600 // then we need to use the same legalization rules we use for private.
13601 if (AS == AMDGPUAS::FLAT_ADDRESS &&
13602 !Subtarget->hasMultiDwordFlatScratchAddressing())
13603 AS = addressMayBeAccessedAsPrivate(Load->getMemOperand(), *MFI)
13606
13607 unsigned NumElements = MemVT.getVectorNumElements();
13608
13609 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
13611 (AS == AMDGPUAS::GLOBAL_ADDRESS && Load->isSimple() &&
13612 (Load->isInvariant() || isMemOpHasNoClobberedMemOperand(Load)))) {
13613 if ((!Op->isDivergent() || AMDGPU::isUniformMMO(MMO)) &&
13614 Alignment >= Align(4) && NumElements < 32) {
13615 if (MemVT.isPow2VectorType() ||
13616 (Subtarget->hasScalarDwordx3Loads() && NumElements == 3))
13617 return SDValue();
13618 return WidenOrSplitVectorLoad(Op, DAG);
13619 }
13620 // Non-uniform loads will be selected to MUBUF instructions, so they
13621 // have the same legalization requirements as global and private
13622 // loads.
13623 //
13624 }
13625 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
13628 if (NumElements > 4)
13629 return SplitVectorLoad(Op, DAG);
13630 // v3 loads not supported on SI.
13631 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
13632 return WidenOrSplitVectorLoad(Op, DAG);
13633
13634 // v3 and v4 loads are supported for private and global memory.
13635 return SDValue();
13636 }
13637 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
13638 // Depending on the setting of the private_element_size field in the
13639 // resource descriptor, we can only make private accesses up to a certain
13640 // size.
13641 switch (Subtarget->getMaxPrivateElementSize()) {
13642 case 4: {
13643 auto [Op0, Op1] = scalarizeVectorLoad(Load, DAG);
13644 return DAG.getMergeValues({Op0, Op1}, DL);
13645 }
13646 case 8:
13647 if (NumElements > 2)
13648 return SplitVectorLoad(Op, DAG);
13649 return SDValue();
13650 case 16:
13651 // Same as global/flat
13652 if (NumElements > 4)
13653 return SplitVectorLoad(Op, DAG);
13654 // v3 loads not supported on SI.
13655 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
13656 return WidenOrSplitVectorLoad(Op, DAG);
13657
13658 return SDValue();
13659 default:
13660 llvm_unreachable("unsupported private_element_size");
13661 }
13662 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
13663 unsigned Fast = 0;
13664 auto Flags = Load->getMemOperand()->getFlags();
13666 Load->getAlign(), Flags, &Fast) &&
13667 Fast > 1)
13668 return SDValue();
13669
13670 return SplitVectorLoad(Op, DAG);
13671 }
13672
13674 MemVT, *Load->getMemOperand())) {
13675 auto [Op0, Op1] = expandUnalignedLoad(Load, DAG);
13676 return DAG.getMergeValues({Op0, Op1}, DL);
13677 }
13678
13679 return SDValue();
13680}
13681
13682SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13683 EVT VT = Op.getValueType();
13684 if (VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256 ||
13685 VT.getSizeInBits() == 512)
13686 return splitTernaryVectorOp(Op, DAG);
13687
13688 assert(VT.getSizeInBits() == 64);
13689
13690 SDLoc DL(Op);
13691 SDValue Cond = DAG.getFreeze(Op.getOperand(0));
13692
13693 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
13694 SDValue One = DAG.getConstant(1, DL, MVT::i32);
13695
13696 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
13697 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
13698
13699 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
13700 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
13701
13702 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
13703
13704 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
13705 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
13706
13707 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
13708
13709 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
13710 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
13711}
13712
13713// Catch division cases where we can use shortcuts with rcp and rsq
13714// instructions.
13715SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
13716 SelectionDAG &DAG) const {
13717 SDLoc SL(Op);
13718 SDValue LHS = Op.getOperand(0);
13719 SDValue RHS = Op.getOperand(1);
13720 EVT VT = Op.getValueType();
13721 const SDNodeFlags Flags = Op->getFlags();
13722
13723 bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
13724
13725 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
13726 // Without !fpmath accuracy information, we can't do more because we don't
13727 // know exactly whether rcp is accurate enough to meet !fpmath requirement.
13728 // f16 is always accurate enough
13729 if (!AllowInaccurateRcp && VT != MVT::f16 && VT != MVT::bf16)
13730 return SDValue();
13731
13732 if (CLHS->isOne()) {
13733 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
13734 // the CI documentation has a worst case error of 1 ulp.
13735 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
13736 // use it as long as we aren't trying to use denormals.
13737 //
13738 // v_rcp_f16 and v_rsq_f16 DO support denormals and 0.51ulp.
13739
13740 // 1.0 / sqrt(x) -> rsq(x)
13741
13742 // XXX - Is afn sufficient to do this for f64? The maximum ULP
13743 // error seems really high at 2^29 ULP.
13744 // 1.0 / x -> rcp(x)
13745 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
13746 }
13747
13748 // Same as for 1.0, but expand the sign out of the constant.
13749 if (CLHS->isMinusOne()) {
13750 // -1.0 / x -> fneg (rcp x)
13751 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
13752 return DAG.getNode(ISD::FNEG, SL, VT, Rcp);
13753 }
13754 }
13755
13756 // For f16 and bf16 require afn or arcp.
13757 // For f32 require afn.
13758 if (!AllowInaccurateRcp &&
13759 ((VT != MVT::f16 && VT != MVT::bf16) || !Flags.hasAllowReciprocal()))
13760 return SDValue();
13761
13762 // Turn into multiply by the reciprocal.
13763 // x / y -> x * (1.0 / y)
13764 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
13765 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
13766}
13767
13768SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
13769 SelectionDAG &DAG) const {
13770 SDLoc SL(Op);
13771 SDValue X = Op.getOperand(0);
13772 SDValue Y = Op.getOperand(1);
13773 EVT VT = Op.getValueType();
13774 const SDNodeFlags Flags = Op->getFlags();
13775
13776 bool AllowInaccurateDiv = Flags.hasApproximateFuncs();
13777 if (!AllowInaccurateDiv)
13778 return SDValue();
13779
13780 const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(X);
13781 bool IsNegRcp = CLHS && CLHS->isMinusOne();
13782
13783 // Pull out the negation so it folds for free into the source modifiers.
13784 if (IsNegRcp)
13785 X = DAG.getConstantFP(1.0, SL, VT);
13786
13787 SDValue NegY = IsNegRcp ? Y : DAG.getNode(ISD::FNEG, SL, VT, Y);
13788 SDValue One = DAG.getConstantFP(1.0, SL, VT);
13789
13790 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
13791 if (IsNegRcp)
13792 R = DAG.getNode(ISD::FNEG, SL, VT, R);
13793
13794 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
13795
13796 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
13797 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
13798 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
13799
13800 // Skip the last 2 correction terms for reciprocal.
13801 if (IsNegRcp || (CLHS && CLHS->isOne()))
13802 return R;
13803
13804 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
13805 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
13806 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
13807}
13808
13809static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
13810 EVT VT, SDValue A, SDValue B, SDValue GlueChain,
13811 SDNodeFlags Flags) {
13812 if (GlueChain->getNumValues() <= 1) {
13813 return DAG.getNode(Opcode, SL, VT, A, B, Flags);
13814 }
13815
13816 assert(GlueChain->getNumValues() == 3);
13817
13818 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
13819 switch (Opcode) {
13820 default:
13821 llvm_unreachable("no chain equivalent for opcode");
13822 case ISD::FMUL:
13823 Opcode = AMDGPUISD::FMUL_W_CHAIN;
13824 break;
13825 }
13826
13827 return DAG.getNode(Opcode, SL, VTList,
13828 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
13829 Flags);
13830}
13831
13832static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
13833 EVT VT, SDValue A, SDValue B, SDValue C,
13834 SDValue GlueChain, SDNodeFlags Flags) {
13835 if (GlueChain->getNumValues() <= 1) {
13836 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
13837 }
13838
13839 assert(GlueChain->getNumValues() == 3);
13840
13841 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
13842 switch (Opcode) {
13843 default:
13844 llvm_unreachable("no chain equivalent for opcode");
13845 case ISD::FMA:
13846 Opcode = AMDGPUISD::FMA_W_CHAIN;
13847 break;
13848 }
13849
13850 return DAG.getNode(Opcode, SL, VTList,
13851 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
13852 Flags);
13853}
13854
13855SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
13856 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
13857 return FastLowered;
13858
13859 SDLoc SL(Op);
13860 EVT VT = Op.getValueType();
13861 SDValue LHS = Op.getOperand(0);
13862 SDValue RHS = Op.getOperand(1);
13863
13864 SDValue LHSExt = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, LHS);
13865 SDValue RHSExt = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, RHS);
13866
13867 if (VT == MVT::bf16) {
13868 SDValue ExtDiv =
13869 DAG.getNode(ISD::FDIV, SL, MVT::f32, LHSExt, RHSExt, Op->getFlags());
13870 return DAG.getNode(ISD::FP_ROUND, SL, MVT::bf16, ExtDiv,
13871 DAG.getTargetConstant(0, SL, MVT::i32));
13872 }
13873
13874 assert(VT == MVT::f16);
13875
13876 // a32.u = opx(V_CVT_F32_F16, a.u); // CVT to F32
13877 // b32.u = opx(V_CVT_F32_F16, b.u); // CVT to F32
13878 // r32.u = opx(V_RCP_F32, b32.u); // rcp = 1 / d
13879 // q32.u = opx(V_MUL_F32, a32.u, r32.u); // q = n * rcp
13880 // e32.u = opx(V_MAD_F32, (b32.u^_neg32), q32.u, a32.u); // err = -d * q + n
13881 // q32.u = opx(V_MAD_F32, e32.u, r32.u, q32.u); // q = n * rcp
13882 // e32.u = opx(V_MAD_F32, (b32.u^_neg32), q32.u, a32.u); // err = -d * q + n
13883 // tmp.u = opx(V_MUL_F32, e32.u, r32.u);
13884 // tmp.u = opx(V_AND_B32, tmp.u, 0xff800000)
13885 // q32.u = opx(V_ADD_F32, tmp.u, q32.u);
13886 // q16.u = opx(V_CVT_F16_F32, q32.u);
13887 // q16.u = opx(V_DIV_FIXUP_F16, q16.u, b.u, a.u); // q = touchup(q, d, n)
13888
13889 // We will use ISD::FMA on targets that don't support ISD::FMAD.
13890 unsigned FMADOpCode =
13892 SDValue NegRHSExt = DAG.getNode(ISD::FNEG, SL, MVT::f32, RHSExt);
13893 SDValue Rcp =
13894 DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, RHSExt, Op->getFlags());
13895 SDValue Quot =
13896 DAG.getNode(ISD::FMUL, SL, MVT::f32, LHSExt, Rcp, Op->getFlags());
13897 SDValue Err = DAG.getNode(FMADOpCode, SL, MVT::f32, NegRHSExt, Quot, LHSExt,
13898 Op->getFlags());
13899 Quot = DAG.getNode(FMADOpCode, SL, MVT::f32, Err, Rcp, Quot, Op->getFlags());
13900 Err = DAG.getNode(FMADOpCode, SL, MVT::f32, NegRHSExt, Quot, LHSExt,
13901 Op->getFlags());
13902 SDValue Tmp = DAG.getNode(ISD::FMUL, SL, MVT::f32, Err, Rcp, Op->getFlags());
13903 SDValue TmpCast = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Tmp);
13904 TmpCast = DAG.getNode(ISD::AND, SL, MVT::i32, TmpCast,
13905 DAG.getConstant(0xff800000, SL, MVT::i32));
13906 Tmp = DAG.getNode(ISD::BITCAST, SL, MVT::f32, TmpCast);
13907 Quot = DAG.getNode(ISD::FADD, SL, MVT::f32, Tmp, Quot, Op->getFlags());
13908 SDValue RDst = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot,
13909 DAG.getTargetConstant(0, SL, MVT::i32));
13910 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, RDst, RHS, LHS,
13911 Op->getFlags());
13912}
13913
13914// Faster 2.5 ULP division that does not support denormals.
13915SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
13916 SDNodeFlags Flags = Op->getFlags();
13917 SDLoc SL(Op);
13918 SDValue LHS = Op.getOperand(1);
13919 SDValue RHS = Op.getOperand(2);
13920
13921 // TODO: The combiner should probably handle elimination of redundant fabs.
13923 ? RHS
13924 : DAG.getNode(ISD::FABS, SL, MVT::f32, RHS, Flags);
13925
13926 const APFloat K0Val(0x1p+96f);
13927 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
13928
13929 const APFloat K1Val(0x1p-32f);
13930 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
13931
13932 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
13933
13934 EVT SetCCVT =
13935 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
13936
13937 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
13938
13939 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One, Flags);
13940
13941 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3, Flags);
13942
13943 // rcp does not support denormals.
13944 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1, Flags);
13945
13946 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0, Flags);
13947
13948 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul, Flags);
13949}
13950
13951// Returns immediate value for setting the F32 denorm mode when using the
13952// S_DENORM_MODE instruction.
13954 const SIMachineFunctionInfo *Info,
13955 const GCNSubtarget *ST) {
13956 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
13957 uint32_t DPDenormModeDefault = Info->getMode().fpDenormModeDPValue();
13958 uint32_t Mode = SPDenormMode | (DPDenormModeDefault << 2);
13959 return DAG.getTargetConstant(Mode, SDLoc(), MVT::i32);
13960}
13961
13962SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
13963 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
13964 return FastLowered;
13965
13966 // The selection matcher assumes anything with a chain selecting to a
13967 // mayRaiseFPException machine instruction. Since we're introducing a chain
13968 // here, we need to explicitly report nofpexcept for the regular fdiv
13969 // lowering.
13970 SDNodeFlags Flags = Op->getFlags();
13971 Flags.setNoFPExcept(true);
13972
13973 SDLoc SL(Op);
13974 SDValue LHS = Op.getOperand(0);
13975 SDValue RHS = Op.getOperand(1);
13976
13977 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
13978
13979 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
13980
13981 SDValue DenominatorScaled =
13982 DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, {RHS, RHS, LHS}, Flags);
13983 SDValue NumeratorScaled =
13984 DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, {LHS, RHS, LHS}, Flags);
13985
13986 // Denominator is scaled to not be denormal, so using rcp is ok.
13987 SDValue ApproxRcp =
13988 DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, DenominatorScaled, Flags);
13989 SDValue NegDivScale0 =
13990 DAG.getNode(ISD::FNEG, SL, MVT::f32, DenominatorScaled, Flags);
13991
13992 using namespace AMDGPU::Hwreg;
13993 const unsigned Denorm32Reg = HwregEncoding::encode(ID_MODE, 4, 2);
13994 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
13995
13996 const MachineFunction &MF = DAG.getMachineFunction();
13997 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
13998 const DenormalMode DenormMode = Info->getMode().FP32Denormals;
13999
14000 const bool PreservesDenormals = DenormMode == DenormalMode::getIEEE();
14001 const bool HasDynamicDenormals =
14002 (DenormMode.Input == DenormalMode::Dynamic) ||
14003 (DenormMode.Output == DenormalMode::Dynamic);
14004
14005 SDValue SavedDenormMode;
14006
14007 if (!PreservesDenormals) {
14008 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
14009 // lowering. The chain dependence is insufficient, and we need glue. We do
14010 // not need the glue variants in a strictfp function.
14011
14012 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
14013
14014 SDValue Glue = DAG.getEntryNode();
14015 if (HasDynamicDenormals) {
14016 SDNode *GetReg = DAG.getMachineNode(AMDGPU::S_GETREG_B32, SL,
14017 DAG.getVTList(MVT::i32, MVT::Glue),
14018 {BitField, Glue});
14019 SavedDenormMode = SDValue(GetReg, 0);
14020
14021 Glue = DAG.getMergeValues(
14022 {DAG.getEntryNode(), SDValue(GetReg, 0), SDValue(GetReg, 1)}, SL);
14023 }
14024
14025 SDNode *EnableDenorm;
14026 if (Subtarget->hasDenormModeInst()) {
14027 const SDValue EnableDenormValue =
14028 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, Info, Subtarget);
14029
14030 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, Glue,
14031 EnableDenormValue)
14032 .getNode();
14033 } else {
14034 const SDValue EnableDenormValue =
14035 DAG.getConstant(FP_DENORM_FLUSH_NONE, SL, MVT::i32);
14036 EnableDenorm = DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
14037 {EnableDenormValue, BitField, Glue});
14038 }
14039
14040 SDValue Ops[3] = {NegDivScale0, SDValue(EnableDenorm, 0),
14041 SDValue(EnableDenorm, 1)};
14042
14043 NegDivScale0 = DAG.getMergeValues(Ops, SL);
14044 }
14045
14046 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
14047 ApproxRcp, One, NegDivScale0, Flags);
14048
14049 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
14050 ApproxRcp, Fma0, Flags);
14051
14052 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, Fma1,
14053 Fma1, Flags);
14054
14055 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
14056 NumeratorScaled, Mul, Flags);
14057
14058 SDValue Fma3 =
14059 getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2, Flags);
14060
14061 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
14062 NumeratorScaled, Fma3, Flags);
14063
14064 if (!PreservesDenormals) {
14065 SDNode *DisableDenorm;
14066 if (!HasDynamicDenormals && Subtarget->hasDenormModeInst()) {
14067 const SDValue DisableDenormValue = getSPDenormModeValue(
14068 FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, Info, Subtarget);
14069
14070 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
14071 DisableDenorm =
14072 DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
14073 Fma4.getValue(1), DisableDenormValue, Fma4.getValue(2))
14074 .getNode();
14075 } else {
14076 assert(HasDynamicDenormals == (bool)SavedDenormMode);
14077 const SDValue DisableDenormValue =
14078 HasDynamicDenormals
14079 ? SavedDenormMode
14080 : DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
14081
14082 DisableDenorm = DAG.getMachineNode(
14083 AMDGPU::S_SETREG_B32, SL, MVT::Other,
14084 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
14085 }
14086
14087 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
14088 SDValue(DisableDenorm, 0), DAG.getRoot());
14089 DAG.setRoot(OutputChain);
14090 }
14091
14092 SDValue Scale = NumeratorScaled.getValue(1);
14093 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
14094 {Fma4, Fma1, Fma3, Scale}, Flags);
14095
14096 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
14097}
14098
14099SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
14100 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
14101 return FastLowered;
14102
14103 SDLoc SL(Op);
14104 SDValue X = Op.getOperand(0);
14105 SDValue Y = Op.getOperand(1);
14106
14107 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
14108
14109 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
14110
14111 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
14112
14113 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
14114
14115 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
14116
14117 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
14118
14119 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
14120
14121 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
14122
14123 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
14124
14125 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
14126 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
14127
14128 SDValue Fma4 =
14129 DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Mul, DivScale1);
14130
14131 SDValue Scale;
14132
14133 if (!Subtarget->hasUsableDivScaleConditionOutput()) {
14134 // Workaround a hardware bug on SI where the condition output from div_scale
14135 // is not usable.
14136
14137 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
14138
14139 // Figure out if the scale to use for div_fmas.
14140 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
14141 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
14142 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
14143 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
14144
14145 SDValue NumHi =
14146 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
14147 SDValue DenHi =
14148 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
14149
14150 SDValue Scale0Hi =
14151 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
14152 SDValue Scale1Hi =
14153 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
14154
14155 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
14156 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
14157 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
14158 } else {
14159 Scale = DivScale1.getValue(1);
14160 }
14161
14162 SDValue Fmas =
14163 DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, Fma4, Fma3, Mul, Scale);
14164
14165 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
14166}
14167
14168SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
14169 EVT VT = Op.getValueType();
14170
14171 if (VT == MVT::f32)
14172 return LowerFDIV32(Op, DAG);
14173
14174 if (VT == MVT::f64)
14175 return LowerFDIV64(Op, DAG);
14176
14177 if (VT == MVT::f16 || VT == MVT::bf16)
14178 return LowerFDIV16(Op, DAG);
14179
14180 llvm_unreachable("Unexpected type for fdiv");
14181}
14182
14183SDValue SITargetLowering::LowerFFREXP(SDValue Op, SelectionDAG &DAG) const {
14184 SDLoc dl(Op);
14185 SDValue Val = Op.getOperand(0);
14186 EVT VT = Val.getValueType();
14187 EVT ResultExpVT = Op->getValueType(1);
14188 EVT InstrExpVT = VT == MVT::f16 ? MVT::i16 : MVT::i32;
14189
14190 SDValue Mant = DAG.getNode(
14192 DAG.getTargetConstant(Intrinsic::amdgcn_frexp_mant, dl, MVT::i32), Val);
14193
14194 SDValue Exp = DAG.getNode(
14195 ISD::INTRINSIC_WO_CHAIN, dl, InstrExpVT,
14196 DAG.getTargetConstant(Intrinsic::amdgcn_frexp_exp, dl, MVT::i32), Val);
14197
14198 if (Subtarget->hasFractBug()) {
14199 SDValue Fabs = DAG.getNode(ISD::FABS, dl, VT, Val);
14200 SDValue Inf =
14202
14203 SDValue IsFinite = DAG.getSetCC(dl, MVT::i1, Fabs, Inf, ISD::SETOLT);
14204 SDValue Zero = DAG.getConstant(0, dl, InstrExpVT);
14205 Exp = DAG.getNode(ISD::SELECT, dl, InstrExpVT, IsFinite, Exp, Zero);
14206 Mant = DAG.getNode(ISD::SELECT, dl, VT, IsFinite, Mant, Val);
14207 }
14208
14209 SDValue CastExp = DAG.getSExtOrTrunc(Exp, dl, ResultExpVT);
14210 return DAG.getMergeValues({Mant, CastExp}, dl);
14211}
14212
14213SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
14214 SDLoc DL(Op);
14215 StoreSDNode *Store = cast<StoreSDNode>(Op);
14216 assert(!Store->isTruncatingStore() && "Unexpected custom truncating store!");
14217 EVT VT = Store->getMemoryVT();
14218
14219 if (VT == MVT::i1) {
14220 return DAG.getTruncStore(
14221 Store->getChain(), DL,
14222 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
14223 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
14224 }
14225
14226 assert(VT.isVector() &&
14227 Store->getValue().getValueType().getScalarType() == MVT::i32);
14228
14229 unsigned AS = Store->getAddressSpace();
14230 if (Subtarget->hasLDSMisalignedBugInWGPMode() &&
14231 AS == AMDGPUAS::FLAT_ADDRESS &&
14232 Store->getAlign().value() < VT.getStoreSize() &&
14233 VT.getSizeInBits() > 32) {
14234 return SplitVectorStore(Op, DAG);
14235 }
14236
14238 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
14239 // If there is a possibility that flat instruction access scratch memory
14240 // then we need to use the same legalization rules we use for private.
14241 if (AS == AMDGPUAS::FLAT_ADDRESS &&
14242 !Subtarget->hasMultiDwordFlatScratchAddressing())
14243 AS = addressMayBeAccessedAsPrivate(Store->getMemOperand(), *MFI)
14246
14247 unsigned NumElements = VT.getVectorNumElements();
14249 if (NumElements > 4)
14250 return SplitVectorStore(Op, DAG);
14251 // v3 stores not supported on SI.
14252 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
14253 return SplitVectorStore(Op, DAG);
14254
14256 VT, *Store->getMemOperand()))
14257 return expandUnalignedStore(Store, DAG);
14258
14259 return SDValue();
14260 }
14261 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
14262 switch (Subtarget->getMaxPrivateElementSize()) {
14263 case 4:
14264 return scalarizeVectorStore(Store, DAG);
14265 case 8:
14266 if (NumElements > 2)
14267 return SplitVectorStore(Op, DAG);
14268 return SDValue();
14269 case 16:
14270 if (NumElements > 4 ||
14271 (NumElements == 3 && !Subtarget->hasFlatScratchEnabled()))
14272 return SplitVectorStore(Op, DAG);
14273 return SDValue();
14274 default:
14275 llvm_unreachable("unsupported private_element_size");
14276 }
14277 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
14278 unsigned Fast = 0;
14279 auto Flags = Store->getMemOperand()->getFlags();
14281 Store->getAlign(), Flags, &Fast) &&
14282 Fast > 1)
14283 return SDValue();
14284
14285 return SplitVectorStore(Op, DAG);
14286 }
14287
14288 // Probably an invalid store. If so we'll end up emitting a selection error.
14289 return SDValue();
14290}
14291
14292// Avoid the full correct expansion for f32 sqrt when promoting from f16.
14293SDValue SITargetLowering::lowerFSQRTF16(SDValue Op, SelectionDAG &DAG) const {
14294 SDLoc SL(Op);
14295 assert(!Subtarget->has16BitInsts());
14296 SDNodeFlags Flags = Op->getFlags();
14297 SDValue Ext =
14298 DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Op.getOperand(0), Flags);
14299
14300 SDValue SqrtID = DAG.getTargetConstant(Intrinsic::amdgcn_sqrt, SL, MVT::i32);
14301 SDValue Sqrt =
14302 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::f32, SqrtID, Ext, Flags);
14303
14304 return DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Sqrt,
14305 DAG.getTargetConstant(0, SL, MVT::i32), Flags);
14306}
14307
14308SDValue SITargetLowering::lowerFSQRTF32(SDValue Op, SelectionDAG &DAG) const {
14309 SDLoc DL(Op);
14310 SDNodeFlags Flags = Op->getFlags();
14311 MVT VT = Op.getValueType().getSimpleVT();
14312 const SDValue X = Op.getOperand(0);
14313
14314 if (allowApproxFunc(DAG, Flags)) {
14315 // Instruction is 1ulp but ignores denormals.
14316 return DAG.getNode(
14318 DAG.getTargetConstant(Intrinsic::amdgcn_sqrt, DL, MVT::i32), X, Flags);
14319 }
14320
14321 SDValue ScaleThreshold = DAG.getConstantFP(0x1.0p-96f, DL, VT);
14322 SDValue NeedScale = DAG.getSetCC(DL, MVT::i1, X, ScaleThreshold, ISD::SETOLT);
14323
14324 SDValue ScaleUpFactor = DAG.getConstantFP(0x1.0p+32f, DL, VT);
14325
14326 SDValue ScaledX = DAG.getNode(ISD::FMUL, DL, VT, X, ScaleUpFactor, Flags);
14327
14328 SDValue SqrtX =
14329 DAG.getNode(ISD::SELECT, DL, VT, NeedScale, ScaledX, X, Flags);
14330
14331 SDValue SqrtS;
14332 if (needsDenormHandlingF32(DAG, X, Flags)) {
14333 SDValue SqrtID =
14334 DAG.getTargetConstant(Intrinsic::amdgcn_sqrt, DL, MVT::i32);
14335 SqrtS = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, SqrtID, SqrtX, Flags);
14336
14337 SDValue SqrtSAsInt = DAG.getNode(ISD::BITCAST, DL, MVT::i32, SqrtS);
14338 SDValue SqrtSNextDownInt =
14339 DAG.getNode(ISD::ADD, DL, MVT::i32, SqrtSAsInt,
14340 DAG.getAllOnesConstant(DL, MVT::i32));
14341 SDValue SqrtSNextDown = DAG.getNode(ISD::BITCAST, DL, VT, SqrtSNextDownInt);
14342
14343 SDValue NegSqrtSNextDown =
14344 DAG.getNode(ISD::FNEG, DL, VT, SqrtSNextDown, Flags);
14345
14346 SDValue SqrtVP =
14347 DAG.getNode(ISD::FMA, DL, VT, NegSqrtSNextDown, SqrtS, SqrtX, Flags);
14348
14349 SDValue SqrtSNextUpInt = DAG.getNode(ISD::ADD, DL, MVT::i32, SqrtSAsInt,
14350 DAG.getConstant(1, DL, MVT::i32));
14351 SDValue SqrtSNextUp = DAG.getNode(ISD::BITCAST, DL, VT, SqrtSNextUpInt);
14352
14353 SDValue NegSqrtSNextUp = DAG.getNode(ISD::FNEG, DL, VT, SqrtSNextUp, Flags);
14354 SDValue SqrtVS =
14355 DAG.getNode(ISD::FMA, DL, VT, NegSqrtSNextUp, SqrtS, SqrtX, Flags);
14356
14357 SDValue Zero = DAG.getConstantFP(0.0f, DL, VT);
14358 SDValue SqrtVPLE0 = DAG.getSetCC(DL, MVT::i1, SqrtVP, Zero, ISD::SETOLE);
14359
14360 SqrtS = DAG.getNode(ISD::SELECT, DL, VT, SqrtVPLE0, SqrtSNextDown, SqrtS,
14361 Flags);
14362
14363 SDValue SqrtVPVSGT0 = DAG.getSetCC(DL, MVT::i1, SqrtVS, Zero, ISD::SETOGT);
14364 SqrtS = DAG.getNode(ISD::SELECT, DL, VT, SqrtVPVSGT0, SqrtSNextUp, SqrtS,
14365 Flags);
14366 } else {
14367 SDValue SqrtR = DAG.getNode(AMDGPUISD::RSQ, DL, VT, SqrtX, Flags);
14368
14369 SqrtS = DAG.getNode(ISD::FMUL, DL, VT, SqrtX, SqrtR, Flags);
14370
14371 SDValue Half = DAG.getConstantFP(0.5f, DL, VT);
14372 SDValue SqrtH = DAG.getNode(ISD::FMUL, DL, VT, SqrtR, Half, Flags);
14373 SDValue NegSqrtH = DAG.getNode(ISD::FNEG, DL, VT, SqrtH, Flags);
14374
14375 SDValue SqrtE = DAG.getNode(ISD::FMA, DL, VT, NegSqrtH, SqrtS, Half, Flags);
14376 SqrtH = DAG.getNode(ISD::FMA, DL, VT, SqrtH, SqrtE, SqrtH, Flags);
14377 SqrtS = DAG.getNode(ISD::FMA, DL, VT, SqrtS, SqrtE, SqrtS, Flags);
14378
14379 SDValue NegSqrtS = DAG.getNode(ISD::FNEG, DL, VT, SqrtS, Flags);
14380 SDValue SqrtD =
14381 DAG.getNode(ISD::FMA, DL, VT, NegSqrtS, SqrtS, SqrtX, Flags);
14382 SqrtS = DAG.getNode(ISD::FMA, DL, VT, SqrtD, SqrtH, SqrtS, Flags);
14383 }
14384
14385 SDValue ScaleDownFactor = DAG.getConstantFP(0x1.0p-16f, DL, VT);
14386
14387 SDValue ScaledDown =
14388 DAG.getNode(ISD::FMUL, DL, VT, SqrtS, ScaleDownFactor, Flags);
14389
14390 SqrtS = DAG.getNode(ISD::SELECT, DL, VT, NeedScale, ScaledDown, SqrtS, Flags);
14391 SDValue IsZeroOrInf =
14392 DAG.getNode(ISD::IS_FPCLASS, DL, MVT::i1, SqrtX,
14393 DAG.getTargetConstant(fcZero | fcPosInf, DL, MVT::i32));
14394
14395 return DAG.getNode(ISD::SELECT, DL, VT, IsZeroOrInf, SqrtX, SqrtS, Flags);
14396}
14397
14398SDValue SITargetLowering::lowerFSQRTF64(SDValue Op, SelectionDAG &DAG) const {
14399 // For double type, the SQRT and RSQ instructions don't have required
14400 // precision, we apply Goldschmidt's algorithm to improve the result:
14401 //
14402 // y0 = rsq(x)
14403 // g0 = x * y0
14404 // h0 = 0.5 * y0
14405 //
14406 // r0 = 0.5 - h0 * g0
14407 // g1 = g0 * r0 + g0
14408 // h1 = h0 * r0 + h0
14409 //
14410 // r1 = 0.5 - h1 * g1 => d0 = x - g1 * g1
14411 // g2 = g1 * r1 + g1 g2 = d0 * h1 + g1
14412 // h2 = h1 * r1 + h1
14413 //
14414 // r2 = 0.5 - h2 * g2 => d1 = x - g2 * g2
14415 // g3 = g2 * r2 + g2 g3 = d1 * h1 + g2
14416 //
14417 // sqrt(x) = g3
14418
14419 SDNodeFlags Flags = Op->getFlags();
14420
14421 SDLoc DL(Op);
14422
14423 SDValue X = Op.getOperand(0);
14424 SDValue ZeroInt = DAG.getConstant(0, DL, MVT::i32);
14425
14426 SDValue SqrtX = X;
14427 SDValue Scaling;
14428 if (!Flags.hasApproximateFuncs()) {
14429 SDValue ScaleConstant = DAG.getConstantFP(0x1.0p-767, DL, MVT::f64);
14430 Scaling = DAG.getSetCC(DL, MVT::i1, X, ScaleConstant, ISD::SETOLT);
14431
14432 // Scale up input if it is too small.
14433 SDValue ScaleUpFactor = DAG.getConstant(256, DL, MVT::i32);
14434 SDValue ScaleUp =
14435 DAG.getNode(ISD::SELECT, DL, MVT::i32, Scaling, ScaleUpFactor, ZeroInt);
14436 SqrtX = DAG.getNode(ISD::FLDEXP, DL, MVT::f64, X, ScaleUp, Flags);
14437 }
14438
14439 SDValue SqrtY = DAG.getNode(AMDGPUISD::RSQ, DL, MVT::f64, SqrtX);
14440
14441 SDValue SqrtS0 = DAG.getNode(ISD::FMUL, DL, MVT::f64, SqrtX, SqrtY);
14442
14443 SDValue Half = DAG.getConstantFP(0.5, DL, MVT::f64);
14444 SDValue SqrtH0 = DAG.getNode(ISD::FMUL, DL, MVT::f64, SqrtY, Half);
14445
14446 SDValue NegSqrtH0 = DAG.getNode(ISD::FNEG, DL, MVT::f64, SqrtH0);
14447 SDValue SqrtR0 = DAG.getNode(ISD::FMA, DL, MVT::f64, NegSqrtH0, SqrtS0, Half);
14448
14449 SDValue SqrtH1 = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtH0, SqrtR0, SqrtH0);
14450
14451 SDValue SqrtS1 = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtS0, SqrtR0, SqrtS0);
14452
14453 SDValue NegSqrtS1 = DAG.getNode(ISD::FNEG, DL, MVT::f64, SqrtS1);
14454 SDValue SqrtD0 =
14455 DAG.getNode(ISD::FMA, DL, MVT::f64, NegSqrtS1, SqrtS1, SqrtX);
14456
14457 SDValue SqrtS2 = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtD0, SqrtH1, SqrtS1);
14458
14459 SDValue SqrtRet = SqrtS2;
14460 if (!Flags.hasApproximateFuncs()) {
14461 SDValue NegSqrtS2 = DAG.getNode(ISD::FNEG, DL, MVT::f64, SqrtS2);
14462 SDValue SqrtD1 =
14463 DAG.getNode(ISD::FMA, DL, MVT::f64, NegSqrtS2, SqrtS2, SqrtX);
14464
14465 SqrtRet = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtD1, SqrtH1, SqrtS2);
14466
14467 SDValue ScaleDownFactor = DAG.getSignedConstant(-128, DL, MVT::i32);
14468 SDValue ScaleDown = DAG.getNode(ISD::SELECT, DL, MVT::i32, Scaling,
14469 ScaleDownFactor, ZeroInt);
14470 SqrtRet = DAG.getNode(ISD::FLDEXP, DL, MVT::f64, SqrtRet, ScaleDown, Flags);
14471 }
14472
14473 // TODO: Check for DAZ and expand to subnormals
14474
14475 SDValue IsZeroOrInf;
14476 if (Flags.hasNoInfs()) {
14477 SDValue Zero = DAG.getConstantFP(0.0, DL, MVT::f64);
14478 IsZeroOrInf = DAG.getSetCC(DL, MVT::i1, SqrtX, Zero, ISD::SETOEQ);
14479 } else {
14480 IsZeroOrInf =
14481 DAG.getNode(ISD::IS_FPCLASS, DL, MVT::i1, SqrtX,
14482 DAG.getTargetConstant(fcZero | fcPosInf, DL, MVT::i32));
14483 }
14484
14485 // If x is +INF, +0, or -0, use its original value
14486 return DAG.getNode(ISD::SELECT, DL, MVT::f64, IsZeroOrInf, SqrtX, SqrtRet,
14487 Flags);
14488}
14489
14490SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
14491 SDLoc DL(Op);
14492 EVT VT = Op.getValueType();
14493 SDValue Arg = Op.getOperand(0);
14494 SDValue TrigVal;
14495
14496 // Propagate fast-math flags so that the multiply we introduce can be folded
14497 // if Arg is already the result of a multiply by constant.
14498 auto Flags = Op->getFlags();
14499
14500 // AMDGPUISD nodes of vector type must be unrolled here since
14501 // they will not be expanded elsewhere.
14502 auto UnrollIfVec = [&DAG](SDValue V) -> SDValue {
14503 if (!V.getValueType().isVector())
14504 return V;
14505
14506 return DAG.UnrollVectorOp(cast<SDNode>(V));
14507 };
14508
14509 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
14510
14511 if (Subtarget->hasTrigReducedRange()) {
14512 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
14513 TrigVal = UnrollIfVec(DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags));
14514 } else {
14515 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
14516 }
14517
14518 switch (Op.getOpcode()) {
14519 case ISD::FCOS:
14520 TrigVal = DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
14521 break;
14522 case ISD::FSIN:
14523 TrigVal = DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
14524 break;
14525 default:
14526 llvm_unreachable("Wrong trig opcode");
14527 }
14528
14529 return UnrollIfVec(TrigVal);
14530}
14531
14532SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
14533 SelectionDAG &DAG) const {
14534 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
14535 assert(AtomicNode->isCompareAndSwap());
14536 unsigned AS = AtomicNode->getAddressSpace();
14537
14538 // No custom lowering required for local address space
14540 return Op;
14541
14542 // Non-local address space requires custom lowering for atomic compare
14543 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
14544 SDLoc DL(Op);
14545 SDValue ChainIn = Op.getOperand(0);
14546 SDValue Addr = Op.getOperand(1);
14547 SDValue Old = Op.getOperand(2);
14548 SDValue New = Op.getOperand(3);
14549 EVT VT = Op.getValueType();
14550 MVT SimpleVT = VT.getSimpleVT();
14551 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
14552
14553 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
14554 SDValue Ops[] = {ChainIn, Addr, NewOld};
14555
14556 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL,
14557 Op->getVTList(), Ops, VT,
14558 AtomicNode->getMemOperand());
14559}
14560
14561//===----------------------------------------------------------------------===//
14562// Custom DAG optimizations
14563//===----------------------------------------------------------------------===//
14564
14565SDValue
14566SITargetLowering::performUCharToFloatCombine(SDNode *N,
14567 DAGCombinerInfo &DCI) const {
14568 EVT VT = N->getValueType(0);
14569 EVT ScalarVT = VT.getScalarType();
14570 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
14571 return SDValue();
14572
14573 SelectionDAG &DAG = DCI.DAG;
14574 SDLoc DL(N);
14575
14576 SDValue Src = N->getOperand(0);
14577 EVT SrcVT = Src.getValueType();
14578
14579 // TODO: We could try to match extracting the higher bytes, which would be
14580 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
14581 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
14582 // about in practice.
14583 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
14584 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
14585 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
14586 DCI.AddToWorklist(Cvt.getNode());
14587
14588 // For the f16 case, fold to a cast to f32 and then cast back to f16.
14589 if (ScalarVT != MVT::f32) {
14590 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
14591 DAG.getTargetConstant(0, DL, MVT::i32));
14592 }
14593 return Cvt;
14594 }
14595 }
14596
14597 return SDValue();
14598}
14599
14600SDValue SITargetLowering::performFCopySignCombine(SDNode *N,
14601 DAGCombinerInfo &DCI) const {
14602 SDValue MagnitudeOp = N->getOperand(0);
14603 SDValue SignOp = N->getOperand(1);
14604
14605 // The generic combine for fcopysign + fp cast is too conservative with
14606 // vectors, and also gets confused by the splitting we will perform here, so
14607 // peek through FP casts.
14608 if (SignOp.getOpcode() == ISD::FP_EXTEND ||
14609 SignOp.getOpcode() == ISD::FP_ROUND)
14610 SignOp = SignOp.getOperand(0);
14611
14612 SelectionDAG &DAG = DCI.DAG;
14613 SDLoc DL(N);
14614 EVT SignVT = SignOp.getValueType();
14615
14616 // f64 fcopysign is really an f32 copysign on the high bits, so replace the
14617 // lower half with a copy.
14618 // fcopysign f64:x, _:y -> x.lo32, (fcopysign (f32 x.hi32), _:y)
14619 EVT MagVT = MagnitudeOp.getValueType();
14620
14621 unsigned NumElts = MagVT.isVector() ? MagVT.getVectorNumElements() : 1;
14622
14623 if (MagVT.getScalarType() == MVT::f64) {
14624 EVT F32VT = MagVT.isVector()
14625 ? EVT::getVectorVT(*DAG.getContext(), MVT::f32, 2 * NumElts)
14626 : MVT::v2f32;
14627
14628 SDValue MagAsVector = DAG.getNode(ISD::BITCAST, DL, F32VT, MagnitudeOp);
14629
14631 for (unsigned I = 0; I != NumElts; ++I) {
14632 SDValue MagLo =
14633 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, MagAsVector,
14634 DAG.getConstant(2 * I, DL, MVT::i32));
14635 SDValue MagHi =
14636 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, MagAsVector,
14637 DAG.getConstant(2 * I + 1, DL, MVT::i32));
14638
14639 SDValue SignOpElt =
14640 MagVT.isVector()
14642 SignOp, DAG.getConstant(I, DL, MVT::i32))
14643 : SignOp;
14644
14645 SDValue HiOp =
14646 DAG.getNode(ISD::FCOPYSIGN, DL, MVT::f32, MagHi, SignOpElt);
14647
14648 SDValue Vector =
14649 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2f32, MagLo, HiOp);
14650
14651 SDValue NewElt = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Vector);
14652 NewElts.push_back(NewElt);
14653 }
14654
14655 if (NewElts.size() == 1)
14656 return NewElts[0];
14657
14658 return DAG.getNode(ISD::BUILD_VECTOR, DL, MagVT, NewElts);
14659 }
14660
14661 if (SignVT.getScalarType() != MVT::f64)
14662 return SDValue();
14663
14664 // Reduce width of sign operand, we only need the highest bit.
14665 //
14666 // fcopysign f64:x, f64:y ->
14667 // fcopysign f64:x, (extract_vector_elt (bitcast f64:y to v2f32), 1)
14668 // TODO: In some cases it might make sense to go all the way to f16.
14669
14670 EVT F32VT = MagVT.isVector()
14671 ? EVT::getVectorVT(*DAG.getContext(), MVT::f32, 2 * NumElts)
14672 : MVT::v2f32;
14673
14674 SDValue SignAsVector = DAG.getNode(ISD::BITCAST, DL, F32VT, SignOp);
14675
14676 SmallVector<SDValue, 8> F32Signs;
14677 for (unsigned I = 0; I != NumElts; ++I) {
14678 // Take sign from odd elements of cast vector
14679 SDValue SignAsF32 =
14680 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, SignAsVector,
14681 DAG.getConstant(2 * I + 1, DL, MVT::i32));
14682 F32Signs.push_back(SignAsF32);
14683 }
14684
14685 SDValue NewSign =
14686 NumElts == 1
14687 ? F32Signs.back()
14689 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumElts),
14690 F32Signs);
14691
14692 return DAG.getNode(ISD::FCOPYSIGN, DL, N->getValueType(0), N->getOperand(0),
14693 NewSign);
14694}
14695
14696// (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
14697// (shl (or x, c1), c2) -> add (shl x, c2), (shl c1, c2) iff x and c1 share no
14698// bits
14699
14700// This is a variant of
14701// (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
14702//
14703// The normal DAG combiner will do this, but only if the add has one use since
14704// that would increase the number of instructions.
14705//
14706// This prevents us from seeing a constant offset that can be folded into a
14707// memory instruction's addressing mode. If we know the resulting add offset of
14708// a pointer can be folded into an addressing offset, we can replace the pointer
14709// operand with the add of new constant offset. This eliminates one of the uses,
14710// and may allow the remaining use to also be simplified.
14711//
14712SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, unsigned AddrSpace,
14713 EVT MemVT,
14714 DAGCombinerInfo &DCI) const {
14715 SDValue N0 = N->getOperand(0);
14716 SDValue N1 = N->getOperand(1);
14717
14718 // We only do this to handle cases where it's profitable when there are
14719 // multiple uses of the add, so defer to the standard combine.
14720 if ((!N0->isAnyAdd() && N0.getOpcode() != ISD::OR) || N0->hasOneUse())
14721 return SDValue();
14722
14723 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
14724 if (!CN1)
14725 return SDValue();
14726
14727 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14728 if (!CAdd)
14729 return SDValue();
14730
14731 SelectionDAG &DAG = DCI.DAG;
14732
14733 if (N0->getOpcode() == ISD::OR &&
14734 !DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1)))
14735 return SDValue();
14736
14737 // If the resulting offset is too large, we can't fold it into the
14738 // addressing mode offset.
14739 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
14740 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
14741
14742 AddrMode AM;
14743 AM.HasBaseReg = true;
14744 AM.BaseOffs = Offset.getSExtValue();
14745 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
14746 return SDValue();
14747
14748 SDLoc SL(N);
14749 EVT VT = N->getValueType(0);
14750
14751 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
14752 SDValue COffset = DAG.getConstant(Offset, SL, VT);
14753
14754 SDNodeFlags Flags;
14755 Flags.setNoUnsignedWrap(
14756 N->getFlags().hasNoUnsignedWrap() &&
14757 (N0.getOpcode() == ISD::OR || N0->getFlags().hasNoUnsignedWrap()));
14758
14759 // Use ISD::ADD even if the original operation was ISD::PTRADD, since we can't
14760 // be sure that the new left operand is a proper base pointer.
14761 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
14762}
14763
14764/// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
14765/// by the chain and intrinsic ID. Theoretically we would also need to check the
14766/// specific intrinsic, but they all place the pointer operand first.
14767static unsigned getBasePtrIndex(const MemSDNode *N) {
14768 switch (N->getOpcode()) {
14769 case ISD::STORE:
14772 return 2;
14773 default:
14774 return 1;
14775 }
14776}
14777
14778SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
14779 DAGCombinerInfo &DCI) const {
14780 SelectionDAG &DAG = DCI.DAG;
14781
14782 unsigned PtrIdx = getBasePtrIndex(N);
14783 SDValue Ptr = N->getOperand(PtrIdx);
14784
14785 // TODO: We could also do this for multiplies.
14786 if (Ptr.getOpcode() == ISD::SHL) {
14787 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
14788 N->getMemoryVT(), DCI);
14789 if (NewPtr) {
14790 SmallVector<SDValue, 8> NewOps(N->ops());
14791
14792 NewOps[PtrIdx] = NewPtr;
14793 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
14794 }
14795 }
14796
14797 return SDValue();
14798}
14799
14800static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
14801 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
14802 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
14803 (Opc == ISD::XOR && Val == 0);
14804}
14805
14806// Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
14807// will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
14808// integer combine opportunities since most 64-bit operations are decomposed
14809// this way. TODO: We won't want this for SALU especially if it is an inline
14810// immediate.
14811SDValue SITargetLowering::splitBinaryBitConstantOp(
14812 DAGCombinerInfo &DCI, const SDLoc &SL, unsigned Opc, SDValue LHS,
14813 const ConstantSDNode *CRHS) const {
14814 uint64_t Val = CRHS->getZExtValue();
14815 uint32_t ValLo = Lo_32(Val);
14816 uint32_t ValHi = Hi_32(Val);
14817 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
14818
14819 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
14821 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
14822 // We have 64-bit scalar and/or/xor, but do not have vector forms.
14823 if (Subtarget->has64BitLiterals() && CRHS->hasOneUse() &&
14824 !CRHS->user_begin()->isDivergent())
14825 return SDValue();
14826
14827 // If we need to materialize a 64-bit immediate, it will be split up later
14828 // anyway. Avoid creating the harder to understand 64-bit immediate
14829 // materialization.
14830 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
14831 }
14832
14833 return SDValue();
14834}
14835
14837 if (V.getValueType() != MVT::i1)
14838 return false;
14839 switch (V.getOpcode()) {
14840 default:
14841 break;
14842 case ISD::SETCC:
14843 case ISD::IS_FPCLASS:
14844 case AMDGPUISD::FP_CLASS:
14845 return true;
14846 case ISD::AND:
14847 case ISD::OR:
14848 case ISD::XOR:
14849 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
14850 case ISD::SADDO:
14851 case ISD::UADDO:
14852 case ISD::SSUBO:
14853 case ISD::USUBO:
14854 case ISD::SMULO:
14855 case ISD::UMULO:
14856 return V.getResNo() == 1;
14858 unsigned IntrinsicID = V.getConstantOperandVal(0);
14859 switch (IntrinsicID) {
14860 case Intrinsic::amdgcn_is_shared:
14861 case Intrinsic::amdgcn_is_private:
14862 return true;
14863 default:
14864 return false;
14865 }
14866
14867 return false;
14868 }
14869 }
14870 return false;
14871}
14872
14874 return (V.getOpcode() == ISD::SIGN_EXTEND ||
14875 V.getOpcode() == ISD::ANY_EXTEND) &&
14876 isBoolSGPR(V.getOperand(0));
14877}
14878
14879// If a constant has all zeroes or all ones within each byte return it.
14880// Otherwise return 0.
14882 // 0xff for any zero byte in the mask
14883 uint32_t ZeroByteMask = 0;
14884 if (!(C & 0x000000ff))
14885 ZeroByteMask |= 0x000000ff;
14886 if (!(C & 0x0000ff00))
14887 ZeroByteMask |= 0x0000ff00;
14888 if (!(C & 0x00ff0000))
14889 ZeroByteMask |= 0x00ff0000;
14890 if (!(C & 0xff000000))
14891 ZeroByteMask |= 0xff000000;
14892 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
14893 if ((NonZeroByteMask & C) != NonZeroByteMask)
14894 return 0; // Partial bytes selected.
14895 return C;
14896}
14897
14898// Check if a node selects whole bytes from its operand 0 starting at a byte
14899// boundary while masking the rest. Returns select mask as in the v_perm_b32
14900// or -1 if not succeeded.
14901// Note byte select encoding:
14902// value 0-3 selects corresponding source byte;
14903// value 0xc selects zero;
14904// value 0xff selects 0xff.
14906 assert(V.getValueSizeInBits() == 32);
14907
14908 if (V.getNumOperands() != 2)
14909 return ~0;
14910
14911 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
14912 if (!N1)
14913 return ~0;
14914
14915 uint32_t C = N1->getZExtValue();
14916
14917 switch (V.getOpcode()) {
14918 default:
14919 break;
14920 case ISD::AND:
14921 if (uint32_t ConstMask = getConstantPermuteMask(C))
14922 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
14923 break;
14924
14925 case ISD::OR:
14926 if (uint32_t ConstMask = getConstantPermuteMask(C))
14927 return (0x03020100 & ~ConstMask) | ConstMask;
14928 break;
14929
14930 case ISD::SHL:
14931 if (C % 8)
14932 return ~0;
14933
14934 return uint32_t((0x030201000c0c0c0cull << C) >> 32);
14935
14936 case ISD::SRL:
14937 if (C % 8)
14938 return ~0;
14939
14940 return uint32_t(0x0c0c0c0c03020100ull >> C);
14941 }
14942
14943 return ~0;
14944}
14945
14946SDValue SITargetLowering::performAndCombine(SDNode *N,
14947 DAGCombinerInfo &DCI) const {
14948 if (DCI.isBeforeLegalize())
14949 return SDValue();
14950
14951 SelectionDAG &DAG = DCI.DAG;
14952 EVT VT = N->getValueType(0);
14953 SDValue LHS = N->getOperand(0);
14954 SDValue RHS = N->getOperand(1);
14955
14956 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
14957 if (VT == MVT::i64 && CRHS) {
14958 if (SDValue Split =
14959 splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
14960 return Split;
14961 }
14962
14963 if (CRHS && VT == MVT::i32) {
14964 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
14965 // nb = number of trailing zeroes in mask
14966 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
14967 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
14968 uint64_t Mask = CRHS->getZExtValue();
14969 unsigned Bits = llvm::popcount(Mask);
14970 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
14971 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
14972 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
14973 unsigned Shift = CShift->getZExtValue();
14974 unsigned NB = CRHS->getAPIntValue().countr_zero();
14975 unsigned Offset = NB + Shift;
14976 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
14977 SDLoc SL(N);
14978 SDValue BFE =
14979 DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, LHS->getOperand(0),
14980 DAG.getConstant(Offset, SL, MVT::i32),
14981 DAG.getConstant(Bits, SL, MVT::i32));
14982 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
14983 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
14984 DAG.getValueType(NarrowVT));
14985 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
14986 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
14987 return Shl;
14988 }
14989 }
14990 }
14991
14992 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
14993 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
14994 isa<ConstantSDNode>(LHS.getOperand(2))) {
14995 uint32_t Sel = getConstantPermuteMask(Mask);
14996 if (!Sel)
14997 return SDValue();
14998
14999 // Select 0xc for all zero bytes
15000 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
15001 SDLoc DL(N);
15002 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
15003 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
15004 }
15005 }
15006
15007 // and (trunc (srl x, c)), mask => srl (trunc x), c
15008 // if mask keeps exactly the bits that srl leaves in the low half
15009 if (CRHS && VT == MVT::i16 && LHS.getOpcode() == ISD::TRUNCATE &&
15010 LHS.hasOneUse() && LHS.getOperand(0).getOpcode() == ISD::SRL) {
15011 auto *Shift = dyn_cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1));
15012 if (Shift && Shift->getZExtValue() < 16 &&
15013 CRHS->getAPIntValue().isMask(16 - Shift->getZExtValue())) {
15014 SDLoc SL(N);
15015 SDValue Trunc =
15016 DAG.getNode(ISD::TRUNCATE, SL, VT, LHS.getOperand(0).getOperand(0));
15017 return DAG.getNode(
15018 ISD::SRL, SL, VT, Trunc,
15019 DAG.getShiftAmountConstant(Shift->getZExtValue(), VT, SL));
15020 }
15021 }
15022
15023 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
15024 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
15025 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
15026 ISD::CondCode LCC = LHS.getOperandCondCode(2);
15027 ISD::CondCode RCC = RHS.getOperandCondCode(2);
15028
15029 SDValue X = LHS.getOperand(0);
15030 SDValue Y = RHS.getOperand(0);
15031 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X ||
15032 !isTypeLegal(X.getValueType()))
15033 return SDValue();
15034
15035 if (LCC == ISD::SETO) {
15036 if (X != LHS.getOperand(1))
15037 return SDValue();
15038
15039 if (RCC == ISD::SETUNE) {
15040 const ConstantFPSDNode *C1 =
15041 dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
15042 if (!C1 || !C1->isInfinity() || C1->isNegative())
15043 return SDValue();
15044
15045 const uint32_t Mask = SIInstrFlags::N_NORMAL |
15049
15050 static_assert(
15053 0x3ff) == Mask,
15054 "mask not equal");
15055
15056 SDLoc DL(N);
15057 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, X,
15058 DAG.getConstant(Mask, DL, MVT::i32));
15059 }
15060 }
15061 }
15062
15063 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
15064 std::swap(LHS, RHS);
15065
15066 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
15067 RHS.hasOneUse()) {
15068 ISD::CondCode LCC = LHS.getOperandCondCode(2);
15069 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan |
15070 // n_nan) and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan
15071 // | n_nan)
15072 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
15073 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
15074 (RHS.getOperand(0) == LHS.getOperand(0) &&
15075 LHS.getOperand(0) == LHS.getOperand(1))) {
15076 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
15077 unsigned NewMask = LCC == ISD::SETO ? Mask->getZExtValue() & ~OrdMask
15078 : Mask->getZExtValue() & OrdMask;
15079
15080 SDLoc DL(N);
15081 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
15082 DAG.getConstant(NewMask, DL, MVT::i32));
15083 }
15084 }
15085
15086 if (VT == MVT::i32 && (RHS.getOpcode() == ISD::SIGN_EXTEND ||
15087 LHS.getOpcode() == ISD::SIGN_EXTEND)) {
15088 // and x, (sext cc from i1) => select cc, x, 0
15089 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
15090 std::swap(LHS, RHS);
15091 if (isBoolSGPR(RHS.getOperand(0)))
15092 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), LHS,
15093 DAG.getConstant(0, SDLoc(N), MVT::i32));
15094 }
15095
15096 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
15097 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
15098 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
15099 TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
15100 uint32_t LHSMask = getPermuteMask(LHS);
15101 uint32_t RHSMask = getPermuteMask(RHS);
15102 if (LHSMask != ~0u && RHSMask != ~0u) {
15103 // Canonicalize the expression in an attempt to have fewer unique masks
15104 // and therefore fewer registers used to hold the masks.
15105 if (LHSMask > RHSMask) {
15106 std::swap(LHSMask, RHSMask);
15107 std::swap(LHS, RHS);
15108 }
15109
15110 // Select 0xc for each lane used from source operand. Zero has 0xc mask
15111 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
15112 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
15113 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
15114
15115 // Check of we need to combine values from two sources within a byte.
15116 if (!(LHSUsedLanes & RHSUsedLanes) &&
15117 // If we select high and lower word keep it for SDWA.
15118 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
15119 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
15120 // Each byte in each mask is either selector mask 0-3, or has higher
15121 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
15122 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
15123 // mask which is not 0xff wins. By anding both masks we have a correct
15124 // result except that 0x0c shall be corrected to give 0x0c only.
15125 uint32_t Mask = LHSMask & RHSMask;
15126 for (unsigned I = 0; I < 32; I += 8) {
15127 uint32_t ByteSel = 0xff << I;
15128 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
15129 Mask &= (0x0c << I) & 0xffffffff;
15130 }
15131
15132 // Add 4 to each active LHS lane. It will not affect any existing 0xff
15133 // or 0x0c.
15134 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
15135 SDLoc DL(N);
15136
15137 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
15138 RHS.getOperand(0),
15139 DAG.getConstant(Sel, DL, MVT::i32));
15140 }
15141 }
15142 }
15143
15144 return SDValue();
15145}
15146
15147// A key component of v_perm is a mapping between byte position of the src
15148// operands, and the byte position of the dest. To provide such, we need: 1. the
15149// node that provides x byte of the dest of the OR, and 2. the byte of the node
15150// used to provide that x byte. calculateByteProvider finds which node provides
15151// a certain byte of the dest of the OR, and calculateSrcByte takes that node,
15152// and finds an ultimate src and byte position For example: The supported
15153// LoadCombine pattern for vector loads is as follows
15154// t1
15155// or
15156// / \
15157// t2 t3
15158// zext shl
15159// | | \
15160// t4 t5 16
15161// or anyext
15162// / \ |
15163// t6 t7 t8
15164// srl shl or
15165// / | / \ / \
15166// t9 t10 t11 t12 t13 t14
15167// trunc* 8 trunc* 8 and and
15168// | | / | | \
15169// t15 t16 t17 t18 t19 t20
15170// trunc* 255 srl -256
15171// | / \
15172// t15 t15 16
15173//
15174// *In this example, the truncs are from i32->i16
15175//
15176// calculateByteProvider would find t6, t7, t13, and t14 for bytes 0-3
15177// respectively. calculateSrcByte would find (given node) -> ultimate src &
15178// byteposition: t6 -> t15 & 1, t7 -> t16 & 0, t13 -> t15 & 0, t14 -> t15 & 3.
15179// After finding the mapping, we can combine the tree into vperm t15, t16,
15180// 0x05000407
15181
15182// Find the source and byte position from a node.
15183// \p DestByte is the byte position of the dest of the or that the src
15184// ultimately provides. \p SrcIndex is the byte of the src that maps to this
15185// dest of the or byte. \p Depth tracks how many recursive iterations we have
15186// performed.
15187static const std::optional<ByteProvider<SDValue>>
15188calculateSrcByte(const SDValue Op, uint64_t DestByte, uint64_t SrcIndex = 0,
15189 unsigned Depth = 0) {
15190 // We may need to recursively traverse a series of SRLs
15191 if (Depth >= 6)
15192 return std::nullopt;
15193
15194 if (Op.getValueSizeInBits() < 8)
15195 return std::nullopt;
15196
15197 if (Op.getValueType().isVector())
15198 return ByteProvider<SDValue>::getSrc(Op, DestByte, SrcIndex);
15199
15200 switch (Op->getOpcode()) {
15201 case ISD::TRUNCATE: {
15202 return calculateSrcByte(Op->getOperand(0), DestByte, SrcIndex, Depth + 1);
15203 }
15204
15205 case ISD::ANY_EXTEND:
15206 case ISD::SIGN_EXTEND:
15207 case ISD::ZERO_EXTEND:
15209 SDValue NarrowOp = Op->getOperand(0);
15210 auto NarrowVT = NarrowOp.getValueType();
15211 if (Op->getOpcode() == ISD::SIGN_EXTEND_INREG) {
15212 auto *VTSign = cast<VTSDNode>(Op->getOperand(1));
15213 NarrowVT = VTSign->getVT();
15214 }
15215 if (!NarrowVT.isByteSized())
15216 return std::nullopt;
15217 uint64_t NarrowByteWidth = NarrowVT.getStoreSize();
15218
15219 if (SrcIndex >= NarrowByteWidth)
15220 return std::nullopt;
15221 return calculateSrcByte(Op->getOperand(0), DestByte, SrcIndex, Depth + 1);
15222 }
15223
15224 case ISD::SRA:
15225 case ISD::SRL: {
15226 auto *ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15227 if (!ShiftOp)
15228 return std::nullopt;
15229
15230 uint64_t BitShift = ShiftOp->getZExtValue();
15231
15232 if (BitShift % 8 != 0)
15233 return std::nullopt;
15234
15235 uint64_t NewSrcIndex = SrcIndex + BitShift / 8;
15236 if (NewSrcIndex >= Op.getScalarValueSizeInBits() / 8)
15237 return std::nullopt;
15238
15239 return calculateSrcByte(Op->getOperand(0), DestByte, NewSrcIndex,
15240 Depth + 1);
15241 }
15242
15243 default: {
15244 return ByteProvider<SDValue>::getSrc(Op, DestByte, SrcIndex);
15245 }
15246 }
15247 llvm_unreachable("fully handled switch");
15248}
15249
15250// For a byte position in the result of an Or, traverse the tree and find the
15251// node (and the byte of the node) which ultimately provides this {Or,
15252// BytePosition}. \p Op is the operand we are currently examining. \p Index is
15253// the byte position of the Op that corresponds with the originally requested
15254// byte of the Or \p Depth tracks how many recursive iterations we have
15255// performed. \p StartingIndex is the originally requested byte of the Or
15256static const std::optional<ByteProvider<SDValue>>
15257calculateByteProvider(const SDValue &Op, unsigned Index, unsigned Depth,
15258 unsigned StartingIndex = 0) {
15259 // Finding Src tree of RHS of or typically requires at least 1 additional
15260 // depth
15261 if (Depth > 6)
15262 return std::nullopt;
15263
15264 unsigned BitWidth = Op.getScalarValueSizeInBits();
15265 if (BitWidth % 8 != 0)
15266 return std::nullopt;
15267 if (Index > BitWidth / 8 - 1)
15268 return std::nullopt;
15269
15270 bool IsVec = Op.getValueType().isVector();
15271 switch (Op.getOpcode()) {
15272 case ISD::OR: {
15273 if (IsVec)
15274 return std::nullopt;
15275
15276 auto RHS = calculateByteProvider(Op.getOperand(1), Index, Depth + 1,
15277 StartingIndex);
15278 if (!RHS)
15279 return std::nullopt;
15280 auto LHS = calculateByteProvider(Op.getOperand(0), Index, Depth + 1,
15281 StartingIndex);
15282 if (!LHS)
15283 return std::nullopt;
15284 // A well formed Or will have two ByteProviders for each byte, one of which
15285 // is constant zero
15286 if (!LHS->isConstantZero() && !RHS->isConstantZero())
15287 return std::nullopt;
15288 if (!LHS || LHS->isConstantZero())
15289 return RHS;
15290 if (!RHS || RHS->isConstantZero())
15291 return LHS;
15292 return std::nullopt;
15293 }
15294
15295 case ISD::AND: {
15296 if (IsVec)
15297 return std::nullopt;
15298
15299 auto *BitMaskOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15300 if (!BitMaskOp)
15301 return std::nullopt;
15302
15303 uint32_t BitMask = BitMaskOp->getZExtValue();
15304 // Bits we expect for our StartingIndex
15305 uint32_t IndexMask = 0xFF << (Index * 8);
15306
15307 if ((IndexMask & BitMask) != IndexMask) {
15308 // If the result of the and partially provides the byte, then it
15309 // is not well formatted
15310 if (IndexMask & BitMask)
15311 return std::nullopt;
15313 }
15314
15315 return calculateSrcByte(Op->getOperand(0), StartingIndex, Index);
15316 }
15317
15318 case ISD::FSHR: {
15319 if (IsVec)
15320 return std::nullopt;
15321
15322 // fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))
15323 auto *ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(2));
15324 if (!ShiftOp || Op.getValueType().isVector())
15325 return std::nullopt;
15326
15327 uint64_t BitsProvided = Op.getValueSizeInBits();
15328 if (BitsProvided % 8 != 0)
15329 return std::nullopt;
15330
15331 uint64_t BitShift = ShiftOp->getAPIntValue().urem(BitsProvided);
15332 if (BitShift % 8)
15333 return std::nullopt;
15334
15335 uint64_t ConcatSizeInBytes = BitsProvided / 4;
15336 uint64_t ByteShift = BitShift / 8;
15337
15338 uint64_t NewIndex = (Index + ByteShift) % ConcatSizeInBytes;
15339 uint64_t BytesProvided = BitsProvided / 8;
15340 SDValue NextOp = Op.getOperand(NewIndex >= BytesProvided ? 0 : 1);
15341 NewIndex %= BytesProvided;
15342 return calculateByteProvider(NextOp, NewIndex, Depth + 1, StartingIndex);
15343 }
15344
15345 case ISD::SRA:
15346 case ISD::SRL: {
15347 if (IsVec)
15348 return std::nullopt;
15349
15350 auto *ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15351 if (!ShiftOp)
15352 return std::nullopt;
15353
15354 uint64_t BitShift = ShiftOp->getZExtValue();
15355 if (BitShift % 8)
15356 return std::nullopt;
15357
15358 auto BitsProvided = Op.getScalarValueSizeInBits();
15359 if (BitsProvided % 8 != 0)
15360 return std::nullopt;
15361
15362 uint64_t BytesProvided = BitsProvided / 8;
15363 uint64_t ByteShift = BitShift / 8;
15364 if (Index + ByteShift < BytesProvided)
15365 return calculateSrcByte(Op->getOperand(0), StartingIndex,
15366 Index + ByteShift);
15367 // SRA's out-of-range bytes are sign bits, not constant zero.
15368 if (Op.getOpcode() == ISD::SRA)
15369 return std::nullopt;
15371 }
15372
15373 case ISD::SHL: {
15374 if (IsVec)
15375 return std::nullopt;
15376
15377 auto *ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15378 if (!ShiftOp)
15379 return std::nullopt;
15380
15381 uint64_t BitShift = ShiftOp->getZExtValue();
15382 if (BitShift % 8 != 0)
15383 return std::nullopt;
15384 uint64_t ByteShift = BitShift / 8;
15385
15386 // If we are shifting by an amount greater than (or equal to)
15387 // the index we are trying to provide, then it provides 0s. If not,
15388 // then this bytes are not definitively 0s, and the corresponding byte
15389 // of interest is Index - ByteShift of the src
15390 return Index < ByteShift
15392 : calculateByteProvider(Op.getOperand(0), Index - ByteShift,
15393 Depth + 1, StartingIndex);
15394 }
15395 case ISD::ANY_EXTEND:
15396 case ISD::SIGN_EXTEND:
15397 case ISD::ZERO_EXTEND:
15399 case ISD::AssertZext:
15400 case ISD::AssertSext: {
15401 if (IsVec)
15402 return std::nullopt;
15403
15404 SDValue NarrowOp = Op->getOperand(0);
15405 unsigned NarrowBitWidth = NarrowOp.getValueSizeInBits();
15406 if (Op->getOpcode() == ISD::SIGN_EXTEND_INREG ||
15407 Op->getOpcode() == ISD::AssertZext ||
15408 Op->getOpcode() == ISD::AssertSext) {
15409 auto *VTSign = cast<VTSDNode>(Op->getOperand(1));
15410 NarrowBitWidth = VTSign->getVT().getSizeInBits();
15411 }
15412 if (NarrowBitWidth % 8 != 0)
15413 return std::nullopt;
15414 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
15415
15416 if (Index >= NarrowByteWidth)
15417 return Op.getOpcode() == ISD::ZERO_EXTEND
15418 ? std::optional<ByteProvider<SDValue>>(
15420 : std::nullopt;
15421 return calculateByteProvider(NarrowOp, Index, Depth + 1, StartingIndex);
15422 }
15423
15424 case ISD::TRUNCATE: {
15425 if (IsVec)
15426 return std::nullopt;
15427
15428 uint64_t NarrowByteWidth = BitWidth / 8;
15429
15430 if (NarrowByteWidth >= Index) {
15431 return calculateByteProvider(Op.getOperand(0), Index, Depth + 1,
15432 StartingIndex);
15433 }
15434
15435 return std::nullopt;
15436 }
15437
15438 case ISD::CopyFromReg: {
15439 if (BitWidth / 8 > Index)
15440 return calculateSrcByte(Op, StartingIndex, Index);
15441
15442 return std::nullopt;
15443 }
15444
15445 case ISD::LOAD: {
15446 auto *L = cast<LoadSDNode>(Op.getNode());
15447
15448 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
15449 if (NarrowBitWidth % 8 != 0)
15450 return std::nullopt;
15451 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
15452
15453 // If the width of the load does not reach byte we are trying to provide for
15454 // and it is not a ZEXTLOAD, then the load does not provide for the byte in
15455 // question
15456 if (Index >= NarrowByteWidth) {
15457 return L->getExtensionType() == ISD::ZEXTLOAD
15458 ? std::optional<ByteProvider<SDValue>>(
15460 : std::nullopt;
15461 }
15462
15463 if (NarrowByteWidth > Index) {
15464 return calculateSrcByte(Op, StartingIndex, Index);
15465 }
15466
15467 return std::nullopt;
15468 }
15469
15470 case ISD::BSWAP: {
15471 if (IsVec)
15472 return std::nullopt;
15473
15474 return calculateByteProvider(Op->getOperand(0), BitWidth / 8 - Index - 1,
15475 Depth + 1, StartingIndex);
15476 }
15477
15479 auto *IdxOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15480 if (!IdxOp)
15481 return std::nullopt;
15482 auto VecIdx = IdxOp->getZExtValue();
15483 auto ScalarSize = Op.getScalarValueSizeInBits();
15484 if (ScalarSize < 32)
15485 Index = ScalarSize == 8 ? VecIdx : VecIdx * 2 + Index;
15486 return calculateSrcByte(ScalarSize >= 32 ? Op : Op.getOperand(0),
15487 StartingIndex, Index);
15488 }
15489
15490 case AMDGPUISD::PERM: {
15491 if (IsVec)
15492 return std::nullopt;
15493
15494 auto *PermMask = dyn_cast<ConstantSDNode>(Op->getOperand(2));
15495 if (!PermMask)
15496 return std::nullopt;
15497
15498 auto IdxMask =
15499 (PermMask->getZExtValue() & (0xFF << (Index * 8))) >> (Index * 8);
15500 if (IdxMask > 0x07 && IdxMask != 0x0c)
15501 return std::nullopt;
15502
15503 auto NextOp = Op.getOperand(IdxMask > 0x03 ? 0 : 1);
15504 auto NextIndex = IdxMask > 0x03 ? IdxMask % 4 : IdxMask;
15505
15506 return IdxMask != 0x0c ? calculateSrcByte(NextOp, StartingIndex, NextIndex)
15509 }
15510
15511 default: {
15512 return std::nullopt;
15513 }
15514 }
15515
15516 llvm_unreachable("fully handled switch");
15517}
15518
15519// Returns true if the Operand is a scalar and is 16 bits
15520static bool isExtendedFrom16Bits(SDValue &Operand) {
15521
15522 switch (Operand.getOpcode()) {
15523 case ISD::ANY_EXTEND:
15524 case ISD::SIGN_EXTEND:
15525 case ISD::ZERO_EXTEND: {
15526 auto OpVT = Operand.getOperand(0).getValueType();
15527 return !OpVT.isVector() && OpVT.getSizeInBits() == 16;
15528 }
15529 case ISD::LOAD: {
15530 LoadSDNode *L = cast<LoadSDNode>(Operand.getNode());
15531 auto ExtType = cast<LoadSDNode>(L)->getExtensionType();
15532 if (ExtType == ISD::ZEXTLOAD || ExtType == ISD::SEXTLOAD ||
15533 ExtType == ISD::EXTLOAD) {
15534 auto MemVT = L->getMemoryVT();
15535 return !MemVT.isVector() && MemVT.getSizeInBits() == 16;
15536 }
15537 return L->getMemoryVT().getSizeInBits() == 16;
15538 }
15539 default:
15540 return false;
15541 }
15542}
15543
15544// Returns true if the mask matches consecutive bytes, and the first byte
15545// begins at a power of 2 byte offset from 0th byte
15546static bool addresses16Bits(int Mask) {
15547 int Low8 = Mask & 0xff;
15548 int Hi8 = (Mask & 0xff00) >> 8;
15549
15550 assert(Low8 < 8 && Hi8 < 8);
15551 // Are the bytes contiguous in the order of increasing addresses.
15552 bool IsConsecutive = (Hi8 - Low8 == 1);
15553 // Is the first byte at location that is aligned for 16 bit instructions.
15554 // A counter example is taking 2 consecutive bytes starting at the 8th bit.
15555 // In this case, we still need code to extract the 16 bit operand, so it
15556 // is better to use i8 v_perm
15557 bool Is16Aligned = !(Low8 % 2);
15558
15559 return IsConsecutive && Is16Aligned;
15560}
15561
15562// Do not lower into v_perm if the operands are actually 16 bit
15563// and the selected bits (based on PermMask) correspond with two
15564// easily addressable 16 bit operands.
15566 SDValue &OtherOp) {
15567 int Low16 = PermMask & 0xffff;
15568 int Hi16 = (PermMask & 0xffff0000) >> 16;
15569
15570 auto TempOp = peekThroughBitcasts(Op);
15571 auto TempOtherOp = peekThroughBitcasts(OtherOp);
15572
15573 auto OpIs16Bit =
15574 TempOp.getValueSizeInBits() == 16 || isExtendedFrom16Bits(TempOp);
15575 if (!OpIs16Bit)
15576 return true;
15577
15578 auto OtherOpIs16Bit = TempOtherOp.getValueSizeInBits() == 16 ||
15579 isExtendedFrom16Bits(TempOtherOp);
15580 if (!OtherOpIs16Bit)
15581 return true;
15582
15583 // Do we cleanly address both
15584 return !addresses16Bits(Low16) || !addresses16Bits(Hi16);
15585}
15586
15588 unsigned DWordOffset) {
15589 SDValue Ret;
15590
15591 auto TypeSize = Src.getValueSizeInBits().getFixedValue();
15592 // ByteProvider must be at least 8 bits
15593 assert(Src.getValueSizeInBits().isKnownMultipleOf(8));
15594
15595 if (TypeSize <= 32)
15596 return DAG.getBitcastedAnyExtOrTrunc(Src, SL, MVT::i32);
15597
15598 if (Src.getValueType().isVector()) {
15599 auto ScalarTySize = Src.getScalarValueSizeInBits();
15600 auto ScalarTy = Src.getValueType().getScalarType();
15601 if (ScalarTySize == 32) {
15602 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Src,
15603 DAG.getConstant(DWordOffset, SL, MVT::i32));
15604 }
15605 if (ScalarTySize > 32) {
15606 Ret = DAG.getNode(
15607 ISD::EXTRACT_VECTOR_ELT, SL, ScalarTy, Src,
15608 DAG.getConstant(DWordOffset / (ScalarTySize / 32), SL, MVT::i32));
15609 auto ShiftVal = 32 * (DWordOffset % (ScalarTySize / 32));
15610 if (ShiftVal)
15611 Ret = DAG.getNode(ISD::SRL, SL, Ret.getValueType(), Ret,
15612 DAG.getConstant(ShiftVal, SL, MVT::i32));
15613 return DAG.getBitcastedAnyExtOrTrunc(Ret, SL, MVT::i32);
15614 }
15615
15616 assert(ScalarTySize < 32);
15617 if (TypeSize % 32 == 0) {
15618 assert(DWordOffset < TypeSize / 32);
15619 SDValue Cast = DAG.getBitcast(
15620 EVT::getVectorVT(*DAG.getContext(), MVT::i32, TypeSize / 32), Src);
15621 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
15622 DAG.getConstant(DWordOffset, SL, MVT::i32));
15623 }
15624
15625 auto NumElements = TypeSize / ScalarTySize;
15626 auto Trunc32Elements = (ScalarTySize * NumElements) / 32;
15627 auto NormalizedTrunc = Trunc32Elements * 32 / ScalarTySize;
15628 auto NumElementsIn32 = 32 / ScalarTySize;
15629 auto NumAvailElements = DWordOffset < Trunc32Elements
15630 ? NumElementsIn32
15631 : NumElements - NormalizedTrunc;
15632
15634 DAG.ExtractVectorElements(Src, VecSrcs, DWordOffset * NumElementsIn32,
15635 NumAvailElements);
15636
15637 Ret = DAG.getBuildVector(
15638 MVT::getVectorVT(MVT::getIntegerVT(ScalarTySize), NumAvailElements), SL,
15639 VecSrcs);
15640 return Ret = DAG.getBitcastedAnyExtOrTrunc(Ret, SL, MVT::i32);
15641 }
15642
15643 /// Scalar Type
15644 auto ShiftVal = 32 * DWordOffset;
15645 Ret = DAG.getNode(ISD::SRL, SL, Src.getValueType(), Src,
15646 DAG.getConstant(ShiftVal, SL, MVT::i32));
15647 return DAG.getBitcastedAnyExtOrTrunc(Ret, SL, MVT::i32);
15648}
15649
15651 SelectionDAG &DAG = DCI.DAG;
15652 [[maybe_unused]] EVT VT = N->getValueType(0);
15654
15655 // VT is known to be MVT::i32, so we need to provide 4 bytes.
15656 assert(VT == MVT::i32);
15657 for (int i = 0; i < 4; i++) {
15658 // Find the ByteProvider that provides the ith byte of the result of OR
15659 std::optional<ByteProvider<SDValue>> P =
15660 calculateByteProvider(SDValue(N, 0), i, 0, /*StartingIndex = */ i);
15661 // TODO support constantZero
15662 if (!P || P->isConstantZero())
15663 return SDValue();
15664
15665 PermNodes.push_back(*P);
15666 }
15667 if (PermNodes.size() != 4)
15668 return SDValue();
15669
15670 std::pair<unsigned, unsigned> FirstSrc(0, PermNodes[0].SrcOffset / 4);
15671 std::optional<std::pair<unsigned, unsigned>> SecondSrc;
15672 uint64_t PermMask = 0x00000000;
15673 for (size_t i = 0; i < PermNodes.size(); i++) {
15674 auto PermOp = PermNodes[i];
15675 // Since the mask is applied to Src1:Src2, Src1 bytes must be offset
15676 // by sizeof(Src2) = 4
15677 int SrcByteAdjust = 4;
15678
15679 // If the Src uses a byte from a different DWORD, then it corresponds
15680 // with a difference source
15681 if (!PermOp.hasSameSrc(PermNodes[FirstSrc.first]) ||
15682 ((PermOp.SrcOffset / 4) != FirstSrc.second)) {
15683 if (SecondSrc)
15684 if (!PermOp.hasSameSrc(PermNodes[SecondSrc->first]) ||
15685 ((PermOp.SrcOffset / 4) != SecondSrc->second))
15686 return SDValue();
15687
15688 // Set the index of the second distinct Src node
15689 SecondSrc = {i, PermNodes[i].SrcOffset / 4};
15690 assert(!(PermNodes[SecondSrc->first].Src->getValueSizeInBits() % 8));
15691 SrcByteAdjust = 0;
15692 }
15693 assert((PermOp.SrcOffset % 4) + SrcByteAdjust < 8);
15695 PermMask |= ((PermOp.SrcOffset % 4) + SrcByteAdjust) << (i * 8);
15696 }
15697 SDLoc DL(N);
15698 SDValue Op = *PermNodes[FirstSrc.first].Src;
15699 Op = getDWordFromOffset(DAG, DL, Op, FirstSrc.second);
15700 assert(Op.getValueSizeInBits() == 32);
15701
15702 // Check that we are not just extracting the bytes in order from an op
15703 if (!SecondSrc) {
15704 int Low16 = PermMask & 0xffff;
15705 int Hi16 = (PermMask & 0xffff0000) >> 16;
15706
15707 bool WellFormedLow = (Low16 == 0x0504) || (Low16 == 0x0100);
15708 bool WellFormedHi = (Hi16 == 0x0706) || (Hi16 == 0x0302);
15709
15710 // The perm op would really just produce Op. So combine into Op
15711 if (WellFormedLow && WellFormedHi)
15712 return DAG.getBitcast(MVT::getIntegerVT(32), Op);
15713 }
15714
15715 SDValue OtherOp = SecondSrc ? *PermNodes[SecondSrc->first].Src : Op;
15716
15717 if (SecondSrc) {
15718 OtherOp = getDWordFromOffset(DAG, DL, OtherOp, SecondSrc->second);
15719 assert(OtherOp.getValueSizeInBits() == 32);
15720 }
15721
15722 // Check that we haven't just recreated the same FSHR node.
15723 if (N->getOpcode() == ISD::FSHR &&
15724 (N->getOperand(0) == Op || N->getOperand(0) == OtherOp) &&
15725 (N->getOperand(1) == Op || N->getOperand(1) == OtherOp))
15726 return SDValue();
15727
15728 if (hasNon16BitAccesses(PermMask, Op, OtherOp)) {
15729
15730 assert(Op.getValueType().isByteSized() &&
15731 OtherOp.getValueType().isByteSized());
15732
15733 // If the ultimate src is less than 32 bits, then we will only be
15734 // using bytes 0: Op.getValueSizeInBytes() - 1 in the or.
15735 // CalculateByteProvider would not have returned Op as source if we
15736 // used a byte that is outside its ValueType. Thus, we are free to
15737 // ANY_EXTEND as the extended bits are dont-cares.
15738 Op = DAG.getBitcastedAnyExtOrTrunc(Op, DL, MVT::i32);
15739 OtherOp = DAG.getBitcastedAnyExtOrTrunc(OtherOp, DL, MVT::i32);
15740
15741 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op, OtherOp,
15742 DAG.getConstant(PermMask, DL, MVT::i32));
15743 }
15744 return SDValue();
15745}
15746
15747SDValue SITargetLowering::performOrCombine(SDNode *N,
15748 DAGCombinerInfo &DCI) const {
15749 SelectionDAG &DAG = DCI.DAG;
15750 SDValue LHS = N->getOperand(0);
15751 SDValue RHS = N->getOperand(1);
15752
15753 EVT VT = N->getValueType(0);
15754 if (VT == MVT::i1) {
15755 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
15756 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
15757 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
15758 SDValue Src = LHS.getOperand(0);
15759 if (Src != RHS.getOperand(0))
15760 return SDValue();
15761
15762 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
15763 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
15764 if (!CLHS || !CRHS)
15765 return SDValue();
15766
15767 // Only 10 bits are used.
15768 static const uint32_t MaxMask = 0x3ff;
15769
15770 uint32_t NewMask =
15771 (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
15772 SDLoc DL(N);
15773 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, Src,
15774 DAG.getConstant(NewMask, DL, MVT::i32));
15775 }
15776
15777 return SDValue();
15778 }
15779
15780 if (VT == MVT::i32 && !DCI.isBeforeLegalize()) {
15781 for (unsigned I : {1u, 0u}) {
15782 SDValue Ext = N->getOperand(I);
15783 // The select may need an e64 cndmask, so only fold when it eliminates
15784 // the extension.
15785 if (!Ext.hasOneUse() || !isBoolSGPRExt(Ext))
15786 continue;
15787 // A divergent select still needs to materialize a uniform condition.
15788 // Sharing that condition can also require converting it back to SCC.
15789 SDValue Cond = Ext.getOperand(0);
15790 if (N->isDivergent() && !Cond->isDivergent() && !Cond.hasOneUse())
15791 continue;
15792
15793 // or x, (sext/anyext cc from i1) => select cc, -1, x
15794 // Any-extended bits can be chosen to match sign extension.
15795 SDLoc DL(N);
15796 return DAG.getSelect(DL, MVT::i32, Cond,
15797 DAG.getAllOnesConstant(DL, MVT::i32),
15798 N->getOperand(1 - I));
15799 }
15800 }
15801
15802 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
15804 LHS.getOpcode() == AMDGPUISD::PERM &&
15805 isa<ConstantSDNode>(LHS.getOperand(2))) {
15806 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
15807 if (!Sel)
15808 return SDValue();
15809
15810 Sel |= LHS.getConstantOperandVal(2);
15811 SDLoc DL(N);
15812 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
15813 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
15814 }
15815
15816 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
15817 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
15818 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
15819 TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
15820
15821 // If all the uses of an or need to extract the individual elements, do not
15822 // attempt to lower into v_perm
15823 auto usesCombinedOperand = [](SDNode *OrUse) {
15824 // If we have any non-vectorized use, then it is a candidate for v_perm
15825 if (OrUse->getOpcode() != ISD::BITCAST ||
15826 !OrUse->getValueType(0).isVector())
15827 return true;
15828
15829 // If we have any non-vectorized use, then it is a candidate for v_perm
15830 for (auto *VUser : OrUse->users()) {
15831 if (!VUser->getValueType(0).isVector())
15832 return true;
15833
15834 // If the use of a vector is a store, then combining via a v_perm
15835 // is beneficial.
15836 // TODO -- whitelist more uses
15837 for (auto VectorwiseOp : {ISD::STORE, ISD::CopyToReg, ISD::CopyFromReg})
15838 if (VUser->getOpcode() == VectorwiseOp)
15839 return true;
15840 }
15841 return false;
15842 };
15843
15844 if (!any_of(N->users(), usesCombinedOperand))
15845 return SDValue();
15846
15847 uint32_t LHSMask = getPermuteMask(LHS);
15848 uint32_t RHSMask = getPermuteMask(RHS);
15849
15850 if (LHSMask != ~0u && RHSMask != ~0u) {
15851 // Canonicalize the expression in an attempt to have fewer unique masks
15852 // and therefore fewer registers used to hold the masks.
15853 if (LHSMask > RHSMask) {
15854 std::swap(LHSMask, RHSMask);
15855 std::swap(LHS, RHS);
15856 }
15857
15858 // Select 0xc for each lane used from source operand. Zero has 0xc mask
15859 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
15860 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
15861 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
15862
15863 // Check of we need to combine values from two sources within a byte.
15864 if (!(LHSUsedLanes & RHSUsedLanes) &&
15865 // If we select high and lower word keep it for SDWA.
15866 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
15867 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
15868 // Kill zero bytes selected by other mask. Zero value is 0xc.
15869 LHSMask &= ~RHSUsedLanes;
15870 RHSMask &= ~LHSUsedLanes;
15871 // Add 4 to each active LHS lane
15872 LHSMask |= LHSUsedLanes & 0x04040404;
15873 // Combine masks
15874 uint32_t Sel = LHSMask | RHSMask;
15875 SDLoc DL(N);
15876
15877 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
15878 RHS.getOperand(0),
15879 DAG.getConstant(Sel, DL, MVT::i32));
15880 }
15881 }
15882 if (LHSMask == ~0u || RHSMask == ~0u) {
15883 if (SDValue Perm = matchPERM(N, DCI))
15884 return Perm;
15885 }
15886 }
15887
15888 // Detect identity v2i32 OR and replace with identity source node.
15889 // Specifically an Or that has operands constructed from the same source node
15890 // via extract_vector_elt and build_vector. I.E.
15891 // v2i32 or(
15892 // v2i32 build_vector(
15893 // i32 extract_elt(%IdentitySrc, 0),
15894 // i32 0
15895 // ),
15896 // v2i32 build_vector(
15897 // i32 0,
15898 // i32 extract_elt(%IdentitySrc, 1)
15899 // ) )
15900 // =>
15901 // v2i32 %IdentitySrc
15902
15903 if (VT == MVT::v2i32 && LHS->getOpcode() == ISD::BUILD_VECTOR &&
15904 RHS->getOpcode() == ISD::BUILD_VECTOR) {
15905
15906 ConstantSDNode *LC = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
15907 ConstantSDNode *RC = dyn_cast<ConstantSDNode>(RHS->getOperand(0));
15908
15909 // Test for and normalise build vectors.
15910 if (LC && RC && LC->getZExtValue() == 0 && RC->getZExtValue() == 0) {
15911
15912 // Get the extract_vector_element operands.
15913 SDValue LEVE = LHS->getOperand(0);
15914 SDValue REVE = RHS->getOperand(1);
15915
15916 if (LEVE->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15918 // Check that different elements from the same vector are
15919 // extracted.
15920 if (LEVE->getOperand(0) == REVE->getOperand(0) &&
15921 LEVE->getOperand(1) != REVE->getOperand(1)) {
15922 SDValue IdentitySrc = LEVE.getOperand(0);
15923 return IdentitySrc;
15924 }
15925 }
15926 }
15927 }
15928
15929 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
15930 return SDValue();
15931
15932 // TODO: This could be a generic combine with a predicate for extracting the
15933 // high half of an integer being free.
15934
15935 // (or i64:x, (zero_extend i32:y)) ->
15936 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
15937 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
15938 RHS.getOpcode() != ISD::ZERO_EXTEND)
15939 std::swap(LHS, RHS);
15940
15941 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
15942 SDValue ExtSrc = RHS.getOperand(0);
15943 EVT SrcVT = ExtSrc.getValueType();
15944 if (SrcVT == MVT::i32) {
15945 SDLoc SL(N);
15946 auto [LowLHS, HiBits] = split64BitValue(LHS, DAG);
15947 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
15948
15949 DCI.AddToWorklist(LowOr.getNode());
15950 DCI.AddToWorklist(HiBits.getNode());
15951
15952 SDValue Vec =
15953 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, LowOr, HiBits);
15954 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
15955 }
15956 }
15957
15958 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
15959 if (CRHS) {
15960 if (SDValue Split = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
15961 N->getOperand(0), CRHS))
15962 return Split;
15963 }
15964
15965 return SDValue();
15966}
15967
15968SDValue SITargetLowering::performXorCombine(SDNode *N,
15969 DAGCombinerInfo &DCI) const {
15970 if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
15971 return RV;
15972
15973 SDValue LHS = N->getOperand(0);
15974 SDValue RHS = N->getOperand(1);
15975
15976 const ConstantSDNode *CRHS = isConstOrConstSplat(RHS);
15977 SelectionDAG &DAG = DCI.DAG;
15978
15979 EVT VT = N->getValueType(0);
15980 if (CRHS && VT == MVT::i64) {
15981 if (SDValue Split =
15982 splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
15983 return Split;
15984 }
15985
15986 // v2i32 (xor (vselect cc, x, y), K) ->
15987 // (v2i32 svelect cc, (xor x, K), (xor y, K)) This enables the xor to be
15988 // replaced with source modifiers when the select is lowered to CNDMASK.
15989 unsigned Opc = LHS.getOpcode();
15990 if (((Opc == ISD::VSELECT && VT == MVT::v2i32) ||
15991 (Opc == ISD::SELECT && VT == MVT::i64)) &&
15992 CRHS && CRHS->getAPIntValue().isSignMask()) {
15993 SDValue CC = LHS->getOperand(0);
15994 SDValue TRUE = LHS->getOperand(1);
15995 SDValue FALSE = LHS->getOperand(2);
15996 SDValue XTrue = DAG.getNode(ISD::XOR, SDLoc(N), VT, TRUE, RHS);
15997 SDValue XFalse = DAG.getNode(ISD::XOR, SDLoc(N), VT, FALSE, RHS);
15998 SDValue XSelect =
15999 DAG.getNode(ISD::VSELECT, SDLoc(N), VT, CC, XTrue, XFalse);
16000 return XSelect;
16001 }
16002
16003 // Make sure to apply the 64-bit constant splitting fold before trying to fold
16004 // fneg-like xors into 64-bit select.
16005 if (LHS.getOpcode() == ISD::SELECT && VT == MVT::i32) {
16006 // This looks like an fneg, try to fold as a source modifier.
16007 if (CRHS && CRHS->getAPIntValue().isSignMask() &&
16009 // xor (select c, a, b), 0x80000000 ->
16010 // bitcast (select c, (fneg (bitcast a)), (fneg (bitcast b)))
16011 SDLoc DL(N);
16012 SDValue CastLHS =
16013 DAG.getNode(ISD::BITCAST, DL, MVT::f32, LHS->getOperand(1));
16014 SDValue CastRHS =
16015 DAG.getNode(ISD::BITCAST, DL, MVT::f32, LHS->getOperand(2));
16016 SDValue FNegLHS = DAG.getNode(ISD::FNEG, DL, MVT::f32, CastLHS);
16017 SDValue FNegRHS = DAG.getNode(ISD::FNEG, DL, MVT::f32, CastRHS);
16018 SDValue NewSelect = DAG.getNode(ISD::SELECT, DL, MVT::f32,
16019 LHS->getOperand(0), FNegLHS, FNegRHS);
16020 return DAG.getNode(ISD::BITCAST, DL, VT, NewSelect);
16021 }
16022 }
16023
16024 return SDValue();
16025}
16026
16027SDValue
16028SITargetLowering::performZeroOrAnyExtendCombine(SDNode *N,
16029 DAGCombinerInfo &DCI) const {
16030 if (!Subtarget->has16BitInsts() ||
16031 DCI.getDAGCombineLevel() < AfterLegalizeTypes)
16032 return SDValue();
16033
16034 EVT VT = N->getValueType(0);
16035 if (VT != MVT::i32)
16036 return SDValue();
16037
16038 SDValue Src = N->getOperand(0);
16039 if (Src.getValueType() != MVT::i16)
16040 return SDValue();
16041
16042 if (!Src->hasOneUse())
16043 return SDValue();
16044
16045 if (SDValue Ext = performExtendTruncShiftCombine(N, DCI))
16046 return Ext;
16047
16048 // TODO: We bail out below if SrcOffset is not in the first dword (>= 4). It's
16049 // possible we're missing out on some combine opportunities, but we'd need to
16050 // weigh the cost of extracting the byte from the upper dwords.
16051
16052 std::optional<ByteProvider<SDValue>> BP0 =
16053 calculateByteProvider(SDValue(N, 0), 0, 0, 0);
16054 if (!BP0 || BP0->SrcOffset >= 4 || !BP0->Src)
16055 return SDValue();
16056 SDValue V0 = *BP0->Src;
16057
16058 std::optional<ByteProvider<SDValue>> BP1 =
16059 calculateByteProvider(SDValue(N, 0), 1, 0, 1);
16060 if (!BP1 || BP1->SrcOffset >= 4 || !BP1->Src)
16061 return SDValue();
16062
16063 SDValue V1 = *BP1->Src;
16064
16065 if (V0 == V1)
16066 return SDValue();
16067
16068 SelectionDAG &DAG = DCI.DAG;
16069 SDLoc DL(N);
16070 uint32_t PermMask = 0x0c0c0c0c;
16071 if (V0) {
16072 V0 = getDWordFromOffset(DAG, DL, V0, /*DWordOffset=*/0);
16073 PermMask = (PermMask & ~0xFF) | (BP0->SrcOffset + 4);
16074 }
16075
16076 if (V1) {
16077 V1 = getDWordFromOffset(DAG, DL, V1, /*DWordOffset=*/0);
16078 PermMask = (PermMask & ~(0xFF << 8)) | (BP1->SrcOffset << 8);
16079 }
16080
16081 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, V0, V1,
16082 DAG.getConstant(PermMask, DL, MVT::i32));
16083}
16084
16085// zext (srl (trunc x), c) => and (srl x, c), lowbits
16086// aext (srl (trunc x), c) => and (srl x, c), lowbits
16087// sext (sra (trunc x), 8) => sext_inreg (srl x, 8), i8
16088SDValue
16089SITargetLowering::performExtendTruncShiftCombine(SDNode *N,
16090 DAGCombinerInfo &DCI) const {
16091 if (DCI.getDAGCombineLevel() < AfterLegalizeTypes)
16092 return SDValue();
16093
16094 const unsigned Opc = N->getOpcode();
16095 const bool IsSigned = Opc == ISD::SIGN_EXTEND;
16096 SDValue Src = N->getOperand(0);
16097 if (N->getValueType(0) != MVT::i32 || Src.getValueType() != MVT::i16 ||
16098 Src.getOpcode() != (IsSigned ? ISD::SRA : ISD::SRL) || !Src.hasOneUse() ||
16099 Src.getOperand(0).getOpcode() != ISD::TRUNCATE)
16100 return SDValue();
16101
16102 // A uniform i16 srl is promoted to i32 later and yields the same nodes.
16103 // Skip it so that the node order, and with it the schedule, stays the same.
16104 if (!IsSigned && !Src->isDivergent())
16105 return SDValue();
16106
16107 SDValue X = Src.getOperand(0).getOperand(0);
16108 auto *Shift = dyn_cast<ConstantSDNode>(Src.getOperand(1));
16109 if (X.getValueType() != MVT::i32 || !Shift || Shift->getZExtValue() == 0 ||
16110 Shift->getZExtValue() >= 16 || (IsSigned && Shift->getZExtValue() != 8))
16111 return SDValue();
16112
16113 SelectionDAG &DAG = DCI.DAG;
16114 SDLoc SL(N);
16115 const unsigned Width = 16 - Shift->getZExtValue();
16116 SDValue Srl = DAG.getNode(
16117 ISD::SRL, SL, MVT::i32, X,
16118 DAG.getShiftAmountConstant(Shift->getZExtValue(), MVT::i32, SL));
16119 if (IsSigned)
16120 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, Srl,
16121 DAG.getValueType(MVT::i8));
16122 return DAG.getNode(
16123 ISD::AND, SL, MVT::i32, Srl,
16124 DAG.getConstant(maskTrailingOnes<uint32_t>(Width), SL, MVT::i32));
16125}
16126
16127SDValue
16128SITargetLowering::performSignExtendInRegCombine(SDNode *N,
16129 DAGCombinerInfo &DCI) const {
16130 SDValue Src = N->getOperand(0);
16131 auto *VTSign = cast<VTSDNode>(N->getOperand(1));
16132
16133 // Combine s_buffer_load_u8 or s_buffer_load_u16 with sext and replace them
16134 // with s_buffer_load_i8 and s_buffer_load_i16 respectively.
16135 if (((Src.getOpcode() == AMDGPUISD::SBUFFER_LOAD_UBYTE &&
16136 VTSign->getVT() == MVT::i8) ||
16137 (Src.getOpcode() == AMDGPUISD::SBUFFER_LOAD_USHORT &&
16138 VTSign->getVT() == MVT::i16))) {
16139 assert(Subtarget->hasScalarSubwordLoads() &&
16140 "s_buffer_load_{u8, i8} are supported "
16141 "in GFX12 (or newer) architectures.");
16142 unsigned Opc = (Src.getOpcode() == AMDGPUISD::SBUFFER_LOAD_UBYTE)
16143 ? AMDGPUISD::SBUFFER_LOAD_BYTE
16144 : AMDGPUISD::SBUFFER_LOAD_SHORT;
16145 SDLoc DL(N);
16146 SDVTList ResList =
16147 DCI.DAG.getVTList(MVT::i32, Src.getOperand(0).getValueType());
16148 SDValue Ops[] = {
16149 Src.getOperand(0), // Chain
16150 Src.getOperand(1), // source register
16151 Src.getOperand(2), // offset
16152 Src.getOperand(3) // cachePolicy
16153 };
16154 auto *M = cast<MemSDNode>(Src);
16155 SDValue BufferLoad = DCI.DAG.getMemIntrinsicNode(
16156 Opc, DL, ResList, Ops, M->getMemoryVT(), M->getMemOperand());
16157 return DCI.DAG.getMergeValues({BufferLoad, BufferLoad.getValue(1)}, DL);
16158 }
16159 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
16160 VTSign->getVT() == MVT::i8) ||
16161 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
16162 VTSign->getVT() == MVT::i16)) &&
16163 Src.hasOneUse()) {
16164 auto *M = cast<MemSDNode>(Src);
16165 SDValue Ops[] = {Src.getOperand(0), // Chain
16166 Src.getOperand(1), // rsrc
16167 Src.getOperand(2), // vindex
16168 Src.getOperand(3), // voffset
16169 Src.getOperand(4), // soffset
16170 Src.getOperand(5), // offset
16171 Src.getOperand(6), Src.getOperand(7)};
16172 // replace with BUFFER_LOAD_BYTE/SHORT
16173 SDVTList ResList =
16174 DCI.DAG.getVTList(MVT::i32, Src.getOperand(0).getValueType());
16175 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE)
16176 ? AMDGPUISD::BUFFER_LOAD_BYTE
16177 : AMDGPUISD::BUFFER_LOAD_SHORT;
16178 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(
16179 Opc, SDLoc(N), ResList, Ops, M->getMemoryVT(), M->getMemOperand());
16180 return DCI.DAG.getMergeValues(
16181 {BufferLoadSignExt, BufferLoadSignExt.getValue(1)}, SDLoc(N));
16182 }
16183 return SDValue();
16184}
16185
16186SDValue SITargetLowering::performClassCombine(SDNode *N,
16187 DAGCombinerInfo &DCI) const {
16188 SelectionDAG &DAG = DCI.DAG;
16189 SDValue Mask = N->getOperand(1);
16190
16191 // fp_class x, 0 -> false
16192 if (isNullConstant(Mask))
16193 return DAG.getConstant(0, SDLoc(N), MVT::i1);
16194
16195 if (N->getOperand(0).isUndef())
16196 return DAG.getUNDEF(MVT::i1);
16197
16198 return SDValue();
16199}
16200
16201SDValue SITargetLowering::performRcpCombine(SDNode *N,
16202 DAGCombinerInfo &DCI) const {
16203 EVT VT = N->getValueType(0);
16204 SDValue N0 = N->getOperand(0);
16205
16206 if (N0.isUndef()) {
16207 return DCI.DAG.getConstantFP(APFloat::getQNaN(VT.getFltSemantics()),
16208 SDLoc(N), VT);
16209 }
16210
16211 // TODO: Could handle f32 + amdgcn.sqrt but probably never reaches here.
16212 if ((VT == MVT::f16 && N0.getOpcode() == ISD::FSQRT) &&
16213 N->getFlags().hasAllowContract() && N0->getFlags().hasAllowContract()) {
16214 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, N0.getOperand(0),
16215 N->getFlags());
16216 }
16217
16219}
16220
16222 SDNodeFlags UserFlags,
16223 unsigned MaxDepth) const {
16224 EVT VT = Op.getValueType();
16225 assert(VT.isFloatingPoint() &&
16226 "expected a floating-point value to query canonicality of");
16227 return isCanonicalized(DAG, Op, VT.getScalarType(), UserFlags, MaxDepth);
16228}
16229
16231 EVT QueryVT, SDNodeFlags UserFlags,
16232 unsigned MaxDepth) const {
16233 assert(QueryVT.isFloatingPoint() && !QueryVT.isVector() &&
16234 "QueryVT must be a floating-point scalar type");
16235 EVT VT = Op.getValueType();
16236 if (VT.isFloatingPoint() && VT.getScalarType() != QueryVT)
16237 return false;
16238
16239 unsigned Opcode = Op.getOpcode();
16240 if (Opcode == ISD::FCANONICALIZE)
16241 return true;
16242
16243 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
16244 const auto &F = CFP->getValueAPF();
16245 if (F.isNaN() && F.isSignaling())
16246 return false;
16247 if (!F.isDenormal())
16248 return true;
16249
16250 DenormalMode Mode =
16251 DAG.getMachineFunction().getDenormalMode(F.getSemantics());
16252 return Mode == DenormalMode::getIEEE();
16253 }
16254
16255 // If source is a result of another standard FP operation it is already in
16256 // canonical form.
16257 if (MaxDepth == 0)
16258 return false;
16259
16260 switch (Opcode) {
16261 // These will flush denorms if required.
16262 case ISD::FADD:
16263 case ISD::FSUB:
16264 case ISD::FMUL:
16265 case ISD::FCEIL:
16266 case ISD::FFLOOR:
16267 case ISD::FMA:
16268 case ISD::FMAD:
16269 case ISD::FSQRT:
16270 case ISD::FDIV:
16271 case ISD::FREM:
16272 case ISD::FP_ROUND:
16273 case ISD::FP_EXTEND:
16274 case ISD::FP16_TO_FP:
16275 case ISD::FP_TO_FP16:
16276 case ISD::BF16_TO_FP:
16277 case ISD::FP_TO_BF16:
16278 case ISD::FLDEXP:
16279 case AMDGPUISD::FMUL_LEGACY:
16280 case AMDGPUISD::FMAD_FTZ:
16281 case AMDGPUISD::RCP:
16282 case AMDGPUISD::RSQ:
16283 case AMDGPUISD::RSQ_CLAMP:
16284 case AMDGPUISD::RCP_LEGACY:
16285 case AMDGPUISD::RCP_IFLAG:
16286 case AMDGPUISD::LOG:
16287 case AMDGPUISD::EXP:
16288 case AMDGPUISD::DIV_SCALE:
16289 case AMDGPUISD::DIV_FMAS:
16290 case AMDGPUISD::DIV_FIXUP:
16291 case AMDGPUISD::FRACT:
16292 case AMDGPUISD::CVT_PKRTZ_F16_F32:
16293 case AMDGPUISD::CVT_F32_UBYTE0:
16294 case AMDGPUISD::CVT_F32_UBYTE1:
16295 case AMDGPUISD::CVT_F32_UBYTE2:
16296 case AMDGPUISD::CVT_F32_UBYTE3:
16297 case AMDGPUISD::FP_TO_FP16:
16298 case AMDGPUISD::SIN_HW:
16299 case AMDGPUISD::COS_HW:
16300 return true;
16301
16302 // It can/will be lowered or combined as a bit operation.
16303 // Need to check their input recursively to handle.
16304 case ISD::FNEG:
16305 case ISD::FABS:
16306 case ISD::FCOPYSIGN:
16307 return isCanonicalized(DAG, Op.getOperand(0), QueryVT, UserFlags,
16308 MaxDepth - 1);
16309
16310 case ISD::AND:
16311 if (Op.getValueType() == MVT::i32) {
16312 // Be careful as we only know it is a bitcast floating point type. It
16313 // could be f32, v2f16, we have no way of knowing. Luckily the constant
16314 // value that we optimize for, which comes up in fp32 to bf16 conversions,
16315 // is valid to optimize for all types.
16316 if (auto *RHS = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16317 if (RHS->getZExtValue() == 0xffff0000) {
16318 return isCanonicalized(DAG, Op.getOperand(0), QueryVT, UserFlags,
16319 MaxDepth - 1);
16320 }
16321 }
16322 }
16323 break;
16324
16325 case ISD::FSIN:
16326 case ISD::FCOS:
16327 case ISD::FSINCOS:
16328 return Op.getValueType().getScalarType() != MVT::f16;
16329
16330 case ISD::FMINNUM:
16331 case ISD::FMAXNUM:
16332 case ISD::FMINNUM_IEEE:
16333 case ISD::FMAXNUM_IEEE:
16334 case ISD::FMINIMUM:
16335 case ISD::FMAXIMUM:
16336 case ISD::FMINIMUMNUM:
16337 case ISD::FMAXIMUMNUM:
16338 case AMDGPUISD::CLAMP:
16339 case AMDGPUISD::FMED3:
16340 case AMDGPUISD::FMAX3:
16341 case AMDGPUISD::FMIN3:
16342 case AMDGPUISD::FMAXIMUM3:
16343 case AMDGPUISD::FMINIMUM3: {
16344 // FIXME: Shouldn't treat the generic operations different based these.
16345 // However, we aren't really required to flush the result from
16346 // minnum/maxnum..
16347
16348 // snans will be quieted, so we only need to worry about denormals.
16349 if (Subtarget->supportsMinMaxDenormModes() ||
16350 // FIXME: denormalsEnabledForType is broken for dynamic
16351 denormalsEnabledForType(DAG, Op.getValueType()))
16352 return true;
16353
16354 // Flushing may be required.
16355 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
16356 // targets need to check their input recursively.
16357
16358 // FIXME: Does this apply with clamp? It's implemented with max.
16359 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
16360 if (!isCanonicalized(DAG, Op.getOperand(I), QueryVT, UserFlags,
16361 MaxDepth - 1))
16362 return false;
16363 }
16364
16365 return true;
16366 }
16367 case ISD::SELECT: {
16368 return isCanonicalized(DAG, Op.getOperand(1), QueryVT, UserFlags,
16369 MaxDepth - 1) &&
16370 isCanonicalized(DAG, Op.getOperand(2), QueryVT, UserFlags,
16371 MaxDepth - 1);
16372 }
16373 case ISD::BUILD_VECTOR: {
16374 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
16375 SDValue SrcOp = Op.getOperand(i);
16376 if (!isCanonicalized(DAG, SrcOp, QueryVT, UserFlags, MaxDepth - 1))
16377 return false;
16378 }
16379
16380 return true;
16381 }
16384 return isCanonicalized(DAG, Op.getOperand(0), QueryVT, UserFlags,
16385 MaxDepth - 1);
16386 }
16388 return isCanonicalized(DAG, Op.getOperand(0), QueryVT, UserFlags,
16389 MaxDepth - 1) &&
16390 isCanonicalized(DAG, Op.getOperand(1), QueryVT, UserFlags,
16391 MaxDepth - 1);
16392 }
16393 case ISD::POISON:
16394 return true;
16395 case ISD::UNDEF:
16396 // Could be anything.
16397 return false;
16398
16399 case ISD::BITCAST: {
16400 // Carry QueryVT through the bitcast unchanged. The top-of-function guard
16401 // rejects a source whose FP format differs from the consumed type, so a
16402 // value canonical in one FP format is not assumed canonical in another.
16403 SDValue Src = peekThroughBitcasts(Op.getOperand(0));
16404 return isCanonicalized(DAG, Src, QueryVT, UserFlags, MaxDepth - 1);
16405 }
16406 case ISD::TRUNCATE: {
16407 // Hack round the mess we make when legalizing extract_vector_elt
16408 if (Op.getValueType() == MVT::i16) {
16409 SDValue TruncSrc = Op.getOperand(0);
16410 if (TruncSrc.getValueType() == MVT::i32 &&
16411 TruncSrc.getOpcode() == ISD::BITCAST &&
16412 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
16413 return isCanonicalized(DAG, TruncSrc.getOperand(0), QueryVT, UserFlags,
16414 MaxDepth - 1);
16415 }
16416 }
16417 return false;
16418 }
16420 unsigned IntrinsicID = Op.getConstantOperandVal(0);
16421 // TODO: Handle more intrinsics
16422 switch (IntrinsicID) {
16423 case Intrinsic::amdgcn_update_dpp: {
16424 enum UpdateDPPOperand {
16425 Src = 2,
16426 RowMask = 4,
16427 BankMask = 5,
16428 BoundCtrl = 6,
16429 };
16430
16431 if (QueryVT == MVT::f32 && (VT == MVT::i32 || VT == MVT::f32) &&
16432 Op.getConstantOperandVal(RowMask) == 0xf && // Enable all rows.
16433 Op.getConstantOperandVal(BankMask) == 0xf && // Enable all banks.
16434 Op.getConstantOperandVal(BoundCtrl) != 0) // Zero-fill OOB lanes.
16435 return isCanonicalized(DAG, Op.getOperand(2), QueryVT, UserFlags,
16436 MaxDepth - 1);
16437 return false;
16438 }
16439 case Intrinsic::amdgcn_cvt_pkrtz:
16440 case Intrinsic::amdgcn_cubeid:
16441 case Intrinsic::amdgcn_frexp_mant:
16442 case Intrinsic::amdgcn_fdot2:
16443 case Intrinsic::amdgcn_rcp:
16444 case Intrinsic::amdgcn_rsq:
16445 case Intrinsic::amdgcn_rsq_clamp:
16446 case Intrinsic::amdgcn_rcp_legacy:
16447 case Intrinsic::amdgcn_rsq_legacy:
16448 case Intrinsic::amdgcn_trig_preop:
16449 case Intrinsic::amdgcn_tanh:
16450 case Intrinsic::amdgcn_log:
16451 case Intrinsic::amdgcn_exp2:
16452 case Intrinsic::amdgcn_sqrt:
16453 return true;
16454 default:
16455 break;
16456 }
16457
16458 break;
16459 }
16460 default:
16461 break;
16462 }
16463
16464 // FIXME: denormalsEnabledForType is broken for dynamic
16465 return denormalsEnabledForType(DAG, Op.getValueType()) &&
16466 (UserFlags.hasNoNaNs() || DAG.isKnownNeverSNaN(Op));
16467}
16468
16470 unsigned MaxDepth) const {
16471 const MachineRegisterInfo &MRI = MF.getRegInfo();
16472 MachineInstr *MI = MRI.getVRegDef(Reg);
16473 unsigned Opcode = MI->getOpcode();
16474
16475 if (Opcode == AMDGPU::G_FCANONICALIZE)
16476 return true;
16477
16478 std::optional<FPValueAndVReg> FCR;
16479 // Constant splat (can be padded with undef) or scalar constant.
16481 if (FCR->Value.isSignaling())
16482 return false;
16483 if (!FCR->Value.isDenormal())
16484 return true;
16485
16486 DenormalMode Mode = MF.getDenormalMode(FCR->Value.getSemantics());
16487 return Mode == DenormalMode::getIEEE();
16488 }
16489
16490 if (MaxDepth == 0)
16491 return false;
16492
16493 switch (Opcode) {
16494 case AMDGPU::G_FADD:
16495 case AMDGPU::G_FSUB:
16496 case AMDGPU::G_FMUL:
16497 case AMDGPU::G_FCEIL:
16498 case AMDGPU::G_FFLOOR:
16499 case AMDGPU::G_FRINT:
16500 case AMDGPU::G_FNEARBYINT:
16501 case AMDGPU::G_INTRINSIC_FPTRUNC_ROUND:
16502 case AMDGPU::G_INTRINSIC_TRUNC:
16503 case AMDGPU::G_INTRINSIC_ROUNDEVEN:
16504 case AMDGPU::G_FMA:
16505 case AMDGPU::G_FMAD:
16506 case AMDGPU::G_FSQRT:
16507 case AMDGPU::G_FDIV:
16508 case AMDGPU::G_FREM:
16509 case AMDGPU::G_FPOW:
16510 case AMDGPU::G_FPEXT:
16511 case AMDGPU::G_FLOG:
16512 case AMDGPU::G_FLOG2:
16513 case AMDGPU::G_FLOG10:
16514 case AMDGPU::G_FPTRUNC:
16515 case AMDGPU::G_AMDGPU_RCP_IFLAG:
16516 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE0:
16517 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE1:
16518 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE2:
16519 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE3:
16520 return true;
16521 case AMDGPU::G_FNEG:
16522 case AMDGPU::G_FABS:
16523 case AMDGPU::G_FCOPYSIGN:
16524 return isCanonicalized(MI->getOperand(1).getReg(), MF, MaxDepth - 1);
16525 case AMDGPU::G_FMINNUM:
16526 case AMDGPU::G_FMAXNUM:
16527 case AMDGPU::G_FMINNUM_IEEE:
16528 case AMDGPU::G_FMAXNUM_IEEE:
16529 case AMDGPU::G_FMINIMUM:
16530 case AMDGPU::G_FMAXIMUM:
16531 case AMDGPU::G_FMINIMUMNUM:
16532 case AMDGPU::G_FMAXIMUMNUM: {
16533 if (Subtarget->supportsMinMaxDenormModes() ||
16534 // FIXME: denormalsEnabledForType is broken for dynamic
16535 denormalsEnabledForType(MRI.getType(Reg), MF))
16536 return true;
16537
16538 [[fallthrough]];
16539 }
16540 case AMDGPU::G_BUILD_VECTOR:
16541 for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
16542 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
16543 return false;
16544 return true;
16545 case AMDGPU::G_INTRINSIC:
16546 case AMDGPU::G_INTRINSIC_CONVERGENT:
16547 switch (cast<GIntrinsic>(MI)->getIntrinsicID()) {
16548 case Intrinsic::amdgcn_fmul_legacy:
16549 case Intrinsic::amdgcn_fmad_ftz:
16550 case Intrinsic::amdgcn_sqrt:
16551 case Intrinsic::amdgcn_fmed3:
16552 case Intrinsic::amdgcn_sin:
16553 case Intrinsic::amdgcn_cos:
16554 case Intrinsic::amdgcn_log:
16555 case Intrinsic::amdgcn_exp2:
16556 case Intrinsic::amdgcn_log_clamp:
16557 case Intrinsic::amdgcn_rcp:
16558 case Intrinsic::amdgcn_rcp_legacy:
16559 case Intrinsic::amdgcn_rsq:
16560 case Intrinsic::amdgcn_rsq_clamp:
16561 case Intrinsic::amdgcn_rsq_legacy:
16562 case Intrinsic::amdgcn_div_scale:
16563 case Intrinsic::amdgcn_div_fmas:
16564 case Intrinsic::amdgcn_div_fixup:
16565 case Intrinsic::amdgcn_fract:
16566 case Intrinsic::amdgcn_cvt_pkrtz:
16567 case Intrinsic::amdgcn_cubeid:
16568 case Intrinsic::amdgcn_cubema:
16569 case Intrinsic::amdgcn_cubesc:
16570 case Intrinsic::amdgcn_cubetc:
16571 case Intrinsic::amdgcn_frexp_mant:
16572 case Intrinsic::amdgcn_fdot2:
16573 case Intrinsic::amdgcn_trig_preop:
16574 case Intrinsic::amdgcn_tanh:
16575 return true;
16576 default:
16577 break;
16578 }
16579
16580 [[fallthrough]];
16581 default:
16582 return false;
16583 }
16584
16585 llvm_unreachable("invalid operation");
16586}
16587
16588// Constant fold canonicalize.
16589SDValue SITargetLowering::getCanonicalConstantFP(SelectionDAG &DAG,
16590 const SDLoc &SL, EVT VT,
16591 const APFloat &C) const {
16592 // Flush denormals to 0 if not enabled.
16593 if (C.isDenormal()) {
16594 DenormalMode Mode =
16595 DAG.getMachineFunction().getDenormalMode(C.getSemantics());
16596 if (Mode == DenormalMode::getPreserveSign()) {
16597 return DAG.getConstantFP(
16598 APFloat::getZero(C.getSemantics(), C.isNegative()), SL, VT);
16599 }
16600
16601 if (Mode != DenormalMode::getIEEE())
16602 return SDValue();
16603 }
16604
16605 if (C.isNaN()) {
16606 if (C.isSignaling()) {
16607 // Quiet a signaling NaN.
16608 return DAG.getConstantFP(C.makeQuiet(), SL, VT);
16609 }
16610 }
16611
16612 // Already canonical.
16613 return DAG.getConstantFP(C, SL, VT);
16614}
16615
16617 return Op.isUndef() || isa<ConstantFPSDNode>(Op);
16618}
16619
16620SDValue
16621SITargetLowering::performFCanonicalizeCombine(SDNode *N,
16622 DAGCombinerInfo &DCI) const {
16623 SelectionDAG &DAG = DCI.DAG;
16624 SDValue N0 = N->getOperand(0);
16625 EVT VT = N->getValueType(0);
16626
16627 // fcanonicalize undef -> qnan
16628 if (N0.isUndef()) {
16630 return DAG.getConstantFP(QNaN, SDLoc(N), VT);
16631 }
16632
16633 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0))
16634 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
16635
16636 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
16637 // (fcanonicalize k)
16638 //
16639 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
16640
16641 // TODO: This could be better with wider vectors that will be split to v2f16,
16642 // and to consider uses since there aren't that many packed operations.
16643 if (N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNumOperands() == 2 &&
16644 isTypeLegal(VT)) {
16645 SDLoc SL(N);
16646 SDValue NewElts[2];
16647 SDValue Lo = N0.getOperand(0);
16648 SDValue Hi = N0.getOperand(1);
16649 EVT EltVT = Lo.getValueType();
16650
16651 // Only apply this optimization if scalar canonicalize is legal for the
16652 // element type. Otherwise, scalarizing may require widening the scalar back
16653 // to a vector, adding overhead (e.g., bf16 has no scalar instructions).
16655 return SDValue();
16656
16658 for (unsigned I = 0; I != 2; ++I) {
16659 SDValue Op = N0.getOperand(I);
16660 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
16661 NewElts[I] =
16662 getCanonicalConstantFP(DAG, SL, EltVT, CFP->getValueAPF());
16663 } else if (Op.isUndef()) {
16664 // Handled below based on what the other operand is.
16665 NewElts[I] = Op;
16666 } else {
16667 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
16668 }
16669 }
16670
16671 // If one half is undef, and one is constant, prefer a splat vector.
16672 // Otherwise, convert the undef to 0.0 since that's cheaper to use and may
16673 // be free with a packed operation.
16674 if (NewElts[0].isUndef()) {
16675 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1])
16676 ? NewElts[1]
16677 : DAG.getConstantFP(0.0f, SL, EltVT);
16678 }
16679
16680 if (NewElts[1].isUndef()) {
16681 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0])
16682 ? NewElts[0]
16683 : DAG.getConstantFP(0.0f, SL, EltVT);
16684 }
16685
16686 return DAG.getBuildVector(VT, SL, NewElts);
16687 }
16688 }
16689
16690 return SDValue();
16691}
16692
16693static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
16694 switch (Opc) {
16695 case ISD::FMAXNUM:
16696 case ISD::FMAXNUM_IEEE:
16697 case ISD::FMAXIMUMNUM:
16698 return AMDGPUISD::FMAX3;
16699 case ISD::FMAXIMUM:
16700 return AMDGPUISD::FMAXIMUM3;
16701 case ISD::SMAX:
16702 return AMDGPUISD::SMAX3;
16703 case ISD::UMAX:
16704 return AMDGPUISD::UMAX3;
16705 case ISD::FMINNUM:
16706 case ISD::FMINNUM_IEEE:
16707 case ISD::FMINIMUMNUM:
16708 return AMDGPUISD::FMIN3;
16709 case ISD::FMINIMUM:
16710 return AMDGPUISD::FMINIMUM3;
16711 case ISD::SMIN:
16712 return AMDGPUISD::SMIN3;
16713 case ISD::UMIN:
16714 return AMDGPUISD::UMIN3;
16715 default:
16716 llvm_unreachable("Not a min/max opcode");
16717 }
16718}
16719
16720SDValue SITargetLowering::performIntMed3ImmCombine(SelectionDAG &DAG,
16721 const SDLoc &SL, SDValue Src,
16722 SDValue MinVal,
16723 SDValue MaxVal,
16724 bool Signed) const {
16725
16726 // med3 comes from
16727 // min(max(x, K0), K1), K0 < K1
16728 // max(min(x, K0), K1), K1 < K0
16729 //
16730 // "MinVal" and "MaxVal" respectively refer to the rhs of the
16731 // min/max op.
16732 ConstantSDNode *MinK = dyn_cast<ConstantSDNode>(MinVal);
16733 ConstantSDNode *MaxK = dyn_cast<ConstantSDNode>(MaxVal);
16734
16735 if (!MinK || !MaxK)
16736 return SDValue();
16737
16738 if (Signed) {
16739 if (MaxK->getAPIntValue().sge(MinK->getAPIntValue()))
16740 return SDValue();
16741 } else {
16742 if (MaxK->getAPIntValue().uge(MinK->getAPIntValue()))
16743 return SDValue();
16744 }
16745
16746 EVT VT = MinK->getValueType(0);
16747 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
16748 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16()))
16749 return DAG.getNode(Med3Opc, SL, VT, Src, MaxVal, MinVal);
16750
16751 // Note: we could also extend to i32 and use i32 med3 if i16 med3 is
16752 // not available, but this is unlikely to be profitable as constants
16753 // will often need to be materialized & extended, especially on
16754 // pre-GFX10 where VOP3 instructions couldn't take literal operands.
16755 return SDValue();
16756}
16757
16760 return C;
16761
16763 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
16764 return C;
16765 }
16766
16767 return nullptr;
16768}
16769
16770SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
16771 const SDLoc &SL, SDValue Op0,
16772 SDValue Op1,
16773 bool IsKnownNoNaNs) const {
16774 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
16775 if (!K1)
16776 return SDValue();
16777
16778 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
16779 if (!K0)
16780 return SDValue();
16781
16782 // Ordered >= (although NaN inputs should have folded away by now).
16783 if (K0->getValueAPF() > K1->getValueAPF())
16784 return SDValue();
16785
16786 // med3 with a nan input acts like
16787 // v_min_f32(v_min_f32(S0.f32, S1.f32), S2.f32)
16788 //
16789 // So the result depends on whether the IEEE mode bit is enabled or not with a
16790 // signaling nan input.
16791 // ieee=1
16792 // s0 snan: yields s2
16793 // s1 snan: yields s2
16794 // s2 snan: qnan
16795
16796 // s0 qnan: min(s1, s2)
16797 // s1 qnan: min(s0, s2)
16798 // s2 qnan: min(s0, s1)
16799
16800 // ieee=0
16801 // s0 snan: min(s1, s2)
16802 // s1 snan: min(s0, s2)
16803 // s2 snan: qnan
16804
16805 // s0 qnan: min(s1, s2)
16806 // s1 qnan: min(s0, s2)
16807 // s2 qnan: min(s0, s1)
16808 const MachineFunction &MF = DAG.getMachineFunction();
16809 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
16810
16811 // TODO: Check IEEE bit enabled. We can form fmed3 with IEEE=0 regardless of
16812 // whether the input is a signaling nan if op0 is fmaximum or fmaximumnum. We
16813 // can only form if op0 is fmaxnum_ieee if IEEE=1.
16814 EVT VT = Op0.getValueType();
16815 if (Info->getMode().DX10Clamp) {
16816 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
16817 // hardware fmed3 behavior converting to a min.
16818 // FIXME: Should this be allowing -0.0?
16819 if (K1->isOne() && K0->isPosZero())
16820 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
16821 }
16822
16823 // med3 for f16 is only available on gfx9+, and not available for v2f16.
16824 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
16825 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
16826 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
16827 // then give the other result, which is different from med3 with a NaN
16828 // input.
16829 SDValue Var = Op0.getOperand(0);
16830 if (!IsKnownNoNaNs && !DAG.isKnownNeverSNaN(Var))
16831 return SDValue();
16832
16833 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
16834
16835 if ((!K0->hasOneUse() || TII->isInlineConstant(K0->getValueAPF())) &&
16836 (!K1->hasOneUse() || TII->isInlineConstant(K1->getValueAPF()))) {
16837 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), Var,
16838 SDValue(K0, 0), SDValue(K1, 0));
16839 }
16840 }
16841
16842 return SDValue();
16843}
16844
16845/// \return true if the subtarget supports minimum3 and maximum3 with the given
16846/// base min/max opcode \p Opc for type \p VT.
16847static bool supportsMin3Max3(const GCNSubtarget &Subtarget, unsigned Opc,
16848 EVT VT) {
16849 switch (Opc) {
16850 case ISD::FMINNUM:
16851 case ISD::FMAXNUM:
16852 case ISD::FMINNUM_IEEE:
16853 case ISD::FMAXNUM_IEEE:
16854 case ISD::FMINIMUMNUM:
16855 case ISD::FMAXIMUMNUM:
16856 return (VT == MVT::f32) || (VT == MVT::f16 && Subtarget.hasMin3Max3_16()) ||
16857 (VT == MVT::v2f16 && Subtarget.hasMin3Max3PKF16());
16858 case ISD::FMINIMUM:
16859 case ISD::FMAXIMUM:
16860 return (VT == MVT::f32 && Subtarget.hasMinimum3Maximum3F32()) ||
16861 (VT == MVT::f16 && Subtarget.hasMinimum3Maximum3F16()) ||
16862 (VT == MVT::v2f16 && Subtarget.hasMinimum3Maximum3PKF16());
16863 case ISD::SMAX:
16864 case ISD::SMIN:
16865 case ISD::UMAX:
16866 case ISD::UMIN:
16867 return (VT == MVT::i32) || (VT == MVT::i16 && Subtarget.hasMin3Max3_16());
16868 default:
16869 return false;
16870 }
16871
16872 llvm_unreachable("not a min/max opcode");
16873}
16874
16875SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
16876 DAGCombinerInfo &DCI) const {
16877 SelectionDAG &DAG = DCI.DAG;
16878
16879 EVT VT = N->getValueType(0);
16880 unsigned Opc = N->getOpcode();
16881 SDValue Op0 = N->getOperand(0);
16882 SDValue Op1 = N->getOperand(1);
16883
16884 // Only do this if the inner op has one use since this will just increases
16885 // register pressure for no benefit.
16886
16887 if (supportsMin3Max3(*Subtarget, Opc, VT)) {
16888 auto IsTreeWithCombinableChildren = [Opc](SDValue Op) {
16889 return (Op.getOperand(0).getOpcode() == Opc &&
16890 Op.getOperand(0).hasOneUse()) ||
16891 (Op.getOperand(1).getOpcode() == Opc &&
16892 Op.getOperand(1).hasOneUse());
16893 };
16894
16895 bool CanTreeCombineApply = Op0.getOpcode() == Opc && Op0.hasOneUse() &&
16896 Op1.getOpcode() == Opc && Op1.hasOneUse();
16897 bool HasCombinableTreeChild =
16898 CanTreeCombineApply && (IsTreeWithCombinableChildren(Op0) ||
16899 IsTreeWithCombinableChildren(Op1));
16900
16901 // Tree reduction: when both operands are the same min/max op, restructure
16902 // to keep a 2-op node on top so higher tree levels can still combine.
16903 //
16904 // max(max(a, b), max(c, d)) -> max(max3(a, b, c), d)
16905 // min(min(a, b), min(c, d)) -> min(min3(a, b, c), d)
16906 //
16907 // Defer when either inner op is a tree node with combinable children.
16908 if (CanTreeCombineApply && !HasCombinableTreeChild) {
16909 SDLoc DL(N);
16910 SDValue Inner =
16912 Op0.getOperand(1), Op1.getOperand(0));
16913 return DAG.getNode(Opc, DL, VT, Inner, Op1.getOperand(1));
16914 }
16915
16916 // max(max(a, b), c) -> max3(a, b, c)
16917 // min(min(a, b), c) -> min3(a, b, c)
16918 // Deferred when Op0 is a tree node with combinable children.
16919 if (Op0.getOpcode() == Opc && Op0.hasOneUse() && !HasCombinableTreeChild) {
16920 SDLoc DL(N);
16921 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), DL, N->getValueType(0),
16922 Op0.getOperand(0), Op0.getOperand(1), Op1);
16923 }
16924
16925 // Try commuted.
16926 // max(a, max(b, c)) -> max3(a, b, c)
16927 // min(a, min(b, c)) -> min3(a, b, c)
16928 // Deferred when Op1 is a tree node with combinable children.
16929 if (Op1.getOpcode() == Opc && Op1.hasOneUse() && !HasCombinableTreeChild) {
16930 SDLoc DL(N);
16931 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), DL, N->getValueType(0),
16932 Op0, Op1.getOperand(0), Op1.getOperand(1));
16933 }
16934 }
16935
16936 // umin(sffbh(x), bitwidth) -> sffbh(x) if x is known to be not 0 or -1.
16937 SDValue FfbhSrc;
16938 uint64_t Clamp = 0;
16939 if (Opc == ISD::UMIN &&
16940 sd_match(Op0,
16942 sd_match(Op1, m_ConstInt(Clamp))) {
16943 unsigned BitWidth = FfbhSrc.getValueType().getScalarSizeInBits();
16944 if (Clamp >= BitWidth) {
16945 KnownBits Known = DAG.computeKnownBits(FfbhSrc);
16946 if (Known.isNonZero() && Known.Zero.getBoolValue())
16947 return Op0;
16948 }
16949 }
16950
16951 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
16952 // max(min(x, K0), K1), K1 < K0 -> med3(x, K1, K0)
16953 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
16954 if (SDValue Med3 = performIntMed3ImmCombine(
16955 DAG, SDLoc(N), Op0->getOperand(0), Op1, Op0->getOperand(1), true))
16956 return Med3;
16957 }
16958 if (Opc == ISD::SMAX && Op0.getOpcode() == ISD::SMIN && Op0.hasOneUse()) {
16959 if (SDValue Med3 = performIntMed3ImmCombine(
16960 DAG, SDLoc(N), Op0->getOperand(0), Op0->getOperand(1), Op1, true))
16961 return Med3;
16962 }
16963
16964 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
16965 if (SDValue Med3 = performIntMed3ImmCombine(
16966 DAG, SDLoc(N), Op0->getOperand(0), Op1, Op0->getOperand(1), false))
16967 return Med3;
16968 }
16969 if (Opc == ISD::UMAX && Op0.getOpcode() == ISD::UMIN && Op0.hasOneUse()) {
16970 if (SDValue Med3 = performIntMed3ImmCombine(
16971 DAG, SDLoc(N), Op0->getOperand(0), Op0->getOperand(1), Op1, false))
16972 return Med3;
16973 }
16974
16975 // if !is_snan(x):
16976 // fminnum(fmaxnum(x, K0), K1), K0 < K1 -> fmed3(x, K0, K1)
16977 // fminnum_ieee(fmaxnum_ieee(x, K0), K1), K0 < K1 -> fmed3(x, K0, K1)
16978 // fminnumnum(fmaxnumnum(x, K0), K1), K0 < K1 -> fmed3(x, K0, K1)
16979 // fmin_legacy(fmax_legacy(x, K0), K1), K0 < K1 -> fmed3(x, K0, K1)
16980 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
16983 (Opc == AMDGPUISD::FMIN_LEGACY &&
16984 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
16985 (VT == MVT::f32 || VT == MVT::f64 ||
16986 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
16987 (VT == MVT::bf16 && Subtarget->hasBF16PackedInsts()) ||
16988 (VT == MVT::v2bf16 && Subtarget->hasBF16PackedInsts()) ||
16989 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
16990 Op0.hasOneUse()) {
16991 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1,
16992 N->getFlags().hasNoNaNs()))
16993 return Res;
16994 }
16995
16996 // Prefer fminnum_ieee over fminimum. For gfx950, minimum/maximum are legal
16997 // for some types, but at a higher cost since it's implemented with a 3
16998 // operand form.
16999 const SDNodeFlags Flags = N->getFlags();
17000 if ((Opc == ISD::FMINIMUM || Opc == ISD::FMAXIMUM) && Flags.hasNoNaNs() &&
17001 !Subtarget->hasIEEEMinimumMaximumInsts() &&
17003 unsigned NewOpc =
17005 return DAG.getNode(NewOpc, SDLoc(N), VT, Op0, Op1, Flags);
17006 }
17007
17008 return SDValue();
17009}
17010
17014 // FIXME: Should this be allowing -0.0?
17015 return (CA->isPosZero() && CB->isOne()) ||
17016 (CA->isOne() && CB->isPosZero());
17017 }
17018 }
17019
17020 return false;
17021}
17022
17023// FIXME: Should only worry about snans for version with chain.
17024SDValue SITargetLowering::performFMed3Combine(SDNode *N,
17025 DAGCombinerInfo &DCI) const {
17026 EVT VT = N->getValueType(0);
17027 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
17028 // NaNs. With a NaN input, the order of the operands may change the result.
17029
17030 SelectionDAG &DAG = DCI.DAG;
17031 SDLoc SL(N);
17032
17033 SDValue Src0 = N->getOperand(0);
17034 SDValue Src1 = N->getOperand(1);
17035 SDValue Src2 = N->getOperand(2);
17036
17037 if (isClampZeroToOne(Src0, Src1)) {
17038 // const_a, const_b, x -> clamp is safe in all cases including signaling
17039 // nans.
17040 // FIXME: Should this be allowing -0.0?
17041 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
17042 }
17043
17044 const MachineFunction &MF = DAG.getMachineFunction();
17045 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
17046
17047 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
17048 // handling no dx10-clamp?
17049 if (Info->getMode().DX10Clamp) {
17050 // If NaNs is clamped to 0, we are free to reorder the inputs.
17051
17052 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
17053 std::swap(Src0, Src1);
17054
17055 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
17056 std::swap(Src1, Src2);
17057
17058 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
17059 std::swap(Src0, Src1);
17060
17061 if (isClampZeroToOne(Src1, Src2))
17062 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
17063 }
17064
17065 return SDValue();
17066}
17067
17068SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
17069 DAGCombinerInfo &DCI) const {
17070 SDValue Src0 = N->getOperand(0);
17071 SDValue Src1 = N->getOperand(1);
17072 if (Src0.isUndef() && Src1.isUndef())
17073 return DCI.DAG.getUNDEF(N->getValueType(0));
17074 return SDValue();
17075}
17076
17077/// V_CVT_SCALEF32_* conversions to a narrow format only read the exponent
17078/// field of their f32 scale operand.
17079SDValue
17080SITargetLowering::performExponentOnlyScaleCombine(SDNode *N,
17081 DAGCombinerInfo &DCI) const {
17082 std::optional<unsigned> ScaleArgIdx =
17083 AMDGPU::getExponentOnlyScaleArgIdx(N->getConstantOperandVal(0));
17084 if (!ScaleArgIdx)
17085 return SDValue();
17086
17087 // Operand 0 is the intrinsic ID.
17088 unsigned OpIdx = *ScaleArgIdx + 1;
17089 SelectionDAG &DAG = DCI.DAG;
17090 SDValue Scale = N->getOperand(OpIdx);
17092
17093 if (SDValue DemandedScale =
17094 SimplifyMultipleUseDemandedBits(Scale, Demanded, DAG)) {
17095 SmallVector<SDValue> Ops(N->ops());
17096 Ops[OpIdx] = DemandedScale;
17097 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getVTList(), Ops);
17098 }
17099
17100 if (SimplifyDemandedBits(Scale, Demanded, DCI))
17101 return SDValue(N, 0);
17102
17103 return SDValue();
17104}
17105
17106// Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
17107// expanded into a set of cmp/select instructions.
17109 unsigned NumElem,
17110 bool IsDivergentIdx,
17111 const GCNSubtarget *Subtarget) {
17112 if (Subtarget->getCLOpts().use_divergent_register_indexing)
17113 return false;
17114
17115 unsigned VecSize = EltSize * NumElem;
17116
17117 // Sub-dword vectors of size 2 dword or less have better implementation.
17118 if (VecSize <= 64 && EltSize < 32)
17119 return false;
17120
17121 // Always expand the rest of sub-dword instructions, otherwise it will be
17122 // lowered via memory.
17123 if (EltSize < 32)
17124 return true;
17125
17126 // Always do this if var-idx is divergent, otherwise it will become a loop.
17127 if (IsDivergentIdx)
17128 return true;
17129
17130 // Large vectors would yield too many compares and v_cndmask_b32 instructions.
17131 unsigned NumInsts = NumElem /* Number of compares */ +
17132 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
17133
17134 // On some architectures (GFX9) movrel is not available and it's better
17135 // to expand.
17136 if (Subtarget->useVGPRIndexMode())
17137 return NumInsts <= 16;
17138
17139 // If movrel is available, use it instead of expanding for vector of 8
17140 // elements.
17141 if (Subtarget->hasMovrel())
17142 return NumInsts <= 15;
17143
17144 return true;
17145}
17146
17148 SDValue Idx = N->getOperand(N->getNumOperands() - 1);
17149 if (isa<ConstantSDNode>(Idx))
17150 return false;
17151
17152 SDValue Vec = N->getOperand(0);
17153 EVT VecVT = Vec.getValueType();
17154 EVT EltVT = VecVT.getVectorElementType();
17155 unsigned EltSize = EltVT.getSizeInBits();
17156 unsigned NumElem = VecVT.getVectorNumElements();
17157
17159 EltSize, NumElem, Idx->isDivergent(), getSubtarget());
17160}
17161
17162SDValue
17163SITargetLowering::performExtractVectorEltCombine(SDNode *N,
17164 DAGCombinerInfo &DCI) const {
17165 SDValue Vec = N->getOperand(0);
17166 SelectionDAG &DAG = DCI.DAG;
17167
17168 EVT VecVT = Vec.getValueType();
17169 EVT VecEltVT = VecVT.getVectorElementType();
17170 EVT ResVT = N->getValueType(0);
17171
17172 unsigned VecSize = VecVT.getSizeInBits();
17173 unsigned VecEltSize = VecEltVT.getSizeInBits();
17174
17175 if ((Vec.getOpcode() == ISD::FNEG || Vec.getOpcode() == ISD::FABS) &&
17177 SDLoc SL(N);
17178 SDValue Idx = N->getOperand(1);
17179 SDValue Elt =
17180 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT, Vec.getOperand(0), Idx);
17181 return DAG.getNode(Vec.getOpcode(), SL, ResVT, Elt);
17182 }
17183
17184 // (extract_vector_element (and {y0, y1}, (build_vector 0x1f, 0x1f)), index)
17185 // -> (and (extract_vector_element {y0, y1}, index), 0x1f)
17186 // There are optimisations to transform 64-bit shifts into 32-bit shifts
17187 // depending on the shift operand. See e.g. performSraCombine().
17188 // This combine ensures that the optimisation is compatible with v2i32
17189 // legalised AND.
17190 if (VecVT == MVT::v2i32 && Vec->getOpcode() == ISD::AND &&
17191 Vec->getOperand(1)->getOpcode() == ISD::BUILD_VECTOR) {
17192
17194 if (!C || C->getZExtValue() != 0x1f)
17195 return SDValue();
17196
17197 SDLoc SL(N);
17198 SDValue AndMask = DAG.getConstant(0x1f, SL, MVT::i32);
17199 SDValue EVE = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32,
17200 Vec->getOperand(0), N->getOperand(1));
17201 SDValue A = DAG.getNode(ISD::AND, SL, MVT::i32, EVE, AndMask);
17202 DAG.ReplaceAllUsesWith(N, A.getNode());
17203 }
17204
17205 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
17206 // =>
17207 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
17208 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
17209 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
17210 if (Vec.hasOneUse() && DCI.isBeforeLegalize() && VecEltVT == ResVT) {
17211 SDLoc SL(N);
17212 SDValue Idx = N->getOperand(1);
17213 unsigned Opc = Vec.getOpcode();
17214
17215 switch (Opc) {
17216 default:
17217 break;
17218 // TODO: Support other binary operations.
17219 case ISD::FADD:
17220 case ISD::FSUB:
17221 case ISD::FMUL:
17222 case ISD::ADD:
17223 case ISD::UMIN:
17224 case ISD::UMAX:
17225 case ISD::SMIN:
17226 case ISD::SMAX:
17227 case ISD::FMAXNUM:
17228 case ISD::FMINNUM:
17229 case ISD::FMAXNUM_IEEE:
17230 case ISD::FMINNUM_IEEE:
17231 case ISD::FMAXIMUM:
17232 case ISD::FMINIMUM: {
17233 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT,
17234 Vec.getOperand(0), Idx);
17235 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT,
17236 Vec.getOperand(1), Idx);
17237
17238 DCI.AddToWorklist(Elt0.getNode());
17239 DCI.AddToWorklist(Elt1.getNode());
17240 return DAG.getNode(Opc, SL, ResVT, Elt0, Elt1, Vec->getFlags());
17241 }
17242 }
17243 }
17244
17245 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
17247 SDLoc SL(N);
17248 SDValue Idx = N->getOperand(1);
17249 SDValue V;
17250 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
17251 SDValue IC = DAG.getVectorIdxConstant(I, SL);
17252 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT, Vec, IC);
17253 if (I == 0)
17254 V = Elt;
17255 else
17256 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
17257 }
17258 return V;
17259 }
17260
17261 // EXTRACT_VECTOR_ELT (v2i32 bitcast (i64/f64:k), Idx)
17262 // =>
17263 // i32:Lo(k) if Idx == 0, or
17264 // i32:Hi(k) if Idx == 1
17265 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
17266 if (Vec.getOpcode() == ISD::BITCAST && VecVT == MVT::v2i32 && Idx) {
17267 SDLoc SL(N);
17268 SDValue PeekThrough = Vec.getOperand(0);
17269 auto *KImm = dyn_cast<ConstantSDNode>(PeekThrough);
17270 if (KImm && KImm->getValueType(0).getSizeInBits() == 64) {
17271 uint64_t KImmValue = KImm->getZExtValue();
17272 return DAG.getConstant(
17273 (KImmValue >> (32 * Idx->getZExtValue())) & 0xffffffff, SL, MVT::i32);
17274 }
17275 auto *KFPImm = dyn_cast<ConstantFPSDNode>(PeekThrough);
17276 if (KFPImm && KFPImm->getValueType(0).getSizeInBits() == 64) {
17277 uint64_t KFPImmValue =
17278 KFPImm->getValueAPF().bitcastToAPInt().getZExtValue();
17279 return DAG.getConstant((KFPImmValue >> (32 * Idx->getZExtValue())) &
17280 0xffffffff,
17281 SL, MVT::i32);
17282 }
17283 }
17284
17285 if (!DCI.isBeforeLegalize())
17286 return SDValue();
17287
17288 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
17289 // elements. This exposes more load reduction opportunities by replacing
17290 // multiple small extract_vector_elements with a single 32-bit extract.
17291 if (isa<MemSDNode>(Vec) && VecEltSize <= 16 && VecEltVT.isByteSized() &&
17292 VecSize > 32 && VecSize % 32 == 0 && Idx) {
17293 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
17294
17295 unsigned BitIndex = Idx->getZExtValue() * VecEltSize;
17296 unsigned EltIdx = BitIndex / 32;
17297 unsigned LeftoverBitIdx = BitIndex % 32;
17298 SDLoc SL(N);
17299
17300 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
17301 DCI.AddToWorklist(Cast.getNode());
17302
17303 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
17304 DAG.getConstant(EltIdx, SL, MVT::i32));
17305 DCI.AddToWorklist(Elt.getNode());
17306 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
17307 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
17308 DCI.AddToWorklist(Srl.getNode());
17309
17310 EVT VecEltAsIntVT = VecEltVT.changeTypeToInteger();
17311 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VecEltAsIntVT, Srl);
17312 DCI.AddToWorklist(Trunc.getNode());
17313
17314 if (VecEltVT == ResVT) {
17315 return DAG.getNode(ISD::BITCAST, SL, VecEltVT, Trunc);
17316 }
17317
17318 assert(ResVT.isScalarInteger());
17319 return DAG.getAnyExtOrTrunc(Trunc, SL, ResVT);
17320 }
17321
17322 return SDValue();
17323}
17324
17325SDValue
17326SITargetLowering::performInsertVectorEltCombine(SDNode *N,
17327 DAGCombinerInfo &DCI) const {
17328 SDValue Vec = N->getOperand(0);
17329 SDValue Idx = N->getOperand(2);
17330 EVT VecVT = Vec.getValueType();
17331 EVT EltVT = VecVT.getVectorElementType();
17332
17333 // INSERT_VECTOR_ELT (<n x e>, var-idx)
17334 // => BUILD_VECTOR n x select (e, const-idx)
17335 // 16-bit elements are left to lowerINSERT_VECTOR_ELT, which is cheaper.
17337 (EltVT.getSizeInBits() == 16 &&
17339 return SDValue();
17340
17341 SelectionDAG &DAG = DCI.DAG;
17342 SDLoc SL(N);
17343 SDValue Ins = N->getOperand(1);
17344 EVT IdxVT = Idx.getValueType();
17345
17347 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
17348 SDValue IC = DAG.getConstant(I, SL, IdxVT);
17349 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
17350 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
17351 Ops.push_back(V);
17352 }
17353
17354 return DAG.getBuildVector(VecVT, SL, Ops);
17355}
17356
17357/// Return the source of an fp_extend from f16 to f32, or a converted FP
17358/// constant.
17360 if (Src.getOpcode() == ISD::FP_EXTEND &&
17361 Src.getOperand(0).getValueType() == MVT::f16) {
17362 return Src.getOperand(0);
17363 }
17364
17365 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Src)) {
17366 APFloat Val = CFP->getValueAPF();
17367 bool LosesInfo = true;
17369 if (!LosesInfo)
17370 return DAG.getConstantFP(Val, SDLoc(Src), MVT::f16);
17371 }
17372
17373 return SDValue();
17374}
17375
17376SDValue SITargetLowering::performFPRoundCombine(SDNode *N,
17377 DAGCombinerInfo &DCI) const {
17378 assert(Subtarget->has16BitInsts() && !Subtarget->hasMed3_16() &&
17379 "combine only useful on gfx8");
17380
17381 SDValue TruncSrc = N->getOperand(0);
17382 EVT VT = N->getValueType(0);
17383 if (VT != MVT::f16)
17384 return SDValue();
17385
17386 if (TruncSrc.getOpcode() != AMDGPUISD::FMED3 ||
17387 TruncSrc.getValueType() != MVT::f32 || !TruncSrc.hasOneUse())
17388 return SDValue();
17389
17390 SelectionDAG &DAG = DCI.DAG;
17391 SDLoc SL(N);
17392
17393 // Optimize f16 fmed3 pattern performed on f32. On gfx8 there is no f16 fmed3,
17394 // and expanding it with min/max saves 1 instruction vs. casting to f32 and
17395 // casting back.
17396
17397 // fptrunc (f32 (fmed3 (fpext f16:a, fpext f16:b, fpext f16:c))) =>
17398 // fmin(fmax(a, b), fmax(fmin(a, b), c))
17399 SDValue A = strictFPExtFromF16(DAG, TruncSrc.getOperand(0));
17400 if (!A)
17401 return SDValue();
17402
17403 SDValue B = strictFPExtFromF16(DAG, TruncSrc.getOperand(1));
17404 if (!B)
17405 return SDValue();
17406
17407 SDValue C = strictFPExtFromF16(DAG, TruncSrc.getOperand(2));
17408 if (!C)
17409 return SDValue();
17410
17411 // This changes signaling nan behavior. If an input is a signaling nan, it
17412 // would have been quieted by the fpext originally. We don't care because
17413 // these are unconstrained ops. If we needed to insert quieting canonicalizes
17414 // we would be worse off than just doing the promotion.
17415 SDValue A1 = DAG.getNode(ISD::FMINNUM_IEEE, SL, VT, A, B);
17416 SDValue B1 = DAG.getNode(ISD::FMAXNUM_IEEE, SL, VT, A, B);
17417 SDValue C1 = DAG.getNode(ISD::FMAXNUM_IEEE, SL, VT, A1, C);
17418 return DAG.getNode(ISD::FMINNUM_IEEE, SL, VT, B1, C1);
17419}
17420
17421unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
17422 const SDNode *N0,
17423 const SDNode *N1) const {
17424 EVT VT = N0->getValueType(0);
17425
17426 // Only do this if we are not trying to support denormals. v_mad_f32 does not
17427 // support denormals ever.
17428 if (((VT == MVT::f32 &&
17430 (VT == MVT::f16 && Subtarget->hasMadF16() &&
17433 return ISD::FMAD;
17434
17435 if (N0->getFlags().hasAllowContract() && N1->getFlags().hasAllowContract() &&
17437 return ISD::FMA;
17438 }
17439
17440 return 0;
17441}
17442
17443// For a reassociatable opcode perform:
17444// op x, (op y, z) -> op (op x, z), y, if x and z are uniform
17445SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
17446 SelectionDAG &DAG) const {
17447 EVT VT = N->getValueType(0);
17448 if (VT != MVT::i32 && VT != MVT::i64)
17449 return SDValue();
17450
17451 if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
17452 return SDValue();
17453
17454 unsigned Opc = N->getOpcode();
17455 SDValue Op0 = N->getOperand(0);
17456 SDValue Op1 = N->getOperand(1);
17457
17458 if (!(Op0->isDivergent() ^ Op1->isDivergent()))
17459 return SDValue();
17460
17461 if (Op0->isDivergent())
17462 std::swap(Op0, Op1);
17463
17464 if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
17465 return SDValue();
17466
17467 SDValue Op2 = Op1.getOperand(1);
17468 Op1 = Op1.getOperand(0);
17469 if (!(Op1->isDivergent() ^ Op2->isDivergent()))
17470 return SDValue();
17471
17472 if (Op1->isDivergent())
17473 std::swap(Op1, Op2);
17474
17475 SDLoc SL(N);
17476 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
17477 return DAG.getNode(Opc, SL, VT, Add1, Op2);
17478}
17479
17480static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, EVT VT,
17481 SDValue N0, SDValue N1, SDValue N2, bool Signed) {
17483 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
17484 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
17485 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
17486}
17487
17488// Fold
17489// y = lshr i64 x, 32
17490// res = add (mul i64 y, Const), x where "Const" is a 64-bit constant
17491// with Const.hi == -1
17492// To
17493// res = mad_u64_u32 y.lo ,Const.lo, x.lo
17495 SDValue MulLHS, SDValue MulRHS,
17496 SDValue AddRHS) {
17497 if (MulRHS.getOpcode() == ISD::SRL)
17498 std::swap(MulLHS, MulRHS);
17499
17500 if (MulLHS.getValueType() != MVT::i64 || MulLHS.getOpcode() != ISD::SRL)
17501 return SDValue();
17502
17503 ConstantSDNode *ShiftVal = dyn_cast<ConstantSDNode>(MulLHS.getOperand(1));
17504 if (!ShiftVal || ShiftVal->getAsZExtVal() != 32 ||
17505 MulLHS.getOperand(0) != AddRHS)
17506 return SDValue();
17507
17509 if (!Const || Hi_32(Const->getZExtValue()) != uint32_t(-1))
17510 return SDValue();
17511
17512 SDValue ConstMul =
17513 DAG.getConstant(Lo_32(Const->getZExtValue()), SL, MVT::i32);
17514 return getMad64_32(DAG, SL, MVT::i64,
17515 DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS), ConstMul,
17516 DAG.getZeroExtendInReg(AddRHS, SL, MVT::i32), false);
17517}
17518
17519// Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high
17520// multiplies, if any.
17521//
17522// Full 64-bit multiplies that feed into an addition are lowered here instead
17523// of using the generic expansion. The generic expansion ends up with
17524// a tree of ADD nodes that prevents us from using the "add" part of the
17525// MAD instruction. The expansion produced here results in a chain of ADDs
17526// instead of a tree.
17527SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N,
17528 DAGCombinerInfo &DCI) const {
17529 assert(N->isAnyAdd());
17530
17531 SelectionDAG &DAG = DCI.DAG;
17532 EVT VT = N->getValueType(0);
17533 SDLoc SL(N);
17534 SDValue LHS = N->getOperand(0);
17535 SDValue RHS = N->getOperand(1);
17536
17537 if (VT.isVector())
17538 return SDValue();
17539
17540 // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall
17541 // result in scalar registers for uniform values.
17542 if (!N->isDivergent() && Subtarget->hasSMulHi())
17543 return SDValue();
17544
17545 unsigned NumBits = VT.getScalarSizeInBits();
17546 if (NumBits <= 32 || NumBits > 64)
17547 return SDValue();
17548
17549 if (LHS.getOpcode() != ISD::MUL) {
17550 assert(RHS.getOpcode() == ISD::MUL);
17551 std::swap(LHS, RHS);
17552 }
17553
17554 // Avoid the fold if it would unduly increase the number of multiplies due to
17555 // multiple uses, except on hardware with full-rate multiply-add (which is
17556 // part of full-rate 64-bit ops).
17557 if (!Subtarget->hasFullRate64Ops()) {
17558 unsigned NumUsers = 0;
17559 for (SDNode *User : LHS->users()) {
17560 // There is a use that does not feed into addition, so the multiply can't
17561 // be removed. We prefer MUL + ADD + ADDC over MAD + MUL.
17562 if (!User->isAnyAdd())
17563 return SDValue();
17564
17565 // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer
17566 // MUL + 3xADD + 3xADDC over 3xMAD.
17567 ++NumUsers;
17568 if (NumUsers >= 3)
17569 return SDValue();
17570 }
17571 }
17572
17573 SDValue MulLHS = LHS.getOperand(0);
17574 SDValue MulRHS = LHS.getOperand(1);
17575 SDValue AddRHS = RHS;
17576
17577 if (SDValue FoldedMAD = tryFoldMADwithSRL(DAG, SL, MulLHS, MulRHS, AddRHS))
17578 return FoldedMAD;
17579
17580 // Always check whether operands are small unsigned values, since that
17581 // knowledge is useful in more cases. Check for small signed values only if
17582 // doing so can unlock a shorter code sequence.
17583 bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32;
17584 bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32;
17585
17586 bool MulSignedLo = false;
17587 if (!MulLHSUnsigned32 || !MulRHSUnsigned32) {
17588 MulSignedLo =
17589 numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32;
17590 }
17591
17592 // The operands and final result all have the same number of bits. If
17593 // operands need to be extended, they can be extended with garbage. The
17594 // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is
17595 // truncated away in the end.
17596 if (VT != MVT::i64) {
17597 MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS);
17598 MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS);
17599 AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS);
17600 }
17601
17602 // The basic code generated is conceptually straightforward. Pseudo code:
17603 //
17604 // accum = mad_64_32 lhs.lo, rhs.lo, accum
17605 // accum.hi = add (mul lhs.hi, rhs.lo), accum.hi
17606 // accum.hi = add (mul lhs.lo, rhs.hi), accum.hi
17607 //
17608 // The second and third lines are optional, depending on whether the factors
17609 // are {sign,zero}-extended or not.
17610 //
17611 // The actual DAG is noisier than the pseudo code, but only due to
17612 // instructions that disassemble values into low and high parts, and
17613 // assemble the final result.
17614 SDValue One = DAG.getConstant(1, SL, MVT::i32);
17615
17616 auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS);
17617 auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS);
17618 SDValue Accum =
17619 getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo);
17620
17621 if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) {
17622 auto [AccumLo, AccumHi] = DAG.SplitScalar(Accum, SL, MVT::i32, MVT::i32);
17623
17624 if (!MulLHSUnsigned32) {
17625 auto MulLHSHi =
17626 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One);
17627 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo);
17628 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
17629 }
17630
17631 if (!MulRHSUnsigned32) {
17632 auto MulRHSHi =
17633 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One);
17634 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi);
17635 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
17636 }
17637
17638 Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi});
17639 Accum = DAG.getBitcast(MVT::i64, Accum);
17640 }
17641
17642 if (VT != MVT::i64)
17643 Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum);
17644 return Accum;
17645}
17646
17647SDValue
17648SITargetLowering::foldAddSub64WithZeroLowBitsTo32(SDNode *N,
17649 DAGCombinerInfo &DCI) const {
17650 SDValue RHS = N->getOperand(1);
17651 auto *CRHS = dyn_cast<ConstantSDNode>(RHS);
17652 if (!CRHS)
17653 return SDValue();
17654
17655 // TODO: Worth using computeKnownBits? Maybe expensive since it's so
17656 // common.
17657 uint64_t Val = CRHS->getZExtValue();
17658 if (countr_zero(Val) >= 32) {
17659 SelectionDAG &DAG = DCI.DAG;
17660 SDLoc SL(N);
17661 SDValue LHS = N->getOperand(0);
17662
17663 // Avoid carry machinery if we know the low half of the add does not
17664 // contribute to the final result.
17665 //
17666 // add i64:x, K if computeTrailingZeros(K) >= 32
17667 // => build_pair (add x.hi, K.hi), x.lo
17668
17669 // Breaking the 64-bit add here with this strange constant is unlikely
17670 // to interfere with addressing mode patterns.
17671
17672 SDValue Hi = getHiHalf64(LHS, DAG);
17673 SDValue ConstHi32 = DAG.getConstant(Hi_32(Val), SL, MVT::i32);
17674 unsigned Opcode = N->getOpcode();
17675 if (Opcode == ISD::PTRADD)
17676 Opcode = ISD::ADD;
17677 SDValue AddHi =
17678 DAG.getNode(Opcode, SL, MVT::i32, Hi, ConstHi32, N->getFlags());
17679
17680 SDValue Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
17681 return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i64, Lo, AddHi);
17682 }
17683
17684 return SDValue();
17685}
17686
17687// Collect the ultimate src of each of the mul node's operands, and confirm
17688// each operand is 8 bytes.
17689static std::optional<ByteProvider<SDValue>>
17690handleMulOperand(const SDValue &MulOperand) {
17691 auto Byte0 = calculateByteProvider(MulOperand, 0, 0);
17692 if (!Byte0 || Byte0->isConstantZero()) {
17693 return std::nullopt;
17694 }
17695 auto Byte1 = calculateByteProvider(MulOperand, 1, 0);
17696 if (Byte1 && !Byte1->isConstantZero()) {
17697 return std::nullopt;
17698 }
17699 return Byte0;
17700}
17701
17702static unsigned addPermMasks(unsigned First, unsigned Second) {
17703 unsigned FirstCs = First & 0x0c0c0c0c;
17704 unsigned SecondCs = Second & 0x0c0c0c0c;
17705 unsigned FirstNoCs = First & ~0x0c0c0c0c;
17706 unsigned SecondNoCs = Second & ~0x0c0c0c0c;
17707
17708 assert((FirstCs & 0xFF) | (SecondCs & 0xFF));
17709 assert((FirstCs & 0xFF00) | (SecondCs & 0xFF00));
17710 assert((FirstCs & 0xFF0000) | (SecondCs & 0xFF0000));
17711 assert((FirstCs & 0xFF000000) | (SecondCs & 0xFF000000));
17712
17713 return (FirstNoCs | SecondNoCs) | (FirstCs & SecondCs);
17714}
17715
17716struct DotSrc {
17718 int64_t PermMask;
17720};
17721
17725 SmallVectorImpl<DotSrc> &Src1s, int Step) {
17726
17727 assert(Src0.Src.has_value() && Src1.Src.has_value());
17728 // Src0s and Src1s are empty, just place arbitrarily.
17729 if (Step == 0) {
17730 Src0s.push_back({*Src0.Src, ((Src0.SrcOffset % 4) << 24) + 0x0c0c0c,
17731 Src0.SrcOffset / 4});
17732 Src1s.push_back({*Src1.Src, ((Src1.SrcOffset % 4) << 24) + 0x0c0c0c,
17733 Src1.SrcOffset / 4});
17734 return;
17735 }
17736
17737 for (int BPI = 0; BPI < 2; BPI++) {
17738 std::pair<ByteProvider<SDValue>, ByteProvider<SDValue>> BPP = {Src0, Src1};
17739 if (BPI == 1) {
17740 BPP = {Src1, Src0};
17741 }
17742 unsigned ZeroMask = 0x0c0c0c0c;
17743 unsigned FMask = 0xFF << (8 * (3 - Step));
17744
17745 unsigned FirstMask =
17746 (BPP.first.SrcOffset % 4) << (8 * (3 - Step)) | (ZeroMask & ~FMask);
17747 unsigned SecondMask =
17748 (BPP.second.SrcOffset % 4) << (8 * (3 - Step)) | (ZeroMask & ~FMask);
17749 // Attempt to find Src vector which contains our SDValue, if so, add our
17750 // perm mask to the existing one. If we are unable to find a match for the
17751 // first SDValue, attempt to find match for the second.
17752 int FirstGroup = -1;
17753 for (int I = 0; I < 2; I++) {
17754 SmallVectorImpl<DotSrc> &Srcs = I == 0 ? Src0s : Src1s;
17755 auto MatchesFirst = [&BPP](DotSrc &IterElt) {
17756 return IterElt.SrcOp == *BPP.first.Src &&
17757 (IterElt.DWordOffset == (BPP.first.SrcOffset / 4));
17758 };
17759
17760 auto *Match = llvm::find_if(Srcs, MatchesFirst);
17761 if (Match != Srcs.end()) {
17762 Match->PermMask = addPermMasks(FirstMask, Match->PermMask);
17763 FirstGroup = I;
17764 break;
17765 }
17766 }
17767 if (FirstGroup != -1) {
17768 SmallVectorImpl<DotSrc> &Srcs = FirstGroup == 1 ? Src0s : Src1s;
17769 auto MatchesSecond = [&BPP](DotSrc &IterElt) {
17770 return IterElt.SrcOp == *BPP.second.Src &&
17771 (IterElt.DWordOffset == (BPP.second.SrcOffset / 4));
17772 };
17773 auto *Match = llvm::find_if(Srcs, MatchesSecond);
17774 if (Match != Srcs.end()) {
17775 Match->PermMask = addPermMasks(SecondMask, Match->PermMask);
17776 } else
17777 Srcs.push_back({*BPP.second.Src, SecondMask, BPP.second.SrcOffset / 4});
17778 return;
17779 }
17780 }
17781
17782 // If we have made it here, then we could not find a match in Src0s or Src1s
17783 // for either Src0 or Src1, so just place them arbitrarily.
17784
17785 unsigned ZeroMask = 0x0c0c0c0c;
17786 unsigned FMask = 0xFF << (8 * (3 - Step));
17787
17788 Src0s.push_back(
17789 {*Src0.Src,
17790 ((Src0.SrcOffset % 4) << (8 * (3 - Step)) | (ZeroMask & ~FMask)),
17791 Src0.SrcOffset / 4});
17792 Src1s.push_back(
17793 {*Src1.Src,
17794 ((Src1.SrcOffset % 4) << (8 * (3 - Step)) | (ZeroMask & ~FMask)),
17795 Src1.SrcOffset / 4});
17796}
17797
17799 SmallVectorImpl<DotSrc> &Srcs, bool IsSigned,
17800 bool IsAny) {
17801
17802 // If we just have one source, just permute it accordingly.
17803 if (Srcs.size() == 1) {
17804 auto *Elt = Srcs.begin();
17805 auto EltOp = getDWordFromOffset(DAG, SL, Elt->SrcOp, Elt->DWordOffset);
17806
17807 // v_perm will produce the original value
17808 if (Elt->PermMask == 0x3020100)
17809 return EltOp;
17810
17811 return DAG.getNode(AMDGPUISD::PERM, SL, MVT::i32, EltOp, EltOp,
17812 DAG.getConstant(Elt->PermMask, SL, MVT::i32));
17813 }
17814
17815 auto *FirstElt = Srcs.begin();
17816 auto *SecondElt = std::next(FirstElt);
17817
17819
17820 // If we have multiple sources in the chain, combine them via perms (using
17821 // calculated perm mask) and Ors.
17822 while (true) {
17823 auto FirstMask = FirstElt->PermMask;
17824 auto SecondMask = SecondElt->PermMask;
17825
17826 unsigned FirstCs = FirstMask & 0x0c0c0c0c;
17827 unsigned FirstPlusFour = FirstMask | 0x04040404;
17828 // 0x0c + 0x04 = 0x10, so anding with 0x0F will produced 0x00 for any
17829 // original 0x0C.
17830 FirstMask = (FirstPlusFour & 0x0F0F0F0F) | FirstCs;
17831
17832 auto PermMask = addPermMasks(FirstMask, SecondMask);
17833 auto FirstVal =
17834 getDWordFromOffset(DAG, SL, FirstElt->SrcOp, FirstElt->DWordOffset);
17835 auto SecondVal =
17836 getDWordFromOffset(DAG, SL, SecondElt->SrcOp, SecondElt->DWordOffset);
17837
17838 Perms.push_back(DAG.getNode(AMDGPUISD::PERM, SL, MVT::i32, FirstVal,
17839 SecondVal,
17840 DAG.getConstant(PermMask, SL, MVT::i32)));
17841
17842 FirstElt = std::next(SecondElt);
17843 if (FirstElt == Srcs.end())
17844 break;
17845
17846 SecondElt = std::next(FirstElt);
17847 // If we only have a FirstElt, then just combine that into the cumulative
17848 // source node.
17849 if (SecondElt == Srcs.end()) {
17850 auto EltOp =
17851 getDWordFromOffset(DAG, SL, FirstElt->SrcOp, FirstElt->DWordOffset);
17852
17853 Perms.push_back(
17854 DAG.getNode(AMDGPUISD::PERM, SL, MVT::i32, EltOp, EltOp,
17855 DAG.getConstant(FirstElt->PermMask, SL, MVT::i32)));
17856 break;
17857 }
17858 }
17859
17860 assert(Perms.size() == 1 || Perms.size() == 2);
17861 return Perms.size() == 2
17862 ? DAG.getNode(ISD::OR, SL, MVT::i32, Perms[0], Perms[1])
17863 : Perms[0];
17864}
17865
17866static void fixMasks(SmallVectorImpl<DotSrc> &Srcs, unsigned ChainLength) {
17867 for (auto &[EntryVal, EntryMask, EntryOffset] : Srcs) {
17868 EntryMask = EntryMask >> ((4 - ChainLength) * 8);
17869 auto ZeroMask = ChainLength == 2 ? 0x0c0c0000 : 0x0c000000;
17870 EntryMask += ZeroMask;
17871 }
17872}
17873
17874static bool isMul(const SDValue Op) {
17875 auto Opcode = Op.getOpcode();
17876
17877 return (Opcode == ISD::MUL || Opcode == AMDGPUISD::MUL_U24 ||
17878 Opcode == AMDGPUISD::MUL_I24);
17879}
17880
17881static std::optional<bool>
17883 ByteProvider<SDValue> &Src1, const SDValue &S0Op,
17884 const SDValue &S1Op, const SelectionDAG &DAG) {
17885 // If we both ops are i8s (pre legalize-dag), then the signedness semantics
17886 // of the dot4 is irrelevant.
17887 if (S0Op.getValueSizeInBits() == 8 && S1Op.getValueSizeInBits() == 8)
17888 return false;
17889
17890 auto Known0 = DAG.computeKnownBits(S0Op, 0);
17891 bool S0IsUnsigned = Known0.countMinLeadingZeros() > 0;
17892 bool S0IsSigned = Known0.countMinLeadingOnes() > 0;
17893 auto Known1 = DAG.computeKnownBits(S1Op, 0);
17894 bool S1IsUnsigned = Known1.countMinLeadingZeros() > 0;
17895 bool S1IsSigned = Known1.countMinLeadingOnes() > 0;
17896
17897 assert(!(S0IsUnsigned && S0IsSigned));
17898 assert(!(S1IsUnsigned && S1IsSigned));
17899
17900 // There are 9 possible permutations of
17901 // {S0IsUnsigned, S0IsSigned, S1IsUnsigned, S1IsSigned}
17902
17903 // In two permutations, the sign bits are known to be the same for both Ops,
17904 // so simply return Signed / Unsigned corresponding to the MSB
17905
17906 if ((S0IsUnsigned && S1IsUnsigned) || (S0IsSigned && S1IsSigned))
17907 return S0IsSigned;
17908
17909 // In another two permutations, the sign bits are known to be opposite. In
17910 // this case return std::nullopt to indicate a bad match.
17911
17912 if ((S0IsUnsigned && S1IsSigned) || (S0IsSigned && S1IsUnsigned))
17913 return std::nullopt;
17914
17915 // In the remaining five permutations, we don't know the value of the sign
17916 // bit for at least one Op. Since we have a valid ByteProvider, we know that
17917 // the upper bits must be extension bits. Thus, the only ways for the sign
17918 // bit to be unknown is if it was sign extended from unknown value, or if it
17919 // was any extended. In either case, it is correct to use the signed
17920 // version of the signedness semantics of dot4
17921
17922 // In two of such permutations, we known the sign bit is set for
17923 // one op, and the other is unknown. It is okay to used signed version of
17924 // dot4.
17925 if ((S0IsSigned && !(S1IsSigned || S1IsUnsigned)) ||
17926 ((S1IsSigned && !(S0IsSigned || S0IsUnsigned))))
17927 return true;
17928
17929 // In one such permutation, we don't know either of the sign bits. It is okay
17930 // to used the signed version of dot4.
17931 if ((!(S1IsSigned || S1IsUnsigned) && !(S0IsSigned || S0IsUnsigned)))
17932 return true;
17933
17934 // In two of such permutations, we known the sign bit is unset for
17935 // one op, and the other is unknown. Return std::nullopt to indicate a
17936 // bad match.
17937 if ((S0IsUnsigned && !(S1IsSigned || S1IsUnsigned)) ||
17938 ((S1IsUnsigned && !(S0IsSigned || S0IsUnsigned))))
17939 return std::nullopt;
17940
17941 llvm_unreachable("Fully covered condition");
17942}
17943
17944SDValue SITargetLowering::performAddCombine(SDNode *N,
17945 DAGCombinerInfo &DCI) const {
17946 SelectionDAG &DAG = DCI.DAG;
17947 EVT VT = N->getValueType(0);
17948 SDLoc SL(N);
17949 SDValue LHS = N->getOperand(0);
17950 SDValue RHS = N->getOperand(1);
17951
17952 if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) {
17953 if (Subtarget->hasMad64_32()) {
17954 if (SDValue Folded = tryFoldToMad64_32(N, DCI))
17955 return Folded;
17956 }
17957 }
17958
17959 if (SDValue V = reassociateScalarOps(N, DAG)) {
17960 return V;
17961 }
17962
17963 if (VT == MVT::i64) {
17964 if (SDValue Folded = foldAddSub64WithZeroLowBitsTo32(N, DCI))
17965 return Folded;
17966 }
17967
17968 // dot4 produces a 32-bit result, so a wider VT can't be folded.
17969 if (!VT.isVector() && VT.getSizeInBits() <= 32 &&
17970 (isMul(LHS) || isMul(RHS)) && Subtarget->hasDot7Insts() &&
17971 (Subtarget->hasDot1Insts() || Subtarget->hasDot8Insts())) {
17972 SDValue TempNode(N, 0);
17973 std::optional<bool> IsSigned;
17977
17978 // Match the v_dot4 tree, while collecting src nodes.
17979 int ChainLength = 0;
17980 for (int I = 0; I < 4; I++) {
17981 auto MulIdx = isMul(LHS) ? 0 : isMul(RHS) ? 1 : -1;
17982 if (MulIdx == -1)
17983 break;
17984 auto Src0 = handleMulOperand(TempNode->getOperand(MulIdx)->getOperand(0));
17985 if (!Src0)
17986 break;
17987 auto Src1 = handleMulOperand(TempNode->getOperand(MulIdx)->getOperand(1));
17988 if (!Src1)
17989 break;
17990
17991 auto IterIsSigned = checkDot4MulSignedness(
17992 TempNode->getOperand(MulIdx), *Src0, *Src1,
17993 TempNode->getOperand(MulIdx)->getOperand(0),
17994 TempNode->getOperand(MulIdx)->getOperand(1), DAG);
17995 if (!IterIsSigned)
17996 break;
17997 if (!IsSigned)
17998 IsSigned = *IterIsSigned;
17999 if (*IterIsSigned != *IsSigned)
18000 break;
18001 placeSources(*Src0, *Src1, Src0s, Src1s, I);
18002 auto AddIdx = 1 - MulIdx;
18003 // Allow the special case where add (add (mul24, 0), mul24) became ->
18004 // add (mul24, mul24).
18005 if (I == 2 && isMul(TempNode->getOperand(AddIdx))) {
18006 Src2s.push_back(TempNode->getOperand(AddIdx));
18007 auto Src0 =
18008 handleMulOperand(TempNode->getOperand(AddIdx)->getOperand(0));
18009 if (!Src0)
18010 break;
18011 auto Src1 =
18012 handleMulOperand(TempNode->getOperand(AddIdx)->getOperand(1));
18013 if (!Src1)
18014 break;
18015 auto IterIsSigned = checkDot4MulSignedness(
18016 TempNode->getOperand(AddIdx), *Src0, *Src1,
18017 TempNode->getOperand(AddIdx)->getOperand(0),
18018 TempNode->getOperand(AddIdx)->getOperand(1), DAG);
18019 if (!IterIsSigned)
18020 break;
18021 assert(IsSigned);
18022 if (*IterIsSigned != *IsSigned)
18023 break;
18024 placeSources(*Src0, *Src1, Src0s, Src1s, I + 1);
18025 Src2s.push_back(DAG.getConstant(0, SL, MVT::i32));
18026 ChainLength = I + 2;
18027 break;
18028 }
18029
18030 TempNode = TempNode->getOperand(AddIdx);
18031 Src2s.push_back(TempNode);
18032 ChainLength = I + 1;
18033 // The loop body treats TempNode's operands as addends.
18034 if (TempNode.getOpcode() != ISD::ADD)
18035 break;
18036 LHS = TempNode->getOperand(0);
18037 RHS = TempNode->getOperand(1);
18038 }
18039
18040 if (ChainLength < 2)
18041 return SDValue();
18042
18043 // Masks were constructed with assumption that we would find a chain of
18044 // length 4. If not, then we need to 0 out the MSB bits (via perm mask of
18045 // 0x0c) so they do not affect dot calculation.
18046 if (ChainLength < 4) {
18047 fixMasks(Src0s, ChainLength);
18048 fixMasks(Src1s, ChainLength);
18049 }
18050
18051 SDValue Src0, Src1;
18052
18053 // If we are just using a single source for both, and have permuted the
18054 // bytes consistently, we can just use the sources without permuting
18055 // (commutation).
18056 bool UseOriginalSrc = false;
18057 if (ChainLength == 4 && Src0s.size() == 1 && Src1s.size() == 1 &&
18058 Src0s.begin()->PermMask == Src1s.begin()->PermMask &&
18059 Src0s.begin()->SrcOp.getValueSizeInBits() >= 32 &&
18060 Src1s.begin()->SrcOp.getValueSizeInBits() >= 32) {
18061 SmallVector<unsigned, 4> SrcBytes;
18062 auto Src0Mask = Src0s.begin()->PermMask;
18063 SrcBytes.push_back((Src0Mask >> 24) & 0xFF);
18064 bool UniqueEntries = true;
18065 for (auto I = 1; I < 4; I++) {
18066 auto NextByte = (Src0Mask >> ((3 - I) * 8)) & 0xFF;
18067
18068 if (is_contained(SrcBytes, NextByte)) {
18069 UniqueEntries = false;
18070 break;
18071 }
18072 SrcBytes.push_back(NextByte);
18073 }
18074
18075 if (UniqueEntries) {
18076 UseOriginalSrc = true;
18077
18078 auto *FirstElt = Src0s.begin();
18079 auto FirstEltOp =
18080 getDWordFromOffset(DAG, SL, FirstElt->SrcOp, FirstElt->DWordOffset);
18081
18082 auto *SecondElt = Src1s.begin();
18083 auto SecondEltOp = getDWordFromOffset(DAG, SL, SecondElt->SrcOp,
18084 SecondElt->DWordOffset);
18085
18086 Src0 = DAG.getBitcastedAnyExtOrTrunc(FirstEltOp, SL,
18087 MVT::getIntegerVT(32));
18088 Src1 = DAG.getBitcastedAnyExtOrTrunc(SecondEltOp, SL,
18089 MVT::getIntegerVT(32));
18090 }
18091 }
18092
18093 if (!UseOriginalSrc) {
18094 Src0 = resolveSources(DAG, SL, Src0s, false, true);
18095 Src1 = resolveSources(DAG, SL, Src1s, false, true);
18096 }
18097
18098 assert(IsSigned);
18099 SDValue Src2 =
18100 DAG.getExtOrTrunc(*IsSigned, Src2s[ChainLength - 1], SL, MVT::i32);
18101
18102 SDValue IID = DAG.getTargetConstant(*IsSigned ? Intrinsic::amdgcn_sdot4
18103 : Intrinsic::amdgcn_udot4,
18104 SL, MVT::i64);
18105
18106 assert(!VT.isVector());
18107 auto Dot = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32, IID, Src0,
18108 Src1, Src2, DAG.getTargetConstant(0, SL, MVT::i1));
18109
18110 return DAG.getExtOrTrunc(*IsSigned, Dot, SL, VT);
18111 }
18112
18113 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
18114 return SDValue();
18115
18116 // add x, zext (setcc) => uaddo_carry x, 0, setcc
18117 // add x, sext (setcc) => usubo_carry x, 0, setcc
18118 unsigned Opc = LHS.getOpcode();
18121 std::swap(RHS, LHS);
18122
18123 Opc = RHS.getOpcode();
18124 switch (Opc) {
18125 default:
18126 break;
18127 case ISD::ZERO_EXTEND:
18128 case ISD::SIGN_EXTEND:
18129 case ISD::ANY_EXTEND: {
18130 auto Cond = RHS.getOperand(0);
18131 // If this won't be a real VOPC output, we would still need to insert an
18132 // extra instruction anyway.
18133 if (!isBoolSGPR(Cond))
18134 break;
18135 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
18136 SDValue Args[] = {LHS, DAG.getConstant(0, SL, MVT::i32), Cond};
18138 return DAG.getNode(Opc, SL, VTList, Args);
18139 }
18140 case ISD::UADDO_CARRY: {
18141 // add x, (uaddo_carry y, 0, cc) => uaddo_carry x, y, cc
18142 if (!isNullConstant(RHS.getOperand(1)))
18143 break;
18144 SDValue Args[] = {LHS, RHS.getOperand(0), RHS.getOperand(2)};
18145 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), RHS->getVTList(), Args);
18146 }
18147 }
18148 return SDValue();
18149}
18150
18151SDValue SITargetLowering::performPtrAddCombine(SDNode *N,
18152 DAGCombinerInfo &DCI) const {
18153 SelectionDAG &DAG = DCI.DAG;
18154 SDLoc DL(N);
18155 EVT VT = N->getValueType(0);
18156 SDValue N0 = N->getOperand(0);
18157 SDValue N1 = N->getOperand(1);
18158
18159 // The following folds transform PTRADDs into regular arithmetic in cases
18160 // where the PTRADD wouldn't be folded as an immediate offset into memory
18161 // instructions anyway. They are target-specific in that other targets might
18162 // prefer to not lose information about the pointer arithmetic.
18163
18164 // Fold (ptradd x, shl(0 - v, k)) -> sub(x, shl(v, k)).
18165 // Adapted from DAGCombiner::visitADDLikeCommutative.
18166 SDValue V, K;
18167 if (sd_match(N1, m_Shl(m_Neg(m_Value(V)), m_Value(K)))) {
18168 SDNodeFlags ShlFlags = N1->getFlags();
18169 // If the original shl is NUW and NSW, the first k+1 bits of 0-v are all 0,
18170 // so v is either 0 or the first k+1 bits of v are all 1 -> NSW can be
18171 // preserved.
18172 SDNodeFlags NewShlFlags =
18173 ShlFlags.hasNoUnsignedWrap() && ShlFlags.hasNoSignedWrap()
18175 : SDNodeFlags();
18176 SDValue Inner = DAG.getNode(ISD::SHL, DL, VT, V, K, NewShlFlags);
18177 DCI.AddToWorklist(Inner.getNode());
18178 return DAG.getNode(ISD::SUB, DL, VT, N0, Inner);
18179 }
18180
18181 // Fold into Mad64 if the right-hand side is a MUL. Analogous to a fold in
18182 // performAddCombine.
18183 if (N1.getOpcode() == ISD::MUL) {
18184 if (Subtarget->hasMad64_32()) {
18185 if (SDValue Folded = tryFoldToMad64_32(N, DCI))
18186 return Folded;
18187 }
18188 }
18189
18190 // If the 32 low bits of the constant are all zero, there is nothing to fold
18191 // into an immediate offset, so it's better to eliminate the unnecessary
18192 // addition for the lower 32 bits than to preserve the PTRADD.
18193 // Analogous to a fold in performAddCombine.
18194 if (VT == MVT::i64) {
18195 if (SDValue Folded = foldAddSub64WithZeroLowBitsTo32(N, DCI))
18196 return Folded;
18197 }
18198
18199 if (N1.getOpcode() != ISD::ADD || !N1.hasOneUse())
18200 return SDValue();
18201
18202 SDValue X = N0;
18203 SDValue Y = N1.getOperand(0);
18204 SDValue Z = N1.getOperand(1);
18205 bool YIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Y);
18206 bool ZIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Z);
18207
18208 if (!YIsConstant && !ZIsConstant && !X->isDivergent() &&
18209 Y->isDivergent() != Z->isDivergent()) {
18210 // Reassociate (ptradd x, (add y, z)) -> (ptradd (ptradd x, y), z) if x and
18211 // y are uniform and z isn't.
18212 // Reassociate (ptradd x, (add y, z)) -> (ptradd (ptradd x, z), y) if x and
18213 // z are uniform and y isn't.
18214 // The goal is to push uniform operands up in the computation, so that they
18215 // can be handled with scalar operations. We can't use reassociateScalarOps
18216 // for this since it requires two identical commutative operations to
18217 // reassociate.
18218 if (Y->isDivergent())
18219 std::swap(Y, Z);
18220 // If both additions in the original were NUW, reassociation preserves that.
18221 SDNodeFlags ReassocFlags =
18222 (N->getFlags() & N1->getFlags()) & SDNodeFlags::NoUnsignedWrap;
18223 SDValue UniformInner = DAG.getMemBasePlusOffset(X, Y, DL, ReassocFlags);
18224 DCI.AddToWorklist(UniformInner.getNode());
18225 return DAG.getMemBasePlusOffset(UniformInner, Z, DL, ReassocFlags);
18226 }
18227
18228 return SDValue();
18229}
18230
18231static bool isCtlzOpc(unsigned Opc) {
18232 return Opc == ISD::CTLZ || Opc == ISD::CTLZ_ZERO_POISON;
18233}
18234
18235SDValue SITargetLowering::performSubCombine(SDNode *N,
18236 DAGCombinerInfo &DCI) const {
18237 SelectionDAG &DAG = DCI.DAG;
18238 EVT VT = N->getValueType(0);
18239
18240 if (VT == MVT::i64) {
18241 if (SDValue Folded = foldAddSub64WithZeroLowBitsTo32(N, DCI))
18242 return Folded;
18243 }
18244
18245 if (VT != MVT::i32)
18246 return SDValue();
18247
18248 SDLoc SL(N);
18249 SDValue LHS = N->getOperand(0);
18250 SDValue RHS = N->getOperand(1);
18251
18252 // sub x, zext (setcc) => usubo_carry x, 0, setcc
18253 // sub x, sext (setcc) => uaddo_carry x, 0, setcc
18254 unsigned Opc = RHS.getOpcode();
18255 switch (Opc) {
18256 default:
18257 break;
18258 case ISD::ZERO_EXTEND:
18259 case ISD::SIGN_EXTEND:
18260 case ISD::ANY_EXTEND: {
18261 auto Cond = RHS.getOperand(0);
18262 // If this won't be a real VOPC output, we would still need to insert an
18263 // extra instruction anyway.
18264 if (!isBoolSGPR(Cond))
18265 break;
18266 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
18267 SDValue Args[] = {LHS, DAG.getConstant(0, SL, MVT::i32), Cond};
18269 return DAG.getNode(Opc, SL, VTList, Args);
18270 }
18271 }
18272
18273 if (LHS.getOpcode() == ISD::USUBO_CARRY) {
18274 // sub (usubo_carry x, 0, cc), y => usubo_carry x, y, cc
18275 if (!isNullConstant(LHS.getOperand(1)))
18276 return SDValue();
18277 SDValue Args[] = {LHS.getOperand(0), RHS, LHS.getOperand(2)};
18278 return DAG.getNode(ISD::USUBO_CARRY, SDLoc(N), LHS->getVTList(), Args);
18279 }
18280
18281 // sub (ctlz (xor x, (sra x, 31))), 1 -> ctls x.
18282 if (isOneConstant(RHS) && isCtlzOpc(LHS.getOpcode())) {
18283 SDValue CtlzSrc = LHS.getOperand(0);
18284 // Check for xor x, (sra x, 31) pattern.
18285 if (CtlzSrc.getOpcode() == ISD::XOR) {
18286 SDValue X = CtlzSrc.getOperand(0);
18287 SDValue SignExt = CtlzSrc.getOperand(1);
18288 // Try both ordering of XOR operands.
18289 if (SignExt.getOpcode() != ISD::SRA)
18290 std::swap(X, SignExt);
18291 if (SignExt.getOpcode() == ISD::SRA && SignExt.getOperand(0) == X) {
18292 ConstantSDNode *ShiftAmt =
18294 unsigned BitWidth = X.getValueType().getScalarSizeInBits();
18295 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1)
18296 return DAG.getNode(ISD::CTLS, SL, VT, X);
18297 }
18298 }
18299 }
18300
18301 return SDValue();
18302}
18303
18304SDValue SITargetLowering::performFAddCombine(SDNode *N,
18305 DAGCombinerInfo &DCI) const {
18306 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
18307 return SDValue();
18308
18309 SelectionDAG &DAG = DCI.DAG;
18310 EVT VT = N->getValueType(0);
18311
18312 SDLoc SL(N);
18313 SDValue LHS = N->getOperand(0);
18314 SDValue RHS = N->getOperand(1);
18315
18316 // These should really be instruction patterns, but writing patterns with
18317 // source modifiers is a pain.
18318
18319 // fadd (fadd (a, a), b) -> mad 2.0, a, b
18320 if (LHS.getOpcode() == ISD::FADD) {
18321 SDValue A = LHS.getOperand(0);
18322 if (A == LHS.getOperand(1)) {
18323 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
18324 if (FusedOp != 0) {
18325 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
18326 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
18327 }
18328 }
18329 }
18330
18331 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
18332 if (RHS.getOpcode() == ISD::FADD) {
18333 SDValue A = RHS.getOperand(0);
18334 if (A == RHS.getOperand(1)) {
18335 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
18336 if (FusedOp != 0) {
18337 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
18338 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
18339 }
18340 }
18341 }
18342
18343 return SDValue();
18344}
18345
18346SDValue SITargetLowering::performFSubCombine(SDNode *N,
18347 DAGCombinerInfo &DCI) const {
18348 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
18349 return SDValue();
18350
18351 SelectionDAG &DAG = DCI.DAG;
18352 SDLoc SL(N);
18353 EVT VT = N->getValueType(0);
18354 assert(!VT.isVector());
18355
18356 // Try to get the fneg to fold into the source modifier. This undoes generic
18357 // DAG combines and folds them into the mad.
18358 //
18359 // Only do this if we are not trying to support denormals. v_mad_f32 does
18360 // not support denormals ever.
18361 SDValue LHS = N->getOperand(0);
18362 SDValue RHS = N->getOperand(1);
18363 if (LHS.getOpcode() == ISD::FADD) {
18364 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
18365 SDValue A = LHS.getOperand(0);
18366 if (A == LHS.getOperand(1)) {
18367 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
18368 if (FusedOp != 0) {
18369 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
18370 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
18371
18372 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
18373 }
18374 }
18375 }
18376
18377 if (RHS.getOpcode() == ISD::FADD) {
18378 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
18379
18380 SDValue A = RHS.getOperand(0);
18381 if (A == RHS.getOperand(1)) {
18382 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
18383 if (FusedOp != 0) {
18384 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
18385 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
18386 }
18387 }
18388 }
18389
18390 return SDValue();
18391}
18392
18393SDValue SITargetLowering::performFDivCombine(SDNode *N,
18394 DAGCombinerInfo &DCI) const {
18395 SelectionDAG &DAG = DCI.DAG;
18396 SDLoc SL(N);
18397 EVT VT = N->getValueType(0);
18398
18399 if (VT != MVT::f16 && VT != MVT::bf16)
18400 return SDValue();
18401
18402 SDValue LHS = N->getOperand(0);
18403 SDValue RHS = N->getOperand(1);
18404
18405 SDNodeFlags Flags = N->getFlags();
18406 SDNodeFlags RHSFlags = RHS->getFlags();
18407 if (!Flags.hasAllowContract() || !RHSFlags.hasAllowContract() ||
18408 !RHS->hasOneUse())
18409 return SDValue();
18410
18411 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
18412 bool IsNegative = false;
18413 if (CLHS->isOne() || (IsNegative = CLHS->isMinusOne())) {
18414 // fdiv contract 1.0, (sqrt contract x) -> rsq
18415 // fdiv contract -1.0, (sqrt contract x) -> fneg(rsq)
18416 if (RHS.getOpcode() == ISD::FSQRT) {
18417 // TODO: Or in RHS flags, somehow missing from SDNodeFlags
18418 SDValue SqrtOp = RHS.getOperand(0);
18419 SDValue Rsq;
18420 if (isOperationLegal(ISD::FSQRT, VT)) {
18421 // fsqrt legality correlates to rsq availability of the same type.
18422 Rsq = DAG.getNode(AMDGPUISD::RSQ, SL, VT, SqrtOp, Flags);
18423 } else if (VT == MVT::f16) {
18424 // Targets without 16-bit instructions (gfx6/gfx7) have no f16 rsq,
18425 // but v_rsq_f32 is more than accurate enough for f16. Unlike bf16,
18426 // every f16 value (including denormals) extends to a normal f32, and
18427 // an f16 rsq result is never denormal, so the f32 reciprocal square
18428 // root needs no denormal handling. Compute it in f32 and round back.
18429 SDValue Ext =
18430 DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, SqrtOp, Flags);
18431 SDValue F32Rsq =
18432 DAG.getNode(AMDGPUISD::RSQ, SL, MVT::f32, Ext, Flags);
18433 Rsq = DAG.getNode(ISD::FP_ROUND, SL, VT, F32Rsq,
18434 DAG.getTargetConstant(0, SL, MVT::i32), Flags);
18435 } else {
18436 // bf16 shares f32's exponent range, so bf16 denormals would extend to
18437 // f32 denormals that v_rsq_f32 does not handle. Leave it expanded.
18438 return SDValue();
18439 }
18440 return IsNegative ? DAG.getNode(ISD::FNEG, SL, VT, Rsq, Flags) : Rsq;
18441 }
18442 }
18443 }
18444
18445 return SDValue();
18446}
18447
18448SDValue SITargetLowering::performFMulCombine(SDNode *N,
18449 DAGCombinerInfo &DCI) const {
18450 SelectionDAG &DAG = DCI.DAG;
18451 EVT VT = N->getValueType(0);
18452 EVT ScalarVT = VT.getScalarType();
18453 EVT IntVT = VT.changeElementType(*DAG.getContext(), MVT::i32);
18454
18455 if (!N->isDivergent() && getSubtarget()->hasSALUFloatInsts() &&
18456 (ScalarVT == MVT::f32 || ScalarVT == MVT::f16)) {
18457 // Prefer to use s_mul_f16/f32 instead of v_ldexp_f16/f32.
18458 return SDValue();
18459 }
18460
18461 SDValue LHS = N->getOperand(0);
18462 SDValue RHS = N->getOperand(1);
18463
18464 // It is cheaper to realize i32 inline constants as compared against
18465 // materializing f16 or f64 (or even non-inline f32) values,
18466 // possible via ldexp usage, as shown below :
18467 //
18468 // Given : A = 2^a & B = 2^b ; where a and b are integers.
18469 // fmul x, (select y, A, B) -> ldexp( x, (select i32 y, a, b) )
18470 // fmul x, (select y, -A, -B) -> ldexp( (fneg x), (select i32 y, a, b) )
18471 if ((ScalarVT == MVT::f64 || ScalarVT == MVT::f32 || ScalarVT == MVT::f16) &&
18472 (RHS.hasOneUse() && RHS.getOpcode() == ISD::SELECT)) {
18473 const ConstantFPSDNode *TrueNode = isConstOrConstSplatFP(RHS.getOperand(1));
18474 if (!TrueNode)
18475 return SDValue();
18476 const ConstantFPSDNode *FalseNode =
18477 isConstOrConstSplatFP(RHS.getOperand(2));
18478 if (!FalseNode)
18479 return SDValue();
18480
18481 if (TrueNode->isNegative() != FalseNode->isNegative())
18482 return SDValue();
18483
18484 // For f32, only non-inline constants should be transformed.
18485 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
18486 if (ScalarVT == MVT::f32 &&
18487 TII->isInlineConstant(TrueNode->getValueAPF()) &&
18488 TII->isInlineConstant(FalseNode->getValueAPF()))
18489 return SDValue();
18490
18491 int TrueNodeExpVal = TrueNode->getValueAPF().getExactLog2Abs();
18492 if (TrueNodeExpVal == INT_MIN)
18493 return SDValue();
18494 int FalseNodeExpVal = FalseNode->getValueAPF().getExactLog2Abs();
18495 if (FalseNodeExpVal == INT_MIN)
18496 return SDValue();
18497
18498 SDLoc SL(N);
18499 SDValue SelectNode =
18500 DAG.getNode(ISD::SELECT, SL, IntVT, RHS.getOperand(0),
18501 DAG.getSignedConstant(TrueNodeExpVal, SL, IntVT),
18502 DAG.getSignedConstant(FalseNodeExpVal, SL, IntVT));
18503
18504 LHS = TrueNode->isNegative()
18505 ? DAG.getNode(ISD::FNEG, SL, VT, LHS, LHS->getFlags())
18506 : LHS;
18507
18508 return DAG.getNode(ISD::FLDEXP, SL, VT, LHS, SelectNode, N->getFlags());
18509 }
18510
18511 return SDValue();
18512}
18513
18514SDValue SITargetLowering::performFMACombine(SDNode *N,
18515 DAGCombinerInfo &DCI) const {
18516 SelectionDAG &DAG = DCI.DAG;
18517 EVT VT = N->getValueType(0);
18518 SDLoc SL(N);
18519
18520 if (!Subtarget->hasDot10Insts() || VT != MVT::f32)
18521 return SDValue();
18522
18523 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
18524 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
18525 SDValue Op1 = N->getOperand(0);
18526 SDValue Op2 = N->getOperand(1);
18527 SDValue FMA = N->getOperand(2);
18528
18529 if (FMA.getOpcode() != ISD::FMA || Op1.getOpcode() != ISD::FP_EXTEND ||
18530 Op2.getOpcode() != ISD::FP_EXTEND)
18531 return SDValue();
18532
18533 // The fdot2 fold (fma_mix -> dot2) is only safe when both instructions agree
18534 // on how f16 subnormal inputs are handled. However, if both FMAs carry afn
18535 // the caller accepts approximate results, so any subnormal flushing
18536 // introduced by dot2 is acceptable regardless of mode.
18537 //
18538 // gfx90a (CDNA2) is the sole exception (dot2UnconditionalFlush): v_dot2c
18539 // unconditionally flushes f16 subnormal inputs to zero regardless of MODE,
18540 // while v_fma_mix_f32 preserves them when ieee=1 (the default compute kernel
18541 // mode). The fold is safe only when f32 denorm = PreserveSign, which implies
18542 // ieee=0 so both flush.
18543 //
18544 // All other GPUs: v_dot2 does NOT flush f16 subnormal inputs. v_fma_mix_f32
18545 // flushes them only when f32 denorm = PreserveSign. The fold is safe only
18546 // when f32 denorm is IEEE (both preserve the subnormal). Dynamic mode is
18547 // also rejected since the runtime value is unknown.
18548 bool AllowInaccuracy = N->getFlags().hasApproximateFuncs() &&
18549 FMA->getFlags().hasApproximateFuncs();
18550 if (!AllowInaccuracy) {
18551 const MachineFunction &MF = DAG.getMachineFunction();
18552 DenormalMode Mode = MF.getDenormalMode(APFloat::IEEEsingle());
18553 if (Subtarget->dot2UnconditionalFlush()) {
18554 // gfx90a: fold safe only when f32 denorm flushes.
18556 return SDValue();
18557 } else {
18558 // All other GPUs: fold safe only when f32 denorm is IEEE.
18559 if (Mode != DenormalMode::getIEEE())
18560 return SDValue();
18561 }
18562 }
18563
18564 // fp-contract allows reassociating the fma tree into a dot product.
18565 if (N->getFlags().hasAllowContract() && FMA->getFlags().hasAllowContract()) {
18566 Op1 = Op1.getOperand(0);
18567 Op2 = Op2.getOperand(0);
18568 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18570 return SDValue();
18571
18572 SDValue Vec1 = Op1.getOperand(0);
18573 SDValue Idx1 = Op1.getOperand(1);
18574 SDValue Vec2 = Op2.getOperand(0);
18575
18576 SDValue FMAOp1 = FMA.getOperand(0);
18577 SDValue FMAOp2 = FMA.getOperand(1);
18578 SDValue FMAAcc = FMA.getOperand(2);
18579
18580 if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
18581 FMAOp2.getOpcode() != ISD::FP_EXTEND)
18582 return SDValue();
18583
18584 FMAOp1 = FMAOp1.getOperand(0);
18585 FMAOp2 = FMAOp2.getOperand(0);
18586 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18588 return SDValue();
18589
18590 SDValue Vec3 = FMAOp1.getOperand(0);
18591 SDValue Vec4 = FMAOp2.getOperand(0);
18592 SDValue Idx2 = FMAOp1.getOperand(1);
18593
18594 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1))
18595 return SDValue();
18596
18597 if (!isa<ConstantSDNode>(Idx1) || !isa<ConstantSDNode>(Idx2) ||
18598 Idx1 == Idx2)
18599 return SDValue();
18600
18601 if (Vec1 == Vec2 || Vec3 == Vec4)
18602 return SDValue();
18603
18604 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
18605 return SDValue();
18606
18607 if ((Vec1 == Vec3 && Vec2 == Vec4) || (Vec1 == Vec4 && Vec2 == Vec3)) {
18608 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
18609 DAG.getTargetConstant(0, SL, MVT::i1));
18610 }
18611 }
18612 return SDValue();
18613}
18614
18615// Given a double-precision ordered or unordered comparison, return the
18616// condition code for an equivalent integral comparison of the operands' upper
18617// 32 bits, or `SETCC_INVALID` if not possible.
18618// For simplicity, no simplification occurs if the operands are not both known
18619// to have sign bit zero.
18620//
18621// EQ/NE:
18622// If LHS.lo32 == RHS.lo32:
18623// setcc LHS, RHS, eq/ne => setcc LHS.hi32, RHS.hi32, eq/ne
18624// If LHS.lo32 != RHS.lo32:
18625// setcc LHS, RHS, eq/ne => setcc LHS.hi32, RHS.hi32, false/true
18626// The reduction is not possible if operands may be +0 and -0.
18627// For ordered eq / unordered ne, at most one operand may be NaN.
18628// For unordered eq / ordered ne, neither operand can be NaN.
18629//
18630// LT/GE:
18631// If LHS.lo32 >= RHS.lo32 (unsigned):
18632// setcc LHS, RHS, [u]lt/ge => LHS.hi32, RHS.hi32, [u]lt/ge
18633// If LHS.lo32 < RHS.lo32 (unsigned):
18634// setcc LHS, RHS, [u]lt/ge => LHS.hi32, RHS.hi32, [u]le/gt
18635// The reduction is only supported if both operands are nonnegative.
18636// For ordered lt / unordered ge, the RHS cannot be NaN.
18637// For unordered lt / ordered ge, neither operand can be NaN.
18638//
18639// LE/GT:
18640// If LHS.lo32 > RHS.lo32 (unsigned):
18641// setcc LHS, RHS, [u]le/gt => LHS.hi32, RHS.hi32, [u]lt/ge
18642// If LHS.lo32 <= RHS.lo32 (unsigned):
18643// setcc LHS, RHS, [u]le/gt => LHS.hi32, RHS.hi32, [u]le/gt
18644// The reduction is only supported if both operands are nonnegative.
18645// For unordered le / ordered gt, the LHS cannot be NaN.
18646// For ordered le / unordered gt, neither operand can be NaN.
18648 const SDValue LHS,
18649 const SDValue RHS,
18650 const SelectionDAG &DAG) {
18651 EVT VT = LHS.getValueType();
18652 assert(VT == MVT::f64 && "Incorrect operand type!");
18653
18654 const KnownBits RHSBits = DAG.computeKnownBits(RHS);
18655 // Bail if RHS sign bit is not known to be zero.
18656 if (!RHSBits.Zero.isSignBitSet())
18657 return ISD::SETCC_INVALID;
18658
18659 const KnownBits RHSKnownLo32 = RHSBits.trunc(32);
18660 const KnownFPClass RHSFPClass =
18662 const bool RHSMaybeNaN = !RHSFPClass.isKnownNeverNaN();
18663
18664 const KnownBits LHSBits = DAG.computeKnownBits(LHS);
18665 const KnownBits LHSKnownLo32 = LHSBits.trunc(32);
18666 const KnownFPClass LHSFPClass =
18668 const bool LHSMaybeNaN = !LHSFPClass.isKnownNeverNaN();
18669
18670 // Bail if LHS sign bit is not known to be zero.
18671 if (!LHSBits.Zero.isSignBitSet())
18672 return ISD::SETCC_INVALID;
18673
18674 switch (CC) {
18675 default:
18676 break;
18677 case ISD::SETEQ:
18678 case ISD::SETOEQ:
18679 case ISD::SETUEQ:
18680 case ISD::SETONE:
18681 case ISD::SETUNE: {
18682 // OEQ should be false if either operand is NaN, so it suffices that at
18683 // least one operand is not NaN.
18684 if (CC == ISD::SETOEQ && LHSMaybeNaN && RHSMaybeNaN)
18685 break;
18686 // UEQ should be true if either operand is NaN, but this cannot be checked
18687 // on underlying bits.
18688 if (CC == ISD::SETUEQ && (LHSMaybeNaN || RHSMaybeNaN))
18689 break;
18690 // ONE should be false if either operand is NaN, but this cannot be
18691 // checked on underlying bits.
18692 if (CC == ISD::SETONE && (LHSMaybeNaN || RHSMaybeNaN))
18693 break;
18694 // UNE should be true if either operand is NaN, so it suffices that they
18695 // are not both NaN.
18696 if (CC == ISD::SETUNE && LHSMaybeNaN && RHSMaybeNaN)
18697 break;
18698
18699 const std::optional<bool> KnownEq =
18700 KnownBits::eq(LHSKnownLo32, RHSKnownLo32);
18701
18702 if (!KnownEq)
18703 break;
18704
18705 if (*KnownEq)
18706 return (CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ)
18707 ? ISD::SETEQ
18708 : ISD::SETNE;
18709
18710 return (CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ)
18712 : ISD::SETTRUE;
18713 }
18714 case ISD::SETLT:
18715 case ISD::SETOLT:
18716 case ISD::SETULT:
18717 case ISD::SETGE:
18718 case ISD::SETOGE:
18719 case ISD::SETUGE: {
18720 // OLT should be false if either operand is NaN.
18721 // Since NaNs have maximum exponent and nonzero mantissa, false positives
18722 // are only possible if the RHS is NaN. (No issue with RHS == +inf since
18723 // the inequality is strict)
18724 if (CC == ISD::SETOLT && RHSMaybeNaN)
18725 break;
18726 // ULT should be true if either operand is NaN, but this cannot be ensured
18727 // with a truncated comparison.
18728 if (CC == ISD::SETULT && (LHSMaybeNaN || RHSMaybeNaN))
18729 break;
18730 // OGE should be false if either operand is NaN, but this cannot be
18731 // ensured with a truncated comparison.
18732 if (CC == ISD::SETOGE && (LHSMaybeNaN || RHSMaybeNaN))
18733 break;
18734 // UGE should be true if either operand is NaN.
18735 // False negatives are only possible if the RHS is NaN.
18736 // (No issue with RHS == +inf since the inequality is inclusive)
18737 if (CC == ISD::SETUGE && RHSMaybeNaN)
18738 break;
18739
18740 const std::optional<bool> KnownUge =
18741 KnownBits::uge(LHSKnownLo32, RHSKnownLo32);
18742
18743 if (!KnownUge)
18744 break;
18745
18746 if (*KnownUge) {
18747 // LHS.lo32 uge RHS.lo32, so LHS >= RHS iff LHS.hi32 >= RHS.hi32
18748 return (CC == ISD::SETLT || CC == ISD::SETOLT || CC == ISD::SETULT)
18749 ? ISD::SETLT
18750 : ISD::SETGE;
18751 }
18752 // LHS.lo32 ult RHS.lo32, so LHS >= RHS iff LHS.hi32 > RHS.hi32
18753 return (CC == ISD::SETLT || CC == ISD::SETOLT || CC == ISD::SETULT)
18754 ? ISD::SETLE
18755 : ISD::SETGT;
18756 }
18757 case ISD::SETLE:
18758 case ISD::SETOLE:
18759 case ISD::SETULE:
18760 case ISD::SETGT:
18761 case ISD::SETOGT:
18762 case ISD::SETUGT: {
18763 // OLE should be false if either operand is NaN, but this cannot be
18764 // ensured with a truncated comparison.
18765 if (CC == ISD::SETOLE && (LHSMaybeNaN || RHSMaybeNaN))
18766 break;
18767 // ULE should be true if either operand is NaN.
18768 // False negatives are only possible if the LHS is NaN.
18769 // (No issue with LHS == +inf since the inequality is inclusive)
18770 if (CC == ISD::SETULE && LHSMaybeNaN)
18771 break;
18772 // OGT should be false if either operand is NaN.
18773 // False positives are only possible if the LHS is NaN.
18774 // (No issue with LHS == +inf since the inequality is strict)
18775 if (CC == ISD::SETOGT && LHSMaybeNaN)
18776 break;
18777 // UGT should be true if either operand is NaN, but this cannot be ensured
18778 // with a truncated comparison.
18779 if (CC == ISD::SETUGT && (LHSMaybeNaN || RHSMaybeNaN))
18780 break;
18781
18782 const std::optional<bool> KnownUle =
18783 KnownBits::ule(LHSKnownLo32, RHSKnownLo32);
18784
18785 if (!KnownUle)
18786 break;
18787
18788 if (*KnownUle) {
18789 // LHS.lo32 ule RHS.lo32, so LHS <= RHS iff LHS.hi32 <= RHS.hi32
18790 return (CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE)
18791 ? ISD::SETLE
18792 : ISD::SETGT;
18793 }
18794 // LHS.lo32 ugt RHS.lo32, so LHS <= RHS iff LHS.hi32 < RHS.hi32
18795 return (CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE)
18796 ? ISD::SETLT
18797 : ISD::SETGE;
18798 }
18799 }
18800
18801 return ISD::SETCC_INVALID;
18802}
18803
18804SDValue SITargetLowering::performSetCCCombine(SDNode *N,
18805 DAGCombinerInfo &DCI) const {
18806 SelectionDAG &DAG = DCI.DAG;
18807 SDLoc SL(N);
18808
18809 SDValue LHS = N->getOperand(0);
18810 SDValue RHS = N->getOperand(1);
18811 EVT VT = LHS.getValueType();
18812 ISD::CondCode CC = N->getOperandCondCode(2);
18813
18814 auto *CRHS = dyn_cast<ConstantSDNode>(RHS);
18815 if (!CRHS) {
18817 if (CRHS) {
18818 std::swap(LHS, RHS);
18820 }
18821 }
18822
18823 if (CRHS) {
18824 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
18825 isBoolSGPR(LHS.getOperand(0))) {
18826 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
18827 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
18828 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
18829 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
18830 if ((CRHS->isAllOnes() &&
18831 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
18832 (CRHS->isZero() &&
18833 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
18834 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
18835 DAG.getAllOnesConstant(SL, MVT::i1));
18836 if ((CRHS->isAllOnes() &&
18837 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
18838 (CRHS->isZero() &&
18839 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
18840 return LHS.getOperand(0);
18841 }
18842
18843 const APInt &CRHSVal = CRHS->getAPIntValue();
18844 if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
18845 LHS.getOpcode() == ISD::SELECT &&
18846 isa<ConstantSDNode>(LHS.getOperand(1)) &&
18847 isa<ConstantSDNode>(LHS.getOperand(2)) &&
18848 isBoolSGPR(LHS.getOperand(0))) {
18849 // Given CT != FT:
18850 // setcc (select cc, CT, CF), CF, eq => xor cc, -1
18851 // setcc (select cc, CT, CF), CF, ne => cc
18852 // setcc (select cc, CT, CF), CT, ne => xor cc, -1
18853 // setcc (select cc, CT, CF), CT, eq => cc
18854 const APInt &CT = LHS.getConstantOperandAPInt(1);
18855 const APInt &CF = LHS.getConstantOperandAPInt(2);
18856
18857 if (CT != CF) {
18858 if ((CF == CRHSVal && CC == ISD::SETEQ) ||
18859 (CT == CRHSVal && CC == ISD::SETNE))
18860 return DAG.getNOT(SL, LHS.getOperand(0), MVT::i1);
18861 if ((CF == CRHSVal && CC == ISD::SETNE) ||
18862 (CT == CRHSVal && CC == ISD::SETEQ))
18863 return LHS.getOperand(0);
18864 }
18865 }
18866 }
18867
18868 // Truncate 64-bit setcc to only test upper or lower 32-bits.
18869 if (VT == MVT::i64) {
18870 const KnownBits LHSKnown = DAG.computeKnownBits(LHS);
18871 const KnownBits RHSKnown = DAG.computeKnownBits(RHS);
18872 const KnownBits LHSKnownLo32 = LHSKnown.trunc(32);
18873 const KnownBits RHSKnownLo32 = RHSKnown.trunc(32);
18874 // Truncate 64-bit setcc to test only upper 32-bits of its operands in the
18875 // following cases where information about the lower 32-bits of its operands
18876 // is known:
18877 //
18878 // If LHS.lo32 == RHS.lo32:
18879 // setcc LHS, RHS, eq/ne => setcc LHS.hi32, RHS.hi32, eq/ne
18880 // If LHS.lo32 != RHS.lo32:
18881 // setcc LHS, RHS, eq/ne => setcc LHS.hi32, RHS.hi32, false/true
18882 // If LHS.lo32 >= RHS.lo32 (unsigned):
18883 // setcc LHS, RHS, [u]lt/ge => LHS.hi32, RHS.hi32, [u]lt/ge
18884 // If LHS.lo32 > RHS.lo32 (unsigned):
18885 // setcc LHS, RHS, [u]le/gt => LHS.hi32, RHS.hi32, [u]lt/ge
18886 // If LHS.lo32 <= RHS.lo32 (unsigned):
18887 // setcc LHS, RHS, [u]le/gt => LHS.hi32, RHS.hi32, [u]le/gt
18888 // If LHS.lo32 < RHS.lo32 (unsigned):
18889 // setcc LHS, RHS, [u]lt/ge => LHS.hi32, RHS.hi32, [u]le/gt
18890
18891 // NewCC is valid iff we can truncate the setcc to only test the upper 32
18892 // bits
18894
18895 switch (CC) {
18896 default:
18897 llvm_unreachable("Unexpected condition code for integer setcc");
18898 break;
18899 case ISD::SETEQ: {
18900 const std::optional<bool> KnownEq =
18901 KnownBits::eq(LHSKnownLo32, RHSKnownLo32);
18902 if (KnownEq)
18903 NewCC = *KnownEq ? ISD::SETEQ : ISD::SETFALSE;
18904
18905 break;
18906 }
18907 case ISD::SETNE: {
18908 const std::optional<bool> KnownEq =
18909 KnownBits::eq(LHSKnownLo32, RHSKnownLo32);
18910 if (KnownEq)
18911 NewCC = *KnownEq ? ISD::SETNE : ISD::SETTRUE;
18912
18913 break;
18914 }
18915 case ISD::SETULT:
18916 case ISD::SETUGE:
18917 case ISD::SETLT:
18918 case ISD::SETGE: {
18919 const std::optional<bool> KnownUge =
18920 KnownBits::uge(LHSKnownLo32, RHSKnownLo32);
18921 if (KnownUge) {
18922 if (*KnownUge) {
18923 // LHS.lo32 uge RHS.lo32, so LHS >= RHS iff LHS.hi32 >= RHS.hi32
18924 NewCC = CC;
18925 } else {
18926 // LHS.lo32 ult RHS.lo32, so LHS >= RHS iff LHS.hi32 > RHS.hi32
18927 NewCC = CC == ISD::SETULT ? ISD::SETULE
18929 : CC == ISD::SETLT ? ISD::SETLE
18930 : ISD::SETGT;
18931 }
18932 }
18933 break;
18934 }
18935 case ISD::SETULE:
18936 case ISD::SETUGT:
18937 case ISD::SETLE:
18938 case ISD::SETGT: {
18939 const std::optional<bool> KnownUle =
18940 KnownBits::ule(LHSKnownLo32, RHSKnownLo32);
18941 if (KnownUle) {
18942 if (*KnownUle) {
18943 // LHS.lo32 ule RHS.lo32, so LHS <= RHS iff LHS.hi32 <= RHS.hi32
18944 NewCC = CC;
18945 } else {
18946 // LHS.lo32 ugt RHS.lo32, so LHS <= RHS iff LHS.hi32 < RHS.hi32
18947 NewCC = CC == ISD::SETULE ? ISD::SETULT
18949 : CC == ISD::SETLE ? ISD::SETLT
18950 : ISD::SETGE;
18951 }
18952 }
18953 break;
18954 }
18955 }
18956
18957 if (NewCC != ISD::SETCC_INVALID)
18958 return DAG.getSetCC(SL, N->getValueType(0), getHiHalf64(LHS, DAG),
18959 getHiHalf64(RHS, DAG), NewCC);
18960
18961 // Truncate 64-bit setcc to test only lower 32-bits when upper 32-bits are
18962 // known equal.
18963 const KnownBits LHSKnownHi32 = LHSKnown.extractBits(32, 32);
18964 const KnownBits RHSKnownHi32 = RHSKnown.extractBits(32, 32);
18965 const std::optional<bool> KnownEq =
18966 KnownBits::eq(LHSKnownHi32, RHSKnownHi32);
18967
18968 if (KnownEq == true) {
18969 // For signed comparisons, convert to unsigned since upper halves match
18971
18972 SDValue LHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
18973 SDValue RHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, RHS);
18974 return DAG.getSetCC(SL, N->getValueType(0), LHSLo, RHSLo, NewCC);
18975 }
18976 }
18977
18978 // Eliminate setcc by using carryout from add/sub instruction
18979
18980 // LHS = ADD i64 RHS, Z LHSlo = UADDO i32 RHSlo, Zlo
18981 // setcc LHS ult RHS -> LHSHi = UADDO_CARRY i32 RHShi, Zhi
18982 // similarly for subtraction
18983
18984 // LHS = ADD i64 Y, 1 LHSlo = UADDO i32 Ylo, 1
18985 // setcc LHS eq 0 -> LHSHi = UADDO_CARRY i32 Yhi, 0
18986
18987 if (VT == MVT::i64 && ((CC == ISD::SETULT &&
18989 (CC == ISD::SETUGT &&
18991 (CC == ISD::SETEQ && CRHS && CRHS->isZero() &&
18992 sd_match(LHS, m_Add(m_Value(), m_One()))))) {
18993 bool IsAdd = LHS.getOpcode() == ISD::ADD;
18994
18995 SDValue Op0 = LHS.getOperand(0);
18996 SDValue Op1 = LHS.getOperand(1);
18997
18998 SDValue Op0Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Op0);
18999 SDValue Op1Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Op1);
19000
19001 SDValue Op0Hi = getHiHalf64(Op0, DAG);
19002 SDValue Op1Hi = getHiHalf64(Op1, DAG);
19003
19004 SDValue NodeLo =
19005 DAG.getNode(IsAdd ? ISD::UADDO : ISD::USUBO, SL,
19006 DAG.getVTList(MVT::i32, MVT::i1), {Op0Lo, Op1Lo});
19007
19008 SDValue CarryInHi = NodeLo.getValue(1);
19009 SDValue NodeHi = DAG.getNode(IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY,
19010 SL, DAG.getVTList(MVT::i32, MVT::i1),
19011 {Op0Hi, Op1Hi, CarryInHi});
19012
19013 SDValue ResultLo = NodeLo.getValue(0);
19014 SDValue ResultHi = NodeHi.getValue(0);
19015
19016 SDValue JoinedResult =
19017 DAG.getBuildVector(MVT::v2i32, SL, {ResultLo, ResultHi});
19018
19019 SDValue Result = DAG.getNode(ISD::BITCAST, SL, VT, JoinedResult);
19020 SDValue Overflow = NodeHi.getValue(1);
19021 DCI.CombineTo(LHS.getNode(), Result);
19022 return Overflow;
19023 }
19024
19025 if (VT != MVT::f32 && VT != MVT::f64 &&
19026 (!Subtarget->has16BitInsts() || VT != MVT::f16))
19027 return SDValue();
19028
19029 // Match isinf/isfinite pattern
19030 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
19031 // (fcmp one (fabs x), inf) -> (fp_class x,
19032 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
19033 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) &&
19034 LHS.getOpcode() == ISD::FABS) {
19035 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
19036 if (!CRHS)
19037 return SDValue();
19038
19039 const APFloat &APF = CRHS->getValueAPF();
19040 if (APF.isInfinity() && !APF.isNegative()) {
19041 const unsigned IsInfMask =
19043 const unsigned IsFiniteMask =
19047 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
19048 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
19049 DAG.getConstant(Mask, SL, MVT::i32));
19050 }
19051 }
19052
19053 if (VT == MVT::f64) {
19055 if (HiHalfCC != ISD::SETCC_INVALID)
19056 return DAG.getSetCC(SL, N->getValueType(0), getHiHalf64(LHS, DAG),
19057 getHiHalf64(RHS, DAG), HiHalfCC);
19058 }
19059
19060 return SDValue();
19061}
19062
19063SDValue
19064SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
19065 DAGCombinerInfo &DCI) const {
19066 SelectionDAG &DAG = DCI.DAG;
19067 SDLoc SL(N);
19068 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
19069
19070 SDValue Src = N->getOperand(0);
19071 SDValue Shift = N->getOperand(0);
19072
19073 // TODO: Extend type shouldn't matter (assuming legal types).
19074 if (Shift.getOpcode() == ISD::ZERO_EXTEND)
19075 Shift = Shift.getOperand(0);
19076
19077 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
19078 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x
19079 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
19080 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
19081 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
19082 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
19083 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
19084 SDValue Shifted = DAG.getZExtOrTrunc(
19085 Shift.getOperand(0), SDLoc(Shift.getOperand(0)), MVT::i32);
19086
19087 unsigned ShiftOffset = 8 * Offset;
19088 if (Shift.getOpcode() == ISD::SHL)
19089 ShiftOffset -= C->getZExtValue();
19090 else
19091 ShiftOffset += C->getZExtValue();
19092
19093 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
19094 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
19095 MVT::f32, Shifted);
19096 }
19097 }
19098 }
19099
19101 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
19102 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
19103 // We simplified Src. If this node is not dead, visit it again so it is
19104 // folded properly.
19105 if (N->getOpcode() != ISD::DELETED_NODE)
19106 DCI.AddToWorklist(N);
19107 return SDValue(N, 0);
19108 }
19109
19110 // Handle (or x, (srl y, 8)) pattern when known bits are zero.
19111 if (SDValue DemandedSrc =
19112 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
19113 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
19114
19115 return SDValue();
19116}
19117
19118SDValue SITargetLowering::performClampCombine(SDNode *N,
19119 DAGCombinerInfo &DCI) const {
19120 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
19121 if (!CSrc)
19122 return SDValue();
19123
19124 const MachineFunction &MF = DCI.DAG.getMachineFunction();
19125 const APFloat &F = CSrc->getValueAPF();
19126 APFloat Zero = APFloat::getZero(F.getSemantics());
19127 if (F < Zero ||
19128 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
19129 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
19130 }
19131
19132 APFloat One = APFloat::getOne(F.getSemantics());
19133 if (F > One)
19134 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
19135
19136 return getCanonicalConstantFP(DCI.DAG, SDLoc(N), N->getValueType(0), F);
19137}
19138
19139// Check if V is the exponent result of a frexp operation. Returns the frexp
19140// input via FrexpInput if matched. We only match the exponent (not mantissa)
19141// because V_FREXP_MANT returns its input for Inf/NaN, not zero.
19142static bool isFrexpExp(SDValue V, SDValue &FrexpInput) {
19143 // ISD::FFREXP returns {mant, exp} - only match if using the exp result
19144 // (result number 1).
19145 if (V.getOpcode() == ISD::FFREXP && V.getResNo() == 1) {
19146 FrexpInput = V.getOperand(0);
19147 return true;
19148 }
19150 m_Value(FrexpInput))))
19151 return true;
19152 return false;
19153}
19154
19155SDValue
19156SITargetLowering::performFrexpSelectCombine(SDNode *N,
19157 DAGCombinerInfo &DCI) const {
19158 // This optimization only applies when the hardware handles inf/nan correctly.
19159 if (Subtarget->hasFractBug())
19160 return SDValue();
19161
19162 SDValue Cond = N->getOperand(0);
19163 SDValue TrueVal = N->getOperand(1);
19164 SDValue FalseVal = N->getOperand(2);
19165
19166 // Identify which operand is the frexp result and which is the zero constant.
19167 // Pattern 1: select cond, 0, frexp_result (cond true -> return 0)
19168 // Pattern 2: select cond, frexp_result, 0 (cond false -> return 0)
19169 SDValue FrexpVal;
19170 SDValue ZeroVal;
19171 bool CondSelectsZero; // If true, condition=true selects zero
19172
19173 // Check if FrexpVal comes from ISD::FFREXP (exponent result only) or
19174 // amdgcn_frexp_exp intrinsic.
19175 SDValue FrexpInput;
19176 if (isFrexpExp(FalseVal, FrexpInput)) {
19177 FrexpVal = FalseVal;
19178 ZeroVal = TrueVal;
19179 CondSelectsZero = true;
19180 } else if (isFrexpExp(TrueVal, FrexpInput)) {
19181 FrexpVal = TrueVal;
19182 ZeroVal = FalseVal;
19183 CondSelectsZero = false;
19184 } else {
19185 return SDValue();
19186 }
19187
19188 // frexp_exp returns integer, so check for integer zero.
19189 if (!isNullConstant(ZeroVal))
19190 return SDValue();
19191
19192 // The frexp intrinsics ignore sign, so we can strip sign ops when comparing.
19193 SDValue FrexpInputStripped = peekFPSignOps(FrexpInput);
19194
19195 bool IsNonFiniteTest = false;
19196
19197 // Handle SETCC conditions for inf/nan tests.
19198 // The canonical form of these checks is fcmp + fabs.
19199 if (Cond.getOpcode() == ISD::SETCC) {
19200 ISD::CondCode CC = Cond.getOperandCondCode(2);
19201 SDValue CondLHS = Cond.getOperand(0);
19202 SDValue CondRHS = Cond.getOperand(1);
19203
19204 // Check if LHS is fabs(FrexpInput) - required for infinity comparisons.
19205 SDValue FAbsInput;
19206 bool LHSIsFabs = sd_match(CondLHS, m_FAbs(m_Value(FAbsInput)));
19207 bool LHSMatchesFrexp =
19208 (CondLHS == FrexpInput) ||
19209 (LHSIsFabs && peekFPSignOps(FAbsInput) == FrexpInputStripped) ||
19210 (peekFPSignOps(CondLHS) == FrexpInputStripped);
19211 bool RHSMatchesFrexp = (CondRHS == FrexpInput) ||
19212 (peekFPSignOps(CondRHS) == FrexpInputStripped);
19213
19214 if (CC == ISD::SETUO) {
19215 // fcmp uno x, y - true if either x or y is NaN
19216 // We can only fold if the non-frexp operand is known to never be NaN,
19217 // otherwise the comparison could be true due to the other operand.
19218 // Special case: fcmp uno x, x (same operand) is a valid NaN test.
19219 SelectionDAG &DAG = DCI.DAG;
19220 if (LHSMatchesFrexp &&
19221 (CondLHS == CondRHS || DAG.isKnownNeverNaN(CondRHS)))
19222 IsNonFiniteTest = CondSelectsZero;
19223 else if (RHSMatchesFrexp && DAG.isKnownNeverNaN(CondLHS))
19224 IsNonFiniteTest = CondSelectsZero;
19225 } else if ((CC == ISD::SETOEQ || CC == ISD::SETUEQ) && LHSMatchesFrexp &&
19226 LHSIsFabs &&
19227 sd_match(CondRHS,
19229 CondRHS.getValueType().getFltSemantics())))) {
19230 // fcmp oeq/ueq fabs(x), +inf - true if x is inf (or inf/nan for ueq)
19231 IsNonFiniteTest = CondSelectsZero;
19232 } else if ((CC == ISD::SETONE || CC == ISD::SETUNE) && LHSMatchesFrexp &&
19233 LHSIsFabs &&
19234 sd_match(CondRHS,
19236 CondRHS.getValueType().getFltSemantics())))) {
19237 // fcmp one/une fabs(x), +inf - true if x is NOT inf
19238 IsNonFiniteTest = !CondSelectsZero;
19239 } else if (CC == ISD::SETO) {
19240 // fcmp ord x, y - true if both are NOT NaN
19241 // We can only fold if the non-frexp operand is known to never be NaN,
19242 // otherwise the comparison could be false due to the other operand.
19243 // Special case: fcmp ord x, x (same operand) is a valid not-NaN test.
19244 SelectionDAG &DAG = DCI.DAG;
19245 if (LHSMatchesFrexp &&
19246 (CondLHS == CondRHS || DAG.isKnownNeverNaN(CondRHS)))
19247 IsNonFiniteTest = !CondSelectsZero;
19248 else if (RHSMatchesFrexp && DAG.isKnownNeverNaN(CondLHS))
19249 IsNonFiniteTest = !CondSelectsZero;
19250 }
19251 }
19252
19253 if (!IsNonFiniteTest)
19254 return SDValue();
19255
19256 // The select can be eliminated - just return the frexp result directly.
19257 return FrexpVal;
19258}
19259
19260SDValue SITargetLowering::performSelectCombine(SDNode *N,
19261 DAGCombinerInfo &DCI) const {
19262
19263 // Try to fold CMP + SELECT patterns with shared constants (both FP and
19264 // integer).
19265 // Detect when CMP and SELECT use the same constant and fold them to avoid
19266 // loading the constant twice. Specifically handles patterns like:
19267 // %cmp = icmp eq i32 %val, 4242
19268 // %sel = select i1 %cmp, i32 4242, i32 %other
19269 // It can be optimized to reuse %val instead of 4242 in select.
19270 SDValue Cond = N->getOperand(0);
19271 SDValue TrueVal = N->getOperand(1);
19272 SDValue FalseVal = N->getOperand(2);
19273
19274 // Check if condition is a comparison.
19275 if (Cond.getOpcode() != ISD::SETCC)
19276 return SDValue();
19277
19278 SDValue LHS = Cond.getOperand(0);
19279 SDValue RHS = Cond.getOperand(1);
19280 ISD::CondCode CC = Cond.getOperandCondCode(2);
19281
19282 bool isFloatingPoint = LHS.getValueType().isFloatingPoint();
19283 bool isInteger = LHS.getValueType().isInteger();
19284
19285 // Handle simple floating-point and integer types only.
19286 if (!isFloatingPoint && !isInteger)
19287 return SDValue();
19288
19289 // Bare SETEQ/SETNE is the builder's NaN-impossible downgrade.
19290 bool isEquality = CC == ISD::SETEQ || (isFloatingPoint && CC == ISD::SETOEQ);
19291 bool isNonEquality =
19292 CC == ISD::SETNE || (isFloatingPoint && CC == ISD::SETONE);
19293 if (!isEquality && !isNonEquality)
19294 return SDValue();
19295
19296 SDValue ArgVal, ConstVal;
19297 if ((isFloatingPoint && isa<ConstantFPSDNode>(RHS)) ||
19298 (isInteger && isa<ConstantSDNode>(RHS))) {
19299 ConstVal = RHS;
19300 ArgVal = LHS;
19301 } else if ((isFloatingPoint && isa<ConstantFPSDNode>(LHS)) ||
19302 (isInteger && isa<ConstantSDNode>(LHS))) {
19303 ConstVal = LHS;
19304 ArgVal = RHS;
19305 } else {
19306 return SDValue();
19307 }
19308
19309 // Skip optimization for inlinable immediates.
19310 if (isFloatingPoint) {
19311 const APFloat &Val = cast<ConstantFPSDNode>(ConstVal)->getValueAPF();
19312 if (!Val.isNormal() || Subtarget->getInstrInfo()->isInlineConstant(Val))
19313 return SDValue();
19314 } else {
19315 const std::optional<int64_t> Val =
19316 cast<ConstantSDNode>(ConstVal)->getAPIntValue().trySExtValue();
19317 if (Val && AMDGPU::isInlinableIntLiteral(*Val))
19318 return SDValue();
19319 }
19320
19321 // For equality and non-equality comparisons, patterns:
19322 // select (setcc x, const), const, y -> select (setcc x, const), x, y
19323 // select (setccinv x, const), y, const -> select (setccinv x, const), y, x
19324 if (!(isEquality && TrueVal == ConstVal) &&
19325 !(isNonEquality && FalseVal == ConstVal))
19326 return SDValue();
19327
19328 // SETONE's false arm is also taken for NaN ArgVal, so require NaN excluded.
19329 if (isFloatingPoint && isNonEquality && FalseVal == ConstVal &&
19330 !Cond->getFlags().hasNoNaNs() && !DCI.DAG.isKnownNeverNaN(ArgVal))
19331 return SDValue();
19332
19333 SDValue SelectLHS = (isEquality && TrueVal == ConstVal) ? ArgVal : TrueVal;
19334 SDValue SelectRHS =
19335 (isNonEquality && FalseVal == ConstVal) ? ArgVal : FalseVal;
19336 return DCI.DAG.getNode(ISD::SELECT, SDLoc(N), N->getValueType(0), Cond,
19337 SelectLHS, SelectRHS);
19338}
19339
19341 DAGCombinerInfo &DCI) const {
19342 switch (N->getOpcode()) {
19343 case ISD::ABS:
19344 if (SDValue Res = promoteUniformUnaryOpToI32(SDValue(N, 0), DCI))
19345 return Res;
19346 break;
19347 case ISD::ADD:
19348 case ISD::SUB:
19349 case ISD::SHL:
19350 case ISD::SRL:
19351 case ISD::SRA:
19352 case ISD::AND:
19353 case ISD::OR:
19354 case ISD::XOR:
19355 case ISD::MUL:
19356 case ISD::SETCC:
19357 case ISD::SELECT:
19358 case ISD::SMIN:
19359 case ISD::SMAX:
19360 case ISD::UMIN:
19361 case ISD::UMAX:
19362 case ISD::USUBSAT:
19363 case ISD::UADDSAT:
19364 if (auto Res = promoteUniformOpToI32(SDValue(N, 0), DCI))
19365 return Res;
19366 break;
19367 case ISD::LOAD:
19368 case ISD::STORE:
19369 // TODO: Move this to LowerLOAD and LowerSTORE once the action of a
19370 // non-extending load or non-truncating store can depend on the address
19371 // space. Until then one whose action is Legal, such as i32, never reaches
19372 // them.
19374 if (SDValue V = lowerLoadStoreVGPR(SDValue(N, 0), DCI.DAG))
19375 return V;
19376 }
19377 break;
19378 default:
19379 break;
19380 }
19381
19382 if (getTargetMachine().getOptLevel() == CodeGenOptLevel::None)
19383 return SDValue();
19384
19385 switch (N->getOpcode()) {
19386 case ISD::ADD:
19387 return performAddCombine(N, DCI);
19388 case ISD::PTRADD:
19389 return performPtrAddCombine(N, DCI);
19390 case ISD::SUB:
19391 return performSubCombine(N, DCI);
19392 case ISD::FADD:
19393 return performFAddCombine(N, DCI);
19394 case ISD::FSUB:
19395 return performFSubCombine(N, DCI);
19396 case ISD::FDIV:
19397 return performFDivCombine(N, DCI);
19398 case ISD::FMUL:
19399 return performFMulCombine(N, DCI);
19400 case ISD::SETCC:
19401 return performSetCCCombine(N, DCI);
19402 case ISD::SELECT:
19403 if (auto Res = performFrexpSelectCombine(N, DCI))
19404 return Res;
19405 if (auto Res = performSelectCombine(N, DCI))
19406 return Res;
19407 break;
19408 case ISD::FMAXNUM:
19409 case ISD::FMINNUM:
19410 case ISD::FMAXNUM_IEEE:
19411 case ISD::FMINNUM_IEEE:
19412 case ISD::FMAXIMUM:
19413 case ISD::FMINIMUM:
19414 case ISD::FMAXIMUMNUM:
19415 case ISD::FMINIMUMNUM:
19416 case ISD::SMAX:
19417 case ISD::SMIN:
19418 case ISD::UMAX:
19419 case ISD::UMIN:
19420 case AMDGPUISD::FMIN_LEGACY:
19421 case AMDGPUISD::FMAX_LEGACY:
19422 return performMinMaxCombine(N, DCI);
19423 case ISD::FMA:
19424 return performFMACombine(N, DCI);
19425 case ISD::AND:
19426 return performAndCombine(N, DCI);
19427 case ISD::OR:
19428 return performOrCombine(N, DCI);
19429 case ISD::FSHR: {
19431 if (N->getValueType(0) == MVT::i32 && N->isDivergent() &&
19432 TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
19433 return matchPERM(N, DCI);
19434 }
19435 break;
19436 }
19437 case ISD::XOR:
19438 return performXorCombine(N, DCI);
19439 case ISD::ANY_EXTEND:
19440 case ISD::ZERO_EXTEND:
19441 return performZeroOrAnyExtendCombine(N, DCI);
19442 case ISD::SIGN_EXTEND:
19443 return performExtendTruncShiftCombine(N, DCI);
19445 return performSignExtendInRegCombine(N, DCI);
19446 case AMDGPUISD::FP_CLASS:
19447 return performClassCombine(N, DCI);
19448 case ISD::FCANONICALIZE:
19449 return performFCanonicalizeCombine(N, DCI);
19450 case AMDGPUISD::RCP:
19451 return performRcpCombine(N, DCI);
19452 case ISD::FLDEXP:
19453 case AMDGPUISD::FRACT:
19454 case AMDGPUISD::RSQ:
19455 case AMDGPUISD::RCP_LEGACY:
19456 case AMDGPUISD::RCP_IFLAG:
19457 case AMDGPUISD::RSQ_CLAMP: {
19458 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
19459 SDValue Src = N->getOperand(0);
19460 if (Src.isUndef())
19461 return Src;
19462 break;
19463 }
19464 case ISD::SINT_TO_FP:
19465 case ISD::UINT_TO_FP:
19466 return performUCharToFloatCombine(N, DCI);
19467 case ISD::FCOPYSIGN:
19468 return performFCopySignCombine(N, DCI);
19469 case AMDGPUISD::CVT_F32_UBYTE0:
19470 case AMDGPUISD::CVT_F32_UBYTE1:
19471 case AMDGPUISD::CVT_F32_UBYTE2:
19472 case AMDGPUISD::CVT_F32_UBYTE3:
19473 return performCvtF32UByteNCombine(N, DCI);
19474 case AMDGPUISD::FMED3:
19475 return performFMed3Combine(N, DCI);
19476 case AMDGPUISD::CVT_PKRTZ_F16_F32:
19477 return performCvtPkRTZCombine(N, DCI);
19479 if (SDValue Res = performExponentOnlyScaleCombine(N, DCI))
19480 return Res;
19481 break;
19482 case AMDGPUISD::CLAMP:
19483 return performClampCombine(N, DCI);
19484 case ISD::SCALAR_TO_VECTOR: {
19485 SelectionDAG &DAG = DCI.DAG;
19486 EVT VT = N->getValueType(0);
19487
19488 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
19489 if (VT == MVT::v2i16 || VT == MVT::v2f16 || VT == MVT::v2bf16) {
19490 SDLoc SL(N);
19491 SDValue Src = N->getOperand(0);
19492 EVT EltVT = Src.getValueType();
19493 if (EltVT != MVT::i16)
19494 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
19495
19496 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
19497 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
19498 }
19499
19500 break;
19501 }
19503 return performExtractVectorEltCombine(N, DCI);
19505 return performInsertVectorEltCombine(N, DCI);
19506 case ISD::FP_ROUND:
19507 return performFPRoundCombine(N, DCI);
19508 case ISD::LOAD: {
19509 if (SDValue Widened = widenLoad(cast<LoadSDNode>(N), DCI))
19510 return Widened;
19511 [[fallthrough]];
19512 }
19513 default: {
19514 if (!DCI.isBeforeLegalize()) {
19515 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
19516 return performMemSDNodeCombine(MemNode, DCI);
19517 }
19518
19519 break;
19520 }
19521 }
19522
19524}
19525
19526/// Helper function for adjustWritemask
19527static unsigned SubIdx2Lane(unsigned Idx) {
19528 switch (Idx) {
19529 default:
19530 return ~0u;
19531 case AMDGPU::sub0:
19532 return 0;
19533 case AMDGPU::sub1:
19534 return 1;
19535 case AMDGPU::sub2:
19536 return 2;
19537 case AMDGPU::sub3:
19538 return 3;
19539 case AMDGPU::sub4:
19540 return 4; // Possible with TFE/LWE
19541 }
19542}
19543
19544/// Adjust the writemask of MIMG, VIMAGE or VSAMPLE instructions
19545SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
19546 SelectionDAG &DAG) const {
19547 unsigned Opcode = Node->getMachineOpcode();
19548
19549 // Subtract 1 because the vdata output is not a MachineSDNode operand.
19550 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
19551 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
19552 return Node; // not implemented for D16
19553
19554 SDNode *Users[5] = {nullptr};
19555 unsigned Lane = 0;
19556 unsigned DmaskIdx =
19557 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
19558 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
19559 unsigned NewDmask = 0;
19560 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
19561 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
19562 bool UsesTFC = (int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
19563 (int(LWEIdx) >= 0 && Node->getConstantOperandVal(LWEIdx));
19564 unsigned TFCLane = 0;
19565 bool HasChain = Node->getNumValues() > 1;
19566
19567 if (OldDmask == 0) {
19568 // These are folded out, but on the chance it happens don't assert.
19569 return Node;
19570 }
19571
19572 unsigned OldBitsSet = llvm::popcount(OldDmask);
19573 // Work out which is the TFE/LWE lane if that is enabled.
19574 if (UsesTFC) {
19575 TFCLane = OldBitsSet;
19576 }
19577
19578 // Try to figure out the used register components
19579 for (SDUse &Use : Node->uses()) {
19580
19581 // Don't look at users of the chain.
19582 if (Use.getResNo() != 0)
19583 continue;
19584
19585 SDNode *User = Use.getUser();
19586
19587 // Abort if we can't understand the usage
19588 if (!User->isMachineOpcode() ||
19589 User->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
19590 return Node;
19591
19592 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
19593 // Note that subregs are packed, i.e. Lane==0 is the first bit set
19594 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
19595 // set, etc.
19596 Lane = SubIdx2Lane(User->getConstantOperandVal(1));
19597 if (Lane == ~0u)
19598 return Node;
19599
19600 // Check if the use is for the TFE/LWE generated result at VGPRn+1.
19601 if (UsesTFC && Lane == TFCLane) {
19602 Users[Lane] = User;
19603 } else {
19604 // Set which texture component corresponds to the lane.
19605 unsigned Comp;
19606 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
19607 Comp = llvm::countr_zero(Dmask);
19608 Dmask &= ~(1 << Comp);
19609 }
19610
19611 // Abort if we have more than one user per component.
19612 if (Users[Lane])
19613 return Node;
19614
19615 Users[Lane] = User;
19616 NewDmask |= 1 << Comp;
19617 }
19618 }
19619
19620 // Don't allow 0 dmask, as hardware assumes one channel enabled.
19621 bool NoChannels = !NewDmask;
19622 if (NoChannels) {
19623 if (!UsesTFC) {
19624 // No uses of the result and not using TFC. Then do nothing.
19625 return Node;
19626 }
19627 // If the original dmask has one channel - then nothing to do
19628 if (OldBitsSet == 1)
19629 return Node;
19630 // Use an arbitrary dmask - required for the instruction to work
19631 NewDmask = 1;
19632 }
19633 // Abort if there's no change
19634 if (NewDmask == OldDmask)
19635 return Node;
19636
19637 unsigned BitsSet = llvm::popcount(NewDmask);
19638
19639 // Check for TFE or LWE - increase the number of channels by one to account
19640 // for the extra return value
19641 // This will need adjustment for D16 if this is also included in
19642 // adjustWriteMask (this function) but at present D16 are excluded.
19643 unsigned NewChannels = BitsSet + UsesTFC;
19644
19645 int NewOpcode =
19646 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
19647 assert(NewOpcode != -1 &&
19648 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
19649 "failed to find equivalent MIMG op");
19650
19651 // Adjust the writemask in the node
19653 llvm::append_range(Ops, Node->ops().take_front(DmaskIdx));
19654 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
19655 llvm::append_range(Ops, Node->ops().drop_front(DmaskIdx + 1));
19656
19657 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
19658
19659 MVT ResultVT = NewChannels == 1
19660 ? SVT
19661 : MVT::getVectorVT(SVT, NewChannels == 3 ? 4
19662 : NewChannels == 5 ? 8
19663 : NewChannels);
19664 SDVTList NewVTList =
19665 HasChain ? DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
19666
19667 MachineSDNode *NewNode =
19668 DAG.getMachineNode(NewOpcode, SDLoc(Node), NewVTList, Ops);
19669
19670 if (HasChain) {
19671 // Update chain.
19672 DAG.setNodeMemRefs(NewNode, Node->memoperands());
19673 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
19674 }
19675
19676 if (NewChannels == 1) {
19677 assert(Node->hasNUsesOfValue(1, 0));
19678 SDNode *Copy =
19679 DAG.getMachineNode(TargetOpcode::COPY, SDLoc(Node),
19680 Users[Lane]->getValueType(0), SDValue(NewNode, 0));
19681 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
19682 return nullptr;
19683 }
19684
19685 // Update the users of the node with the new indices
19686 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
19687 SDNode *User = Users[i];
19688 if (!User) {
19689 // Handle the special case of NoChannels. We set NewDmask to 1 above, but
19690 // Users[0] is still nullptr because channel 0 doesn't really have a use.
19691 if (i || !NoChannels)
19692 continue;
19693 } else {
19694 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
19695 SDNode *NewUser = DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
19696 if (NewUser != User) {
19697 DAG.ReplaceAllUsesWith(SDValue(User, 0), SDValue(NewUser, 0));
19698 DAG.RemoveDeadNode(User);
19699 }
19700 }
19701
19702 switch (Idx) {
19703 default:
19704 break;
19705 case AMDGPU::sub0:
19706 Idx = AMDGPU::sub1;
19707 break;
19708 case AMDGPU::sub1:
19709 Idx = AMDGPU::sub2;
19710 break;
19711 case AMDGPU::sub2:
19712 Idx = AMDGPU::sub3;
19713 break;
19714 case AMDGPU::sub3:
19715 Idx = AMDGPU::sub4;
19716 break;
19717 }
19718 }
19719
19720 DAG.RemoveDeadNode(Node);
19721 return nullptr;
19722}
19723
19725 if (Op.getOpcode() == ISD::AssertZext)
19726 Op = Op.getOperand(0);
19727
19728 return isa<FrameIndexSDNode>(Op);
19729}
19730
19731/// Legalize target independent instructions (e.g. INSERT_SUBREG)
19732/// with frame index operands.
19733/// LLVM assumes that inputs are to these instructions are registers.
19734SDNode *
19736 SelectionDAG &DAG) const {
19737 if (Node->getOpcode() == ISD::CopyToReg) {
19738 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
19739 SDValue SrcVal = Node->getOperand(2);
19740
19741 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
19742 // to try understanding copies to physical registers.
19743 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
19744 SDLoc SL(Node);
19746 SDValue VReg = DAG.getRegister(
19747 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
19748
19749 SDNode *Glued = Node->getGluedNode();
19750 SDValue ToVReg = DAG.getCopyToReg(
19751 Node->getOperand(0), SL, VReg, SrcVal,
19752 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
19753 SDValue ToResultReg = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
19754 VReg, ToVReg.getValue(1));
19755 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
19756 DAG.RemoveDeadNode(Node);
19757 return ToResultReg.getNode();
19758 }
19759 }
19760
19762 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
19763 if (!isFrameIndexOp(Node->getOperand(i))) {
19764 Ops.push_back(Node->getOperand(i));
19765 continue;
19766 }
19767
19768 SDLoc DL(Node);
19769 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
19770 Node->getOperand(i).getValueType(),
19771 Node->getOperand(i)),
19772 0));
19773 }
19774
19775 return DAG.UpdateNodeOperands(Node, Ops);
19776}
19777
19778/// Fold the instructions after selecting them.
19779/// Returns null if users were already updated.
19781 SelectionDAG &DAG) const {
19783 unsigned Opcode = Node->getMachineOpcode();
19784
19785 if (TII->isImage(Opcode) && !TII->get(Opcode).mayStore() &&
19786 !TII->isGather4(Opcode) &&
19787 AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::dmask)) {
19788 return adjustWritemask(Node, DAG);
19789 }
19790
19791 if (Opcode == AMDGPU::INSERT_SUBREG || Opcode == AMDGPU::REG_SEQUENCE) {
19793 return Node;
19794 }
19795
19796 switch (Opcode) {
19797 case AMDGPU::V_DIV_SCALE_F32_e64:
19798 case AMDGPU::V_DIV_SCALE_F64_e64: {
19799 // Satisfy the operand register constraint when one of the inputs is
19800 // undefined. Ordinarily each undef value will have its own implicit_def of
19801 // a vreg, so force these to use a single register.
19802 SDValue Src0 = Node->getOperand(1);
19803 SDValue Src1 = Node->getOperand(3);
19804 SDValue Src2 = Node->getOperand(5);
19805
19806 if ((Src0.isMachineOpcode() &&
19807 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
19808 (Src0 == Src1 || Src0 == Src2))
19809 break;
19810
19811 MVT VT = Src0.getValueType().getSimpleVT();
19812 const TargetRegisterClass *RC =
19813 getRegClassFor(VT, Src0.getNode()->isDivergent());
19814
19816 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
19817
19818 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), UndefReg,
19819 Src0, SDValue());
19820
19821 // src0 must be the same register as src1 or src2, even if the value is
19822 // undefined, so make sure we don't violate this constraint.
19823 if (Src0.isMachineOpcode() &&
19824 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
19825 if (Src1.isMachineOpcode() &&
19826 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
19827 Src0 = Src1;
19828 else if (Src2.isMachineOpcode() &&
19829 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
19830 Src0 = Src2;
19831 else {
19832 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
19833 Src0 = UndefReg;
19834 Src1 = UndefReg;
19835 }
19836 } else
19837 break;
19838
19840 Ops[1] = Src0;
19841 Ops[3] = Src1;
19842 Ops[5] = Src2;
19843 Ops.push_back(ImpDef.getValue(1));
19844 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
19845 }
19846 default:
19847 break;
19848 }
19849
19850 return Node;
19851}
19852
19853// Any MIMG instructions that use tfe or lwe require an initialization of the
19854// result register that will be written in the case of a memory access failure.
19855// The required code is also added to tie this init code to the result of the
19856// img instruction.
19859 const SIRegisterInfo &TRI = TII->getRegisterInfo();
19860 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
19861 MachineBasicBlock &MBB = *MI.getParent();
19862
19863 int DstIdx =
19864 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
19865 unsigned InitIdx = 0;
19866
19867 if (TII->isImage(MI)) {
19868 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
19869 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
19870 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
19871
19872 if (!TFE && !LWE) // intersect_ray
19873 return;
19874
19875 unsigned TFEVal = TFE ? TFE->getImm() : 0;
19876 unsigned LWEVal = LWE ? LWE->getImm() : 0;
19877 unsigned D16Val = D16 ? D16->getImm() : 0;
19878
19879 if (!TFEVal && !LWEVal)
19880 return;
19881
19882 // At least one of TFE or LWE are non-zero
19883 // We have to insert a suitable initialization of the result value and
19884 // tie this to the dest of the image instruction.
19885
19886 // Calculate which dword we have to initialize to 0.
19887 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
19888
19889 // check that dmask operand is found.
19890 assert(MO_Dmask && "Expected dmask operand in instruction");
19891
19892 unsigned dmask = MO_Dmask->getImm();
19893 // Determine the number of active lanes taking into account the
19894 // Gather4 special case
19895 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : llvm::popcount(dmask);
19896
19897 bool Packed = !Subtarget->hasUnpackedD16VMem();
19898
19899 InitIdx = D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
19900
19901 // Abandon attempt if the dst size isn't large enough
19902 // - this is in fact an error but this is picked up elsewhere and
19903 // reported correctly.
19904 const TargetRegisterClass *DstRC = TII->getRegClass(MI.getDesc(), DstIdx);
19905
19906 uint32_t DstSize = TRI.getRegSizeInBits(*DstRC) / 32;
19907 if (DstSize < InitIdx)
19908 return;
19909 } else if (TII->isMUBUF(MI) && AMDGPU::getMUBUFTfe(MI.getOpcode())) {
19910 const TargetRegisterClass *DstRC = TII->getRegClass(MI.getDesc(), DstIdx);
19911 InitIdx = TRI.getRegSizeInBits(*DstRC) / 32;
19912 } else {
19913 return;
19914 }
19915
19916 const DebugLoc &DL = MI.getDebugLoc();
19917
19918 // Create a register for the initialization value.
19919 Register PrevDst = MRI.cloneVirtualRegister(MI.getOperand(DstIdx).getReg());
19920 unsigned NewDst = 0; // Final initialized value will be in here
19921
19922 // If PRTStrictNull feature is enabled (the default) then initialize
19923 // all the result registers to 0, otherwise just the error indication
19924 // register (VGPRn+1)
19925 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
19926 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
19927
19928 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
19929 for (; SizeLeft; SizeLeft--, CurrIdx++) {
19930 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
19931 // Initialize dword
19932 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
19933 // clang-format off
19934 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
19935 .addImm(0);
19936 // clang-format on
19937 // Insert into the super-reg
19938 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
19939 .addReg(PrevDst)
19940 .addReg(SubReg)
19942
19943 PrevDst = NewDst;
19944 }
19945
19946 // Add as an implicit operand
19947 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
19948
19949 // Tie the just added implicit operand to the dst
19950 MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
19951}
19952
19953/// Assign the register class depending on the number of
19954/// bits set in the writemask
19956 SDNode *Node) const {
19958
19959 MachineFunction *MF = MI.getMF();
19961
19962 if (TII->isVOP3(MI.getOpcode())) {
19963 // Make sure constant bus requirements are respected.
19964 TII->legalizeOperandsVOP3(MRI, MI);
19965
19966 if (TII->isMAI(MI)) {
19967 // The ordinary src0, src1, src2 were legalized above.
19968 //
19969 // We have to also legalize the appended v_mfma_ld_scale_b32 operands,
19970 // as a separate instruction.
19971 int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
19972 AMDGPU::OpName::scale_src0);
19973 if (Src0Idx != -1) {
19974 int Src1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
19975 AMDGPU::OpName::scale_src1);
19976 if (TII->usesConstantBus(MRI, MI, Src0Idx) &&
19977 TII->usesConstantBus(MRI, MI, Src1Idx))
19978 TII->legalizeOpWithMove(MI, Src1Idx);
19979 }
19980 }
19981
19982 return;
19983 }
19984
19985 if (TII->isImage(MI))
19986 TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr);
19987}
19988
19990 uint64_t Val) {
19991 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
19992 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
19993}
19994
19996 const SDLoc &DL,
19997 SDValue Ptr) const {
19999
20000 // Build the half of the subregister with the constants before building the
20001 // full 128-bit register. If we are building multiple resource descriptors,
20002 // this will allow CSEing of the 2-component register.
20003 const SDValue Ops0[] = {
20004 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
20005 buildSMovImm32(DAG, DL, 0),
20006 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
20007 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
20008 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)};
20009
20010 SDValue SubRegHi = SDValue(
20011 DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v2i32, Ops0), 0);
20012
20013 // Combine the constants and the pointer.
20014 const SDValue Ops1[] = {
20015 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), Ptr,
20016 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), SubRegHi,
20017 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)};
20018
20019 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
20020}
20021
20022/// Return a resource descriptor with the 'Add TID' bit enabled
20023/// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
20024/// of the resource descriptor) to create an offset, which is added to
20025/// the resource pointer.
20027 SDValue Ptr, uint32_t RsrcDword1,
20028 uint64_t RsrcDword2And3) const {
20029 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
20030 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
20031 if (RsrcDword1) {
20032 PtrHi = DAG.getNode(ISD::OR, DL, MVT::i32, PtrHi,
20033 DAG.getConstant(RsrcDword1, DL, MVT::i32));
20034 }
20035
20036 SDValue DataLo =
20037 buildSMovImm32(DAG, DL, RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
20038 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
20039
20040 const SDValue Ops[] = {
20041 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
20042 PtrLo,
20043 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
20044 PtrHi,
20045 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
20046 DataLo,
20047 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
20048 DataHi,
20049 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)};
20050
20051 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
20052}
20053
20054//===----------------------------------------------------------------------===//
20055// SI Inline Assembly Support
20056//===----------------------------------------------------------------------===//
20057
20058std::pair<unsigned, const TargetRegisterClass *>
20060 StringRef Constraint,
20061 MVT VT) const {
20062 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
20063
20064 const TargetRegisterClass *RC = nullptr;
20065 if (Constraint.size() == 1) {
20066 // Check if we cannot determine the bit size of the given value type. This
20067 // can happen, for example, in this situation where we have an empty struct
20068 // (size 0): `call void asm "", "v"({} poison)`-
20069 if (VT == MVT::Other)
20070 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20071 const unsigned BitWidth = VT.getSizeInBits();
20072 switch (Constraint[0]) {
20073 default:
20074 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20075 case 's':
20076 case 'r':
20077 switch (BitWidth) {
20078 case 16:
20079 RC = &AMDGPU::SReg_32RegClass;
20080 break;
20081 case 64:
20082 RC = &AMDGPU::SGPR_64RegClass;
20083 break;
20084 default:
20086 if (!RC)
20087 return std::pair(0U, nullptr);
20088 break;
20089 }
20090 break;
20091 case 'v':
20092 switch (BitWidth) {
20093 case 1:
20094 return std::pair(0U, nullptr);
20095 case 16:
20096 RC = Subtarget->useRealTrue16Insts() ? &AMDGPU::VGPR_16RegClass
20097 : &AMDGPU::VGPR_32_Lo256RegClass;
20098 break;
20099 default:
20100 RC = Subtarget->hasVGPRMSBs()
20101 ? TRI->getAlignedLo256VGPRClassForBitWidth(BitWidth)
20102 : TRI->getVGPRClassForBitWidth(BitWidth);
20103 if (!RC)
20104 return std::pair(0U, nullptr);
20105 break;
20106 }
20107 break;
20108 case 'a':
20109 if (!Subtarget->hasMAIInsts())
20110 break;
20111 switch (BitWidth) {
20112 case 1:
20113 return std::pair(0U, nullptr);
20114 case 16:
20115 RC = &AMDGPU::AGPR_32RegClass;
20116 break;
20117 default:
20118 RC = TRI->getAGPRClassForBitWidth(BitWidth);
20119 if (!RC)
20120 return std::pair(0U, nullptr);
20121 break;
20122 }
20123 break;
20124 }
20125 } else if (Constraint == "VA" && Subtarget->hasGFX90AInsts()) {
20126 const unsigned BitWidth = VT.getSizeInBits();
20127 switch (BitWidth) {
20128 case 16:
20129 RC = &AMDGPU::AV_32RegClass;
20130 break;
20131 default:
20132 RC = TRI->getVectorSuperClassForBitWidth(BitWidth);
20133 if (!RC)
20134 return std::pair(0U, nullptr);
20135 break;
20136 }
20137 }
20138
20139 // We actually support i128, i16 and f16 as inline parameters
20140 // even if they are not reported as legal
20141 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
20142 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
20143 return std::pair(0U, RC);
20144
20145 auto [Kind, Idx, NumRegs] = AMDGPU::parseAsmConstraintPhysReg(Constraint);
20146 if (Kind != '\0') {
20147 if (Kind == 'v') {
20148 RC = &AMDGPU::VGPR_32_Lo256RegClass;
20149 } else if (Kind == 's') {
20150 RC = &AMDGPU::SGPR_32RegClass;
20151 } else if (Kind == 'a') {
20152 RC = &AMDGPU::AGPR_32RegClass;
20153 }
20154
20155 if (RC) {
20156 if (NumRegs > 1) {
20157 if (Idx >= RC->getNumRegs() || Idx + NumRegs - 1 >= RC->getNumRegs())
20158 return std::pair(0U, nullptr);
20159
20160 uint32_t Width = NumRegs * 32;
20161 // Prohibit constraints for register ranges with a width that does not
20162 // match the required type.
20163 if (VT.SimpleTy != MVT::Other && Width != VT.getSizeInBits())
20164 return std::pair(0U, nullptr);
20165
20166 MCRegister Reg = RC->getRegister(Idx);
20168 RC = TRI->getVGPRClassForBitWidth(Width);
20169 else if (SIRegisterInfo::isSGPRClass(RC))
20170 RC = TRI->getSGPRClassForBitWidth(Width);
20171 else if (SIRegisterInfo::isAGPRClass(RC))
20172 RC = TRI->getAGPRClassForBitWidth(Width);
20173 if (RC) {
20174 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
20175 if (!Reg) {
20176 // The register class does not contain the requested register,
20177 // e.g., because it is an SGPR pair that would violate alignment
20178 // requirements.
20179 return std::pair(0U, nullptr);
20180 }
20181 return std::pair(Reg, RC);
20182 }
20183 }
20184
20185 // Reject types that do not fit a single 32-bit register: any scalar wider
20186 // than 32 bits, or a vector that is not exactly 32 bits.
20187 if (VT.SimpleTy != MVT::Other &&
20188 (VT.getSizeInBits() > 32 ||
20189 (VT.isVector() && VT.getSizeInBits() != 32)))
20190 return std::pair(0U, nullptr);
20191 if (RC && Idx < RC->getNumRegs())
20192 return std::pair(RC->getRegister(Idx), RC);
20193 return std::pair(0U, nullptr);
20194 }
20195 }
20196
20197 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20198 if (Ret.first) {
20199 Ret.second = TRI->getPhysRegBaseClass(Ret.first);
20200 if (!Subtarget->useRealTrue16Insts() &&
20201 TRI->getRegSizeInBits(*Ret.second) == 16)
20202 return std::pair(0U, nullptr);
20203 }
20204
20205 return Ret;
20206}
20207
20208static bool isImmConstraint(StringRef Constraint) {
20209 if (Constraint.size() == 1) {
20210 switch (Constraint[0]) {
20211 default:
20212 break;
20213 case 'I':
20214 case 'J':
20215 case 'A':
20216 case 'B':
20217 case 'C':
20218 return true;
20219 }
20220 } else if (Constraint == "DA" || Constraint == "DB") {
20221 return true;
20222 }
20223 return false;
20224}
20225
20228 if (Constraint.size() == 1) {
20229 switch (Constraint[0]) {
20230 default:
20231 break;
20232 case 's':
20233 case 'v':
20234 case 'a':
20235 return C_RegisterClass;
20236 case 'm':
20237 return C_Memory;
20238 }
20239 } else if (Constraint.size() == 2) {
20240 if (Constraint == "VA")
20241 return C_RegisterClass;
20242 if (Constraint == "RF")
20243 return C_Memory;
20244 }
20245 if (isImmConstraint(Constraint)) {
20246 return C_Other;
20247 }
20248 return TargetLowering::getConstraintType(Constraint);
20249}
20250
20253 if (ConstraintCode == "RF")
20255
20256 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
20257}
20258
20259static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
20261 Val = Val & maskTrailingOnes<uint64_t>(Size);
20262 }
20263 return Val;
20264}
20265
20267 StringRef Constraint,
20268 std::vector<SDValue> &Ops,
20269 SelectionDAG &DAG) const {
20270 if (isImmConstraint(Constraint)) {
20271 uint64_t Val;
20272 if (getAsmOperandConstVal(Op, Val) &&
20273 checkAsmConstraintVal(Op, Constraint, Val)) {
20274 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
20275 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
20276 }
20277 } else {
20279 }
20280}
20281
20283 unsigned Size = Op.getScalarValueSizeInBits();
20284 if (Size > 64)
20285 return false;
20286
20287 if (Size == 16 && !Subtarget->has16BitInsts())
20288 return false;
20289
20291 Val = C->getSExtValue();
20292 return true;
20293 }
20295 Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
20296 return true;
20297 }
20299 if (Size != 16 || Op.getNumOperands() != 2)
20300 return false;
20301 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
20302 return false;
20303 if (ConstantSDNode *C = V->getConstantSplatNode()) {
20304 Val = C->getSExtValue();
20305 return true;
20306 }
20307 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
20308 Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
20309 return true;
20310 }
20311 }
20312
20313 return false;
20314}
20315
20317 uint64_t Val) const {
20318 if (Constraint.size() == 1) {
20319 switch (Constraint[0]) {
20320 case 'I':
20322 case 'J':
20323 return isInt<16>(Val);
20324 case 'A':
20325 return checkAsmConstraintValA(Op, Val);
20326 case 'B':
20327 return isInt<32>(Val);
20328 case 'C':
20329 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
20331 default:
20332 break;
20333 }
20334 } else if (Constraint.size() == 2) {
20335 if (Constraint == "DA") {
20336 int64_t HiBits = static_cast<int32_t>(Val >> 32);
20337 int64_t LoBits = static_cast<int32_t>(Val);
20338 return checkAsmConstraintValA(Op, HiBits, 32) &&
20339 checkAsmConstraintValA(Op, LoBits, 32);
20340 }
20341 if (Constraint == "DB") {
20342 return true;
20343 }
20344 }
20345 llvm_unreachable("Invalid asm constraint");
20346}
20347
20349 unsigned MaxSize) const {
20350 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
20351 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
20352 if (Size == 16) {
20353 MVT VT = Op.getSimpleValueType();
20354 switch (VT.SimpleTy) {
20355 default:
20356 return false;
20357 case MVT::i16:
20358 return AMDGPU::isInlinableLiteralI16(Val, HasInv2Pi);
20359 case MVT::f16:
20360 return AMDGPU::isInlinableLiteralFP16(Val, HasInv2Pi);
20361 case MVT::bf16:
20362 return AMDGPU::isInlinableLiteralBF16(Val, HasInv2Pi);
20363 case MVT::v2i16:
20364 return AMDGPU::getInlineEncodingV2I16(Val).has_value();
20365 case MVT::v2f16:
20366 return AMDGPU::getInlineEncodingV2F16(Val).has_value();
20367 case MVT::v2bf16:
20368 return AMDGPU::getInlineEncodingV2BF16(Val).has_value();
20369 }
20370 }
20371 if ((Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
20372 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi)))
20373 return true;
20374 return false;
20375}
20376
20377static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
20378 switch (UnalignedClassID) {
20379 case AMDGPU::VReg_64RegClassID:
20380 return AMDGPU::VReg_64_Align2RegClassID;
20381 case AMDGPU::VReg_96RegClassID:
20382 return AMDGPU::VReg_96_Align2RegClassID;
20383 case AMDGPU::VReg_128RegClassID:
20384 return AMDGPU::VReg_128_Align2RegClassID;
20385 case AMDGPU::VReg_160RegClassID:
20386 return AMDGPU::VReg_160_Align2RegClassID;
20387 case AMDGPU::VReg_192RegClassID:
20388 return AMDGPU::VReg_192_Align2RegClassID;
20389 case AMDGPU::VReg_224RegClassID:
20390 return AMDGPU::VReg_224_Align2RegClassID;
20391 case AMDGPU::VReg_256RegClassID:
20392 return AMDGPU::VReg_256_Align2RegClassID;
20393 case AMDGPU::VReg_288RegClassID:
20394 return AMDGPU::VReg_288_Align2RegClassID;
20395 case AMDGPU::VReg_320RegClassID:
20396 return AMDGPU::VReg_320_Align2RegClassID;
20397 case AMDGPU::VReg_352RegClassID:
20398 return AMDGPU::VReg_352_Align2RegClassID;
20399 case AMDGPU::VReg_384RegClassID:
20400 return AMDGPU::VReg_384_Align2RegClassID;
20401 case AMDGPU::VReg_512RegClassID:
20402 return AMDGPU::VReg_512_Align2RegClassID;
20403 case AMDGPU::VReg_1024RegClassID:
20404 return AMDGPU::VReg_1024_Align2RegClassID;
20405 case AMDGPU::AReg_64RegClassID:
20406 return AMDGPU::AReg_64_Align2RegClassID;
20407 case AMDGPU::AReg_96RegClassID:
20408 return AMDGPU::AReg_96_Align2RegClassID;
20409 case AMDGPU::AReg_128RegClassID:
20410 return AMDGPU::AReg_128_Align2RegClassID;
20411 case AMDGPU::AReg_160RegClassID:
20412 return AMDGPU::AReg_160_Align2RegClassID;
20413 case AMDGPU::AReg_192RegClassID:
20414 return AMDGPU::AReg_192_Align2RegClassID;
20415 case AMDGPU::AReg_256RegClassID:
20416 return AMDGPU::AReg_256_Align2RegClassID;
20417 case AMDGPU::AReg_512RegClassID:
20418 return AMDGPU::AReg_512_Align2RegClassID;
20419 case AMDGPU::AReg_1024RegClassID:
20420 return AMDGPU::AReg_1024_Align2RegClassID;
20421 default:
20422 return -1;
20423 }
20424}
20425
20426// Figure out which registers should be reserved for stack access. Only after
20427// the function is legalized do we know all of the non-spill stack objects or if
20428// calls are present.
20432 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
20433 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
20434 const SIInstrInfo *TII = ST.getInstrInfo();
20435
20436 if (Info->isEntryFunction()) {
20437 // Callable functions have fixed registers used for stack access.
20439 }
20440
20441 // TODO: Move this logic to getReservedRegs()
20442 // Reserve the SGPR(s) to save/restore EXEC for WWM spill/copy handling.
20443 unsigned MaxNumSGPRs = ST.getMaxNumSGPRs(MF);
20444 Register SReg = ST.isWave32()
20445 ? AMDGPU::SGPR_32RegClass.getRegister(MaxNumSGPRs - 1)
20446 : TRI->getAlignedHighSGPRForRC(MF, /*Align=*/2,
20447 &AMDGPU::SGPR_64RegClass);
20448 Info->setSGPRForEXECCopy(SReg);
20449
20450 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
20451 Info->getStackPtrOffsetReg()));
20452 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
20453 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
20454
20455 // We need to worry about replacing the default register with itself in case
20456 // of MIR testcases missing the MFI.
20457 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
20458 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
20459
20460 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
20461 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
20462
20463 Info->limitOccupancy(MF);
20464
20465 if (ST.isWave32() && !MF.empty()) {
20466 for (auto &MBB : MF) {
20467 for (auto &MI : MBB) {
20468 TII->fixImplicitOperands(MI);
20469 }
20470 }
20471 }
20472
20473 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
20474 // classes if required. Ideally the register class constraints would differ
20475 // per-subtarget, but there's no easy way to achieve that right now. This is
20476 // not a problem for VGPRs because the correctly aligned VGPR class is implied
20477 // from using them as the register class for legal types.
20478 if (ST.needsAlignedVGPRs()) {
20479 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
20480 const Register Reg = Register::index2VirtReg(I);
20481 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
20482 if (!RC)
20483 continue;
20484 int NewClassID = getAlignedAGPRClassID(RC->getID());
20485 if (NewClassID != -1)
20486 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
20487 }
20488 }
20489
20491}
20492
20495 const APInt &DemandedElts,
20496 const SelectionDAG &DAG,
20497 unsigned Depth) const {
20498 Known.resetAll();
20499 unsigned Opc = Op.getOpcode();
20500 switch (Opc) {
20502 unsigned IID = Op.getConstantOperandVal(0);
20503 switch (IID) {
20504 case Intrinsic::amdgcn_mbcnt_lo:
20505 case Intrinsic::amdgcn_mbcnt_hi: {
20506 const GCNSubtarget &ST =
20508 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
20509 // most 31 + src1.
20510 Known.Zero.setBitsFrom(
20511 IID == Intrinsic::amdgcn_mbcnt_lo ? ST.getWavefrontSizeLog2() : 5);
20512 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(2), Depth + 1);
20513 Known = KnownBits::add(Known, Known2);
20514 return;
20515 }
20516 }
20517 break;
20518 }
20519 }
20521 Op, Known, DemandedElts, DAG, Depth);
20522}
20523
20525 KnownBits &Known, const MachineFunction &MF, Align Alignment) const {
20527
20528 // Set the high bits to zero based on the maximum allowed scratch size per
20529 // wave. We can't use vaddr in MUBUF instructions if we don't know the address
20530 // calculation won't overflow, so assume the sign bit is never set.
20531 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
20532}
20533
20536 unsigned Dim) {
20537 unsigned MaxValue =
20538 ST.getMaxWorkitemID(VT.getMachineFunction().getFunction(), Dim);
20539 Known.Zero.setHighBits(llvm::countl_zero(MaxValue));
20540}
20541
20543 KnownBits &Known, const APInt &DemandedElts,
20544 unsigned BFEWidth, bool SExt, unsigned Depth) {
20546 const MachineOperand &Src1 = MI.getOperand(2);
20547
20548 unsigned Src1Cst = 0;
20549 if (Src1.isImm()) {
20550 Src1Cst = Src1.getImm();
20551 } else if (Src1.isReg()) {
20552 auto Cst = getIConstantVRegValWithLookThrough(Src1.getReg(), MRI);
20553 if (!Cst)
20554 return;
20555 Src1Cst = Cst->Value.getZExtValue();
20556 } else {
20557 return;
20558 }
20559
20560 // Offset is at bits [4:0] for 32 bit, [5:0] for 64 bit.
20561 // Width is always [22:16].
20562 const unsigned Offset =
20563 Src1Cst & maskTrailingOnes<unsigned>((BFEWidth == 32) ? 5 : 6);
20564 const unsigned Width = (Src1Cst >> 16) & maskTrailingOnes<unsigned>(6);
20565
20566 if (Width >= BFEWidth) // Ill-formed.
20567 return;
20568
20569 VT.computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
20570 Depth + 1);
20571
20572 Known = Known.extractBits(Width, Offset);
20573
20574 if (SExt)
20575 Known = Known.sext(BFEWidth);
20576 else
20577 Known = Known.zext(BFEWidth);
20578}
20579
20582 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
20583 unsigned Depth) const {
20584 Known.resetAll();
20585 const MachineInstr *MI = MRI.getVRegDef(R);
20586 switch (MI->getOpcode()) {
20587 case AMDGPU::S_BFE_I32:
20588 return knownBitsForSBFE(*MI, VT, Known, DemandedElts, /*Width=*/32,
20589 /*SExt=*/true, Depth);
20590 case AMDGPU::S_BFE_U32:
20591 return knownBitsForSBFE(*MI, VT, Known, DemandedElts, /*Width=*/32,
20592 /*SExt=*/false, Depth);
20593 case AMDGPU::S_BFE_I64:
20594 return knownBitsForSBFE(*MI, VT, Known, DemandedElts, /*Width=*/64,
20595 /*SExt=*/true, Depth);
20596 case AMDGPU::S_BFE_U64:
20597 return knownBitsForSBFE(*MI, VT, Known, DemandedElts, /*Width=*/64,
20598 /*SExt=*/false, Depth);
20599 case AMDGPU::G_INTRINSIC:
20600 case AMDGPU::G_INTRINSIC_CONVERGENT: {
20601 Intrinsic::ID IID = cast<GIntrinsic>(MI)->getIntrinsicID();
20602 switch (IID) {
20603 case Intrinsic::amdgcn_workitem_id_x:
20605 break;
20606 case Intrinsic::amdgcn_workitem_id_y:
20608 break;
20609 case Intrinsic::amdgcn_workitem_id_z:
20611 break;
20612 case Intrinsic::amdgcn_mbcnt_lo:
20613 case Intrinsic::amdgcn_mbcnt_hi: {
20614 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
20615 // most 31 + src1.
20616 Known.Zero.setBitsFrom(IID == Intrinsic::amdgcn_mbcnt_lo
20617 ? getSubtarget()->getWavefrontSizeLog2()
20618 : 5);
20619 KnownBits Known2;
20620 VT.computeKnownBitsImpl(MI->getOperand(3).getReg(), Known2, DemandedElts,
20621 Depth + 1);
20622 Known = KnownBits::add(Known, Known2);
20623 break;
20624 }
20625 case Intrinsic::amdgcn_groupstaticsize: {
20626 // We can report everything over the maximum size as 0. We can't report
20627 // based on the actual size because we don't know if it's accurate or not
20628 // at any given point.
20629 Known.Zero.setHighBits(
20630 llvm::countl_zero(getSubtarget()->getAddressableLocalMemorySize()));
20631 break;
20632 }
20633 case Intrinsic::amdgcn_readfirstlane:
20634 case Intrinsic::amdgcn_readlane: {
20635 // Result is the data operand's value from some lane.
20636 VT.computeKnownBitsImpl(MI->getOperand(2).getReg(), Known, DemandedElts,
20637 Depth + 1);
20638 break;
20639 }
20640 case Intrinsic::amdgcn_mul_u24:
20641 case Intrinsic::amdgcn_mul_i24: {
20642 Register LHS = MI->getOperand(2).getReg();
20643 Register RHS = MI->getOperand(3).getReg();
20644
20645 KnownBits RHSKnown;
20646 VT.computeKnownBitsImpl(RHS, RHSKnown, DemandedElts, Depth + 1);
20647
20648 bool SelfMultiply = LHS == RHS;
20649
20650 // For a self-multiply both operands are the same value, so RHSKnown also
20651 // describes the LHS; avoid the duplicated query.
20652 KnownBits LHSKnown;
20653 if (SelfMultiply)
20654 LHSKnown = RHSKnown;
20655 else
20656 VT.computeKnownBitsImpl(LHS, LHSKnown, DemandedElts, Depth + 1);
20657
20658 if (SelfMultiply)
20659 SelfMultiply &= isGuaranteedNotToBeUndef(LHS, MRI, Depth + 1);
20660
20661 Known = computeKnownBitsForMul24(LHSKnown, RHSKnown, Known.getBitWidth(),
20662 IID == Intrinsic::amdgcn_mul_i24,
20663 SelfMultiply);
20664 break;
20665 }
20666 }
20667 break;
20668 }
20669 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
20670 Known.Zero.setHighBits(24);
20671 break;
20672 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
20673 Known.Zero.setHighBits(16);
20674 break;
20675 case AMDGPU::G_AMDGPU_COPY_SCC_VCC:
20676 // G_AMDGPU_COPY_SCC_VCC converts a uniform boolean in VCC to SGPR s32,
20677 // producing exactly 0 or 1.
20678 Known.Zero.setHighBits(Known.getBitWidth() - 1);
20679 break;
20680 case AMDGPU::G_AMDGPU_SMED3:
20681 case AMDGPU::G_AMDGPU_UMED3: {
20682 auto [Dst, Src0, Src1, Src2] = MI->getFirst4Regs();
20683
20684 KnownBits Known2;
20685 VT.computeKnownBitsImpl(Src2, Known2, DemandedElts, Depth + 1);
20686 if (Known2.isUnknown())
20687 break;
20688
20689 KnownBits Known1;
20690 VT.computeKnownBitsImpl(Src1, Known1, DemandedElts, Depth + 1);
20691 if (Known1.isUnknown())
20692 break;
20693
20694 KnownBits Known0;
20695 VT.computeKnownBitsImpl(Src0, Known0, DemandedElts, Depth + 1);
20696 if (Known0.isUnknown())
20697 break;
20698
20699 // TODO: Handle LeadZero/LeadOne from UMIN/UMAX handling.
20700 Known.Zero = Known0.Zero & Known1.Zero & Known2.Zero;
20701 Known.One = Known0.One & Known1.One & Known2.One;
20702 break;
20703 }
20704 }
20705}
20706
20709 unsigned Depth) const {
20710 const MachineInstr *MI = MRI.getVRegDef(R);
20711 if (auto *GI = dyn_cast<GIntrinsic>(MI)) {
20712 // FIXME: Can this move to generic code? What about the case where the call
20713 // site specifies a lower alignment?
20714 Intrinsic::ID IID = GI->getIntrinsicID();
20716 AttributeList Attrs =
20717 Intrinsic::getAttributes(Ctx, IID, Intrinsic::getType(Ctx, IID));
20718 if (MaybeAlign RetAlign = Attrs.getRetAlignment())
20719 return *RetAlign;
20720 }
20721 return Align(1);
20722}
20723
20725 MachineLoop *ML, const MachineBasicBlock *BlockToAlign) const {
20727 const Align CacheLineAlign = Align(64);
20728
20729 // GFX950: Prevent an 8-byte instruction at the block being aligned from being
20730 // split by the 32-byte instruction fetch window boundary. This avoids a
20731 // significant fetch delay after a backward branch. We use 32-byte alignment
20732 // with max padding of 4 bytes (one s_nop), see
20733 // getMaxPermittedBytesForAlignment().
20734 if (ML && getSubtarget()->getCLOpts().loop_alignment &&
20735 getSubtarget()->hasLoopHeadInstSplitSensitivity()) {
20736 // Loop rotation can make the backedge destination a block other than the
20737 // LoopInfo header, so prefer the block the caller is actually aligning.
20738 if (!BlockToAlign)
20739 BlockToAlign = ML->getHeader();
20740 // Respect user-specified or previously set alignment.
20741 if (BlockToAlign->getAlignment() != PrefAlign)
20742 return BlockToAlign->getAlignment();
20743 if (needsFetchWindowAlignment(*BlockToAlign))
20744 return Align(32);
20745 }
20746
20747 // Pre-GFX10 target did not benefit from loop alignment
20748 if (!ML || !getSubtarget()->getCLOpts().loop_alignment ||
20749 !getSubtarget()->hasInstPrefetch() ||
20750 getSubtarget()->hasInstFwdPrefetchBug())
20751 return PrefAlign;
20752
20753 // On GFX10 I$ is 4 x 64 bytes cache lines.
20754 // By default prefetcher keeps one cache line behind and reads two ahead.
20755 // We can modify it with S_INST_PREFETCH for larger loops to have two lines
20756 // behind and one ahead.
20757 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
20758 // If loop fits 64 bytes it always spans no more than two cache lines and
20759 // does not need an alignment.
20760 // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
20761 // Else if loop is less or equal 192 bytes we need two lines behind.
20762
20764 const MachineBasicBlock *Header = ML->getHeader();
20765 if (Header->getAlignment() != PrefAlign)
20766 return Header->getAlignment(); // Already processed.
20767
20768 unsigned LoopSize = 0;
20769 for (const MachineBasicBlock *MBB : ML->blocks()) {
20770 // If inner loop block is aligned assume in average half of the alignment
20771 // size to be added as nops.
20772 if (MBB != Header)
20773 LoopSize += MBB->getAlignment().value() / 2;
20774
20775 for (const MachineInstr &MI : *MBB) {
20776 LoopSize += TII->getInstSizeInBytes(MI);
20777 if (LoopSize > 192)
20778 return PrefAlign;
20779 }
20780 }
20781
20782 if (LoopSize <= 64)
20783 return PrefAlign;
20784
20785 if (LoopSize <= 128)
20786 return CacheLineAlign;
20787
20788 // If any of parent loops is surrounded by prefetch instructions do not
20789 // insert new for inner loop, which would reset parent's settings.
20790 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
20791 if (MachineBasicBlock *Exit = P->getExitBlock()) {
20792 auto I = Exit->getFirstNonDebugInstr();
20793 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
20794 return CacheLineAlign;
20795 }
20796 }
20797
20798 MachineBasicBlock *Pre = ML->getLoopPreheader();
20799 MachineBasicBlock *Exit = ML->getExitBlock();
20800
20801 if (Pre && Exit) {
20802 auto PreTerm = Pre->getFirstTerminator();
20803 if (PreTerm == Pre->begin() ||
20804 std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
20805 BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
20806 .addImm(1); // prefetch 2 lines behind PC
20807
20808 auto ExitHead = Exit->getFirstNonDebugInstr();
20809 if (ExitHead == Exit->end() ||
20810 ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
20811 BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
20812 .addImm(2); // prefetch 1 line behind PC
20813 }
20814
20815 return CacheLineAlign;
20816}
20817
20819 MachineBasicBlock *MBB) const {
20820 // GFX950: Limit padding to 4 bytes (one s_nop) for blocks where an 8-byte
20821 // instruction could be split by the 32-byte fetch window boundary.
20822 // See getPrefLoopAlignment() for context.
20823 if (needsFetchWindowAlignment(*MBB))
20824 return 4;
20826}
20827
20828bool SITargetLowering::needsFetchWindowAlignment(
20829 const MachineBasicBlock &MBB) const {
20830 if (!getSubtarget()->hasLoopHeadInstSplitSensitivity())
20831 return false;
20833 for (const MachineInstr &MI : MBB) {
20834 if (MI.isMetaInstruction())
20835 continue;
20836 // Instructions larger than 4 bytes can be split by a 32-byte boundary.
20837 return TII->getInstSizeInBytes(MI) > 4;
20838 }
20839 return false;
20840}
20841
20842[[maybe_unused]]
20843static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
20844 assert(N->getOpcode() == ISD::CopyFromReg);
20845 do {
20846 // Follow the chain until we find an INLINEASM node.
20847 N = N->getOperand(0).getNode();
20848 if (N->getOpcode() == ISD::INLINEASM || N->getOpcode() == ISD::INLINEASM_BR)
20849 return true;
20850 } while (N->getOpcode() == ISD::CopyFromReg);
20851 return false;
20852}
20853
20856 UniformityInfo *UA) const {
20857 switch (N->getOpcode()) {
20858 case ISD::CopyFromReg: {
20859 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
20860 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
20861 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
20862 Register Reg = R->getReg();
20863
20864 // FIXME: Why does this need to consider isLiveIn?
20865 if (Reg.isPhysical() || MRI.isLiveIn(Reg))
20866 return !TRI->isSGPRReg(MRI, Reg);
20867
20868 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
20869 return UA->isDivergentAtDef(V);
20870
20872 return !TRI->isSGPRReg(MRI, Reg);
20873 }
20874 case ISD::LOAD: {
20875 const LoadSDNode *L = cast<LoadSDNode>(N);
20876 unsigned AS = L->getAddressSpace();
20877 // A flat load may access private memory, and a VGPR load reads each lane's
20878 // own registers.
20879 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS ||
20880 AS == AMDGPUAS::VGPR;
20881 }
20882 // As above, after the pre-ISel combine.
20883 case AMDGPUISD::REG_LOAD:
20884 return true;
20885 case ISD::CALLSEQ_END:
20886 return true;
20888 return AMDGPU::isIntrinsicSourceOfDivergence(N->getConstantOperandVal(0));
20890 return AMDGPU::isIntrinsicSourceOfDivergence(N->getConstantOperandVal(1));
20891 case AMDGPUISD::ATOMIC_CMP_SWAP:
20892 case AMDGPUISD::BUFFER_ATOMIC_SWAP:
20893 case AMDGPUISD::BUFFER_ATOMIC_ADD:
20894 case AMDGPUISD::BUFFER_ATOMIC_SUB:
20895 case AMDGPUISD::BUFFER_ATOMIC_SMIN:
20896 case AMDGPUISD::BUFFER_ATOMIC_UMIN:
20897 case AMDGPUISD::BUFFER_ATOMIC_SMAX:
20898 case AMDGPUISD::BUFFER_ATOMIC_UMAX:
20899 case AMDGPUISD::BUFFER_ATOMIC_AND:
20900 case AMDGPUISD::BUFFER_ATOMIC_OR:
20901 case AMDGPUISD::BUFFER_ATOMIC_XOR:
20902 case AMDGPUISD::BUFFER_ATOMIC_INC:
20903 case AMDGPUISD::BUFFER_ATOMIC_DEC:
20904 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
20905 case AMDGPUISD::BUFFER_ATOMIC_FADD:
20906 case AMDGPUISD::BUFFER_ATOMIC_FMIN:
20907 case AMDGPUISD::BUFFER_ATOMIC_FMAX:
20908 // Target-specific read-modify-write atomics are sources of divergence.
20909 return true;
20910 default:
20911 if (auto *A = dyn_cast<AtomicSDNode>(N)) {
20912 // Generic read-modify-write atomics are sources of divergence.
20913 return A->readMem() && A->writeMem();
20914 }
20915 return false;
20916 }
20917}
20918
20920 EVT VT) const {
20921 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
20922 case MVT::f32:
20924 case MVT::f64:
20925 case MVT::f16:
20927 default:
20928 return false;
20929 }
20930}
20931
20933 LLT Ty, const MachineFunction &MF) const {
20934 switch (Ty.getScalarSizeInBits()) {
20935 case 32:
20936 return !denormalModeIsFlushAllF32(MF);
20937 case 64:
20938 case 16:
20939 return !denormalModeIsFlushAllF64F16(MF);
20940 default:
20941 return false;
20942 }
20943}
20944
20946 const APInt &DemandedElts,
20947 const SelectionDAG &DAG,
20948 bool SNaN,
20949 unsigned Depth) const {
20950 if (Op.getOpcode() == AMDGPUISD::CLAMP) {
20951 const MachineFunction &MF = DAG.getMachineFunction();
20953
20954 if (Info->getMode().DX10Clamp)
20955 return true; // Clamped to 0.
20956 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
20957 }
20958
20960 DAG, SNaN, Depth);
20961}
20962
20963namespace {
20964
20965/// Why a floating-point atomic instruction which may flush denormals is
20966/// acceptable.
20967enum class AtomicFlushDenormalReason {
20968 Native,
20969 IEEE,
20970 IgnoreDenormalMode,
20971 FunctionFlushesDenormals
20972};
20973
20974/// Why a native floating-point atomic instruction is acceptable for a global
20975/// memory address.
20976enum class GlobalFPAtomicLegality {
20977 Illegal,
20978 AgentScopeFineGrainedRemoteMemory,
20979 EmulatedSystemScope,
20980 NoRemoteMemory,
20981 NoFineGrainedMemory
20982};
20983
20984} // end anonymous namespace
20985
20986// On older subtargets, global FP atomic instructions have a hardcoded FP mode
20987// and do not support FP32 denormals, and only support v2f16/f64 denormals.
20988static AtomicFlushDenormalReason
20990 if (RMW->hasMetadata(LLVMContext::MD_atomic_ignore_denormal_mode))
20991 return AtomicFlushDenormalReason::IgnoreDenormalMode;
20992
20993 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
20994 auto DenormMode = RMW->getFunction()->getDenormalMode(Flt);
20995 return DenormMode == DenormalMode::getPreserveSign()
20996 ? AtomicFlushDenormalReason::FunctionFlushesDenormals
20997 : AtomicFlushDenormalReason::IEEE;
20998}
20999
21000static OptimizationRemark
21002 GlobalFPAtomicLegality MemLegality,
21003 AtomicFlushDenormalReason DenormReason) {
21004 LLVMContext &Ctx = RMW->getContext();
21005 StringRef MemScope = Ctx.getSyncScopeName(RMW->getSyncScopeID()).value_or("");
21006 if (MemScope.empty())
21007 MemScope = "system";
21008
21009 OptimizationRemark R(DEBUG_TYPE, "Passed", RMW);
21010 R << "hardware instruction generated for atomic "
21011 << ore::NV("Operation", RMW->getOperationName(RMW->getOperation()))
21012 << " at " << ore::NV("SyncScope", MemScope) << " scope since ";
21013
21014 switch (MemLegality) {
21015 case GlobalFPAtomicLegality::AgentScopeFineGrainedRemoteMemory:
21016 R << "fine-grained remote memory atomics work below system scope";
21017 break;
21018 case GlobalFPAtomicLegality::EmulatedSystemScope:
21019 R << "system scope atomics are emulated in hardware";
21020 break;
21021 case GlobalFPAtomicLegality::NoRemoteMemory:
21022 R << "memory is not remote (!amdgpu.no.remote.memory)";
21023 break;
21024 case GlobalFPAtomicLegality::NoFineGrainedMemory:
21025 R << "memory is not fine-grained (!amdgpu.no.fine.grained.memory)";
21026 break;
21027 case GlobalFPAtomicLegality::Illegal:
21028 llvm_unreachable("remark for illegal atomic");
21029 }
21030
21031 switch (DenormReason) {
21032 case AtomicFlushDenormalReason::Native:
21033 break;
21034 case AtomicFlushDenormalReason::IgnoreDenormalMode:
21035 R << ", and denormals may be flushed (!atomic.ignore.denormal.mode)";
21036 break;
21037 case AtomicFlushDenormalReason::FunctionFlushesDenormals:
21038 R << ", and the floating-point environment flushes denormals";
21039 break;
21040 case AtomicFlushDenormalReason::IEEE:
21041 llvm_unreachable("remark for illegal atomic");
21042 }
21043
21044 return R;
21045}
21046
21047static bool isV2F16OrV2BF16(Type *Ty) {
21048 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
21049 Type *EltTy = VT->getElementType();
21050 return VT->getNumElements() == 2 &&
21051 (EltTy->isHalfTy() || EltTy->isBFloatTy());
21052 }
21053
21054 return false;
21055}
21056
21057static bool isV2F16(Type *Ty) {
21059 return VT && VT->getNumElements() == 2 && VT->getElementType()->isHalfTy();
21060}
21061
21062static bool isV2BF16(Type *Ty) {
21064 return VT && VT->getNumElements() == 2 && VT->getElementType()->isBFloatTy();
21065}
21066
21067/// \return true if atomicrmw integer ops work for the type.
21068static bool isAtomicRMWLegalIntTy(Type *Ty) {
21069 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
21070 unsigned BW = IT->getBitWidth();
21071 return BW == 32 || BW == 64;
21072 }
21073
21074 return false;
21075}
21076
21077/// \return true if this atomicrmw xchg type can be selected.
21078static bool isAtomicRMWLegalXChgTy(const AtomicRMWInst *RMW) {
21079 Type *Ty = RMW->getType();
21080 if (isAtomicRMWLegalIntTy(Ty))
21081 return true;
21082
21083 if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
21084 const DataLayout &DL = RMW->getFunction()->getDataLayout();
21085 unsigned BW = DL.getPointerSizeInBits(PT->getAddressSpace());
21086 return BW == 32 || BW == 64;
21087 }
21088
21089 if (Ty->isFloatTy() || Ty->isDoubleTy())
21090 return true;
21091
21093 return VT->getNumElements() == 2 &&
21094 VT->getElementType()->getPrimitiveSizeInBits() == 16;
21095 }
21096
21097 return false;
21098}
21099
21100/// \returns whether it's valid to emit a native instruction for \p RMW, and
21101/// why, based on the properties of the target memory.
21102static GlobalFPAtomicLegality
21104 const AtomicRMWInst *RMW, bool HasSystemScope) {
21105 // The remote/fine-grained access logic is different from the integer
21106 // atomics. Without AgentScopeFineGrainedRemoteMemoryAtomics support,
21107 // fine-grained access does not work, even for a device local allocation.
21108 //
21109 // With AgentScopeFineGrainedRemoteMemoryAtomics, system scoped device local
21110 // allocations work.
21111 if (HasSystemScope) {
21112 if (Subtarget.hasAgentScopeFineGrainedRemoteMemoryAtomics() &&
21113 RMW->hasMetadata("amdgpu.no.remote.memory"))
21114 return GlobalFPAtomicLegality::NoRemoteMemory;
21115 if (Subtarget.hasEmulatedSystemScopeAtomics())
21116 return GlobalFPAtomicLegality::EmulatedSystemScope;
21117 } else if (Subtarget.hasAgentScopeFineGrainedRemoteMemoryAtomics())
21118 return GlobalFPAtomicLegality::AgentScopeFineGrainedRemoteMemory;
21119
21120 return RMW->hasMetadata("amdgpu.no.fine.grained.memory")
21121 ? GlobalFPAtomicLegality::NoFineGrainedMemory
21122 : GlobalFPAtomicLegality::Illegal;
21123}
21124
21125/// \return Action to perform on AtomicRMWInsts for integer operations.
21132
21133/// Return if a flat address space atomicrmw can access private memory.
21135 const MDNode *MD = I->getMetadata(LLVMContext::MD_noalias_addrspace);
21136 return !MD ||
21138}
21139
21142 // For GAS, lower to flat atomic.
21143 return STI.hasGloballyAddressableScratch()
21146}
21147
21150 unsigned AS = RMW->getPointerAddressSpace();
21151 if (AS == AMDGPUAS::PRIVATE_ADDRESS)
21153
21154 // Only the executing lane can access its view of the VGPRs, so as with
21155 // private memory there is nothing to be atomic with respect to.
21156 if (AS == AMDGPUAS::VGPR)
21158
21159 // 64-bit flat atomics that dynamically reside in private memory will silently
21160 // be dropped.
21161 //
21162 // Note that we will emit a new copy of the original atomic in the expansion,
21163 // which will be incrementally relegalized.
21164 const DataLayout &DL = RMW->getFunction()->getDataLayout();
21165 if (AS == AMDGPUAS::FLAT_ADDRESS &&
21166 DL.getTypeSizeInBits(RMW->getType()) == 64 &&
21169
21170 GlobalFPAtomicLegality MemLegality = GlobalFPAtomicLegality::Illegal;
21171 AtomicFlushDenormalReason DenormReason = AtomicFlushDenormalReason::Native;
21172 auto ReportHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
21174 ORE.emit([&]() {
21175 return emitAtomicRMWLegalRemark(RMW, MemLegality, DenormReason);
21176 });
21177 return Kind;
21178 };
21179
21180 auto SSID = RMW->getSyncScopeID();
21181 bool HasSystemScope =
21182 SSID == SyncScope::System ||
21184 getTargetMachine().getTargetTriple(), AtomicScope::System,
21185 /*OneAddressSpace=*/true));
21186
21187 auto Op = RMW->getOperation();
21188 switch (Op) {
21190 // PCIe supports add and xchg for system atomics.
21191 return isAtomicRMWLegalXChgTy(RMW)
21194 case AtomicRMWInst::Add:
21195 // PCIe supports add and xchg for system atomics.
21197 case AtomicRMWInst::Sub:
21198 case AtomicRMWInst::And:
21199 case AtomicRMWInst::Or:
21200 case AtomicRMWInst::Xor:
21201 case AtomicRMWInst::Max:
21202 case AtomicRMWInst::Min:
21209 if (Op == AtomicRMWInst::USubCond && !Subtarget->hasCondSubInsts())
21211 if (Op == AtomicRMWInst::USubSat) {
21212 // The global and buffer forms predate the LDS and flat ones.
21213 if (!Subtarget->hasSubClampInsts() ||
21214 (AS == AMDGPUAS::LOCAL_ADDRESS &&
21215 !Subtarget->hasAtomicDsCondSubClampInsts()) ||
21216 (AS == AMDGPUAS::FLAT_ADDRESS &&
21217 !Subtarget->hasAtomicCondSubClampFlatInsts()))
21219 }
21221 auto *IT = dyn_cast<IntegerType>(RMW->getType());
21222 if (!IT || IT->getBitWidth() != 32)
21224 }
21225
21228 if (Subtarget->hasEmulatedSystemScopeAtomics())
21230
21231 // On most subtargets, for atomicrmw operations other than add/xchg,
21232 // whether or not the instructions will behave correctly depends on where
21233 // the address physically resides and what interconnect is used in the
21234 // system configuration. On some some targets the instruction will nop,
21235 // and in others synchronization will only occur at degraded device scope.
21236 //
21237 // If the allocation is known local to the device, the instructions should
21238 // work correctly.
21239 if (RMW->hasMetadata("amdgpu.no.remote.memory"))
21241
21242 // If fine-grained remote memory works at device scope, we don't need to
21243 // do anything.
21244 if (!HasSystemScope &&
21245 Subtarget->hasAgentScopeFineGrainedRemoteMemoryAtomics())
21247
21248 // If we are targeting a remote allocated address, it depends what kind of
21249 // allocation the address belongs to.
21250 //
21251 // If the allocation is fine-grained (in host memory, or in PCIe peer
21252 // device memory), the operation will fail depending on the target.
21253 //
21254 // Note fine-grained host memory access does work on APUs or if XGMI is
21255 // used, but we do not know if we are targeting an APU or the system
21256 // configuration from the ISA version/target-cpu.
21257 if (RMW->hasMetadata("amdgpu.no.fine.grained.memory"))
21259
21262 // Atomic sub/or/xor do not work over PCI express, but atomic add
21263 // does. InstCombine transforms these with 0 to or, so undo that.
21264 // Sub-word types are not selectable and take the cmpxchg expansion.
21265 if (const Constant *ConstVal = dyn_cast<Constant>(RMW->getValOperand());
21266 ConstVal && ConstVal->isNullValue() &&
21269 }
21270
21271 // If the allocation could be in remote, fine-grained memory, the rmw
21272 // instructions may fail. cmpxchg should work, so emit that. On some
21273 // system configurations, PCIe atomics aren't supported so cmpxchg won't
21274 // even work, so you're out of luck anyway.
21275
21276 // In summary:
21277 //
21278 // Cases that may fail:
21279 // - fine-grained pinned host memory
21280 // - fine-grained migratable host memory
21281 // - fine-grained PCIe peer device
21282 //
21283 // Cases that should work, but may be treated overly conservatively.
21284 // - fine-grained host memory on an APU
21285 // - fine-grained XGMI peer device
21287 }
21288
21290 }
21291 case AtomicRMWInst::FAdd: {
21292 Type *Ty = RMW->getType();
21293
21294 // TODO: Handle REGION_ADDRESS
21295 if (AS == AMDGPUAS::LOCAL_ADDRESS) {
21296 // DS F32 FP atomics do respect the denormal mode, but the rounding mode
21297 // is fixed to round-to-nearest-even.
21298 //
21299 // F64 / PK_F16 / PK_BF16 never flush and are also fixed to
21300 // round-to-nearest-even.
21301 //
21302 // We ignore the rounding mode problem, even in strictfp. The C++ standard
21303 // suggests it is OK if the floating-point mode may not match the calling
21304 // thread.
21305 if (Ty->isFloatTy()) {
21306 return Subtarget->hasLDSFPAtomicAddF32() ? AtomicExpansionKind::None
21308 }
21309
21310 if (Ty->isDoubleTy()) {
21311 // Ignores denormal mode, but we don't consider flushing mandatory.
21312 return Subtarget->hasLdsAtomicAddF64() ? AtomicExpansionKind::None
21314 }
21315
21316 if (Subtarget->hasAtomicDsPkAdd16Insts() && isV2F16OrV2BF16(Ty))
21318
21320 }
21321
21322 // LDS atomics respect the denormal mode from the mode register.
21323 //
21324 // Traditionally f32 global/buffer memory atomics would unconditionally
21325 // flush denormals, but newer targets do not flush. f64/f16/bf16 cases never
21326 // flush.
21327 //
21328 // On targets with flat atomic fadd, denormals would flush depending on
21329 // whether the target address resides in LDS or global memory. We consider
21330 // this flat-maybe-flush as will-flush.
21331 if (Ty->isFloatTy() &&
21332 !Subtarget->hasMemoryAtomicFaddF32DenormalSupport()) {
21333 DenormReason = getAtomicFlushDenormalReason(RMW);
21334 if (DenormReason == AtomicFlushDenormalReason::IEEE)
21336 }
21337
21338 MemLegality =
21339 getGlobalMemoryFPAtomicLegality(*Subtarget, RMW, HasSystemScope);
21340 if (MemLegality != GlobalFPAtomicLegality::Illegal) {
21341 if (AS == AMDGPUAS::FLAT_ADDRESS) {
21342 // gfx942, gfx12
21343 if (Subtarget->hasAtomicFlatPkAdd16Insts() && isV2F16OrV2BF16(Ty))
21344 return ReportHWInst(AtomicExpansionKind::None);
21345 } else if (AMDGPU::isExtendedGlobalAddrSpace(AS)) {
21346 // gfx90a, gfx942, gfx12
21347 if (Subtarget->hasAtomicBufferGlobalPkAddF16Insts() && isV2F16(Ty))
21348 return ReportHWInst(AtomicExpansionKind::None);
21349
21350 // gfx942, gfx12
21351 if (Subtarget->hasAtomicGlobalPkAddBF16Inst() && isV2BF16(Ty))
21352 return ReportHWInst(AtomicExpansionKind::None);
21353 } else if (AS == AMDGPUAS::BUFFER_FAT_POINTER) {
21354 // gfx90a, gfx942, gfx12
21355 if (Subtarget->hasAtomicBufferGlobalPkAddF16Insts() && isV2F16(Ty))
21356 return ReportHWInst(AtomicExpansionKind::None);
21357
21358 // While gfx90a/gfx942 supports v2bf16 for global/flat, it does not for
21359 // buffer. gfx12 does have the buffer version.
21360 if (Subtarget->hasAtomicBufferPkAddBF16Inst() && isV2BF16(Ty))
21361 return ReportHWInst(AtomicExpansionKind::None);
21362 }
21363
21364 // global and flat atomic fadd f64: gfx90a, gfx942.
21365 if (Subtarget->hasFlatBufferGlobalAtomicFaddF64Inst() && Ty->isDoubleTy())
21366 return ReportHWInst(AtomicExpansionKind::None);
21367
21368 if (AS != AMDGPUAS::FLAT_ADDRESS) {
21369 if (Ty->isFloatTy()) {
21370 // global/buffer atomic fadd f32 no-rtn: gfx908, gfx90a, gfx942,
21371 // gfx11+.
21372 if (RMW->use_empty() && Subtarget->hasAtomicFaddNoRtnInsts())
21373 return ReportHWInst(AtomicExpansionKind::None);
21374 // global/buffer atomic fadd f32 rtn: gfx90a, gfx942, gfx11+.
21375 if (!RMW->use_empty() && Subtarget->hasAtomicFaddRtnInsts())
21376 return ReportHWInst(AtomicExpansionKind::None);
21377 } else {
21378 // gfx908
21379 if (RMW->use_empty() &&
21380 Subtarget->hasAtomicBufferGlobalPkAddF16NoRtnInsts() &&
21381 isV2F16(Ty))
21382 return ReportHWInst(AtomicExpansionKind::None);
21383 }
21384 }
21385
21386 // flat atomic fadd f32: gfx942, gfx11+.
21387 if (AS == AMDGPUAS::FLAT_ADDRESS && Ty->isFloatTy()) {
21388 if (Subtarget->hasFlatAtomicFaddF32Inst())
21389 return ReportHWInst(AtomicExpansionKind::None);
21390
21391 // If it is in flat address space, and the type is float, we will try to
21392 // expand it, if the target supports global and lds atomic fadd. The
21393 // reason we need that is, in the expansion, we emit the check of
21394 // address space. If it is in global address space, we emit the global
21395 // atomic fadd; if it is in shared address space, we emit the LDS atomic
21396 // fadd.
21397 if (Subtarget->hasLDSFPAtomicAddF32()) {
21398 if (RMW->use_empty() && Subtarget->hasAtomicFaddNoRtnInsts())
21400 if (!RMW->use_empty() && Subtarget->hasAtomicFaddRtnInsts())
21402 }
21403 }
21404 }
21405
21407 }
21409 case AtomicRMWInst::FMax: {
21410 Type *Ty = RMW->getType();
21411
21412 // LDS float and double fmin/fmax were always supported.
21413 if (AS == AMDGPUAS::LOCAL_ADDRESS) {
21414 return Ty->isFloatTy() || Ty->isDoubleTy() ? AtomicExpansionKind::None
21416 }
21417
21418 MemLegality =
21419 getGlobalMemoryFPAtomicLegality(*Subtarget, RMW, HasSystemScope);
21420 if (MemLegality != GlobalFPAtomicLegality::Illegal) {
21421 // For flat and global cases:
21422 // float, double in gfx7. Manual claims denormal support.
21423 // Removed in gfx8.
21424 // float, double restored in gfx10.
21425 // double removed again in gfx11, so only f32 for gfx11/gfx12.
21426 //
21427 // For gfx9, gfx90a and gfx942 support f64 for global (same as fadd), but
21428 // no f32.
21429 if (AS == AMDGPUAS::FLAT_ADDRESS) {
21430 if (Subtarget->hasAtomicFMinFMaxF32FlatInsts() && Ty->isFloatTy())
21431 return ReportHWInst(AtomicExpansionKind::None);
21432 if (Subtarget->hasAtomicFMinFMaxF64FlatInsts() && Ty->isDoubleTy())
21433 return ReportHWInst(AtomicExpansionKind::None);
21434 } else if (AMDGPU::isExtendedGlobalAddrSpace(AS) ||
21436 if (Subtarget->hasAtomicFMinFMaxF32GlobalInsts() && Ty->isFloatTy())
21437 return ReportHWInst(AtomicExpansionKind::None);
21438 if (Subtarget->hasAtomicFMinFMaxF64GlobalInsts() && Ty->isDoubleTy())
21439 return ReportHWInst(AtomicExpansionKind::None);
21440 }
21441 }
21442
21444 }
21447 default:
21449 }
21450
21451 llvm_unreachable("covered atomicrmw op switch");
21452}
21453
21462
21465 if (SI->getPointerAddressSpace() == AMDGPUAS::VGPR)
21467 return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
21470}
21471
21474 const AtomicCmpXchgInst *CmpX) const {
21475 unsigned AddrSpace = CmpX->getPointerAddressSpace();
21476 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS)
21478
21479 if (AddrSpace == AMDGPUAS::VGPR)
21481
21482 if (AddrSpace != AMDGPUAS::FLAT_ADDRESS || !flatInstrMayAccessPrivate(CmpX))
21484
21485 const DataLayout &DL = CmpX->getDataLayout();
21486
21487 Type *ValTy = CmpX->getNewValOperand()->getType();
21488
21489 // If a 64-bit flat atomic may alias private, we need to avoid using the
21490 // atomic in the private case.
21491 return DL.getTypeSizeInBits(ValTy) == 64 ? AtomicExpansionKind::CustomExpand
21493}
21494
21495const TargetRegisterClass *
21496SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
21498 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
21499 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
21500 return Subtarget->isWave64() ? &AMDGPU::SReg_64RegClass
21501 : &AMDGPU::SReg_32RegClass;
21502 if (!TRI->isSGPRClass(RC) && !isDivergent)
21503 return TRI->getEquivalentSGPRClass(RC);
21504 if (TRI->isSGPRClass(RC) && isDivergent) {
21505 if (Subtarget->hasGFX90AInsts())
21506 return TRI->getEquivalentAVClass(RC);
21507 return TRI->getEquivalentVGPRClass(RC);
21508 }
21509
21510 return RC;
21511}
21512
21513// FIXME: This is a workaround for DivergenceAnalysis not understanding always
21514// uniform values (as produced by the mask results of control flow intrinsics)
21515// used outside of divergent blocks. The phi users need to also be treated as
21516// always uniform.
21517//
21518// FIXME: DA is no longer in-use. Does this still apply to UniformityAnalysis?
21520 unsigned WaveSize) {
21521 // FIXME: We assume we never cast the mask results of a control flow
21522 // intrinsic.
21523 // Early exit if the type won't be consistent as a compile time hack.
21524 IntegerType *IT = dyn_cast<IntegerType>(V->getType());
21525 if (!IT || IT->getBitWidth() != WaveSize)
21526 return false;
21527
21528 if (!isa<Instruction>(V))
21529 return false;
21530 if (!Visited.insert(V).second)
21531 return false;
21532 bool Result = false;
21533 for (const auto *U : V->users()) {
21535 if (V == U->getOperand(1)) {
21536 switch (Intrinsic->getIntrinsicID()) {
21537 default:
21538 Result = false;
21539 break;
21540 case Intrinsic::amdgcn_if_break:
21541 case Intrinsic::amdgcn_if:
21542 case Intrinsic::amdgcn_else:
21543 Result = true;
21544 break;
21545 }
21546 }
21547 if (V == U->getOperand(0)) {
21548 switch (Intrinsic->getIntrinsicID()) {
21549 default:
21550 Result = false;
21551 break;
21552 case Intrinsic::amdgcn_end_cf:
21553 case Intrinsic::amdgcn_loop:
21554 Result = true;
21555 break;
21556 }
21557 }
21558 } else {
21559 Result = hasCFUser(U, Visited, WaveSize);
21560 }
21561 if (Result)
21562 break;
21563 }
21564 return Result;
21565}
21566
21568 const Value *V) const {
21569 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
21570 if (CI->isInlineAsm()) {
21571 // FIXME: This cannot give a correct answer. This should only trigger in
21572 // the case where inline asm returns mixed SGPR and VGPR results, used
21573 // outside the defining block. We don't have a specific result to
21574 // consider, so this assumes if any value is SGPR, the overall register
21575 // also needs to be SGPR.
21576 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
21578 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
21579 for (auto &TC : TargetConstraints) {
21580 if (TC.Type == InlineAsm::isOutput) {
21582 const TargetRegisterClass *RC =
21583 getRegForInlineAsmConstraint(SIRI, TC.ConstraintCode,
21584 TC.ConstraintVT)
21585 .second;
21586 if (RC && SIRI->isSGPRClass(RC))
21587 return true;
21588 }
21589 }
21590 }
21591 }
21593 return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
21594}
21595
21597 for (SDUse &Use : N->uses()) {
21599 if (getBasePtrIndex(M) == Use.getOperandNo())
21600 return true;
21601 }
21602 }
21603 return false;
21604}
21605
21607 SDValue N1) const {
21608 if (!N0.hasOneUse())
21609 return false;
21610 // Take care of the opportunity to keep N0 uniform
21611 if (N0->isDivergent() || !N1->isDivergent())
21612 return true;
21613 // Check if we have a good chance to form the memory access pattern with the
21614 // base and offset
21615 return (DAG.isBaseWithConstantOffset(N0) &&
21617}
21618
21620 Register N0, Register N1) const {
21621 return MRI.hasOneNonDBGUse(N0); // FIXME: handle regbanks
21622}
21623
21626 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
21628 if (I.getMetadata("amdgpu.noclobber"))
21629 Flags |= MONoClobber;
21630 if (I.getMetadata("amdgpu.last.use"))
21631 Flags |= MOLastUse;
21632 if (MDNode *N = I.getMetadata("amdgpu.cfs")) {
21633 const ConstantAsMetadata *CAM = cast<ConstantAsMetadata>(N->getOperand(0));
21635 unsigned CFS = CI->getZExtValue() & AMDGPU::CPol::CFS_MASK;
21636 static_assert((MOCFSB0 << 1) == MOCFSB1,
21637 "MOCFSB0 and MOCFSB1 are not adjacent bits");
21638 Flags |= static_cast<MachineMemOperand::Flags>(CFS * MOCFSB0);
21639 }
21640 return Flags;
21641}
21642
21644 Instruction *AI) const {
21645 // Given: atomicrmw fadd ptr %addr, float %val ordering
21646 //
21647 // With this expansion we produce the following code:
21648 // [...]
21649 // %is.shared = call i1 @llvm.amdgcn.is.shared(ptr %addr)
21650 // br i1 %is.shared, label %atomicrmw.shared, label %atomicrmw.check.private
21651 //
21652 // atomicrmw.shared:
21653 // %cast.shared = addrspacecast ptr %addr to ptr addrspace(3)
21654 // %loaded.shared = atomicrmw fadd ptr addrspace(3) %cast.shared,
21655 // float %val ordering
21656 // br label %atomicrmw.phi
21657 //
21658 // atomicrmw.check.private:
21659 // %is.private = call i1 @llvm.amdgcn.is.private(ptr %int8ptr)
21660 // br i1 %is.private, label %atomicrmw.private, label %atomicrmw.global
21661 //
21662 // atomicrmw.private:
21663 // %cast.private = addrspacecast ptr %addr to ptr addrspace(5)
21664 // %loaded.private = load float, ptr addrspace(5) %cast.private
21665 // %val.new = fadd float %loaded.private, %val
21666 // store float %val.new, ptr addrspace(5) %cast.private
21667 // br label %atomicrmw.phi
21668 //
21669 // atomicrmw.global:
21670 // %cast.global = addrspacecast ptr %addr to ptr addrspace(1)
21671 // %loaded.global = atomicrmw fadd ptr addrspace(1) %cast.global,
21672 // float %val ordering
21673 // br label %atomicrmw.phi
21674 //
21675 // atomicrmw.phi:
21676 // %loaded.phi = phi float [ %loaded.shared, %atomicrmw.shared ],
21677 // [ %loaded.private, %atomicrmw.private ],
21678 // [ %loaded.global, %atomicrmw.global ]
21679 // br label %atomicrmw.end
21680 //
21681 // atomicrmw.end:
21682 // [...]
21683 //
21684 //
21685 // For 64-bit atomics which may reside in private memory, we perform a simpler
21686 // version that only inserts the private check, and uses the flat operation.
21687
21688 IRBuilder<> Builder(AI);
21689 LLVMContext &Ctx = Builder.getContext();
21690
21691 auto *RMW = dyn_cast<AtomicRMWInst>(AI);
21692 const unsigned PtrOpIdx = RMW ? AtomicRMWInst::getPointerOperandIndex()
21694 Value *Addr = AI->getOperand(PtrOpIdx);
21695
21696 /// TODO: Only need to check private, then emit flat-known-not private (no
21697 /// need for shared block, or cast to global).
21699
21700 Align Alignment;
21701 if (RMW)
21702 Alignment = RMW->getAlign();
21703 else if (CX)
21704 Alignment = CX->getAlign();
21705 else
21706 llvm_unreachable("unhandled atomic operation");
21707
21708 // FullFlatEmulation is true if we need to issue the private, shared, and
21709 // global cases.
21710 //
21711 // If this is false, we are only dealing with the flat-targeting-private case,
21712 // where we only insert a check for private and still use the flat instruction
21713 // for global and shared.
21714
21715 bool FullFlatEmulation =
21716 RMW && RMW->getOperation() == AtomicRMWInst::FAdd &&
21717 ((Subtarget->hasAtomicFaddInsts() && RMW->getType()->isFloatTy()) ||
21718 (Subtarget->hasFlatBufferGlobalAtomicFaddF64Inst() &&
21719 RMW->getType()->isDoubleTy()));
21720
21721 // If the return value isn't used, do not introduce a false use in the phi.
21722 bool ReturnValueIsUsed = !AI->use_empty();
21723
21724 BasicBlock *BB = Builder.GetInsertBlock();
21725 Function *F = BB->getParent();
21726 BasicBlock *ExitBB =
21727 BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
21728 BasicBlock *SharedBB = nullptr;
21729
21730 BasicBlock *CheckPrivateBB = BB;
21731 if (FullFlatEmulation) {
21732 SharedBB = BasicBlock::Create(Ctx, "atomicrmw.shared", F, ExitBB);
21733 CheckPrivateBB =
21734 BasicBlock::Create(Ctx, "atomicrmw.check.private", F, ExitBB);
21735 }
21736
21737 BasicBlock *PrivateBB =
21738 BasicBlock::Create(Ctx, "atomicrmw.private", F, ExitBB);
21739 BasicBlock *GlobalBB = BasicBlock::Create(Ctx, "atomicrmw.global", F, ExitBB);
21740 BasicBlock *PhiBB = BasicBlock::Create(Ctx, "atomicrmw.phi", F, ExitBB);
21741
21742 std::prev(BB->end())->eraseFromParent();
21743 Builder.SetInsertPoint(BB);
21744
21745 Value *LoadedShared = nullptr;
21746 if (FullFlatEmulation) {
21747 Value *IsShared = Builder.CreateIntrinsic(Intrinsic::amdgcn_is_shared,
21748 {Addr}, nullptr, "is.shared");
21749 Builder.CreateCondBr(IsShared, SharedBB, CheckPrivateBB);
21750 Builder.SetInsertPoint(SharedBB);
21751 Value *CastToLocal = Builder.CreateAddrSpaceCast(
21753
21754 Instruction *Clone = AI->clone();
21755 Clone->insertInto(SharedBB, SharedBB->end());
21756 Clone->getOperandUse(PtrOpIdx).set(CastToLocal);
21757 LoadedShared = Clone;
21758
21759 Builder.CreateBr(PhiBB);
21760 Builder.SetInsertPoint(CheckPrivateBB);
21761 }
21762
21763 Value *IsPrivate = Builder.CreateIntrinsic(Intrinsic::amdgcn_is_private,
21764 {Addr}, nullptr, "is.private");
21765 Builder.CreateCondBr(IsPrivate, PrivateBB, GlobalBB);
21766
21767 Builder.SetInsertPoint(PrivateBB);
21768
21769 Value *CastToPrivate = Builder.CreateAddrSpaceCast(
21771
21772 Value *LoadedPrivate;
21773 if (RMW) {
21774 LoadedPrivate = Builder.CreateAlignedLoad(
21775 RMW->getType(), CastToPrivate, RMW->getAlign(), RMW->isVolatile(),
21776 "loaded.private");
21777
21778 Value *NewVal = buildAtomicRMWValue(RMW->getOperation(), Builder,
21779 LoadedPrivate, RMW->getValOperand());
21780
21781 Builder.CreateAlignedStore(NewVal, CastToPrivate, RMW->getAlign(),
21782 RMW->isVolatile());
21783 } else {
21784 auto [ResultLoad, Equal] = buildCmpXchgValue(
21785 Builder, CastToPrivate, CX->getCompareOperand(), CX->getNewValOperand(),
21786 CX->getAlign(), CX->isVolatile());
21787
21788 Value *Insert = Builder.CreateInsertValue(PoisonValue::get(CX->getType()),
21789 ResultLoad, 0);
21790 LoadedPrivate = Builder.CreateInsertValue(Insert, Equal, 1);
21791 }
21792
21793 Builder.CreateBr(PhiBB);
21794
21795 Builder.SetInsertPoint(GlobalBB);
21796
21797 // Continue using a flat instruction if we only emitted the check for private.
21798 Instruction *LoadedGlobal = AI;
21799 if (FullFlatEmulation) {
21800 Value *CastToGlobal = Builder.CreateAddrSpaceCast(
21802 AI->getOperandUse(PtrOpIdx).set(CastToGlobal);
21803 }
21804
21805 AI->removeFromParent();
21806 AI->insertInto(GlobalBB, GlobalBB->end());
21807
21808 // The new atomicrmw may go through another round of legalization later.
21809 if (!FullFlatEmulation) {
21810 // We inserted the runtime check already, make sure we do not try to
21811 // re-expand this.
21812 // TODO: Should union with any existing metadata.
21813 MDBuilder MDB(F->getContext());
21814 MDNode *RangeNotPrivate =
21817 LoadedGlobal->setMetadata(LLVMContext::MD_noalias_addrspace,
21818 RangeNotPrivate);
21819 }
21820
21821 Builder.CreateBr(PhiBB);
21822
21823 Builder.SetInsertPoint(PhiBB);
21824
21825 if (ReturnValueIsUsed) {
21826 PHINode *Loaded = Builder.CreatePHI(AI->getType(), 3);
21827 AI->replaceAllUsesWith(Loaded);
21828 if (FullFlatEmulation)
21829 Loaded->addIncoming(LoadedShared, SharedBB);
21830 Loaded->addIncoming(LoadedPrivate, PrivateBB);
21831 Loaded->addIncoming(LoadedGlobal, GlobalBB);
21832 Loaded->takeName(AI);
21833 }
21834
21835 Builder.CreateBr(ExitBB);
21836}
21837
21839 unsigned PtrOpIdx) {
21840 Value *PtrOp = I->getOperand(PtrOpIdx);
21843
21844 Type *FlatPtr = PointerType::get(I->getContext(), AMDGPUAS::FLAT_ADDRESS);
21845 Value *ASCast = CastInst::CreatePointerCast(PtrOp, FlatPtr, "scratch.ascast",
21846 I->getIterator());
21847 I->setOperand(PtrOpIdx, ASCast);
21848}
21849
21852
21855
21858 if (const auto *ConstVal = dyn_cast<Constant>(AI->getValOperand());
21859 ConstVal && ConstVal->isNullValue() &&
21861 // atomicrmw or %ptr, 0 -> atomicrmw add %ptr, 0
21863
21864 // We may still need the private-alias-flat handling below.
21865
21866 // TODO: Skip this for cases where we cannot access remote memory.
21867 }
21868 }
21869
21870 // The non-flat expansions should only perform the de-canonicalization of
21871 // identity values.
21873 return;
21874
21876}
21877
21884
21888
21890 "Expand Atomic Load only handles SCRATCH -> FLAT conversion");
21891}
21892
21894 if (SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
21895 return convertScratchAtomicToFlatAtomic(SI, SI->getPointerOperandIndex());
21896
21898 "Expand Atomic Store only handles SCRATCH -> FLAT conversion");
21899}
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
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
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)
#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)
if(PassOpts->AAPipeline)
static constexpr MCPhysReg SPReg
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
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 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 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 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 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)
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:171
#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:380
static constexpr const fltSemantics & IEEEhalf()
Definition APFloat.h:303
static constexpr const fltSemantics & IEEEsingle()
Definition APFloat.h:305
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1253
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6106
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1683
bool isNegative() const
Definition APFloat.h:1612
bool isNormal() const
Definition APFloat.h:1616
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1221
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1271
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1231
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1212
bool isInfinity() const
Definition APFloat.h:1609
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:448
LLVM_ABI MemoryEffects getMemoryEffects() const
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
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:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
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:64
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
bool isBigEndian() const
Definition DataLayout.h:221
A debug info location.
Definition DebugLoc.h:127
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.
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. Should be passed by value.
Definition MCRegister.h:41
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.
AtomicExpansionKind shouldExpandAtomicStoreInIR(StoreInst *SI) const override
Returns how the given (atomic) store should be expanded by the IR-level AtomicExpand pass into.
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.
AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const override
Returns how the given (atomic) load should be expanded by the IR-level AtomicExpand pass.
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.
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
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:526
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
@ 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
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