Bug Summary

File:llvm/lib/Target/AMDGPU/SIISelLowering.cpp
Warning:line 11189, column 52
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SIISelLowering.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Target/AMDGPU -I /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU -I include -I /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/build-llvm -ferror-limit 19 -fvisibility hidden -fvisibility-inlines-hidden -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-11-10-160236-22541-1 -x c++ /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp
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 "AMDGPUInstrInfo.h"
17#include "AMDGPUTargetMachine.h"
18#include "SIMachineFunctionInfo.h"
19#include "SIRegisterInfo.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
22#include "llvm/Analysis/OptimizationRemarkEmitter.h"
23#include "llvm/BinaryFormat/ELF.h"
24#include "llvm/CodeGen/Analysis.h"
25#include "llvm/CodeGen/FunctionLoweringInfo.h"
26#include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
27#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineLoopInfo.h"
29#include "llvm/IR/DiagnosticInfo.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/IntrinsicsAMDGPU.h"
32#include "llvm/IR/IntrinsicsR600.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/KnownBits.h"
35
36using namespace llvm;
37
38#define DEBUG_TYPE"si-lower" "si-lower"
39
40STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"si-lower", "NumTailCalls"
, "Number of tail calls"}
;
41
42static cl::opt<bool> DisableLoopAlignment(
43 "amdgpu-disable-loop-alignment",
44 cl::desc("Do not align and prefetch loops"),
45 cl::init(false));
46
47static cl::opt<bool> VGPRReserveforSGPRSpill(
48 "amdgpu-reserve-vgpr-for-sgpr-spill",
49 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
50
51static cl::opt<bool> UseDivergentRegisterIndexing(
52 "amdgpu-use-divergent-register-indexing",
53 cl::Hidden,
54 cl::desc("Use indirect register addressing for divergent indexes"),
55 cl::init(false));
56
57static bool hasFP32Denormals(const MachineFunction &MF) {
58 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
59 return Info->getMode().allFP32Denormals();
60}
61
62static bool hasFP64FP16Denormals(const MachineFunction &MF) {
63 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
64 return Info->getMode().allFP64FP16Denormals();
65}
66
67static unsigned findFirstFreeSGPR(CCState &CCInfo) {
68 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
69 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
70 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
71 return AMDGPU::SGPR0 + Reg;
72 }
73 }
74 llvm_unreachable("Cannot allocate sgpr")::llvm::llvm_unreachable_internal("Cannot allocate sgpr", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 74)
;
75}
76
77SITargetLowering::SITargetLowering(const TargetMachine &TM,
78 const GCNSubtarget &STI)
79 : AMDGPUTargetLowering(TM, STI),
80 Subtarget(&STI) {
81 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
82 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
83
84 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
85 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
86
87 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
88
89 const SIRegisterInfo *TRI = STI.getRegisterInfo();
90 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
91
92 addRegisterClass(MVT::f64, V64RegClass);
93 addRegisterClass(MVT::v2f32, V64RegClass);
94
95 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
96 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
97
98 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
99 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
100
101 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
102 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
103
104 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
105 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
106
107 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
108 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
109
110 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
111 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
112
113 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
114 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
115
116 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
117 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
118
119 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
120 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
121
122 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
123 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
124
125 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
126 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
127
128 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
129 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
130
131 if (Subtarget->has16BitInsts()) {
132 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
133 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
134
135 // Unless there are also VOP3P operations, not operations are really legal.
136 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
137 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
138 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
139 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
140 }
141
142 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
143 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
144
145 computeRegisterProperties(Subtarget->getRegisterInfo());
146
147 // The boolean content concept here is too inflexible. Compares only ever
148 // really produce a 1-bit result. Any copy/extend from these will turn into a
149 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
150 // it's what most targets use.
151 setBooleanContents(ZeroOrOneBooleanContent);
152 setBooleanVectorContents(ZeroOrOneBooleanContent);
153
154 // We need to custom lower vector stores from local memory
155 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
156 setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
157 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
158 setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
159 setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
160 setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
161 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
162 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
163 setOperationAction(ISD::LOAD, MVT::i1, Custom);
164 setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
165
166 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
167 setOperationAction(ISD::STORE, MVT::v3i32, Custom);
168 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
169 setOperationAction(ISD::STORE, MVT::v5i32, Custom);
170 setOperationAction(ISD::STORE, MVT::v6i32, Custom);
171 setOperationAction(ISD::STORE, MVT::v7i32, Custom);
172 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
173 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
174 setOperationAction(ISD::STORE, MVT::i1, Custom);
175 setOperationAction(ISD::STORE, MVT::v32i32, Custom);
176
177 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
178 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
179 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
180 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
181 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
182 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
183 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
184 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
185 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
186 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
187 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
188 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
189 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
190 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
191 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
192 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
193
194 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
195 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
196 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
197 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
198 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
199 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
200 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
201
202 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
203 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
204
205 setOperationAction(ISD::SELECT, MVT::i1, Promote);
206 setOperationAction(ISD::SELECT, MVT::i64, Custom);
207 setOperationAction(ISD::SELECT, MVT::f64, Promote);
208 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
209
210 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
211 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
212 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
213 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
214 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
215
216 setOperationAction(ISD::SETCC, MVT::i1, Promote);
217 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
218 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
219 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
220
221 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
222 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
223 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
224 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
225 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
226 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
227 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
228 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
229 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
230 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
231 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
232 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
233 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
234 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
235 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
236 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
237
238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
245 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
246
247 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
248 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
249 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
250 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
251 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
252 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
253
254 setOperationAction(ISD::UADDO, MVT::i32, Legal);
255 setOperationAction(ISD::USUBO, MVT::i32, Legal);
256
257 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
258 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
259
260 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
261 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
262 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
263
264#if 0
265 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
266 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
267#endif
268
269 // We only support LOAD/STORE and vector manipulation ops for vectors
270 // with > 4 elements.
271 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
272 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
273 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
274 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
275 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
276 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
277 switch (Op) {
278 case ISD::LOAD:
279 case ISD::STORE:
280 case ISD::BUILD_VECTOR:
281 case ISD::BITCAST:
282 case ISD::EXTRACT_VECTOR_ELT:
283 case ISD::INSERT_VECTOR_ELT:
284 case ISD::EXTRACT_SUBVECTOR:
285 case ISD::SCALAR_TO_VECTOR:
286 break;
287 case ISD::INSERT_SUBVECTOR:
288 case ISD::CONCAT_VECTORS:
289 setOperationAction(Op, VT, Custom);
290 break;
291 default:
292 setOperationAction(Op, VT, Expand);
293 break;
294 }
295 }
296 }
297
298 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
299
300 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
301 // is expanded to avoid having two separate loops in case the index is a VGPR.
302
303 // Most operations are naturally 32-bit vector operations. We only support
304 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
305 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
306 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
307 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
308
309 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
310 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
311
312 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
313 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
314
315 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
316 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
317 }
318
319 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
320 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
321 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
322
323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
324 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
325
326 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
327 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
328
329 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
330 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
331 }
332
333 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
334 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
335 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
336
337 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
338 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
339
340 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
341 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
342
343 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
344 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
345 }
346
347 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
348 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
349 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
350
351 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
352 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
353
354 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
355 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
356
357 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
358 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
359 }
360
361 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
362 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
363 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
364
365 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
366 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
367
368 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
369 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
370
371 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
372 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
373 }
374
375 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
376 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
377 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
378 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
379
380 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
381 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
382
383 // Avoid stack access for these.
384 // TODO: Generalize to more vector types.
385 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
386 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
387 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
388 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
389
390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
391 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
396
397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
399 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
400 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
401
402 // Deal with vec3 vector operations when widened to vec4.
403 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
404 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
405 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
406 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
407
408 // Deal with vec5/6/7 vector operations when widened to vec8.
409 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom);
412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom);
413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom);
414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom);
415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
416 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
417
418 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
419 // and output demarshalling
420 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
421 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
422
423 // We can't return success/failure, only the old value,
424 // let LLVM add the comparison
425 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
426 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
427
428 if (Subtarget->hasFlatAddressSpace()) {
429 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
430 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
431 }
432
433 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
434 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
435
436 // FIXME: This should be narrowed to i32, but that only happens if i64 is
437 // illegal.
438 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
439 setOperationAction(ISD::BSWAP, MVT::i64, Legal);
440 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
441
442 // On SI this is s_memtime and s_memrealtime on VI.
443 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
444 setOperationAction(ISD::TRAP, MVT::Other, Custom);
445 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
446
447 if (Subtarget->has16BitInsts()) {
448 setOperationAction(ISD::FPOW, MVT::f16, Promote);
449 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
450 setOperationAction(ISD::FLOG, MVT::f16, Custom);
451 setOperationAction(ISD::FEXP, MVT::f16, Custom);
452 setOperationAction(ISD::FLOG10, MVT::f16, Custom);
453 }
454
455 if (Subtarget->hasMadMacF32Insts())
456 setOperationAction(ISD::FMAD, MVT::f32, Legal);
457
458 if (!Subtarget->hasBFI()) {
459 // fcopysign can be done in a single instruction with BFI.
460 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
461 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
462 }
463
464 if (!Subtarget->hasBCNT(32))
465 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
466
467 if (!Subtarget->hasBCNT(64))
468 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
469
470 if (Subtarget->hasFFBH()) {
471 setOperationAction(ISD::CTLZ, MVT::i32, Custom);
472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
473 }
474
475 if (Subtarget->hasFFBL()) {
476 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
477 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
478 }
479
480 // We only really have 32-bit BFE instructions (and 16-bit on VI).
481 //
482 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
483 // effort to match them now. We want this to be false for i64 cases when the
484 // extraction isn't restricted to the upper or lower half. Ideally we would
485 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
486 // span the midpoint are probably relatively rare, so don't worry about them
487 // for now.
488 if (Subtarget->hasBFE())
489 setHasExtractBitsInsn(true);
490
491 // Clamp modifier on add/sub
492 if (Subtarget->hasIntClamp()) {
493 setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
494 setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
495 }
496
497 if (Subtarget->hasAddNoCarry()) {
498 setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
499 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
500 setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
501 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
502 }
503
504 setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
505 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
506 setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
507 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
508
509
510 // These are really only legal for ieee_mode functions. We should be avoiding
511 // them for functions that don't have ieee_mode enabled, so just say they are
512 // legal.
513 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
514 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
515 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
516 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
517
518
519 if (Subtarget->haveRoundOpsF64()) {
520 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
521 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
522 setOperationAction(ISD::FRINT, MVT::f64, Legal);
523 } else {
524 setOperationAction(ISD::FCEIL, MVT::f64, Custom);
525 setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
526 setOperationAction(ISD::FRINT, MVT::f64, Custom);
527 setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
528 }
529
530 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
531
532 setOperationAction(ISD::FSIN, MVT::f32, Custom);
533 setOperationAction(ISD::FCOS, MVT::f32, Custom);
534 setOperationAction(ISD::FDIV, MVT::f32, Custom);
535 setOperationAction(ISD::FDIV, MVT::f64, Custom);
536
537 if (Subtarget->has16BitInsts()) {
538 setOperationAction(ISD::Constant, MVT::i16, Legal);
539
540 setOperationAction(ISD::SMIN, MVT::i16, Legal);
541 setOperationAction(ISD::SMAX, MVT::i16, Legal);
542
543 setOperationAction(ISD::UMIN, MVT::i16, Legal);
544 setOperationAction(ISD::UMAX, MVT::i16, Legal);
545
546 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
547 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
548
549 setOperationAction(ISD::ROTR, MVT::i16, Expand);
550 setOperationAction(ISD::ROTL, MVT::i16, Expand);
551
552 setOperationAction(ISD::SDIV, MVT::i16, Promote);
553 setOperationAction(ISD::UDIV, MVT::i16, Promote);
554 setOperationAction(ISD::SREM, MVT::i16, Promote);
555 setOperationAction(ISD::UREM, MVT::i16, Promote);
556 setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
557 setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
558
559 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
560
561 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
563 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
564 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
565 setOperationAction(ISD::CTPOP, MVT::i16, Promote);
566
567 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
568
569 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
570
571 setOperationAction(ISD::LOAD, MVT::i16, Custom);
572
573 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
574
575 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
576 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
577 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
578 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
579
580 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
581 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
582
583 // F16 - Constant Actions.
584 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
585
586 // F16 - Load/Store Actions.
587 setOperationAction(ISD::LOAD, MVT::f16, Promote);
588 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
589 setOperationAction(ISD::STORE, MVT::f16, Promote);
590 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
591
592 // F16 - VOP1 Actions.
593 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
594 setOperationAction(ISD::FCOS, MVT::f16, Custom);
595 setOperationAction(ISD::FSIN, MVT::f16, Custom);
596
597 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
598 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
599
600 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
601 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
602 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
603 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
604 setOperationAction(ISD::FROUND, MVT::f16, Custom);
605
606 // F16 - VOP2 Actions.
607 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
608 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
609
610 setOperationAction(ISD::FDIV, MVT::f16, Custom);
611
612 // F16 - VOP3 Actions.
613 setOperationAction(ISD::FMA, MVT::f16, Legal);
614 if (STI.hasMadF16())
615 setOperationAction(ISD::FMAD, MVT::f16, Legal);
616
617 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
618 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
619 switch (Op) {
620 case ISD::LOAD:
621 case ISD::STORE:
622 case ISD::BUILD_VECTOR:
623 case ISD::BITCAST:
624 case ISD::EXTRACT_VECTOR_ELT:
625 case ISD::INSERT_VECTOR_ELT:
626 case ISD::INSERT_SUBVECTOR:
627 case ISD::EXTRACT_SUBVECTOR:
628 case ISD::SCALAR_TO_VECTOR:
629 break;
630 case ISD::CONCAT_VECTORS:
631 setOperationAction(Op, VT, Custom);
632 break;
633 default:
634 setOperationAction(Op, VT, Expand);
635 break;
636 }
637 }
638 }
639
640 // v_perm_b32 can handle either of these.
641 setOperationAction(ISD::BSWAP, MVT::i16, Legal);
642 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
643 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
644
645 // XXX - Do these do anything? Vector constants turn into build_vector.
646 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
647 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
648
649 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
650 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
651
652 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
653 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
654 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
655 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
656
657 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
658 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
659 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
660 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
661
662 setOperationAction(ISD::AND, MVT::v2i16, Promote);
663 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
664 setOperationAction(ISD::OR, MVT::v2i16, Promote);
665 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
666 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
667 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
668
669 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
670 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
671 setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
672 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
673
674 setOperationAction(ISD::STORE, MVT::v4i16, Promote);
675 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
676 setOperationAction(ISD::STORE, MVT::v4f16, Promote);
677 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
678
679 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
680 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
681 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
682 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
683
684 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
685 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
686 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
687
688 if (!Subtarget->hasVOP3PInsts()) {
689 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
690 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
691 }
692
693 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
694 // This isn't really legal, but this avoids the legalizer unrolling it (and
695 // allows matching fneg (fabs x) patterns)
696 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
697
698 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
699 setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
700 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
701 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
702
703 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
704 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
705
706 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
707 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
708 }
709
710 if (Subtarget->hasVOP3PInsts()) {
711 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
712 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
713 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
714 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
715 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
716 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
717 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
718 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
719 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
720 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
721
722 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
723 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
724 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
725 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
726
727 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
728 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
729 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
730
731 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
732 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
733
734 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
735
736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
738
739 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
740 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
741
742 setOperationAction(ISD::SHL, MVT::v4i16, Custom);
743 setOperationAction(ISD::SRA, MVT::v4i16, Custom);
744 setOperationAction(ISD::SRL, MVT::v4i16, Custom);
745 setOperationAction(ISD::ADD, MVT::v4i16, Custom);
746 setOperationAction(ISD::SUB, MVT::v4i16, Custom);
747 setOperationAction(ISD::MUL, MVT::v4i16, Custom);
748
749 setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
750 setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
751 setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
752 setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
753
754 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
755 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
756 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
757 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
758
759 setOperationAction(ISD::FADD, MVT::v4f16, Custom);
760 setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
761 setOperationAction(ISD::FMA, MVT::v4f16, Custom);
762
763 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
764 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
765
766 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
767 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
768 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
769
770 setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
771 setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
772 setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
773
774 if (Subtarget->hasPackedFP32Ops()) {
775 setOperationAction(ISD::FADD, MVT::v2f32, Legal);
776 setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
777 setOperationAction(ISD::FMA, MVT::v2f32, Legal);
778 setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
779
780 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
781 setOperationAction(ISD::FADD, VT, Custom);
782 setOperationAction(ISD::FMUL, VT, Custom);
783 setOperationAction(ISD::FMA, VT, Custom);
784 }
785 }
786 }
787
788 setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
789 setOperationAction(ISD::FABS, MVT::v4f16, Custom);
790
791 if (Subtarget->has16BitInsts()) {
792 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
793 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
794 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
795 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
796 } else {
797 // Legalization hack.
798 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
799 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
800
801 setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
802 setOperationAction(ISD::FABS, MVT::v2f16, Custom);
803 }
804
805 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
806 setOperationAction(ISD::SELECT, VT, Custom);
807 }
808
809 setOperationAction(ISD::SMULO, MVT::i64, Custom);
810 setOperationAction(ISD::UMULO, MVT::i64, Custom);
811
812 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
813 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
814 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
815 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
816 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
817 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
818 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
819
820 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
821 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
822 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
823 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
824 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
825 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
826 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
827 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
828 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
829 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
830 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
831
832 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
833 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
834 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
835 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
836 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
837 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
838 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
839 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
840 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
841 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
842
843 setTargetDAGCombine(ISD::ADD);
844 setTargetDAGCombine(ISD::ADDCARRY);
845 setTargetDAGCombine(ISD::SUB);
846 setTargetDAGCombine(ISD::SUBCARRY);
847 setTargetDAGCombine(ISD::FADD);
848 setTargetDAGCombine(ISD::FSUB);
849 setTargetDAGCombine(ISD::FMINNUM);
850 setTargetDAGCombine(ISD::FMAXNUM);
851 setTargetDAGCombine(ISD::FMINNUM_IEEE);
852 setTargetDAGCombine(ISD::FMAXNUM_IEEE);
853 setTargetDAGCombine(ISD::FMA);
854 setTargetDAGCombine(ISD::SMIN);
855 setTargetDAGCombine(ISD::SMAX);
856 setTargetDAGCombine(ISD::UMIN);
857 setTargetDAGCombine(ISD::UMAX);
858 setTargetDAGCombine(ISD::SETCC);
859 setTargetDAGCombine(ISD::AND);
860 setTargetDAGCombine(ISD::OR);
861 setTargetDAGCombine(ISD::XOR);
862 setTargetDAGCombine(ISD::SINT_TO_FP);
863 setTargetDAGCombine(ISD::UINT_TO_FP);
864 setTargetDAGCombine(ISD::FCANONICALIZE);
865 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
866 setTargetDAGCombine(ISD::ZERO_EXTEND);
867 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
868 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
869 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
870
871 // All memory operations. Some folding on the pointer operand is done to help
872 // matching the constant offsets in the addressing modes.
873 setTargetDAGCombine(ISD::LOAD);
874 setTargetDAGCombine(ISD::STORE);
875 setTargetDAGCombine(ISD::ATOMIC_LOAD);
876 setTargetDAGCombine(ISD::ATOMIC_STORE);
877 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
878 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
879 setTargetDAGCombine(ISD::ATOMIC_SWAP);
880 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
881 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
882 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
883 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
884 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
885 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
886 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
887 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
888 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
889 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
890 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
891 setTargetDAGCombine(ISD::INTRINSIC_VOID);
892 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
893
894 // FIXME: In other contexts we pretend this is a per-function property.
895 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
896
897 setSchedulingPreference(Sched::RegPressure);
898}
899
900const GCNSubtarget *SITargetLowering::getSubtarget() const {
901 return Subtarget;
902}
903
904//===----------------------------------------------------------------------===//
905// TargetLowering queries
906//===----------------------------------------------------------------------===//
907
908// v_mad_mix* support a conversion from f16 to f32.
909//
910// There is only one special case when denormals are enabled we don't currently,
911// where this is OK to use.
912bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
913 EVT DestVT, EVT SrcVT) const {
914 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
915 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
916 DestVT.getScalarType() == MVT::f32 &&
917 SrcVT.getScalarType() == MVT::f16 &&
918 // TODO: This probably only requires no input flushing?
919 !hasFP32Denormals(DAG.getMachineFunction());
920}
921
922bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
923 // SI has some legal vector types, but no legal vector operations. Say no
924 // shuffles are legal in order to prefer scalarizing some vector operations.
925 return false;
926}
927
928MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
929 CallingConv::ID CC,
930 EVT VT) const {
931 if (CC == CallingConv::AMDGPU_KERNEL)
932 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
933
934 if (VT.isVector()) {
935 EVT ScalarVT = VT.getScalarType();
936 unsigned Size = ScalarVT.getSizeInBits();
937 if (Size == 16) {
938 if (Subtarget->has16BitInsts())
939 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
940 return VT.isInteger() ? MVT::i32 : MVT::f32;
941 }
942
943 if (Size < 16)
944 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
945 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
946 }
947
948 if (VT.getSizeInBits() > 32)
949 return MVT::i32;
950
951 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
952}
953
954unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
955 CallingConv::ID CC,
956 EVT VT) const {
957 if (CC == CallingConv::AMDGPU_KERNEL)
958 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
959
960 if (VT.isVector()) {
961 unsigned NumElts = VT.getVectorNumElements();
962 EVT ScalarVT = VT.getScalarType();
963 unsigned Size = ScalarVT.getSizeInBits();
964
965 // FIXME: Should probably promote 8-bit vectors to i16.
966 if (Size == 16 && Subtarget->has16BitInsts())
967 return (NumElts + 1) / 2;
968
969 if (Size <= 32)
970 return NumElts;
971
972 if (Size > 32)
973 return NumElts * ((Size + 31) / 32);
974 } else if (VT.getSizeInBits() > 32)
975 return (VT.getSizeInBits() + 31) / 32;
976
977 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
978}
979
980unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
981 LLVMContext &Context, CallingConv::ID CC,
982 EVT VT, EVT &IntermediateVT,
983 unsigned &NumIntermediates, MVT &RegisterVT) const {
984 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
985 unsigned NumElts = VT.getVectorNumElements();
986 EVT ScalarVT = VT.getScalarType();
987 unsigned Size = ScalarVT.getSizeInBits();
988 // FIXME: We should fix the ABI to be the same on targets without 16-bit
989 // support, but unless we can properly handle 3-vectors, it will be still be
990 // inconsistent.
991 if (Size == 16 && Subtarget->has16BitInsts()) {
992 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
993 IntermediateVT = RegisterVT;
994 NumIntermediates = (NumElts + 1) / 2;
995 return NumIntermediates;
996 }
997
998 if (Size == 32) {
999 RegisterVT = ScalarVT.getSimpleVT();
1000 IntermediateVT = RegisterVT;
1001 NumIntermediates = NumElts;
1002 return NumIntermediates;
1003 }
1004
1005 if (Size < 16 && Subtarget->has16BitInsts()) {
1006 // FIXME: Should probably form v2i16 pieces
1007 RegisterVT = MVT::i16;
1008 IntermediateVT = ScalarVT;
1009 NumIntermediates = NumElts;
1010 return NumIntermediates;
1011 }
1012
1013
1014 if (Size != 16 && Size <= 32) {
1015 RegisterVT = MVT::i32;
1016 IntermediateVT = ScalarVT;
1017 NumIntermediates = NumElts;
1018 return NumIntermediates;
1019 }
1020
1021 if (Size > 32) {
1022 RegisterVT = MVT::i32;
1023 IntermediateVT = RegisterVT;
1024 NumIntermediates = NumElts * ((Size + 31) / 32);
1025 return NumIntermediates;
1026 }
1027 }
1028
1029 return TargetLowering::getVectorTypeBreakdownForCallingConv(
1030 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1031}
1032
1033static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1034 assert(DMaskLanes != 0)(static_cast <bool> (DMaskLanes != 0) ? void (0) : __assert_fail
("DMaskLanes != 0", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1034, __extension__ __PRETTY_FUNCTION__))
;
1035
1036 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1037 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1038 return EVT::getVectorVT(Ty->getContext(),
1039 EVT::getEVT(VT->getElementType()),
1040 NumElts);
1041 }
1042
1043 return EVT::getEVT(Ty);
1044}
1045
1046// Peek through TFE struct returns to only use the data size.
1047static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1048 auto *ST = dyn_cast<StructType>(Ty);
1049 if (!ST)
1050 return memVTFromImageData(Ty, DMaskLanes);
1051
1052 // Some intrinsics return an aggregate type - special case to work out the
1053 // correct memVT.
1054 //
1055 // Only limited forms of aggregate type currently expected.
1056 if (ST->getNumContainedTypes() != 2 ||
1057 !ST->getContainedType(1)->isIntegerTy(32))
1058 return EVT();
1059 return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1060}
1061
1062bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1063 const CallInst &CI,
1064 MachineFunction &MF,
1065 unsigned IntrID) const {
1066 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1067 AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1068 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1069 (Intrinsic::ID)IntrID);
1070 if (Attr.hasFnAttr(Attribute::ReadNone))
1071 return false;
1072
1073 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1074
1075 if (RsrcIntr->IsImage) {
1076 Info.ptrVal =
1077 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1078 Info.align.reset();
1079 } else {
1080 Info.ptrVal =
1081 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1082 }
1083
1084 Info.flags = MachineMemOperand::MODereferenceable;
1085 if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1086 unsigned DMaskLanes = 4;
1087
1088 if (RsrcIntr->IsImage) {
1089 const AMDGPU::ImageDimIntrinsicInfo *Intr
1090 = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1091 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1092 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1093
1094 if (!BaseOpcode->Gather4) {
1095 // If this isn't a gather, we may have excess loaded elements in the
1096 // IR type. Check the dmask for the real number of elements loaded.
1097 unsigned DMask
1098 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1099 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1100 }
1101
1102 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1103 } else
1104 Info.memVT = EVT::getEVT(CI.getType());
1105
1106 // FIXME: What does alignment mean for an image?
1107 Info.opc = ISD::INTRINSIC_W_CHAIN;
1108 Info.flags |= MachineMemOperand::MOLoad;
1109 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1110 Info.opc = ISD::INTRINSIC_VOID;
1111
1112 Type *DataTy = CI.getArgOperand(0)->getType();
1113 if (RsrcIntr->IsImage) {
1114 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1115 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1116 Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1117 } else
1118 Info.memVT = EVT::getEVT(DataTy);
1119
1120 Info.flags |= MachineMemOperand::MOStore;
1121 } else {
1122 // Atomic
1123 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1124 ISD::INTRINSIC_W_CHAIN;
1125 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1126 Info.flags = MachineMemOperand::MOLoad |
1127 MachineMemOperand::MOStore |
1128 MachineMemOperand::MODereferenceable;
1129
1130 // XXX - Should this be volatile without known ordering?
1131 Info.flags |= MachineMemOperand::MOVolatile;
1132 }
1133 return true;
1134 }
1135
1136 switch (IntrID) {
1137 case Intrinsic::amdgcn_atomic_inc:
1138 case Intrinsic::amdgcn_atomic_dec:
1139 case Intrinsic::amdgcn_ds_ordered_add:
1140 case Intrinsic::amdgcn_ds_ordered_swap:
1141 case Intrinsic::amdgcn_ds_fadd:
1142 case Intrinsic::amdgcn_ds_fmin:
1143 case Intrinsic::amdgcn_ds_fmax: {
1144 Info.opc = ISD::INTRINSIC_W_CHAIN;
1145 Info.memVT = MVT::getVT(CI.getType());
1146 Info.ptrVal = CI.getOperand(0);
1147 Info.align.reset();
1148 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1149
1150 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1151 if (!Vol->isZero())
1152 Info.flags |= MachineMemOperand::MOVolatile;
1153
1154 return true;
1155 }
1156 case Intrinsic::amdgcn_buffer_atomic_fadd: {
1157 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1158
1159 Info.opc = ISD::INTRINSIC_W_CHAIN;
1160 Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1161 Info.ptrVal =
1162 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1163 Info.align.reset();
1164 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1165
1166 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1167 if (!Vol || !Vol->isZero())
1168 Info.flags |= MachineMemOperand::MOVolatile;
1169
1170 return true;
1171 }
1172 case Intrinsic::amdgcn_ds_append:
1173 case Intrinsic::amdgcn_ds_consume: {
1174 Info.opc = ISD::INTRINSIC_W_CHAIN;
1175 Info.memVT = MVT::getVT(CI.getType());
1176 Info.ptrVal = CI.getOperand(0);
1177 Info.align.reset();
1178 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1179
1180 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1181 if (!Vol->isZero())
1182 Info.flags |= MachineMemOperand::MOVolatile;
1183
1184 return true;
1185 }
1186 case Intrinsic::amdgcn_global_atomic_csub: {
1187 Info.opc = ISD::INTRINSIC_W_CHAIN;
1188 Info.memVT = MVT::getVT(CI.getType());
1189 Info.ptrVal = CI.getOperand(0);
1190 Info.align.reset();
1191 Info.flags = MachineMemOperand::MOLoad |
1192 MachineMemOperand::MOStore |
1193 MachineMemOperand::MOVolatile;
1194 return true;
1195 }
1196 case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1197 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1198 Info.opc = ISD::INTRINSIC_W_CHAIN;
1199 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1200 Info.ptrVal =
1201 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1202 Info.align.reset();
1203 Info.flags = MachineMemOperand::MOLoad |
1204 MachineMemOperand::MODereferenceable;
1205 return true;
1206 }
1207 case Intrinsic::amdgcn_global_atomic_fadd:
1208 case Intrinsic::amdgcn_global_atomic_fmin:
1209 case Intrinsic::amdgcn_global_atomic_fmax:
1210 case Intrinsic::amdgcn_flat_atomic_fadd:
1211 case Intrinsic::amdgcn_flat_atomic_fmin:
1212 case Intrinsic::amdgcn_flat_atomic_fmax: {
1213 Info.opc = ISD::INTRINSIC_W_CHAIN;
1214 Info.memVT = MVT::getVT(CI.getType());
1215 Info.ptrVal = CI.getOperand(0);
1216 Info.align.reset();
1217 Info.flags = MachineMemOperand::MOLoad |
1218 MachineMemOperand::MOStore |
1219 MachineMemOperand::MODereferenceable |
1220 MachineMemOperand::MOVolatile;
1221 return true;
1222 }
1223 case Intrinsic::amdgcn_ds_gws_init:
1224 case Intrinsic::amdgcn_ds_gws_barrier:
1225 case Intrinsic::amdgcn_ds_gws_sema_v:
1226 case Intrinsic::amdgcn_ds_gws_sema_br:
1227 case Intrinsic::amdgcn_ds_gws_sema_p:
1228 case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1229 Info.opc = ISD::INTRINSIC_VOID;
1230
1231 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1232 Info.ptrVal =
1233 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1234
1235 // This is an abstract access, but we need to specify a type and size.
1236 Info.memVT = MVT::i32;
1237 Info.size = 4;
1238 Info.align = Align(4);
1239
1240 Info.flags = MachineMemOperand::MOStore;
1241 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1242 Info.flags = MachineMemOperand::MOLoad;
1243 return true;
1244 }
1245 default:
1246 return false;
1247 }
1248}
1249
1250bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1251 SmallVectorImpl<Value*> &Ops,
1252 Type *&AccessTy) const {
1253 switch (II->getIntrinsicID()) {
1254 case Intrinsic::amdgcn_atomic_inc:
1255 case Intrinsic::amdgcn_atomic_dec:
1256 case Intrinsic::amdgcn_ds_ordered_add:
1257 case Intrinsic::amdgcn_ds_ordered_swap:
1258 case Intrinsic::amdgcn_ds_append:
1259 case Intrinsic::amdgcn_ds_consume:
1260 case Intrinsic::amdgcn_ds_fadd:
1261 case Intrinsic::amdgcn_ds_fmin:
1262 case Intrinsic::amdgcn_ds_fmax:
1263 case Intrinsic::amdgcn_global_atomic_fadd:
1264 case Intrinsic::amdgcn_flat_atomic_fadd:
1265 case Intrinsic::amdgcn_flat_atomic_fmin:
1266 case Intrinsic::amdgcn_flat_atomic_fmax:
1267 case Intrinsic::amdgcn_global_atomic_csub: {
1268 Value *Ptr = II->getArgOperand(0);
1269 AccessTy = II->getType();
1270 Ops.push_back(Ptr);
1271 return true;
1272 }
1273 default:
1274 return false;
1275 }
1276}
1277
1278bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1279 if (!Subtarget->hasFlatInstOffsets()) {
1280 // Flat instructions do not have offsets, and only have the register
1281 // address.
1282 return AM.BaseOffs == 0 && AM.Scale == 0;
1283 }
1284
1285 return AM.Scale == 0 &&
1286 (AM.BaseOffs == 0 ||
1287 Subtarget->getInstrInfo()->isLegalFLATOffset(
1288 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1289}
1290
1291bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1292 if (Subtarget->hasFlatGlobalInsts())
1293 return AM.Scale == 0 &&
1294 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1295 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1296 SIInstrFlags::FlatGlobal));
1297
1298 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1299 // Assume the we will use FLAT for all global memory accesses
1300 // on VI.
1301 // FIXME: This assumption is currently wrong. On VI we still use
1302 // MUBUF instructions for the r + i addressing mode. As currently
1303 // implemented, the MUBUF instructions only work on buffer < 4GB.
1304 // It may be possible to support > 4GB buffers with MUBUF instructions,
1305 // by setting the stride value in the resource descriptor which would
1306 // increase the size limit to (stride * 4GB). However, this is risky,
1307 // because it has never been validated.
1308 return isLegalFlatAddressingMode(AM);
1309 }
1310
1311 return isLegalMUBUFAddressingMode(AM);
1312}
1313
1314bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1315 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1316 // additionally can do r + r + i with addr64. 32-bit has more addressing
1317 // mode options. Depending on the resource constant, it can also do
1318 // (i64 r0) + (i32 r1) * (i14 i).
1319 //
1320 // Private arrays end up using a scratch buffer most of the time, so also
1321 // assume those use MUBUF instructions. Scratch loads / stores are currently
1322 // implemented as mubuf instructions with offen bit set, so slightly
1323 // different than the normal addr64.
1324 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1325 return false;
1326
1327 // FIXME: Since we can split immediate into soffset and immediate offset,
1328 // would it make sense to allow any immediate?
1329
1330 switch (AM.Scale) {
1331 case 0: // r + i or just i, depending on HasBaseReg.
1332 return true;
1333 case 1:
1334 return true; // We have r + r or r + i.
1335 case 2:
1336 if (AM.HasBaseReg) {
1337 // Reject 2 * r + r.
1338 return false;
1339 }
1340
1341 // Allow 2 * r as r + r
1342 // Or 2 * r + i is allowed as r + r + i.
1343 return true;
1344 default: // Don't allow n * r
1345 return false;
1346 }
1347}
1348
1349bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1350 const AddrMode &AM, Type *Ty,
1351 unsigned AS, Instruction *I) const {
1352 // No global is ever allowed as a base.
1353 if (AM.BaseGV)
1354 return false;
1355
1356 if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1357 return isLegalGlobalAddressingMode(AM);
1358
1359 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1360 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1361 AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1362 // If the offset isn't a multiple of 4, it probably isn't going to be
1363 // correctly aligned.
1364 // FIXME: Can we get the real alignment here?
1365 if (AM.BaseOffs % 4 != 0)
1366 return isLegalMUBUFAddressingMode(AM);
1367
1368 // There are no SMRD extloads, so if we have to do a small type access we
1369 // will use a MUBUF load.
1370 // FIXME?: We also need to do this if unaligned, but we don't know the
1371 // alignment here.
1372 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1373 return isLegalGlobalAddressingMode(AM);
1374
1375 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1376 // SMRD instructions have an 8-bit, dword offset on SI.
1377 if (!isUInt<8>(AM.BaseOffs / 4))
1378 return false;
1379 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1380 // On CI+, this can also be a 32-bit literal constant offset. If it fits
1381 // in 8-bits, it can use a smaller encoding.
1382 if (!isUInt<32>(AM.BaseOffs / 4))
1383 return false;
1384 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1385 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1386 if (!isUInt<20>(AM.BaseOffs))
1387 return false;
1388 } else
1389 llvm_unreachable("unhandled generation")::llvm::llvm_unreachable_internal("unhandled generation", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1389)
;
1390
1391 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1392 return true;
1393
1394 if (AM.Scale == 1 && AM.HasBaseReg)
1395 return true;
1396
1397 return false;
1398
1399 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1400 return isLegalMUBUFAddressingMode(AM);
1401 } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1402 AS == AMDGPUAS::REGION_ADDRESS) {
1403 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1404 // field.
1405 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1406 // an 8-bit dword offset but we don't know the alignment here.
1407 if (!isUInt<16>(AM.BaseOffs))
1408 return false;
1409
1410 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1411 return true;
1412
1413 if (AM.Scale == 1 && AM.HasBaseReg)
1414 return true;
1415
1416 return false;
1417 } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1418 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1419 // For an unknown address space, this usually means that this is for some
1420 // reason being used for pure arithmetic, and not based on some addressing
1421 // computation. We don't have instructions that compute pointers with any
1422 // addressing modes, so treat them as having no offset like flat
1423 // instructions.
1424 return isLegalFlatAddressingMode(AM);
1425 }
1426
1427 // Assume a user alias of global for unknown address spaces.
1428 return isLegalGlobalAddressingMode(AM);
1429}
1430
1431bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1432 const MachineFunction &MF) const {
1433 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1434 return (MemVT.getSizeInBits() <= 4 * 32);
1435 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1436 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1437 return (MemVT.getSizeInBits() <= MaxPrivateBits);
1438 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1439 return (MemVT.getSizeInBits() <= 2 * 32);
1440 }
1441 return true;
1442}
1443
1444bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1445 unsigned Size, unsigned AddrSpace, Align Alignment,
1446 MachineMemOperand::Flags Flags, bool *IsFast) const {
1447 if (IsFast)
1448 *IsFast = false;
1449
1450 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1451 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1452 // Check if alignment requirements for ds_read/write instructions are
1453 // disabled.
1454 if (Subtarget->hasUnalignedDSAccessEnabled() &&
1455 !Subtarget->hasLDSMisalignedBug()) {
1456 if (IsFast)
1457 *IsFast = Alignment != Align(2);
1458 return true;
1459 }
1460
1461 // Either, the alignment requirements are "enabled", or there is an
1462 // unaligned LDS access related hardware bug though alignment requirements
1463 // are "disabled". In either case, we need to check for proper alignment
1464 // requirements.
1465 //
1466 if (Size == 64) {
1467 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1468 // can do a 4 byte aligned, 8 byte access in a single operation using
1469 // ds_read2/write2_b32 with adjacent offsets.
1470 bool AlignedBy4 = Alignment >= Align(4);
1471 if (IsFast)
1472 *IsFast = AlignedBy4;
1473
1474 return AlignedBy4;
1475 }
1476 if (Size == 96) {
1477 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1478 // gfx8 and older.
1479 bool AlignedBy16 = Alignment >= Align(16);
1480 if (IsFast)
1481 *IsFast = AlignedBy16;
1482
1483 return AlignedBy16;
1484 }
1485 if (Size == 128) {
1486 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1487 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a
1488 // single operation using ds_read2/write2_b64.
1489 bool AlignedBy8 = Alignment >= Align(8);
1490 if (IsFast)
1491 *IsFast = AlignedBy8;
1492
1493 return AlignedBy8;
1494 }
1495 }
1496
1497 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1498 bool AlignedBy4 = Alignment >= Align(4);
1499 if (IsFast)
1500 *IsFast = AlignedBy4;
1501
1502 return AlignedBy4 ||
1503 Subtarget->enableFlatScratch() ||
1504 Subtarget->hasUnalignedScratchAccess();
1505 }
1506
1507 // FIXME: We have to be conservative here and assume that flat operations
1508 // will access scratch. If we had access to the IR function, then we
1509 // could determine if any private memory was used in the function.
1510 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1511 !Subtarget->hasUnalignedScratchAccess()) {
1512 bool AlignedBy4 = Alignment >= Align(4);
1513 if (IsFast)
1514 *IsFast = AlignedBy4;
1515
1516 return AlignedBy4;
1517 }
1518
1519 if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1520 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1521 AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1522 // If we have an uniform constant load, it still requires using a slow
1523 // buffer instruction if unaligned.
1524 if (IsFast) {
1525 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1526 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1527 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1528 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1529 Alignment >= Align(4) : Alignment != Align(2);
1530 }
1531
1532 return true;
1533 }
1534
1535 // Smaller than dword value must be aligned.
1536 if (Size < 32)
1537 return false;
1538
1539 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1540 // byte-address are ignored, thus forcing Dword alignment.
1541 // This applies to private, global, and constant memory.
1542 if (IsFast)
1543 *IsFast = true;
1544
1545 return Size >= 32 && Alignment >= Align(4);
1546}
1547
1548bool SITargetLowering::allowsMisalignedMemoryAccesses(
1549 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1550 bool *IsFast) const {
1551 if (IsFast)
1552 *IsFast = false;
1553
1554 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1555 // which isn't a simple VT.
1556 // Until MVT is extended to handle this, simply check for the size and
1557 // rely on the condition below: allow accesses if the size is a multiple of 4.
1558 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1559 VT.getStoreSize() > 16)) {
1560 return false;
1561 }
1562
1563 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1564 Alignment, Flags, IsFast);
1565}
1566
1567EVT SITargetLowering::getOptimalMemOpType(
1568 const MemOp &Op, const AttributeList &FuncAttributes) const {
1569 // FIXME: Should account for address space here.
1570
1571 // The default fallback uses the private pointer size as a guess for a type to
1572 // use. Make sure we switch these to 64-bit accesses.
1573
1574 if (Op.size() >= 16 &&
1575 Op.isDstAligned(Align(4))) // XXX: Should only do for global
1576 return MVT::v4i32;
1577
1578 if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1579 return MVT::v2i32;
1580
1581 // Use the default.
1582 return MVT::Other;
1583}
1584
1585bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1586 const MemSDNode *MemNode = cast<MemSDNode>(N);
1587 const Value *Ptr = MemNode->getMemOperand()->getValue();
1588 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1589 return I && I->getMetadata("amdgpu.noclobber");
1590}
1591
1592bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1593 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1594 AS == AMDGPUAS::PRIVATE_ADDRESS;
1595}
1596
1597bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1598 unsigned DestAS) const {
1599 // Flat -> private/local is a simple truncate.
1600 // Flat -> global is no-op
1601 if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1602 return true;
1603
1604 const GCNTargetMachine &TM =
1605 static_cast<const GCNTargetMachine &>(getTargetMachine());
1606 return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1607}
1608
1609bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1610 const MemSDNode *MemNode = cast<MemSDNode>(N);
1611
1612 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1613}
1614
1615TargetLoweringBase::LegalizeTypeAction
1616SITargetLowering::getPreferredVectorAction(MVT VT) const {
1617 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1618 VT.getScalarType().bitsLE(MVT::i16))
1619 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1620 return TargetLoweringBase::getPreferredVectorAction(VT);
1621}
1622
1623bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1624 Type *Ty) const {
1625 // FIXME: Could be smarter if called for vector constants.
1626 return true;
1627}
1628
1629bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1630 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1631 switch (Op) {
1632 case ISD::LOAD:
1633 case ISD::STORE:
1634
1635 // These operations are done with 32-bit instructions anyway.
1636 case ISD::AND:
1637 case ISD::OR:
1638 case ISD::XOR:
1639 case ISD::SELECT:
1640 // TODO: Extensions?
1641 return true;
1642 default:
1643 return false;
1644 }
1645 }
1646
1647 // SimplifySetCC uses this function to determine whether or not it should
1648 // create setcc with i1 operands. We don't have instructions for i1 setcc.
1649 if (VT == MVT::i1 && Op == ISD::SETCC)
1650 return false;
1651
1652 return TargetLowering::isTypeDesirableForOp(Op, VT);
1653}
1654
1655SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1656 const SDLoc &SL,
1657 SDValue Chain,
1658 uint64_t Offset) const {
1659 const DataLayout &DL = DAG.getDataLayout();
1660 MachineFunction &MF = DAG.getMachineFunction();
1661 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1662
1663 const ArgDescriptor *InputPtrReg;
1664 const TargetRegisterClass *RC;
1665 LLT ArgTy;
1666 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1667
1668 std::tie(InputPtrReg, RC, ArgTy) =
1669 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1670
1671 // We may not have the kernarg segment argument if we have no kernel
1672 // arguments.
1673 if (!InputPtrReg)
1674 return DAG.getConstant(0, SL, PtrVT);
1675
1676 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1677 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1678 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1679
1680 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1681}
1682
1683SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1684 const SDLoc &SL) const {
1685 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1686 FIRST_IMPLICIT);
1687 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1688}
1689
1690SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1691 const SDLoc &SL, SDValue Val,
1692 bool Signed,
1693 const ISD::InputArg *Arg) const {
1694 // First, if it is a widened vector, narrow it.
1695 if (VT.isVector() &&
1696 VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1697 EVT NarrowedVT =
1698 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1699 VT.getVectorNumElements());
1700 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1701 DAG.getConstant(0, SL, MVT::i32));
1702 }
1703
1704 // Then convert the vector elements or scalar value.
1705 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1706 VT.bitsLT(MemVT)) {
1707 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1708 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1709 }
1710
1711 if (MemVT.isFloatingPoint())
1712 Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1713 else if (Signed)
1714 Val = DAG.getSExtOrTrunc(Val, SL, VT);
1715 else
1716 Val = DAG.getZExtOrTrunc(Val, SL, VT);
1717
1718 return Val;
1719}
1720
1721SDValue SITargetLowering::lowerKernargMemParameter(
1722 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1723 uint64_t Offset, Align Alignment, bool Signed,
1724 const ISD::InputArg *Arg) const {
1725 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1726
1727 // Try to avoid using an extload by loading earlier than the argument address,
1728 // and extracting the relevant bits. The load should hopefully be merged with
1729 // the previous argument.
1730 if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1731 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1732 int64_t AlignDownOffset = alignDown(Offset, 4);
1733 int64_t OffsetDiff = Offset - AlignDownOffset;
1734
1735 EVT IntVT = MemVT.changeTypeToInteger();
1736
1737 // TODO: If we passed in the base kernel offset we could have a better
1738 // alignment than 4, but we don't really need it.
1739 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1740 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1741 MachineMemOperand::MODereferenceable |
1742 MachineMemOperand::MOInvariant);
1743
1744 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1745 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1746
1747 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1748 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1749 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1750
1751
1752 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1753 }
1754
1755 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1756 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1757 MachineMemOperand::MODereferenceable |
1758 MachineMemOperand::MOInvariant);
1759
1760 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1761 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1762}
1763
1764SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1765 const SDLoc &SL, SDValue Chain,
1766 const ISD::InputArg &Arg) const {
1767 MachineFunction &MF = DAG.getMachineFunction();
1768 MachineFrameInfo &MFI = MF.getFrameInfo();
1769
1770 if (Arg.Flags.isByVal()) {
1771 unsigned Size = Arg.Flags.getByValSize();
1772 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1773 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1774 }
1775
1776 unsigned ArgOffset = VA.getLocMemOffset();
1777 unsigned ArgSize = VA.getValVT().getStoreSize();
1778
1779 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1780
1781 // Create load nodes to retrieve arguments from the stack.
1782 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1783 SDValue ArgValue;
1784
1785 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1786 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1787 MVT MemVT = VA.getValVT();
1788
1789 switch (VA.getLocInfo()) {
1790 default:
1791 break;
1792 case CCValAssign::BCvt:
1793 MemVT = VA.getLocVT();
1794 break;
1795 case CCValAssign::SExt:
1796 ExtType = ISD::SEXTLOAD;
1797 break;
1798 case CCValAssign::ZExt:
1799 ExtType = ISD::ZEXTLOAD;
1800 break;
1801 case CCValAssign::AExt:
1802 ExtType = ISD::EXTLOAD;
1803 break;
1804 }
1805
1806 ArgValue = DAG.getExtLoad(
1807 ExtType, SL, VA.getLocVT(), Chain, FIN,
1808 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1809 MemVT);
1810 return ArgValue;
1811}
1812
1813SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1814 const SIMachineFunctionInfo &MFI,
1815 EVT VT,
1816 AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1817 const ArgDescriptor *Reg;
1818 const TargetRegisterClass *RC;
1819 LLT Ty;
1820
1821 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1822 if (!Reg) {
1823 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1824 // It's possible for a kernarg intrinsic call to appear in a kernel with
1825 // no allocated segment, in which case we do not add the user sgpr
1826 // argument, so just return null.
1827 return DAG.getConstant(0, SDLoc(), VT);
1828 }
1829
1830 // It's undefined behavior if a function marked with the amdgpu-no-*
1831 // attributes uses the corresponding intrinsic.
1832 return DAG.getUNDEF(VT);
1833 }
1834
1835 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1836}
1837
1838static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1839 CallingConv::ID CallConv,
1840 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1841 FunctionType *FType,
1842 SIMachineFunctionInfo *Info) {
1843 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1844 const ISD::InputArg *Arg = &Ins[I];
1845
1846 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&(static_cast <bool> ((!Arg->VT.isVector() || Arg->
VT.getScalarSizeInBits() == 16) && "vector type argument should have been split"
) ? void (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"vector type argument should have been split\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1847, __extension__ __PRETTY_FUNCTION__))
1847 "vector type argument should have been split")(static_cast <bool> ((!Arg->VT.isVector() || Arg->
VT.getScalarSizeInBits() == 16) && "vector type argument should have been split"
) ? void (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"vector type argument should have been split\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1847, __extension__ __PRETTY_FUNCTION__))
;
1848
1849 // First check if it's a PS input addr.
1850 if (CallConv == CallingConv::AMDGPU_PS &&
1851 !Arg->Flags.isInReg() && PSInputNum <= 15) {
1852 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1853
1854 // Inconveniently only the first part of the split is marked as isSplit,
1855 // so skip to the end. We only want to increment PSInputNum once for the
1856 // entire split argument.
1857 if (Arg->Flags.isSplit()) {
1858 while (!Arg->Flags.isSplitEnd()) {
1859 assert((!Arg->VT.isVector() ||(static_cast <bool> ((!Arg->VT.isVector() || Arg->
VT.getScalarSizeInBits() == 16) && "unexpected vector split in ps argument type"
) ? void (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"unexpected vector split in ps argument type\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1861, __extension__ __PRETTY_FUNCTION__))
1860 Arg->VT.getScalarSizeInBits() == 16) &&(static_cast <bool> ((!Arg->VT.isVector() || Arg->
VT.getScalarSizeInBits() == 16) && "unexpected vector split in ps argument type"
) ? void (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"unexpected vector split in ps argument type\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1861, __extension__ __PRETTY_FUNCTION__))
1861 "unexpected vector split in ps argument type")(static_cast <bool> ((!Arg->VT.isVector() || Arg->
VT.getScalarSizeInBits() == 16) && "unexpected vector split in ps argument type"
) ? void (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"unexpected vector split in ps argument type\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1861, __extension__ __PRETTY_FUNCTION__))
;
1862 if (!SkipArg)
1863 Splits.push_back(*Arg);
1864 Arg = &Ins[++I];
1865 }
1866 }
1867
1868 if (SkipArg) {
1869 // We can safely skip PS inputs.
1870 Skipped.set(Arg->getOrigArgIndex());
1871 ++PSInputNum;
1872 continue;
1873 }
1874
1875 Info->markPSInputAllocated(PSInputNum);
1876 if (Arg->Used)
1877 Info->markPSInputEnabled(PSInputNum);
1878
1879 ++PSInputNum;
1880 }
1881
1882 Splits.push_back(*Arg);
1883 }
1884}
1885
1886// Allocate special inputs passed in VGPRs.
1887void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1888 MachineFunction &MF,
1889 const SIRegisterInfo &TRI,
1890 SIMachineFunctionInfo &Info) const {
1891 const LLT S32 = LLT::scalar(32);
1892 MachineRegisterInfo &MRI = MF.getRegInfo();
1893
1894 if (Info.hasWorkItemIDX()) {
1895 Register Reg = AMDGPU::VGPR0;
1896 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1897
1898 CCInfo.AllocateReg(Reg);
1899 unsigned Mask = (Subtarget->hasPackedTID() &&
1900 Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1901 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1902 }
1903
1904 if (Info.hasWorkItemIDY()) {
1905 assert(Info.hasWorkItemIDX())(static_cast <bool> (Info.hasWorkItemIDX()) ? void (0) :
__assert_fail ("Info.hasWorkItemIDX()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1905, __extension__ __PRETTY_FUNCTION__))
;
1906 if (Subtarget->hasPackedTID()) {
1907 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1908 0x3ff << 10));
1909 } else {
1910 unsigned Reg = AMDGPU::VGPR1;
1911 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1912
1913 CCInfo.AllocateReg(Reg);
1914 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1915 }
1916 }
1917
1918 if (Info.hasWorkItemIDZ()) {
1919 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY())(static_cast <bool> (Info.hasWorkItemIDX() && Info
.hasWorkItemIDY()) ? void (0) : __assert_fail ("Info.hasWorkItemIDX() && Info.hasWorkItemIDY()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1919, __extension__ __PRETTY_FUNCTION__))
;
1920 if (Subtarget->hasPackedTID()) {
1921 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1922 0x3ff << 20));
1923 } else {
1924 unsigned Reg = AMDGPU::VGPR2;
1925 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1926
1927 CCInfo.AllocateReg(Reg);
1928 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1929 }
1930 }
1931}
1932
1933// Try to allocate a VGPR at the end of the argument list, or if no argument
1934// VGPRs are left allocating a stack slot.
1935// If \p Mask is is given it indicates bitfield position in the register.
1936// If \p Arg is given use it with new ]p Mask instead of allocating new.
1937static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1938 ArgDescriptor Arg = ArgDescriptor()) {
1939 if (Arg.isSet())
1940 return ArgDescriptor::createArg(Arg, Mask);
1941
1942 ArrayRef<MCPhysReg> ArgVGPRs
1943 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1944 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1945 if (RegIdx == ArgVGPRs.size()) {
1946 // Spill to stack required.
1947 int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1948
1949 return ArgDescriptor::createStack(Offset, Mask);
1950 }
1951
1952 unsigned Reg = ArgVGPRs[RegIdx];
1953 Reg = CCInfo.AllocateReg(Reg);
1954 assert(Reg != AMDGPU::NoRegister)(static_cast <bool> (Reg != AMDGPU::NoRegister) ? void (
0) : __assert_fail ("Reg != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1954, __extension__ __PRETTY_FUNCTION__))
;
1955
1956 MachineFunction &MF = CCInfo.getMachineFunction();
1957 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1958 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1959 return ArgDescriptor::createRegister(Reg, Mask);
1960}
1961
1962static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1963 const TargetRegisterClass *RC,
1964 unsigned NumArgRegs) {
1965 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1966 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1967 if (RegIdx == ArgSGPRs.size())
1968 report_fatal_error("ran out of SGPRs for arguments");
1969
1970 unsigned Reg = ArgSGPRs[RegIdx];
1971 Reg = CCInfo.AllocateReg(Reg);
1972 assert(Reg != AMDGPU::NoRegister)(static_cast <bool> (Reg != AMDGPU::NoRegister) ? void (
0) : __assert_fail ("Reg != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1972, __extension__ __PRETTY_FUNCTION__))
;
1973
1974 MachineFunction &MF = CCInfo.getMachineFunction();
1975 MF.addLiveIn(Reg, RC);
1976 return ArgDescriptor::createRegister(Reg);
1977}
1978
1979// If this has a fixed position, we still should allocate the register in the
1980// CCInfo state. Technically we could get away with this for values passed
1981// outside of the normal argument range.
1982static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1983 const TargetRegisterClass *RC,
1984 MCRegister Reg) {
1985 Reg = CCInfo.AllocateReg(Reg);
1986 assert(Reg != AMDGPU::NoRegister)(static_cast <bool> (Reg != AMDGPU::NoRegister) ? void (
0) : __assert_fail ("Reg != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1986, __extension__ __PRETTY_FUNCTION__))
;
1987 MachineFunction &MF = CCInfo.getMachineFunction();
1988 MF.addLiveIn(Reg, RC);
1989}
1990
1991static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1992 if (Arg) {
1993 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1994 Arg.getRegister());
1995 } else
1996 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1997}
1998
1999static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2000 if (Arg) {
2001 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2002 Arg.getRegister());
2003 } else
2004 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2005}
2006
2007/// Allocate implicit function VGPR arguments at the end of allocated user
2008/// arguments.
2009void SITargetLowering::allocateSpecialInputVGPRs(
2010 CCState &CCInfo, MachineFunction &MF,
2011 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2012 const unsigned Mask = 0x3ff;
2013 ArgDescriptor Arg;
2014
2015 if (Info.hasWorkItemIDX()) {
2016 Arg = allocateVGPR32Input(CCInfo, Mask);
2017 Info.setWorkItemIDX(Arg);
2018 }
2019
2020 if (Info.hasWorkItemIDY()) {
2021 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2022 Info.setWorkItemIDY(Arg);
2023 }
2024
2025 if (Info.hasWorkItemIDZ())
2026 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2027}
2028
2029/// Allocate implicit function VGPR arguments in fixed registers.
2030void SITargetLowering::allocateSpecialInputVGPRsFixed(
2031 CCState &CCInfo, MachineFunction &MF,
2032 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2033 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2034 if (!Reg)
2035 report_fatal_error("failed to allocated VGPR for implicit arguments");
2036
2037 const unsigned Mask = 0x3ff;
2038 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2039 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2040 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2041}
2042
2043void SITargetLowering::allocateSpecialInputSGPRs(
2044 CCState &CCInfo,
2045 MachineFunction &MF,
2046 const SIRegisterInfo &TRI,
2047 SIMachineFunctionInfo &Info) const {
2048 auto &ArgInfo = Info.getArgInfo();
2049
2050 // We need to allocate these in place regardless of their use.
2051 const bool IsFixed = AMDGPUTargetMachine::EnableFixedFunctionABI;
2052
2053 // TODO: Unify handling with private memory pointers.
2054 if (IsFixed || Info.hasDispatchPtr())
2055 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2056
2057 if (IsFixed || Info.hasQueuePtr())
2058 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2059
2060 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2061 // constant offset from the kernarg segment.
2062 if (IsFixed || Info.hasImplicitArgPtr())
2063 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2064
2065 if (IsFixed || Info.hasDispatchID())
2066 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2067
2068 // flat_scratch_init is not applicable for non-kernel functions.
2069
2070 if (IsFixed || Info.hasWorkGroupIDX())
2071 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2072
2073 if (IsFixed || Info.hasWorkGroupIDY())
2074 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2075
2076 if (IsFixed || Info.hasWorkGroupIDZ())
2077 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2078}
2079
2080// Allocate special inputs passed in user SGPRs.
2081void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2082 MachineFunction &MF,
2083 const SIRegisterInfo &TRI,
2084 SIMachineFunctionInfo &Info) const {
2085 if (Info.hasImplicitBufferPtr()) {
2086 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2087 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2088 CCInfo.AllocateReg(ImplicitBufferPtrReg);
2089 }
2090
2091 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2092 if (Info.hasPrivateSegmentBuffer()) {
2093 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2094 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2095 CCInfo.AllocateReg(PrivateSegmentBufferReg);
2096 }
2097
2098 if (Info.hasDispatchPtr()) {
2099 Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2100 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2101 CCInfo.AllocateReg(DispatchPtrReg);
2102 }
2103
2104 if (Info.hasQueuePtr()) {
2105 Register QueuePtrReg = Info.addQueuePtr(TRI);
2106 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2107 CCInfo.AllocateReg(QueuePtrReg);
2108 }
2109
2110 if (Info.hasKernargSegmentPtr()) {
2111 MachineRegisterInfo &MRI = MF.getRegInfo();
2112 Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2113 CCInfo.AllocateReg(InputPtrReg);
2114
2115 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2116 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2117 }
2118
2119 if (Info.hasDispatchID()) {
2120 Register DispatchIDReg = Info.addDispatchID(TRI);
2121 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2122 CCInfo.AllocateReg(DispatchIDReg);
2123 }
2124
2125 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2126 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2127 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2128 CCInfo.AllocateReg(FlatScratchInitReg);
2129 }
2130
2131 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2132 // these from the dispatch pointer.
2133}
2134
2135// Allocate special input registers that are initialized per-wave.
2136void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2137 MachineFunction &MF,
2138 SIMachineFunctionInfo &Info,
2139 CallingConv::ID CallConv,
2140 bool IsShader) const {
2141 if (Info.hasWorkGroupIDX()) {
2142 Register Reg = Info.addWorkGroupIDX();
2143 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2144 CCInfo.AllocateReg(Reg);
2145 }
2146
2147 if (Info.hasWorkGroupIDY()) {
2148 Register Reg = Info.addWorkGroupIDY();
2149 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2150 CCInfo.AllocateReg(Reg);
2151 }
2152
2153 if (Info.hasWorkGroupIDZ()) {
2154 Register Reg = Info.addWorkGroupIDZ();
2155 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2156 CCInfo.AllocateReg(Reg);
2157 }
2158
2159 if (Info.hasWorkGroupInfo()) {
2160 Register Reg = Info.addWorkGroupInfo();
2161 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2162 CCInfo.AllocateReg(Reg);
2163 }
2164
2165 if (Info.hasPrivateSegmentWaveByteOffset()) {
2166 // Scratch wave offset passed in system SGPR.
2167 unsigned PrivateSegmentWaveByteOffsetReg;
2168
2169 if (IsShader) {
2170 PrivateSegmentWaveByteOffsetReg =
2171 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2172
2173 // This is true if the scratch wave byte offset doesn't have a fixed
2174 // location.
2175 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2176 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2177 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2178 }
2179 } else
2180 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2181
2182 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2183 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2184 }
2185}
2186
2187static void reservePrivateMemoryRegs(const TargetMachine &TM,
2188 MachineFunction &MF,
2189 const SIRegisterInfo &TRI,
2190 SIMachineFunctionInfo &Info) {
2191 // Now that we've figured out where the scratch register inputs are, see if
2192 // should reserve the arguments and use them directly.
2193 MachineFrameInfo &MFI = MF.getFrameInfo();
2194 bool HasStackObjects = MFI.hasStackObjects();
2195 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2196
2197 // Record that we know we have non-spill stack objects so we don't need to
2198 // check all stack objects later.
2199 if (HasStackObjects)
2200 Info.setHasNonSpillStackObjects(true);
2201
2202 // Everything live out of a block is spilled with fast regalloc, so it's
2203 // almost certain that spilling will be required.
2204 if (TM.getOptLevel() == CodeGenOpt::None)
2205 HasStackObjects = true;
2206
2207 // For now assume stack access is needed in any callee functions, so we need
2208 // the scratch registers to pass in.
2209 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2210
2211 if (!ST.enableFlatScratch()) {
2212 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2213 // If we have stack objects, we unquestionably need the private buffer
2214 // resource. For the Code Object V2 ABI, this will be the first 4 user
2215 // SGPR inputs. We can reserve those and use them directly.
2216
2217 Register PrivateSegmentBufferReg =
2218 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2219 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2220 } else {
2221 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2222 // We tentatively reserve the last registers (skipping the last registers
2223 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2224 // we'll replace these with the ones immediately after those which were
2225 // really allocated. In the prologue copies will be inserted from the
2226 // argument to these reserved registers.
2227
2228 // Without HSA, relocations are used for the scratch pointer and the
2229 // buffer resource setup is always inserted in the prologue. Scratch wave
2230 // offset is still in an input SGPR.
2231 Info.setScratchRSrcReg(ReservedBufferReg);
2232 }
2233 }
2234
2235 MachineRegisterInfo &MRI = MF.getRegInfo();
2236
2237 // For entry functions we have to set up the stack pointer if we use it,
2238 // whereas non-entry functions get this "for free". This means there is no
2239 // intrinsic advantage to using S32 over S34 in cases where we do not have
2240 // calls but do need a frame pointer (i.e. if we are requested to have one
2241 // because frame pointer elimination is disabled). To keep things simple we
2242 // only ever use S32 as the call ABI stack pointer, and so using it does not
2243 // imply we need a separate frame pointer.
2244 //
2245 // Try to use s32 as the SP, but move it if it would interfere with input
2246 // arguments. This won't work with calls though.
2247 //
2248 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2249 // registers.
2250 if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2251 Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2252 } else {
2253 assert(AMDGPU::isShader(MF.getFunction().getCallingConv()))(static_cast <bool> (AMDGPU::isShader(MF.getFunction().
getCallingConv())) ? void (0) : __assert_fail ("AMDGPU::isShader(MF.getFunction().getCallingConv())"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2253, __extension__ __PRETTY_FUNCTION__))
;
2254
2255 if (MFI.hasCalls())
2256 report_fatal_error("call in graphics shader with too many input SGPRs");
2257
2258 for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2259 if (!MRI.isLiveIn(Reg)) {
2260 Info.setStackPtrOffsetReg(Reg);
2261 break;
2262 }
2263 }
2264
2265 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2266 report_fatal_error("failed to find register for SP");
2267 }
2268
2269 // hasFP should be accurate for entry functions even before the frame is
2270 // finalized, because it does not rely on the known stack size, only
2271 // properties like whether variable sized objects are present.
2272 if (ST.getFrameLowering()->hasFP(MF)) {
2273 Info.setFrameOffsetReg(AMDGPU::SGPR33);
2274 }
2275}
2276
2277bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2278 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2279 return !Info->isEntryFunction();
2280}
2281
2282void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2283
2284}
2285
2286void SITargetLowering::insertCopiesSplitCSR(
2287 MachineBasicBlock *Entry,
2288 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2289 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2290
2291 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2292 if (!IStart)
2293 return;
2294
2295 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2296 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2297 MachineBasicBlock::iterator MBBI = Entry->begin();
2298 for (const MCPhysReg *I = IStart; *I; ++I) {
2299 const TargetRegisterClass *RC = nullptr;
2300 if (AMDGPU::SReg_64RegClass.contains(*I))
2301 RC = &AMDGPU::SGPR_64RegClass;
2302 else if (AMDGPU::SReg_32RegClass.contains(*I))
2303 RC = &AMDGPU::SGPR_32RegClass;
2304 else
2305 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2305)
;
2306
2307 Register NewVR = MRI->createVirtualRegister(RC);
2308 // Create copy from CSR to a virtual register.
2309 Entry->addLiveIn(*I);
2310 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2311 .addReg(*I);
2312
2313 // Insert the copy-back instructions right before the terminator.
2314 for (auto *Exit : Exits)
2315 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2316 TII->get(TargetOpcode::COPY), *I)
2317 .addReg(NewVR);
2318 }
2319}
2320
2321SDValue SITargetLowering::LowerFormalArguments(
2322 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2323 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2324 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2325 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2326
2327 MachineFunction &MF = DAG.getMachineFunction();
2328 const Function &Fn = MF.getFunction();
2329 FunctionType *FType = MF.getFunction().getFunctionType();
2330 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2331
2332 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2333 DiagnosticInfoUnsupported NoGraphicsHSA(
2334 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2335 DAG.getContext()->diagnose(NoGraphicsHSA);
2336 return DAG.getEntryNode();
2337 }
2338
2339 Info->allocateModuleLDSGlobal(Fn.getParent());
2340
2341 SmallVector<ISD::InputArg, 16> Splits;
2342 SmallVector<CCValAssign, 16> ArgLocs;
2343 BitVector Skipped(Ins.size());
2344 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2345 *DAG.getContext());
2346
2347 bool IsGraphics = AMDGPU::isGraphics(CallConv);
2348 bool IsKernel = AMDGPU::isKernel(CallConv);
2349 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2350
2351 if (IsGraphics) {
2352 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit
() || Subtarget->enableFlatScratch()) && !Info->
hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
!Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo
() && !Info->hasWorkItemIDX() && !Info->
hasWorkItemIDY() && !Info->hasWorkItemIDZ()) ? void
(0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2357, __extension__ __PRETTY_FUNCTION__))
2353 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit
() || Subtarget->enableFlatScratch()) && !Info->
hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
!Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo
() && !Info->hasWorkItemIDX() && !Info->
hasWorkItemIDY() && !Info->hasWorkItemIDZ()) ? void
(0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2357, __extension__ __PRETTY_FUNCTION__))
2354 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit
() || Subtarget->enableFlatScratch()) && !Info->
hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
!Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo
() && !Info->hasWorkItemIDX() && !Info->
hasWorkItemIDY() && !Info->hasWorkItemIDZ()) ? void
(0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2357, __extension__ __PRETTY_FUNCTION__))
2355 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit
() || Subtarget->enableFlatScratch()) && !Info->
hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
!Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo
() && !Info->hasWorkItemIDX() && !Info->
hasWorkItemIDY() && !Info->hasWorkItemIDZ()) ? void
(0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2357, __extension__ __PRETTY_FUNCTION__))
2356 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit
() || Subtarget->enableFlatScratch()) && !Info->
hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
!Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo
() && !Info->hasWorkItemIDX() && !Info->
hasWorkItemIDY() && !Info->hasWorkItemIDZ()) ? void
(0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2357, __extension__ __PRETTY_FUNCTION__))
2357 !Info->hasWorkItemIDZ())(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit
() || Subtarget->enableFlatScratch()) && !Info->
hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
!Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo
() && !Info->hasWorkItemIDX() && !Info->
hasWorkItemIDY() && !Info->hasWorkItemIDZ()) ? void
(0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2357, __extension__ __PRETTY_FUNCTION__))
;
2358 }
2359
2360 if (CallConv == CallingConv::AMDGPU_PS) {
2361 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2362
2363 // At least one interpolation mode must be enabled or else the GPU will
2364 // hang.
2365 //
2366 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2367 // set PSInputAddr, the user wants to enable some bits after the compilation
2368 // based on run-time states. Since we can't know what the final PSInputEna
2369 // will look like, so we shouldn't do anything here and the user should take
2370 // responsibility for the correct programming.
2371 //
2372 // Otherwise, the following restrictions apply:
2373 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2374 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2375 // enabled too.
2376 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2377 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2378 CCInfo.AllocateReg(AMDGPU::VGPR0);
2379 CCInfo.AllocateReg(AMDGPU::VGPR1);
2380 Info->markPSInputAllocated(0);
2381 Info->markPSInputEnabled(0);
2382 }
2383 if (Subtarget->isAmdPalOS()) {
2384 // For isAmdPalOS, the user does not enable some bits after compilation
2385 // based on run-time states; the register values being generated here are
2386 // the final ones set in hardware. Therefore we need to apply the
2387 // workaround to PSInputAddr and PSInputEnable together. (The case where
2388 // a bit is set in PSInputAddr but not PSInputEnable is where the
2389 // frontend set up an input arg for a particular interpolation mode, but
2390 // nothing uses that input arg. Really we should have an earlier pass
2391 // that removes such an arg.)
2392 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2393 if ((PsInputBits & 0x7F) == 0 ||
2394 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2395 Info->markPSInputEnabled(
2396 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2397 }
2398 } else if (IsKernel) {
2399 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX())(static_cast <bool> (Info->hasWorkGroupIDX() &&
Info->hasWorkItemIDX()) ? void (0) : __assert_fail ("Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2399, __extension__ __PRETTY_FUNCTION__))
;
2400 } else {
2401 Splits.append(Ins.begin(), Ins.end());
2402 }
2403
2404 if (IsEntryFunc) {
2405 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2406 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2407 } else {
2408 // For the fixed ABI, pass workitem IDs in the last argument register.
2409 if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2410 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2411 }
2412
2413 if (IsKernel) {
2414 analyzeFormalArgumentsCompute(CCInfo, Ins);
2415 } else {
2416 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2417 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2418 }
2419
2420 SmallVector<SDValue, 16> Chains;
2421
2422 // FIXME: This is the minimum kernel argument alignment. We should improve
2423 // this to the maximum alignment of the arguments.
2424 //
2425 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2426 // kern arg offset.
2427 const Align KernelArgBaseAlign = Align(16);
2428
2429 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2430 const ISD::InputArg &Arg = Ins[i];
2431 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2432 InVals.push_back(DAG.getUNDEF(Arg.VT));
2433 continue;
2434 }
2435
2436 CCValAssign &VA = ArgLocs[ArgIdx++];
2437 MVT VT = VA.getLocVT();
2438
2439 if (IsEntryFunc && VA.isMemLoc()) {
2440 VT = Ins[i].VT;
2441 EVT MemVT = VA.getLocVT();
2442
2443 const uint64_t Offset = VA.getLocMemOffset();
2444 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2445
2446 if (Arg.Flags.isByRef()) {
2447 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2448
2449 const GCNTargetMachine &TM =
2450 static_cast<const GCNTargetMachine &>(getTargetMachine());
2451 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2452 Arg.Flags.getPointerAddrSpace())) {
2453 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2454 Arg.Flags.getPointerAddrSpace());
2455 }
2456
2457 InVals.push_back(Ptr);
2458 continue;
2459 }
2460
2461 SDValue Arg = lowerKernargMemParameter(
2462 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2463 Chains.push_back(Arg.getValue(1));
2464
2465 auto *ParamTy =
2466 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2467 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2468 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2469 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2470 // On SI local pointers are just offsets into LDS, so they are always
2471 // less than 16-bits. On CI and newer they could potentially be
2472 // real pointers, so we can't guarantee their size.
2473 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2474 DAG.getValueType(MVT::i16));
2475 }
2476
2477 InVals.push_back(Arg);
2478 continue;
2479 } else if (!IsEntryFunc && VA.isMemLoc()) {
2480 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2481 InVals.push_back(Val);
2482 if (!Arg.Flags.isByVal())
2483 Chains.push_back(Val.getValue(1));
2484 continue;
2485 }
2486
2487 assert(VA.isRegLoc() && "Parameter must be in a register!")(static_cast <bool> (VA.isRegLoc() && "Parameter must be in a register!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Parameter must be in a register!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2487, __extension__ __PRETTY_FUNCTION__))
;
2488
2489 Register Reg = VA.getLocReg();
2490 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2491 EVT ValVT = VA.getValVT();
2492
2493 Reg = MF.addLiveIn(Reg, RC);
2494 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2495
2496 if (Arg.Flags.isSRet()) {
2497 // The return object should be reasonably addressable.
2498
2499 // FIXME: This helps when the return is a real sret. If it is a
2500 // automatically inserted sret (i.e. CanLowerReturn returns false), an
2501 // extra copy is inserted in SelectionDAGBuilder which obscures this.
2502 unsigned NumBits
2503 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2504 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2505 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2506 }
2507
2508 // If this is an 8 or 16-bit value, it is really passed promoted
2509 // to 32 bits. Insert an assert[sz]ext to capture this, then
2510 // truncate to the right size.
2511 switch (VA.getLocInfo()) {
2512 case CCValAssign::Full:
2513 break;
2514 case CCValAssign::BCvt:
2515 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2516 break;
2517 case CCValAssign::SExt:
2518 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2519 DAG.getValueType(ValVT));
2520 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2521 break;
2522 case CCValAssign::ZExt:
2523 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2524 DAG.getValueType(ValVT));
2525 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2526 break;
2527 case CCValAssign::AExt:
2528 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2529 break;
2530 default:
2531 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2531)
;
2532 }
2533
2534 InVals.push_back(Val);
2535 }
2536
2537 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2538 // Special inputs come after user arguments.
2539 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2540 }
2541
2542 // Start adding system SGPRs.
2543 if (IsEntryFunc) {
2544 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2545 } else {
2546 CCInfo.AllocateReg(Info->getScratchRSrcReg());
2547 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2548 }
2549
2550 auto &ArgUsageInfo =
2551 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2552 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2553
2554 unsigned StackArgSize = CCInfo.getNextStackOffset();
2555 Info->setBytesInStackArgArea(StackArgSize);
2556
2557 return Chains.empty() ? Chain :
2558 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2559}
2560
2561// TODO: If return values can't fit in registers, we should return as many as
2562// possible in registers before passing on stack.
2563bool SITargetLowering::CanLowerReturn(
2564 CallingConv::ID CallConv,
2565 MachineFunction &MF, bool IsVarArg,
2566 const SmallVectorImpl<ISD::OutputArg> &Outs,
2567 LLVMContext &Context) const {
2568 // Replacing returns with sret/stack usage doesn't make sense for shaders.
2569 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2570 // for shaders. Vector types should be explicitly handled by CC.
2571 if (AMDGPU::isEntryFunctionCC(CallConv))
2572 return true;
2573
2574 SmallVector<CCValAssign, 16> RVLocs;
2575 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2576 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2577}
2578
2579SDValue
2580SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2581 bool isVarArg,
2582 const SmallVectorImpl<ISD::OutputArg> &Outs,
2583 const SmallVectorImpl<SDValue> &OutVals,
2584 const SDLoc &DL, SelectionDAG &DAG) const {
2585 MachineFunction &MF = DAG.getMachineFunction();
2586 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2587
2588 if (AMDGPU::isKernel(CallConv)) {
2589 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2590 OutVals, DL, DAG);
2591 }
2592
2593 bool IsShader = AMDGPU::isShader(CallConv);
2594
2595 Info->setIfReturnsVoid(Outs.empty());
2596 bool IsWaveEnd = Info->returnsVoid() && IsShader;
2597
2598 // CCValAssign - represent the assignment of the return value to a location.
2599 SmallVector<CCValAssign, 48> RVLocs;
2600 SmallVector<ISD::OutputArg, 48> Splits;
2601
2602 // CCState - Info about the registers and stack slots.
2603 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2604 *DAG.getContext());
2605
2606 // Analyze outgoing return values.
2607 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2608
2609 SDValue Flag;
2610 SmallVector<SDValue, 48> RetOps;
2611 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2612
2613 // Add return address for callable functions.
2614 if (!Info->isEntryFunction()) {
2615 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2616 SDValue ReturnAddrReg = CreateLiveInRegister(
2617 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2618
2619 SDValue ReturnAddrVirtualReg =
2620 DAG.getRegister(MF.getRegInfo().createVirtualRegister(
2621 CallConv != CallingConv::AMDGPU_Gfx
2622 ? &AMDGPU::CCR_SGPR_64RegClass
2623 : &AMDGPU::Gfx_CCR_SGPR_64RegClass),
2624 MVT::i64);
2625 Chain =
2626 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2627 Flag = Chain.getValue(1);
2628 RetOps.push_back(ReturnAddrVirtualReg);
2629 }
2630
2631 // Copy the result values into the output registers.
2632 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2633 ++I, ++RealRVLocIdx) {
2634 CCValAssign &VA = RVLocs[I];
2635 assert(VA.isRegLoc() && "Can only return in registers!")(static_cast <bool> (VA.isRegLoc() && "Can only return in registers!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2635, __extension__ __PRETTY_FUNCTION__))
;
2636 // TODO: Partially return in registers if return values don't fit.
2637 SDValue Arg = OutVals[RealRVLocIdx];
2638
2639 // Copied from other backends.
2640 switch (VA.getLocInfo()) {
2641 case CCValAssign::Full:
2642 break;
2643 case CCValAssign::BCvt:
2644 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2645 break;
2646 case CCValAssign::SExt:
2647 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2648 break;
2649 case CCValAssign::ZExt:
2650 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2651 break;
2652 case CCValAssign::AExt:
2653 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2654 break;
2655 default:
2656 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2656)
;
2657 }
2658
2659 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2660 Flag = Chain.getValue(1);
2661 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2662 }
2663
2664 // FIXME: Does sret work properly?
2665 if (!Info->isEntryFunction()) {
2666 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2667 const MCPhysReg *I =
2668 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2669 if (I) {
2670 for (; *I; ++I) {
2671 if (AMDGPU::SReg_64RegClass.contains(*I))
2672 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2673 else if (AMDGPU::SReg_32RegClass.contains(*I))
2674 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2675 else
2676 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2676)
;
2677 }
2678 }
2679 }
2680
2681 // Update chain and glue.
2682 RetOps[0] = Chain;
2683 if (Flag.getNode())
2684 RetOps.push_back(Flag);
2685
2686 unsigned Opc = AMDGPUISD::ENDPGM;
2687 if (!IsWaveEnd) {
2688 if (IsShader)
2689 Opc = AMDGPUISD::RETURN_TO_EPILOG;
2690 else if (CallConv == CallingConv::AMDGPU_Gfx)
2691 Opc = AMDGPUISD::RET_GFX_FLAG;
2692 else
2693 Opc = AMDGPUISD::RET_FLAG;
2694 }
2695
2696 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2697}
2698
2699SDValue SITargetLowering::LowerCallResult(
2700 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2701 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2702 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2703 SDValue ThisVal) const {
2704 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2705
2706 // Assign locations to each value returned by this call.
2707 SmallVector<CCValAssign, 16> RVLocs;
2708 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2709 *DAG.getContext());
2710 CCInfo.AnalyzeCallResult(Ins, RetCC);
2711
2712 // Copy all of the result registers out of their specified physreg.
2713 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2714 CCValAssign VA = RVLocs[i];
2715 SDValue Val;
2716
2717 if (VA.isRegLoc()) {
2718 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2719 Chain = Val.getValue(1);
2720 InFlag = Val.getValue(2);
2721 } else if (VA.isMemLoc()) {
2722 report_fatal_error("TODO: return values in memory");
2723 } else
2724 llvm_unreachable("unknown argument location type")::llvm::llvm_unreachable_internal("unknown argument location type"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2724)
;
2725
2726 switch (VA.getLocInfo()) {
2727 case CCValAssign::Full:
2728 break;
2729 case CCValAssign::BCvt:
2730 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2731 break;
2732 case CCValAssign::ZExt:
2733 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2734 DAG.getValueType(VA.getValVT()));
2735 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2736 break;
2737 case CCValAssign::SExt:
2738 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2739 DAG.getValueType(VA.getValVT()));
2740 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2741 break;
2742 case CCValAssign::AExt:
2743 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2744 break;
2745 default:
2746 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2746)
;
2747 }
2748
2749 InVals.push_back(Val);
2750 }
2751
2752 return Chain;
2753}
2754
2755// Add code to pass special inputs required depending on used features separate
2756// from the explicit user arguments present in the IR.
2757void SITargetLowering::passSpecialInputs(
2758 CallLoweringInfo &CLI,
2759 CCState &CCInfo,
2760 const SIMachineFunctionInfo &Info,
2761 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2762 SmallVectorImpl<SDValue> &MemOpChains,
2763 SDValue Chain) const {
2764 // If we don't have a call site, this was a call inserted by
2765 // legalization. These can never use special inputs.
2766 if (!CLI.CB)
2767 return;
2768
2769 SelectionDAG &DAG = CLI.DAG;
2770 const SDLoc &DL = CLI.DL;
2771
2772 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2773 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2774
2775 const AMDGPUFunctionArgInfo *CalleeArgInfo
2776 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2777 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2778 auto &ArgUsageInfo =
2779 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2780 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2781 }
2782
2783 // TODO: Unify with private memory register handling. This is complicated by
2784 // the fact that at least in kernels, the input argument is not necessarily
2785 // in the same location as the input.
2786 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2787 StringLiteral> ImplicitAttrs[] = {
2788 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2789 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2790 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2791 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2792 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2793 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2794 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2795 };
2796
2797 for (auto Attr : ImplicitAttrs) {
2798 const ArgDescriptor *OutgoingArg;
2799 const TargetRegisterClass *ArgRC;
2800 LLT ArgTy;
2801
2802 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2803
2804 // If the callee does not use the attribute value, skip copying the value.
2805 if (CLI.CB->hasFnAttr(Attr.second))
2806 continue;
2807
2808 std::tie(OutgoingArg, ArgRC, ArgTy) =
2809 CalleeArgInfo->getPreloadedValue(InputID);
2810 if (!OutgoingArg)
2811 continue;
2812
2813 const ArgDescriptor *IncomingArg;
2814 const TargetRegisterClass *IncomingArgRC;
2815 LLT Ty;
2816 std::tie(IncomingArg, IncomingArgRC, Ty) =
2817 CallerArgInfo.getPreloadedValue(InputID);
2818 assert(IncomingArgRC == ArgRC)(static_cast <bool> (IncomingArgRC == ArgRC) ? void (0)
: __assert_fail ("IncomingArgRC == ArgRC", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2818, __extension__ __PRETTY_FUNCTION__))
;
2819
2820 // All special arguments are ints for now.
2821 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2822 SDValue InputReg;
2823
2824 if (IncomingArg) {
2825 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2826 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2827 // The implicit arg ptr is special because it doesn't have a corresponding
2828 // input for kernels, and is computed from the kernarg segment pointer.
2829 InputReg = getImplicitArgPtr(DAG, DL);
2830 } else {
2831 // We may have proven the input wasn't needed, although the ABI is
2832 // requiring it. We just need to allocate the register appropriately.
2833 InputReg = DAG.getUNDEF(ArgVT);
2834 }
2835
2836 if (OutgoingArg->isRegister()) {
2837 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2838 if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2839 report_fatal_error("failed to allocate implicit input argument");
2840 } else {
2841 unsigned SpecialArgOffset =
2842 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2843 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2844 SpecialArgOffset);
2845 MemOpChains.push_back(ArgStore);
2846 }
2847 }
2848
2849 // Pack workitem IDs into a single register or pass it as is if already
2850 // packed.
2851 const ArgDescriptor *OutgoingArg;
2852 const TargetRegisterClass *ArgRC;
2853 LLT Ty;
2854
2855 std::tie(OutgoingArg, ArgRC, Ty) =
2856 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2857 if (!OutgoingArg)
2858 std::tie(OutgoingArg, ArgRC, Ty) =
2859 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2860 if (!OutgoingArg)
2861 std::tie(OutgoingArg, ArgRC, Ty) =
2862 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2863 if (!OutgoingArg)
2864 return;
2865
2866 const ArgDescriptor *IncomingArgX = std::get<0>(
2867 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2868 const ArgDescriptor *IncomingArgY = std::get<0>(
2869 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2870 const ArgDescriptor *IncomingArgZ = std::get<0>(
2871 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2872
2873 SDValue InputReg;
2874 SDLoc SL;
2875
2876 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2877 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2878 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2879
2880 // If incoming ids are not packed we need to pack them.
2881 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2882 NeedWorkItemIDX)
2883 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2884
2885 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2886 NeedWorkItemIDY) {
2887 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2888 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2889 DAG.getShiftAmountConstant(10, MVT::i32, SL));
2890 InputReg = InputReg.getNode() ?
2891 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2892 }
2893
2894 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2895 NeedWorkItemIDZ) {
2896 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2897 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2898 DAG.getShiftAmountConstant(20, MVT::i32, SL));
2899 InputReg = InputReg.getNode() ?
2900 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2901 }
2902
2903 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2904 // Workitem ids are already packed, any of present incoming arguments
2905 // will carry all required fields.
2906 ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2907 IncomingArgX ? *IncomingArgX :
2908 IncomingArgY ? *IncomingArgY :
2909 *IncomingArgZ, ~0u);
2910 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2911 }
2912
2913 if (OutgoingArg->isRegister()) {
2914 if (InputReg)
2915 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2916
2917 CCInfo.AllocateReg(OutgoingArg->getRegister());
2918 } else {
2919 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2920 if (InputReg) {
2921 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2922 SpecialArgOffset);
2923 MemOpChains.push_back(ArgStore);
2924 }
2925 }
2926}
2927
2928static bool canGuaranteeTCO(CallingConv::ID CC) {
2929 return CC == CallingConv::Fast;
2930}
2931
2932/// Return true if we might ever do TCO for calls with this calling convention.
2933static bool mayTailCallThisCC(CallingConv::ID CC) {
2934 switch (CC) {
2935 case CallingConv::C:
2936 case CallingConv::AMDGPU_Gfx:
2937 return true;
2938 default:
2939 return canGuaranteeTCO(CC);
2940 }
2941}
2942
2943bool SITargetLowering::isEligibleForTailCallOptimization(
2944 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2945 const SmallVectorImpl<ISD::OutputArg> &Outs,
2946 const SmallVectorImpl<SDValue> &OutVals,
2947 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2948 if (!mayTailCallThisCC(CalleeCC))
2949 return false;
2950
2951 // For a divergent call target, we need to do a waterfall loop over the
2952 // possible callees which precludes us from using a simple jump.
2953 if (Callee->isDivergent())
2954 return false;
2955
2956 MachineFunction &MF = DAG.getMachineFunction();
2957 const Function &CallerF = MF.getFunction();
2958 CallingConv::ID CallerCC = CallerF.getCallingConv();
2959 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2960 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2961
2962 // Kernels aren't callable, and don't have a live in return address so it
2963 // doesn't make sense to do a tail call with entry functions.
2964 if (!CallerPreserved)
2965 return false;
2966
2967 bool CCMatch = CallerCC == CalleeCC;
2968
2969 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2970 if (canGuaranteeTCO(CalleeCC) && CCMatch)
2971 return true;
2972 return false;
2973 }
2974
2975 // TODO: Can we handle var args?
2976 if (IsVarArg)
2977 return false;
2978
2979 for (const Argument &Arg : CallerF.args()) {
2980 if (Arg.hasByValAttr())
2981 return false;
2982 }
2983
2984 LLVMContext &Ctx = *DAG.getContext();
2985
2986 // Check that the call results are passed in the same way.
2987 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2988 CCAssignFnForCall(CalleeCC, IsVarArg),
2989 CCAssignFnForCall(CallerCC, IsVarArg)))
2990 return false;
2991
2992 // The callee has to preserve all registers the caller needs to preserve.
2993 if (!CCMatch) {
2994 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2995 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2996 return false;
2997 }
2998
2999 // Nothing more to check if the callee is taking no arguments.
3000 if (Outs.empty())
3001 return true;
3002
3003 SmallVector<CCValAssign, 16> ArgLocs;
3004 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3005
3006 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3007
3008 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3009 // If the stack arguments for this call do not fit into our own save area then
3010 // the call cannot be made tail.
3011 // TODO: Is this really necessary?
3012 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3013 return false;
3014
3015 const MachineRegisterInfo &MRI = MF.getRegInfo();
3016 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3017}
3018
3019bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3020 if (!CI->isTailCall())
3021 return false;
3022
3023 const Function *ParentFn = CI->getParent()->getParent();
3024 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3025 return false;
3026 return true;
3027}
3028
3029// The wave scratch offset register is used as the global base pointer.
3030SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3031 SmallVectorImpl<SDValue> &InVals) const {
3032 SelectionDAG &DAG = CLI.DAG;
3033 const SDLoc &DL = CLI.DL;
3034 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3035 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3036 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3037 SDValue Chain = CLI.Chain;
3038 SDValue Callee = CLI.Callee;
3039 bool &IsTailCall = CLI.IsTailCall;
3040 CallingConv::ID CallConv = CLI.CallConv;
3041 bool IsVarArg = CLI.IsVarArg;
3042 bool IsSibCall = false;
3043 bool IsThisReturn = false;
3044 MachineFunction &MF = DAG.getMachineFunction();
3045
3046 if (Callee.isUndef() || isNullConstant(Callee)) {
3047 if (!CLI.IsTailCall) {
3048 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3049 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3050 }
3051
3052 return Chain;
3053 }
3054
3055 if (IsVarArg) {
3056 return lowerUnhandledCall(CLI, InVals,
3057 "unsupported call to variadic function ");
3058 }
3059
3060 if (!CLI.CB)
3061 report_fatal_error("unsupported libcall legalization");
3062
3063 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3064 return lowerUnhandledCall(CLI, InVals,
3065 "unsupported required tail call to function ");
3066 }
3067
3068 if (AMDGPU::isShader(CallConv)) {
3069 // Note the issue is with the CC of the called function, not of the call
3070 // itself.
3071 return lowerUnhandledCall(CLI, InVals,
3072 "unsupported call to a shader function ");
3073 }
3074
3075 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3076 CallConv != CallingConv::AMDGPU_Gfx) {
3077 // Only allow calls with specific calling conventions.
3078 return lowerUnhandledCall(CLI, InVals,
3079 "unsupported calling convention for call from "
3080 "graphics shader of function ");
3081 }
3082
3083 if (IsTailCall) {
3084 IsTailCall = isEligibleForTailCallOptimization(
3085 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3086 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3087 report_fatal_error("failed to perform tail call elimination on a call "
3088 "site marked musttail");
3089 }
3090
3091 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3092
3093 // A sibling call is one where we're under the usual C ABI and not planning
3094 // to change that but can still do a tail call:
3095 if (!TailCallOpt && IsTailCall)
3096 IsSibCall = true;
3097
3098 if (IsTailCall)
3099 ++NumTailCalls;
3100 }
3101
3102 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3103 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3104 SmallVector<SDValue, 8> MemOpChains;
3105
3106 // Analyze operands of the call, assigning locations to each operand.
3107 SmallVector<CCValAssign, 16> ArgLocs;
3108 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3109 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3110
3111 if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
3112 CallConv != CallingConv::AMDGPU_Gfx) {
3113 // With a fixed ABI, allocate fixed registers before user arguments.
3114 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3115 }
3116
3117 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3118
3119 // Get a count of how many bytes are to be pushed on the stack.
3120 unsigned NumBytes = CCInfo.getNextStackOffset();
3121
3122 if (IsSibCall) {
3123 // Since we're not changing the ABI to make this a tail call, the memory
3124 // operands are already available in the caller's incoming argument space.
3125 NumBytes = 0;
3126 }
3127
3128 // FPDiff is the byte offset of the call's argument area from the callee's.
3129 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3130 // by this amount for a tail call. In a sibling call it must be 0 because the
3131 // caller will deallocate the entire stack and the callee still expects its
3132 // arguments to begin at SP+0. Completely unused for non-tail calls.
3133 int32_t FPDiff = 0;
3134 MachineFrameInfo &MFI = MF.getFrameInfo();
3135
3136 // Adjust the stack pointer for the new arguments...
3137 // These operations are automatically eliminated by the prolog/epilog pass
3138 if (!IsSibCall) {
3139 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3140
3141 if (!Subtarget->enableFlatScratch()) {
3142 SmallVector<SDValue, 4> CopyFromChains;
3143
3144 // In the HSA case, this should be an identity copy.
3145 SDValue ScratchRSrcReg
3146 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3147 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3148 CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3149 Chain = DAG.getTokenFactor(DL, CopyFromChains);
3150 }
3151 }
3152
3153 MVT PtrVT = MVT::i32;
3154
3155 // Walk the register/memloc assignments, inserting copies/loads.
3156 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3157 CCValAssign &VA = ArgLocs[i];
3158 SDValue Arg = OutVals[i];
3159
3160 // Promote the value if needed.
3161 switch (VA.getLocInfo()) {
3162 case CCValAssign::Full:
3163 break;
3164 case CCValAssign::BCvt:
3165 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3166 break;
3167 case CCValAssign::ZExt:
3168 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3169 break;
3170 case CCValAssign::SExt:
3171 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3172 break;
3173 case CCValAssign::AExt:
3174 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3175 break;
3176 case CCValAssign::FPExt:
3177 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3178 break;
3179 default:
3180 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3180)
;
3181 }
3182
3183 if (VA.isRegLoc()) {
3184 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3185 } else {
3186 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3186, __extension__ __PRETTY_FUNCTION__))
;
3187
3188 SDValue DstAddr;
3189 MachinePointerInfo DstInfo;
3190
3191 unsigned LocMemOffset = VA.getLocMemOffset();
3192 int32_t Offset = LocMemOffset;
3193
3194 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3195 MaybeAlign Alignment;
3196
3197 if (IsTailCall) {
3198 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3199 unsigned OpSize = Flags.isByVal() ?
3200 Flags.getByValSize() : VA.getValVT().getStoreSize();
3201
3202 // FIXME: We can have better than the minimum byval required alignment.
3203 Alignment =
3204 Flags.isByVal()
3205 ? Flags.getNonZeroByValAlign()
3206 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3207
3208 Offset = Offset + FPDiff;
3209 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3210
3211 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3212 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3213
3214 // Make sure any stack arguments overlapping with where we're storing
3215 // are loaded before this eventual operation. Otherwise they'll be
3216 // clobbered.
3217
3218 // FIXME: Why is this really necessary? This seems to just result in a
3219 // lot of code to copy the stack and write them back to the same
3220 // locations, which are supposed to be immutable?
3221 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3222 } else {
3223 // Stores to the argument stack area are relative to the stack pointer.
3224 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3225 MVT::i32);
3226 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3227 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3228 Alignment =
3229 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3230 }
3231
3232 if (Outs[i].Flags.isByVal()) {
3233 SDValue SizeNode =
3234 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3235 SDValue Cpy =
3236 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3237 Outs[i].Flags.getNonZeroByValAlign(),
3238 /*isVol = */ false, /*AlwaysInline = */ true,
3239 /*isTailCall = */ false, DstInfo,
3240 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3241
3242 MemOpChains.push_back(Cpy);
3243 } else {
3244 SDValue Store =
3245 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3246 MemOpChains.push_back(Store);
3247 }
3248 }
3249 }
3250
3251 if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3252 CallConv != CallingConv::AMDGPU_Gfx) {
3253 // Copy special input registers after user input arguments.
3254 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3255 }
3256
3257 if (!MemOpChains.empty())
3258 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3259
3260 // Build a sequence of copy-to-reg nodes chained together with token chain
3261 // and flag operands which copy the outgoing args into the appropriate regs.
3262 SDValue InFlag;
3263 for (auto &RegToPass : RegsToPass) {
3264 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3265 RegToPass.second, InFlag);
3266 InFlag = Chain.getValue(1);
3267 }
3268
3269
3270 SDValue PhysReturnAddrReg;
3271 if (IsTailCall) {
3272 // Since the return is being combined with the call, we need to pass on the
3273 // return address.
3274
3275 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3276 SDValue ReturnAddrReg = CreateLiveInRegister(
3277 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3278
3279 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3280 MVT::i64);
3281 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3282 InFlag = Chain.getValue(1);
3283 }
3284
3285 // We don't usually want to end the call-sequence here because we would tidy
3286 // the frame up *after* the call, however in the ABI-changing tail-call case
3287 // we've carefully laid out the parameters so that when sp is reset they'll be
3288 // in the correct location.
3289 if (IsTailCall && !IsSibCall) {
3290 Chain = DAG.getCALLSEQ_END(Chain,
3291 DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3292 DAG.getTargetConstant(0, DL, MVT::i32),
3293 InFlag, DL);
3294 InFlag = Chain.getValue(1);
3295 }
3296
3297 std::vector<SDValue> Ops;
3298 Ops.push_back(Chain);
3299 Ops.push_back(Callee);
3300 // Add a redundant copy of the callee global which will not be legalized, as
3301 // we need direct access to the callee later.
3302 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3303 const GlobalValue *GV = GSD->getGlobal();
3304 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3305 } else {
3306 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3307 }
3308
3309 if (IsTailCall) {
3310 // Each tail call may have to adjust the stack by a different amount, so
3311 // this information must travel along with the operation for eventual
3312 // consumption by emitEpilogue.
3313 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3314
3315 Ops.push_back(PhysReturnAddrReg);
3316 }
3317
3318 // Add argument registers to the end of the list so that they are known live
3319 // into the call.
3320 for (auto &RegToPass : RegsToPass) {
3321 Ops.push_back(DAG.getRegister(RegToPass.first,
3322 RegToPass.second.getValueType()));
3323 }
3324
3325 // Add a register mask operand representing the call-preserved registers.
3326
3327 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3328 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3329 assert(Mask && "Missing call preserved mask for calling convention")(static_cast <bool> (Mask && "Missing call preserved mask for calling convention"
) ? void (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3329, __extension__ __PRETTY_FUNCTION__))
;
3330 Ops.push_back(DAG.getRegisterMask(Mask));
3331
3332 if (InFlag.getNode())
3333 Ops.push_back(InFlag);
3334
3335 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3336
3337 // If we're doing a tall call, use a TC_RETURN here rather than an
3338 // actual call instruction.
3339 if (IsTailCall) {
3340 MFI.setHasTailCall();
3341 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3342 }
3343
3344 // Returns a chain and a flag for retval copy to use.
3345 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3346 Chain = Call.getValue(0);
3347 InFlag = Call.getValue(1);
3348
3349 uint64_t CalleePopBytes = NumBytes;
3350 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3351 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3352 InFlag, DL);
3353 if (!Ins.empty())
3354 InFlag = Chain.getValue(1);
3355
3356 // Handle result values, copying them out of physregs into vregs that we
3357 // return.
3358 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3359 InVals, IsThisReturn,
3360 IsThisReturn ? OutVals[0] : SDValue());
3361}
3362
3363// This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3364// except for applying the wave size scale to the increment amount.
3365SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3366 SDValue Op, SelectionDAG &DAG) const {
3367 const MachineFunction &MF = DAG.getMachineFunction();
3368 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3369
3370 SDLoc dl(Op);
3371 EVT VT = Op.getValueType();
3372 SDValue Tmp1 = Op;
3373 SDValue Tmp2 = Op.getValue(1);
3374 SDValue Tmp3 = Op.getOperand(2);
3375 SDValue Chain = Tmp1.getOperand(0);
3376
3377 Register SPReg = Info->getStackPtrOffsetReg();
3378
3379 // Chain the dynamic stack allocation so that it doesn't modify the stack
3380 // pointer when other instructions are using the stack.
3381 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3382
3383 SDValue Size = Tmp2.getOperand(1);
3384 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3385 Chain = SP.getValue(1);
3386 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3387 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3388 const TargetFrameLowering *TFL = ST.getFrameLowering();
3389 unsigned Opc =
3390 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3391 ISD::ADD : ISD::SUB;
3392
3393 SDValue ScaledSize = DAG.getNode(
3394 ISD::SHL, dl, VT, Size,
3395 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3396
3397 Align StackAlign = TFL->getStackAlign();
3398 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3399 if (Alignment && *Alignment > StackAlign) {
3400 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3401 DAG.getConstant(-(uint64_t)Alignment->value()
3402 << ST.getWavefrontSizeLog2(),
3403 dl, VT));
3404 }
3405
3406 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
3407 Tmp2 = DAG.getCALLSEQ_END(
3408 Chain, DAG.getIntPtrConstant(0, dl, true),
3409 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3410
3411 return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3412}
3413
3414SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3415 SelectionDAG &DAG) const {
3416 // We only handle constant sizes here to allow non-entry block, static sized
3417 // allocas. A truly dynamic value is more difficult to support because we
3418 // don't know if the size value is uniform or not. If the size isn't uniform,
3419 // we would need to do a wave reduction to get the maximum size to know how
3420 // much to increment the uniform stack pointer.
3421 SDValue Size = Op.getOperand(1);
3422 if (isa<ConstantSDNode>(Size))
3423 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3424
3425 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3426}
3427
3428Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3429 const MachineFunction &MF) const {
3430 Register Reg = StringSwitch<Register>(RegName)
3431 .Case("m0", AMDGPU::M0)
3432 .Case("exec", AMDGPU::EXEC)
3433 .Case("exec_lo", AMDGPU::EXEC_LO)
3434 .Case("exec_hi", AMDGPU::EXEC_HI)
3435 .Case("flat_scratch", AMDGPU::FLAT_SCR)
3436 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3437 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3438 .Default(Register());
3439
3440 if (Reg == AMDGPU::NoRegister) {
3441 report_fatal_error(Twine("invalid register name \""
3442 + StringRef(RegName) + "\"."));
3443
3444 }
3445
3446 if (!Subtarget->hasFlatScrRegister() &&
3447 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3448 report_fatal_error(Twine("invalid register \""
3449 + StringRef(RegName) + "\" for subtarget."));
3450 }
3451
3452 switch (Reg) {
3453 case AMDGPU::M0:
3454 case AMDGPU::EXEC_LO:
3455 case AMDGPU::EXEC_HI:
3456 case AMDGPU::FLAT_SCR_LO:
3457 case AMDGPU::FLAT_SCR_HI:
3458 if (VT.getSizeInBits() == 32)
3459 return Reg;
3460 break;
3461 case AMDGPU::EXEC:
3462 case AMDGPU::FLAT_SCR:
3463 if (VT.getSizeInBits() == 64)
3464 return Reg;
3465 break;
3466 default:
3467 llvm_unreachable("missing register type checking")::llvm::llvm_unreachable_internal("missing register type checking"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3467)
;
3468 }
3469
3470 report_fatal_error(Twine("invalid type for register \""
3471 + StringRef(RegName) + "\"."));
3472}
3473
3474// If kill is not the last instruction, split the block so kill is always a
3475// proper terminator.
3476MachineBasicBlock *
3477SITargetLowering::splitKillBlock(MachineInstr &MI,
3478 MachineBasicBlock *BB) const {
3479 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3480 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3481 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3482 return SplitBB;
3483}
3484
3485// Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3486// \p MI will be the only instruction in the loop body block. Otherwise, it will
3487// be the first instruction in the remainder block.
3488//
3489/// \returns { LoopBody, Remainder }
3490static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3491splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3492 MachineFunction *MF = MBB.getParent();
3493 MachineBasicBlock::iterator I(&MI);
3494
3495 // To insert the loop we need to split the block. Move everything after this
3496 // point to a new block, and insert a new empty block between the two.
3497 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3498 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3499 MachineFunction::iterator MBBI(MBB);
3500 ++MBBI;
3501
3502 MF->insert(MBBI, LoopBB);
3503 MF->insert(MBBI, RemainderBB);
3504
3505 LoopBB->addSuccessor(LoopBB);
3506 LoopBB->addSuccessor(RemainderBB);
3507
3508 // Move the rest of the block into a new block.
3509 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3510
3511 if (InstInLoop) {
3512 auto Next = std::next(I);
3513
3514 // Move instruction to loop body.
3515 LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3516
3517 // Move the rest of the block.
3518 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3519 } else {
3520 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3521 }
3522
3523 MBB.addSuccessor(LoopBB);
3524
3525 return std::make_pair(LoopBB, RemainderBB);
3526}
3527
3528/// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3529void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3530 MachineBasicBlock *MBB = MI.getParent();
3531 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3532 auto I = MI.getIterator();
3533 auto E = std::next(I);
3534
3535 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3536 .addImm(0);
3537
3538 MIBundleBuilder Bundler(*MBB, I, E);
3539 finalizeBundle(*MBB, Bundler.begin());
3540}
3541
3542MachineBasicBlock *
3543SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3544 MachineBasicBlock *BB) const {
3545 const DebugLoc &DL = MI.getDebugLoc();
3546
3547 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3548
3549 MachineBasicBlock *LoopBB;
3550 MachineBasicBlock *RemainderBB;
3551 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3552
3553 // Apparently kill flags are only valid if the def is in the same block?
3554 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3555 Src->setIsKill(false);
3556
3557 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3558
3559 MachineBasicBlock::iterator I = LoopBB->end();
3560
3561 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3562 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3563
3564 // Clear TRAP_STS.MEM_VIOL
3565 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3566 .addImm(0)
3567 .addImm(EncodedReg);
3568
3569 bundleInstWithWaitcnt(MI);
3570
3571 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3572
3573 // Load and check TRAP_STS.MEM_VIOL
3574 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3575 .addImm(EncodedReg);
3576
3577 // FIXME: Do we need to use an isel pseudo that may clobber scc?
3578 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3579 .addReg(Reg, RegState::Kill)
3580 .addImm(0);
3581 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3582 .addMBB(LoopBB);
3583
3584 return RemainderBB;
3585}
3586
3587// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3588// wavefront. If the value is uniform and just happens to be in a VGPR, this
3589// will only do one iteration. In the worst case, this will loop 64 times.
3590//
3591// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3592static MachineBasicBlock::iterator
3593emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3594 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3595 const DebugLoc &DL, const MachineOperand &Idx,
3596 unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3597 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3598 Register &SGPRIdxReg) {
3599
3600 MachineFunction *MF = OrigBB.getParent();
3601 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3602 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3603 MachineBasicBlock::iterator I = LoopBB.begin();
3604
3605 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3606 Register PhiExec = MRI.createVirtualRegister(BoolRC);
3607 Register NewExec = MRI.createVirtualRegister(BoolRC);
3608 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3609 Register CondReg = MRI.createVirtualRegister(BoolRC);
3610
3611 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3612 .addReg(InitReg)
3613 .addMBB(&OrigBB)
3614 .addReg(ResultReg)
3615 .addMBB(&LoopBB);
3616
3617 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3618 .addReg(InitSaveExecReg)
3619 .addMBB(&OrigBB)
3620 .addReg(NewExec)
3621 .addMBB(&LoopBB);
3622
3623 // Read the next variant <- also loop target.
3624 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3625 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3626
3627 // Compare the just read M0 value to all possible Idx values.
3628 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3629 .addReg(CurrentIdxReg)
3630 .addReg(Idx.getReg(), 0, Idx.getSubReg());
3631
3632 // Update EXEC, save the original EXEC value to VCC.
3633 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3634 : AMDGPU::S_AND_SAVEEXEC_B64),
3635 NewExec)
3636 .addReg(CondReg, RegState::Kill);
3637
3638 MRI.setSimpleHint(NewExec, CondReg);
3639
3640 if (UseGPRIdxMode) {
3641 if (Offset == 0) {
3642 SGPRIdxReg = CurrentIdxReg;
3643 } else {
3644 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3645 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3646 .addReg(CurrentIdxReg, RegState::Kill)
3647 .addImm(Offset);
3648 }
3649 } else {
3650 // Move index from VCC into M0
3651 if (Offset == 0) {
3652 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3653 .addReg(CurrentIdxReg, RegState::Kill);
3654 } else {
3655 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3656 .addReg(CurrentIdxReg, RegState::Kill)
3657 .addImm(Offset);
3658 }
3659 }
3660
3661 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3662 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3663 MachineInstr *InsertPt =
3664 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3665 : AMDGPU::S_XOR_B64_term), Exec)
3666 .addReg(Exec)
3667 .addReg(NewExec);
3668
3669 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3670 // s_cbranch_scc0?
3671
3672 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3673 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3674 .addMBB(&LoopBB);
3675
3676 return InsertPt->getIterator();
3677}
3678
3679// This has slightly sub-optimal regalloc when the source vector is killed by
3680// the read. The register allocator does not understand that the kill is
3681// per-workitem, so is kept alive for the whole loop so we end up not re-using a
3682// subregister from it, using 1 more VGPR than necessary. This was saved when
3683// this was expanded after register allocation.
3684static MachineBasicBlock::iterator
3685loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3686 unsigned InitResultReg, unsigned PhiReg, int Offset,
3687 bool UseGPRIdxMode, Register &SGPRIdxReg) {
3688 MachineFunction *MF = MBB.getParent();
3689 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3690 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3691 MachineRegisterInfo &MRI = MF->getRegInfo();
3692 const DebugLoc &DL = MI.getDebugLoc();
3693 MachineBasicBlock::iterator I(&MI);
3694
3695 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3696 Register DstReg = MI.getOperand(0).getReg();
3697 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3698 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3699 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3700 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3701
3702 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3703
3704 // Save the EXEC mask
3705 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3706 .addReg(Exec);
3707
3708 MachineBasicBlock *LoopBB;
3709 MachineBasicBlock *RemainderBB;
3710 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3711
3712 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3713
3714 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3715 InitResultReg, DstReg, PhiReg, TmpExec,
3716 Offset, UseGPRIdxMode, SGPRIdxReg);
3717
3718 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3719 MachineFunction::iterator MBBI(LoopBB);
3720 ++MBBI;
3721 MF->insert(MBBI, LandingPad);
3722 LoopBB->removeSuccessor(RemainderBB);
3723 LandingPad->addSuccessor(RemainderBB);
3724 LoopBB->addSuccessor(LandingPad);
3725 MachineBasicBlock::iterator First = LandingPad->begin();
3726 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3727 .addReg(SaveExec);
3728
3729 return InsPt;
3730}
3731
3732// Returns subreg index, offset
3733static std::pair<unsigned, int>
3734computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3735 const TargetRegisterClass *SuperRC,
3736 unsigned VecReg,
3737 int Offset) {
3738 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3739
3740 // Skip out of bounds offsets, or else we would end up using an undefined
3741 // register.
3742 if (Offset >= NumElts || Offset < 0)
3743 return std::make_pair(AMDGPU::sub0, Offset);
3744
3745 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3746}
3747
3748static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3749 MachineRegisterInfo &MRI, MachineInstr &MI,
3750 int Offset) {
3751 MachineBasicBlock *MBB = MI.getParent();
3752 const DebugLoc &DL = MI.getDebugLoc();
3753 MachineBasicBlock::iterator I(&MI);
3754
3755 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3756
3757 assert(Idx->getReg() != AMDGPU::NoRegister)(static_cast <bool> (Idx->getReg() != AMDGPU::NoRegister
) ? void (0) : __assert_fail ("Idx->getReg() != AMDGPU::NoRegister"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3757, __extension__ __PRETTY_FUNCTION__))
;
3758
3759 if (Offset == 0) {
3760 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3761 } else {
3762 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3763 .add(*Idx)
3764 .addImm(Offset);
3765 }
3766}
3767
3768static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3769 MachineRegisterInfo &MRI, MachineInstr &MI,
3770 int Offset) {
3771 MachineBasicBlock *MBB = MI.getParent();
3772 const DebugLoc &DL = MI.getDebugLoc();
3773 MachineBasicBlock::iterator I(&MI);
3774
3775 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3776
3777 if (Offset == 0)
3778 return Idx->getReg();
3779
3780 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3781 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3782 .add(*Idx)
3783 .addImm(Offset);
3784 return Tmp;
3785}
3786
3787static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3788 MachineBasicBlock &MBB,
3789 const GCNSubtarget &ST) {
3790 const SIInstrInfo *TII = ST.getInstrInfo();
3791 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3792 MachineFunction *MF = MBB.getParent();
3793 MachineRegisterInfo &MRI = MF->getRegInfo();
3794
3795 Register Dst = MI.getOperand(0).getReg();
3796 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3797 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3798 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3799
3800 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3801 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3802
3803 unsigned SubReg;
3804 std::tie(SubReg, Offset)
3805 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3806
3807 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3808
3809 // Check for a SGPR index.
3810 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3811 MachineBasicBlock::iterator I(&MI);
3812 const DebugLoc &DL = MI.getDebugLoc();
3813
3814 if (UseGPRIdxMode) {
3815 // TODO: Look at the uses to avoid the copy. This may require rescheduling
3816 // to avoid interfering with other uses, so probably requires a new
3817 // optimization pass.
3818 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3819
3820 const MCInstrDesc &GPRIDXDesc =
3821 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3822 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3823 .addReg(SrcReg)
3824 .addReg(Idx)
3825 .addImm(SubReg);
3826 } else {
3827 setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3828
3829 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3830 .addReg(SrcReg, 0, SubReg)
3831 .addReg(SrcReg, RegState::Implicit);
3832 }
3833
3834 MI.eraseFromParent();
3835
3836 return &MBB;
3837 }
3838
3839 // Control flow needs to be inserted if indexing with a VGPR.
3840 const DebugLoc &DL = MI.getDebugLoc();
3841 MachineBasicBlock::iterator I(&MI);
3842
3843 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3844 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3845
3846 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3847
3848 Register SGPRIdxReg;
3849 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3850 UseGPRIdxMode, SGPRIdxReg);
3851
3852 MachineBasicBlock *LoopBB = InsPt->getParent();
3853
3854 if (UseGPRIdxMode) {
3855 const MCInstrDesc &GPRIDXDesc =
3856 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3857
3858 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3859 .addReg(SrcReg)
3860 .addReg(SGPRIdxReg)
3861 .addImm(SubReg);
3862 } else {
3863 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3864 .addReg(SrcReg, 0, SubReg)
3865 .addReg(SrcReg, RegState::Implicit);
3866 }
3867
3868 MI.eraseFromParent();
3869
3870 return LoopBB;
3871}
3872
3873static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3874 MachineBasicBlock &MBB,
3875 const GCNSubtarget &ST) {
3876 const SIInstrInfo *TII = ST.getInstrInfo();
3877 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3878 MachineFunction *MF = MBB.getParent();
3879 MachineRegisterInfo &MRI = MF->getRegInfo();
3880
3881 Register Dst = MI.getOperand(0).getReg();
3882 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3883 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3884 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3885 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3886 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3887 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3888
3889 // This can be an immediate, but will be folded later.
3890 assert(Val->getReg())(static_cast <bool> (Val->getReg()) ? void (0) : __assert_fail
("Val->getReg()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3890, __extension__ __PRETTY_FUNCTION__))
;
3891
3892 unsigned SubReg;
3893 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3894 SrcVec->getReg(),
3895 Offset);
3896 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3897
3898 if (Idx->getReg() == AMDGPU::NoRegister) {
3899 MachineBasicBlock::iterator I(&MI);
3900 const DebugLoc &DL = MI.getDebugLoc();
3901
3902 assert(Offset == 0)(static_cast <bool> (Offset == 0) ? void (0) : __assert_fail
("Offset == 0", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3902, __extension__ __PRETTY_FUNCTION__))
;
3903
3904 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3905 .add(*SrcVec)
3906 .add(*Val)
3907 .addImm(SubReg);
3908
3909 MI.eraseFromParent();
3910 return &MBB;
3911 }
3912
3913 // Check for a SGPR index.
3914 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3915 MachineBasicBlock::iterator I(&MI);
3916 const DebugLoc &DL = MI.getDebugLoc();
3917
3918 if (UseGPRIdxMode) {
3919 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3920
3921 const MCInstrDesc &GPRIDXDesc =
3922 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3923 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3924 .addReg(SrcVec->getReg())
3925 .add(*Val)
3926 .addReg(Idx)
3927 .addImm(SubReg);
3928 } else {
3929 setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3930
3931 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3932 TRI.getRegSizeInBits(*VecRC), 32, false);
3933 BuildMI(MBB, I, DL, MovRelDesc, Dst)
3934 .addReg(SrcVec->getReg())
3935 .add(*Val)
3936 .addImm(SubReg);
3937 }
3938 MI.eraseFromParent();
3939 return &MBB;
3940 }
3941
3942 // Control flow needs to be inserted if indexing with a VGPR.
3943 if (Val->isReg())
3944 MRI.clearKillFlags(Val->getReg());
3945
3946 const DebugLoc &DL = MI.getDebugLoc();
3947
3948 Register PhiReg = MRI.createVirtualRegister(VecRC);
3949
3950 Register SGPRIdxReg;
3951 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3952 UseGPRIdxMode, SGPRIdxReg);
3953 MachineBasicBlock *LoopBB = InsPt->getParent();
3954
3955 if (UseGPRIdxMode) {
3956 const MCInstrDesc &GPRIDXDesc =
3957 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3958
3959 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3960 .addReg(PhiReg)
3961 .add(*Val)
3962 .addReg(SGPRIdxReg)
3963 .addImm(AMDGPU::sub0);
3964 } else {
3965 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3966 TRI.getRegSizeInBits(*VecRC), 32, false);
3967 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3968 .addReg(PhiReg)
3969 .add(*Val)
3970 .addImm(AMDGPU::sub0);
3971 }
3972
3973 MI.eraseFromParent();
3974 return LoopBB;
3975}
3976
3977MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3978 MachineInstr &MI, MachineBasicBlock *BB) const {
3979
3980 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3981 MachineFunction *MF = BB->getParent();
3982 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3983
3984 switch (MI.getOpcode()) {
3985 case AMDGPU::S_UADDO_PSEUDO:
3986 case AMDGPU::S_USUBO_PSEUDO: {
3987 const DebugLoc &DL = MI.getDebugLoc();
3988 MachineOperand &Dest0 = MI.getOperand(0);
3989 MachineOperand &Dest1 = MI.getOperand(1);
3990 MachineOperand &Src0 = MI.getOperand(2);
3991 MachineOperand &Src1 = MI.getOperand(3);
3992
3993 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3994 ? AMDGPU::S_ADD_I32
3995 : AMDGPU::S_SUB_I32;
3996 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3997
3998 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3999 .addImm(1)
4000 .addImm(0);
4001
4002 MI.eraseFromParent();
4003 return BB;
4004 }
4005 case AMDGPU::S_ADD_U64_PSEUDO:
4006 case AMDGPU::S_SUB_U64_PSEUDO: {
4007 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4008 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4009 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4010 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4011 const DebugLoc &DL = MI.getDebugLoc();
4012
4013 MachineOperand &Dest = MI.getOperand(0);
4014 MachineOperand &Src0 = MI.getOperand(1);
4015 MachineOperand &Src1 = MI.getOperand(2);
4016
4017 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4018 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4019
4020 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4021 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4022 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4023 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4024
4025 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4026 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4027 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4028 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4029
4030 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4031
4032 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4033 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4034 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4035 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4036 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4037 .addReg(DestSub0)
4038 .addImm(AMDGPU::sub0)
4039 .addReg(DestSub1)
4040 .addImm(AMDGPU::sub1);
4041 MI.eraseFromParent();
4042 return BB;
4043 }
4044 case AMDGPU::V_ADD_U64_PSEUDO:
4045 case AMDGPU::V_SUB_U64_PSEUDO: {
4046 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4047 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4048 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4049 const DebugLoc &DL = MI.getDebugLoc();
4050
4051 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4052
4053 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4054
4055 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4056 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4057
4058 Register CarryReg = MRI.createVirtualRegister(CarryRC);
4059 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4060
4061 MachineOperand &Dest = MI.getOperand(0);
4062 MachineOperand &Src0 = MI.getOperand(1);
4063 MachineOperand &Src1 = MI.getOperand(2);
4064
4065 const TargetRegisterClass *Src0RC = Src0.isReg()
4066 ? MRI.getRegClass(Src0.getReg())
4067 : &AMDGPU::VReg_64RegClass;
4068 const TargetRegisterClass *Src1RC = Src1.isReg()
4069 ? MRI.getRegClass(Src1.getReg())
4070 : &AMDGPU::VReg_64RegClass;
4071
4072 const TargetRegisterClass *Src0SubRC =
4073 TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4074 const TargetRegisterClass *Src1SubRC =
4075 TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4076
4077 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4078 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4079 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4080 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4081
4082 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4083 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4084 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4085 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4086
4087 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4088 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4089 .addReg(CarryReg, RegState::Define)
4090 .add(SrcReg0Sub0)
4091 .add(SrcReg1Sub0)
4092 .addImm(0); // clamp bit
4093
4094 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4095 MachineInstr *HiHalf =
4096 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4097 .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4098 .add(SrcReg0Sub1)
4099 .add(SrcReg1Sub1)
4100 .addReg(CarryReg, RegState::Kill)
4101 .addImm(0); // clamp bit
4102
4103 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4104 .addReg(DestSub0)
4105 .addImm(AMDGPU::sub0)
4106 .addReg(DestSub1)
4107 .addImm(AMDGPU::sub1);
4108 TII->legalizeOperands(*LoHalf);
4109 TII->legalizeOperands(*HiHalf);
4110 MI.eraseFromParent();
4111 return BB;
4112 }
4113 case AMDGPU::S_ADD_CO_PSEUDO:
4114 case AMDGPU::S_SUB_CO_PSEUDO: {
4115 // This pseudo has a chance to be selected
4116 // only from uniform add/subcarry node. All the VGPR operands
4117 // therefore assumed to be splat vectors.
4118 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4119 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4120 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4121 MachineBasicBlock::iterator MII = MI;
4122 const DebugLoc &DL = MI.getDebugLoc();
4123 MachineOperand &Dest = MI.getOperand(0);
4124 MachineOperand &CarryDest = MI.getOperand(1);
4125 MachineOperand &Src0 = MI.getOperand(2);
4126 MachineOperand &Src1 = MI.getOperand(3);
4127 MachineOperand &Src2 = MI.getOperand(4);
4128 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4129 ? AMDGPU::S_ADDC_U32
4130 : AMDGPU::S_SUBB_U32;
4131 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4132 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4133 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4134 .addReg(Src0.getReg());
4135 Src0.setReg(RegOp0);
4136 }
4137 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4138 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4139 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4140 .addReg(Src1.getReg());
4141 Src1.setReg(RegOp1);
4142 }
4143 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4144 if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4145 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4146 .addReg(Src2.getReg());
4147 Src2.setReg(RegOp2);
4148 }
4149
4150 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4151 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4152 assert(WaveSize == 64 || WaveSize == 32)(static_cast <bool> (WaveSize == 64 || WaveSize == 32) ?
void (0) : __assert_fail ("WaveSize == 64 || WaveSize == 32"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4152, __extension__ __PRETTY_FUNCTION__))
;
4153
4154 if (WaveSize == 64) {
4155 if (ST.hasScalarCompareEq64()) {
4156 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4157 .addReg(Src2.getReg())
4158 .addImm(0);
4159 } else {
4160 const TargetRegisterClass *SubRC =
4161 TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4162 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4163 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4164 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4165 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4166 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4167
4168 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4169 .add(Src2Sub0)
4170 .add(Src2Sub1);
4171
4172 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4173 .addReg(Src2_32, RegState::Kill)
4174 .addImm(0);
4175 }
4176 } else {
4177 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4178 .addReg(Src2.getReg())
4179 .addImm(0);
4180 }
4181
4182 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4183
4184 unsigned SelOpc =
4185 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4186
4187 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4188 .addImm(-1)
4189 .addImm(0);
4190
4191 MI.eraseFromParent();
4192 return BB;
4193 }
4194 case AMDGPU::SI_INIT_M0: {
4195 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4196 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4197 .add(MI.getOperand(0));
4198 MI.eraseFromParent();
4199 return BB;
4200 }
4201 case AMDGPU::GET_GROUPSTATICSIZE: {
4202 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||(static_cast <bool> (getTargetMachine().getTargetTriple
().getOS() == Triple::AMDHSA || getTargetMachine().getTargetTriple
().getOS() == Triple::AMDPAL) ? void (0) : __assert_fail ("getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4203, __extension__ __PRETTY_FUNCTION__))
4203 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)(static_cast <bool> (getTargetMachine().getTargetTriple
().getOS() == Triple::AMDHSA || getTargetMachine().getTargetTriple
().getOS() == Triple::AMDPAL) ? void (0) : __assert_fail ("getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4203, __extension__ __PRETTY_FUNCTION__))
;
4204 DebugLoc DL = MI.getDebugLoc();
4205 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4206 .add(MI.getOperand(0))
4207 .addImm(MFI->getLDSSize());
4208 MI.eraseFromParent();
4209 return BB;
4210 }
4211 case AMDGPU::SI_INDIRECT_SRC_V1:
4212 case AMDGPU::SI_INDIRECT_SRC_V2:
4213 case AMDGPU::SI_INDIRECT_SRC_V4:
4214 case AMDGPU::SI_INDIRECT_SRC_V8:
4215 case AMDGPU::SI_INDIRECT_SRC_V16:
4216 case AMDGPU::SI_INDIRECT_SRC_V32:
4217 return emitIndirectSrc(MI, *BB, *getSubtarget());
4218 case AMDGPU::SI_INDIRECT_DST_V1:
4219 case AMDGPU::SI_INDIRECT_DST_V2:
4220 case AMDGPU::SI_INDIRECT_DST_V4:
4221 case AMDGPU::SI_INDIRECT_DST_V8:
4222 case AMDGPU::SI_INDIRECT_DST_V16:
4223 case AMDGPU::SI_INDIRECT_DST_V32:
4224 return emitIndirectDst(MI, *BB, *getSubtarget());
4225 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4226 case AMDGPU::SI_KILL_I1_PSEUDO:
4227 return splitKillBlock(MI, BB);
4228 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4229 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4230 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4231 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4232
4233 Register Dst = MI.getOperand(0).getReg();
4234 Register Src0 = MI.getOperand(1).getReg();
4235 Register Src1 = MI.getOperand(2).getReg();
4236 const DebugLoc &DL = MI.getDebugLoc();
4237 Register SrcCond = MI.getOperand(3).getReg();
4238
4239 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4240 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4241 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4242 Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4243
4244 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4245 .addReg(SrcCond);
4246 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4247 .addImm(0)
4248 .addReg(Src0, 0, AMDGPU::sub0)
4249 .addImm(0)
4250 .addReg(Src1, 0, AMDGPU::sub0)
4251 .addReg(SrcCondCopy);
4252 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4253 .addImm(0)
4254 .addReg(Src0, 0, AMDGPU::sub1)
4255 .addImm(0)
4256 .addReg(Src1, 0, AMDGPU::sub1)
4257 .addReg(SrcCondCopy);
4258
4259 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4260 .addReg(DstLo)
4261 .addImm(AMDGPU::sub0)
4262 .addReg(DstHi)
4263 .addImm(AMDGPU::sub1);
4264 MI.eraseFromParent();
4265 return BB;
4266 }
4267 case AMDGPU::SI_BR_UNDEF: {
4268 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4269 const DebugLoc &DL = MI.getDebugLoc();
4270 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4271 .add(MI.getOperand(0));
4272 Br->getOperand(1).setIsUndef(true); // read undef SCC
4273 MI.eraseFromParent();
4274 return BB;
4275 }
4276 case AMDGPU::ADJCALLSTACKUP:
4277 case AMDGPU::ADJCALLSTACKDOWN: {
4278 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4279 MachineInstrBuilder MIB(*MF, &MI);
4280 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4281 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4282 return BB;
4283 }
4284 case AMDGPU::SI_CALL_ISEL: {
4285 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4286 const DebugLoc &DL = MI.getDebugLoc();
4287
4288 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4289
4290 MachineInstrBuilder MIB;
4291 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4292
4293 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4294 MIB.add(MI.getOperand(I));
4295
4296 MIB.cloneMemRefs(MI);
4297 MI.eraseFromParent();
4298 return BB;
4299 }
4300 case AMDGPU::V_ADD_CO_U32_e32:
4301 case AMDGPU::V_SUB_CO_U32_e32:
4302 case AMDGPU::V_SUBREV_CO_U32_e32: {
4303 // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4304 const DebugLoc &DL = MI.getDebugLoc();
4305 unsigned Opc = MI.getOpcode();
4306
4307 bool NeedClampOperand = false;
4308 if (TII->pseudoToMCOpcode(Opc) == -1) {
4309 Opc = AMDGPU::getVOPe64(Opc);
4310 NeedClampOperand = true;
4311 }
4312
4313 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4314 if (TII->isVOP3(*I)) {
4315 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4316 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4317 I.addReg(TRI->getVCC(), RegState::Define);
4318 }
4319 I.add(MI.getOperand(1))
4320 .add(MI.getOperand(2));
4321 if (NeedClampOperand)
4322 I.addImm(0); // clamp bit for e64 encoding
4323
4324 TII->legalizeOperands(*I);
4325
4326 MI.eraseFromParent();
4327 return BB;
4328 }
4329 case AMDGPU::V_ADDC_U32_e32:
4330 case AMDGPU::V_SUBB_U32_e32:
4331 case AMDGPU::V_SUBBREV_U32_e32:
4332 // These instructions have an implicit use of vcc which counts towards the
4333 // constant bus limit.
4334 TII->legalizeOperands(MI);
4335 return BB;
4336 case AMDGPU::DS_GWS_INIT:
4337 case AMDGPU::DS_GWS_SEMA_BR:
4338 case AMDGPU::DS_GWS_BARRIER:
4339 if (Subtarget->needsAlignedVGPRs()) {
4340 // Add implicit aligned super-reg to force alignment on the data operand.
4341 const DebugLoc &DL = MI.getDebugLoc();
4342 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4343 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4344 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4345 Register DataReg = Op->getReg();
4346 bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4347 Register Undef = MRI.createVirtualRegister(
4348 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4349 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4350 Register NewVR =
4351 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4352 : &AMDGPU::VReg_64_Align2RegClass);
4353 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4354 .addReg(DataReg, 0, Op->getSubReg())
4355 .addImm(AMDGPU::sub0)
4356 .addReg(Undef)
4357 .addImm(AMDGPU::sub1);
4358 Op->setReg(NewVR);
4359 Op->setSubReg(AMDGPU::sub0);
4360 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4361 }
4362 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4363 case AMDGPU::DS_GWS_SEMA_V:
4364 case AMDGPU::DS_GWS_SEMA_P:
4365 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4366 // A s_waitcnt 0 is required to be the instruction immediately following.
4367 if (getSubtarget()->hasGWSAutoReplay()) {
4368 bundleInstWithWaitcnt(MI);
4369 return BB;
4370 }
4371
4372 return emitGWSMemViolTestLoop(MI, BB);
4373 case AMDGPU::S_SETREG_B32: {
4374 // Try to optimize cases that only set the denormal mode or rounding mode.
4375 //
4376 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4377 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4378 // instead.
4379 //
4380 // FIXME: This could be predicates on the immediate, but tablegen doesn't
4381 // allow you to have a no side effect instruction in the output of a
4382 // sideeffecting pattern.
4383 unsigned ID, Offset, Width;
4384 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4385 if (ID != AMDGPU::Hwreg::ID_MODE)
4386 return BB;
4387
4388 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4389 const unsigned SetMask = WidthMask << Offset;
4390
4391 if (getSubtarget()->hasDenormModeInst()) {
4392 unsigned SetDenormOp = 0;
4393 unsigned SetRoundOp = 0;
4394
4395 // The dedicated instructions can only set the whole denorm or round mode
4396 // at once, not a subset of bits in either.
4397 if (SetMask ==
4398 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4399 // If this fully sets both the round and denorm mode, emit the two
4400 // dedicated instructions for these.
4401 SetRoundOp = AMDGPU::S_ROUND_MODE;
4402 SetDenormOp = AMDGPU::S_DENORM_MODE;
4403 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4404 SetRoundOp = AMDGPU::S_ROUND_MODE;
4405 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4406 SetDenormOp = AMDGPU::S_DENORM_MODE;
4407 }
4408
4409 if (SetRoundOp || SetDenormOp) {
4410 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4411 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4412 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4413 unsigned ImmVal = Def->getOperand(1).getImm();
4414 if (SetRoundOp) {
4415 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4416 .addImm(ImmVal & 0xf);
4417
4418 // If we also have the denorm mode, get just the denorm mode bits.
4419 ImmVal >>= 4;
4420 }
4421
4422 if (SetDenormOp) {
4423 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4424 .addImm(ImmVal & 0xf);
4425 }
4426
4427 MI.eraseFromParent();
4428 return BB;
4429 }
4430 }
4431 }
4432
4433 // If only FP bits are touched, used the no side effects pseudo.
4434 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4435 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4436 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4437
4438 return BB;
4439 }
4440 default:
4441 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4442 }
4443}
4444
4445bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4446 return isTypeLegal(VT.getScalarType());
4447}
4448
4449bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4450 // This currently forces unfolding various combinations of fsub into fma with
4451 // free fneg'd operands. As long as we have fast FMA (controlled by
4452 // isFMAFasterThanFMulAndFAdd), we should perform these.
4453
4454 // When fma is quarter rate, for f64 where add / sub are at best half rate,
4455 // most of these combines appear to be cycle neutral but save on instruction
4456 // count / code size.
4457 return true;
4458}
4459
4460EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4461 EVT VT) const {
4462 if (!VT.isVector()) {
4463 return MVT::i1;
4464 }
4465 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4466}
4467
4468MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4469 // TODO: Should i16 be used always if legal? For now it would force VALU
4470 // shifts.
4471 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4472}
4473
4474LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4475 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4476 ? Ty.changeElementSize(16)
4477 : Ty.changeElementSize(32);
4478}
4479
4480// Answering this is somewhat tricky and depends on the specific device which
4481// have different rates for fma or all f64 operations.
4482//
4483// v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4484// regardless of which device (although the number of cycles differs between
4485// devices), so it is always profitable for f64.
4486//
4487// v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4488// only on full rate devices. Normally, we should prefer selecting v_mad_f32
4489// which we can always do even without fused FP ops since it returns the same
4490// result as the separate operations and since it is always full
4491// rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4492// however does not support denormals, so we do report fma as faster if we have
4493// a fast fma device and require denormals.
4494//
4495bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4496 EVT VT) const {
4497 VT = VT.getScalarType();
4498
4499 switch (VT.getSimpleVT().SimpleTy) {
4500 case MVT::f32: {
4501 // If mad is not available this depends only on if f32 fma is full rate.
4502 if (!Subtarget->hasMadMacF32Insts())
4503 return Subtarget->hasFastFMAF32();
4504
4505 // Otherwise f32 mad is always full rate and returns the same result as
4506 // the separate operations so should be preferred over fma.
4507 // However does not support denomals.
4508 if (hasFP32Denormals(MF))
4509 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4510
4511 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4512 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4513 }
4514 case MVT::f64:
4515 return true;
4516 case MVT::f16:
4517 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4518 default:
4519 break;
4520 }
4521
4522 return false;
4523}
4524
4525bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4526 const SDNode *N) const {
4527 // TODO: Check future ftz flag
4528 // v_mad_f32/v_mac_f32 do not support denormals.
4529 EVT VT = N->getValueType(0);
4530 if (VT == MVT::f32)
4531 return Subtarget->hasMadMacF32Insts() &&
4532 !hasFP32Denormals(DAG.getMachineFunction());
4533 if (VT == MVT::f16) {
4534 return Subtarget->hasMadF16() &&
4535 !hasFP64FP16Denormals(DAG.getMachineFunction());
4536 }
4537
4538 return false;
4539}
4540
4541//===----------------------------------------------------------------------===//
4542// Custom DAG Lowering Operations
4543//===----------------------------------------------------------------------===//
4544
4545// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4546// wider vector type is legal.
4547SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4548 SelectionDAG &DAG) const {
4549 unsigned Opc = Op.getOpcode();
4550 EVT VT = Op.getValueType();
4551 assert(VT == MVT::v4f16 || VT == MVT::v4i16)(static_cast <bool> (VT == MVT::v4f16 || VT == MVT::v4i16
) ? void (0) : __assert_fail ("VT == MVT::v4f16 || VT == MVT::v4i16"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4551, __extension__ __PRETTY_FUNCTION__))
;
4552
4553 SDValue Lo, Hi;
4554 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4555
4556 SDLoc SL(Op);
4557 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4558 Op->getFlags());
4559 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4560 Op->getFlags());
4561
4562 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4563}
4564
4565// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4566// wider vector type is legal.
4567SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4568 SelectionDAG &DAG) const {
4569 unsigned Opc = Op.getOpcode();
4570 EVT VT = Op.getValueType();
4571 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||(static_cast <bool> (VT == MVT::v4i16 || VT == MVT::v4f16
|| VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v16f32
|| VT == MVT::v32f32) ? void (0) : __assert_fail ("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4572, __extension__ __PRETTY_FUNCTION__))
4572 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32)(static_cast <bool> (VT == MVT::v4i16 || VT == MVT::v4f16
|| VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v16f32
|| VT == MVT::v32f32) ? void (0) : __assert_fail ("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4572, __extension__ __PRETTY_FUNCTION__))
;
4573
4574 SDValue Lo0, Hi0;
4575 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4576 SDValue Lo1, Hi1;
4577 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4578
4579 SDLoc SL(Op);
4580
4581 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4582 Op->getFlags());
4583 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4584 Op->getFlags());
4585
4586 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4587}
4588
4589SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4590 SelectionDAG &DAG) const {
4591 unsigned Opc = Op.getOpcode();
4592 EVT VT = Op.getValueType();
4593 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||(static_cast <bool> (VT == MVT::v4i16 || VT == MVT::v4f16
|| VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v16f32
|| VT == MVT::v32f32) ? void (0) : __assert_fail ("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4594, __extension__ __PRETTY_FUNCTION__))
4594 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32)(static_cast <bool> (VT == MVT::v4i16 || VT == MVT::v4f16
|| VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v16f32
|| VT == MVT::v32f32) ? void (0) : __assert_fail ("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4594, __extension__ __PRETTY_FUNCTION__))
;
4595
4596 SDValue Lo0, Hi0;
4597 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4598 SDValue Lo1, Hi1;
4599 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4600 SDValue Lo2, Hi2;
4601 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4602
4603 SDLoc SL(Op);
4604
4605 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4606 Op->getFlags());
4607 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4608 Op->getFlags());
4609
4610 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4611}
4612
4613
4614SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4615 switch (Op.getOpcode()) {
4616 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4617 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4618 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4619 case ISD::LOAD: {
4620 SDValue Result = LowerLOAD(Op, DAG);
4621 assert((!Result.getNode() ||(static_cast <bool> ((!Result.getNode() || Result.getNode
()->getNumValues() == 2) && "Load should return a value and a chain"
) ? void (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4623, __extension__ __PRETTY_FUNCTION__))
4622 Result.getNode()->getNumValues() == 2) &&(static_cast <bool> ((!Result.getNode() || Result.getNode
()->getNumValues() == 2) && "Load should return a value and a chain"
) ? void (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4623, __extension__ __PRETTY_FUNCTION__))
4623 "Load should return a value and a chain")(static_cast <bool> ((!Result.getNode() || Result.getNode
()->getNumValues() == 2) && "Load should return a value and a chain"
) ? void (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4623, __extension__ __PRETTY_FUNCTION__))
;
4624 return Result;
4625 }
4626
4627 case ISD::FSIN:
4628 case ISD::FCOS:
4629 return LowerTrig(Op, DAG);
4630 case ISD::SELECT: return LowerSELECT(Op, DAG);
4631 case ISD::FDIV: return LowerFDIV(Op, DAG);
4632 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4633 case ISD::STORE: return LowerSTORE(Op, DAG);
4634 case ISD::GlobalAddress: {
4635 MachineFunction &MF = DAG.getMachineFunction();
4636 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4637 return LowerGlobalAddress(MFI, Op, DAG);
4638 }
4639 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4640 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4641 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4642 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4643 case ISD::INSERT_SUBVECTOR:
4644 return lowerINSERT_SUBVECTOR(Op, DAG);
4645 case ISD::INSERT_VECTOR_ELT:
4646 return lowerINSERT_VECTOR_ELT(Op, DAG);
4647 case ISD::EXTRACT_VECTOR_ELT:
4648 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4649 case ISD::VECTOR_SHUFFLE:
4650 return lowerVECTOR_SHUFFLE(Op, DAG);
4651 case ISD::BUILD_VECTOR:
4652 return lowerBUILD_VECTOR(Op, DAG);
4653 case ISD::FP_ROUND:
4654 return lowerFP_ROUND(Op, DAG);
4655 case ISD::TRAP:
4656 return lowerTRAP(Op, DAG);
4657 case ISD::DEBUGTRAP:
4658 return lowerDEBUGTRAP(Op, DAG);
4659 case ISD::FABS:
4660 case ISD::FNEG:
4661 case ISD::FCANONICALIZE:
4662 case ISD::BSWAP:
4663 return splitUnaryVectorOp(Op, DAG);
4664 case ISD::FMINNUM:
4665 case ISD::FMAXNUM:
4666 return lowerFMINNUM_FMAXNUM(Op, DAG);
4667 case ISD::FMA:
4668 return splitTernaryVectorOp(Op, DAG);
4669 case ISD::FP_TO_SINT:
4670 case ISD::FP_TO_UINT:
4671 return LowerFP_TO_INT(Op, DAG);
4672 case ISD::SHL:
4673 case ISD::SRA:
4674 case ISD::SRL:
4675 case ISD::ADD:
4676 case ISD::SUB:
4677 case ISD::MUL:
4678 case ISD::SMIN:
4679 case ISD::SMAX:
4680 case ISD::UMIN:
4681 case ISD::UMAX:
4682 case ISD::FADD:
4683 case ISD::FMUL:
4684 case ISD::FMINNUM_IEEE:
4685 case ISD::FMAXNUM_IEEE:
4686 case ISD::UADDSAT:
4687 case ISD::USUBSAT:
4688 case ISD::SADDSAT:
4689 case ISD::SSUBSAT:
4690 return splitBinaryVectorOp(Op, DAG);
4691 case ISD::SMULO:
4692 case ISD::UMULO:
4693 return lowerXMULO(Op, DAG);
4694 case ISD::DYNAMIC_STACKALLOC:
4695 return LowerDYNAMIC_STACKALLOC(Op, DAG);
4696 }
4697 return SDValue();
4698}
4699
4700// Used for D16: Casts the result of an instruction into the right vector,
4701// packs values if loads return unpacked values.
4702static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4703 const SDLoc &DL,
4704 SelectionDAG &DAG, bool Unpacked) {
4705 if (!LoadVT.isVector())
4706 return Result;
4707
4708 // Cast back to the original packed type or to a larger type that is a
4709 // multiple of 32 bit for D16. Widening the return type is a required for
4710 // legalization.
4711 EVT FittingLoadVT = LoadVT;
4712 if ((LoadVT.getVectorNumElements() % 2) == 1) {
4713 FittingLoadVT =
4714 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4715 LoadVT.getVectorNumElements() + 1);
4716 }
4717
4718 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4719 // Truncate to v2i16/v4i16.
4720 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4721
4722 // Workaround legalizer not scalarizing truncate after vector op
4723 // legalization but not creating intermediate vector trunc.
4724 SmallVector<SDValue, 4> Elts;
4725 DAG.ExtractVectorElements(Result, Elts);
4726 for (SDValue &Elt : Elts)
4727 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4728
4729 // Pad illegal v1i16/v3fi6 to v4i16
4730 if ((LoadVT.getVectorNumElements() % 2) == 1)
4731 Elts.push_back(DAG.getUNDEF(MVT::i16));
4732
4733 Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4734
4735 // Bitcast to original type (v2f16/v4f16).
4736 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4737 }
4738
4739 // Cast back to the original packed type.
4740 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4741}
4742
4743SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4744 MemSDNode *M,
4745 SelectionDAG &DAG,
4746 ArrayRef<SDValue> Ops,
4747 bool IsIntrinsic) const {
4748 SDLoc DL(M);
4749
4750 bool Unpacked = Subtarget->hasUnpackedD16VMem();
4751 EVT LoadVT = M->getValueType(0);
4752
4753 EVT EquivLoadVT = LoadVT;
4754 if (LoadVT.isVector()) {
4755 if (Unpacked) {
4756 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4757 LoadVT.getVectorNumElements());
4758 } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4759 // Widen v3f16 to legal type
4760 EquivLoadVT =
4761 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4762 LoadVT.getVectorNumElements() + 1);
4763 }
4764 }
4765
4766 // Change from v4f16/v2f16 to EquivLoadVT.
4767 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4768
4769 SDValue Load
4770 = DAG.getMemIntrinsicNode(
4771 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4772 VTList, Ops, M->getMemoryVT(),
4773 M->getMemOperand());
4774
4775 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4776
4777 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4778}
4779
4780SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4781 SelectionDAG &DAG,
4782 ArrayRef<SDValue> Ops) const {
4783 SDLoc DL(M);
4784 EVT LoadVT = M->getValueType(0);
4785 EVT EltType = LoadVT.getScalarType();
4786 EVT IntVT = LoadVT.changeTypeToInteger();
4787
4788 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4789
4790 unsigned Opc =
4791 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4792
4793 if (IsD16) {
4794 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4795 }
4796
4797 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4798 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4799 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4800
4801 if (isTypeLegal(LoadVT)) {
4802 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4803 M->getMemOperand(), DAG);
4804 }
4805
4806 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4807 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4808 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4809 M->getMemOperand(), DAG);
4810 return DAG.getMergeValues(
4811 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4812 DL);
4813}
4814
4815static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4816 SDNode *N, SelectionDAG &DAG) {
4817 EVT VT = N->getValueType(0);
4818 const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4819 unsigned CondCode = CD->getZExtValue();
4820 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4821 return DAG.getUNDEF(VT);
4822
4823 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4824
4825 SDValue LHS = N->getOperand(1);
4826 SDValue RHS = N->getOperand(2);
4827
4828 SDLoc DL(N);
4829
4830 EVT CmpVT = LHS.getValueType();
4831 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4832 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4833 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4834 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4835 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4836 }
4837
4838 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4839
4840 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4841 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4842
4843 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4844 DAG.getCondCode(CCOpcode));
4845 if (VT.bitsEq(CCVT))
4846 return SetCC;
4847 return DAG.getZExtOrTrunc(SetCC, DL, VT);
4848}
4849
4850static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4851 SDNode *N, SelectionDAG &DAG) {
4852 EVT VT = N->getValueType(0);
4853 const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4854
4855 unsigned CondCode = CD->getZExtValue();
4856 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4857 return DAG.getUNDEF(VT);
4858
4859 SDValue Src0 = N->getOperand(1);
4860 SDValue Src1 = N->getOperand(2);
4861 EVT CmpVT = Src0.getValueType();
4862 SDLoc SL(N);
4863
4864 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4865 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4866 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4867 }
4868
4869 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4870 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4871 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4872 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4873 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4874 Src1, DAG.getCondCode(CCOpcode));
4875 if (VT.bitsEq(CCVT))
4876 return SetCC;
4877 return DAG.getZExtOrTrunc(SetCC, SL, VT);
4878}
4879
4880static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4881 SelectionDAG &DAG) {
4882 EVT VT = N->getValueType(0);
4883 SDValue Src = N->getOperand(1);
4884 SDLoc SL(N);
4885
4886 if (Src.getOpcode() == ISD::SETCC) {
4887 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4888 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4889 Src.getOperand(1), Src.getOperand(2));
4890 }
4891 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4892 // (ballot 0) -> 0
4893 if (Arg->isZero())
4894 return DAG.getConstant(0, SL, VT);
4895
4896 // (ballot 1) -> EXEC/EXEC_LO
4897 if (Arg->isOne()) {
4898 Register Exec;
4899 if (VT.getScalarSizeInBits() == 32)
4900 Exec = AMDGPU::EXEC_LO;
4901 else if (VT.getScalarSizeInBits() == 64)
4902 Exec = AMDGPU::EXEC;
4903 else
4904 return SDValue();
4905
4906 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4907 }
4908 }
4909
4910 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4911 // ISD::SETNE)
4912 return DAG.getNode(
4913 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4914 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4915}
4916
4917void SITargetLowering::ReplaceNodeResults(SDNode *N,
4918 SmallVectorImpl<SDValue> &Results,
4919 SelectionDAG &DAG) const {
4920 switch (N->getOpcode()) {
4921 case ISD::INSERT_VECTOR_ELT: {
4922 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4923 Results.push_back(Res);
4924 return;
4925 }
4926 case ISD::EXTRACT_VECTOR_ELT: {
4927 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4928 Results.push_back(Res);
4929 return;
4930 }
4931 case ISD::INTRINSIC_WO_CHAIN: {
4932 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4933 switch (IID) {
4934 case Intrinsic::amdgcn_cvt_pkrtz: {
4935 SDValue Src0 = N->getOperand(1);
4936 SDValue Src1 = N->getOperand(2);
4937 SDLoc SL(N);
4938 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4939 Src0, Src1);
4940 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4941 return;
4942 }
4943 case Intrinsic::amdgcn_cvt_pknorm_i16:
4944 case Intrinsic::amdgcn_cvt_pknorm_u16:
4945 case Intrinsic::amdgcn_cvt_pk_i16:
4946 case Intrinsic::amdgcn_cvt_pk_u16: {
4947 SDValue Src0 = N->getOperand(1);
4948 SDValue Src1 = N->getOperand(2);
4949 SDLoc SL(N);
4950 unsigned Opcode;
4951
4952 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4953 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4954 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4955 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4956 else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4957 Opcode = AMDGPUISD::CVT_PK_I16_I32;
4958 else
4959 Opcode = AMDGPUISD::CVT_PK_U16_U32;
4960
4961 EVT VT = N->getValueType(0);
4962 if (isTypeLegal(VT))
4963 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4964 else {
4965 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4966 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4967 }
4968 return;
4969 }
4970 }
4971 break;
4972 }
4973 case ISD::INTRINSIC_W_CHAIN: {
4974 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4975 if (Res.getOpcode() == ISD::MERGE_VALUES) {
4976 // FIXME: Hacky
4977 for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4978 Results.push_back(Res.getOperand(I));
4979 }
4980 } else {
4981 Results.push_back(Res);
4982 Results.push_back(Res.getValue(1));
4983 }
4984 return;
4985 }
4986
4987 break;
4988 }
4989 case ISD::SELECT: {
4990 SDLoc SL(N);
4991 EVT VT = N->getValueType(0);
4992 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4993 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4994 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4995
4996 EVT SelectVT = NewVT;
4997 if (NewVT.bitsLT(MVT::i32)) {
4998 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4999 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5000 SelectVT = MVT::i32;
5001 }
5002
5003 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5004 N->getOperand(0), LHS, RHS);
5005
5006 if (NewVT != SelectVT)
5007 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5008 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5009 return;
5010 }
5011 case ISD::FNEG: {
5012 if (N->getValueType(0) != MVT::v2f16)
5013 break;
5014
5015 SDLoc SL(N);
5016 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5017
5018 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5019 BC,
5020 DAG.getConstant(0x80008000, SL, MVT::i32));
5021 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5022 return;
5023 }
5024 case ISD::FABS: {
5025 if (N->getValueType(0) != MVT::v2f16)
5026 break;
5027
5028 SDLoc SL(N);
5029 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5030
5031 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5032 BC,
5033 DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5034 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5035 return;
5036 }
5037 default:
5038 break;
5039 }
5040}
5041
5042/// Helper function for LowerBRCOND
5043static SDNode *findUser(SDValue Value, unsigned Opcode) {
5044
5045 SDNode *Parent = Value.getNode();
5046 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5047 I != E; ++I) {
5048
5049 if (I.getUse().get() != Value)
5050 continue;
5051
5052 if (I->getOpcode() == Opcode)
5053 return *I;
5054 }
5055 return nullptr;
5056}
5057
5058unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5059 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5060 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5061 case Intrinsic::amdgcn_if:
5062 return AMDGPUISD::IF;
5063 case Intrinsic::amdgcn_else:
5064 return AMDGPUISD::ELSE;
5065 case Intrinsic::amdgcn_loop:
5066 return AMDGPUISD::LOOP;
5067 case Intrinsic::amdgcn_end_cf:
5068 llvm_unreachable("should not occur")::llvm::llvm_unreachable_internal("should not occur", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5068)
;
5069 default:
5070 return 0;
5071 }
5072 }
5073
5074 // break, if_break, else_break are all only used as inputs to loop, not
5075 // directly as branch conditions.
5076 return 0;
5077}
5078
5079bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5080 const Triple &TT = getTargetMachine().getTargetTriple();
5081 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5082 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5083 AMDGPU::shouldEmitConstantsToTextSection(TT);
5084}
5085
5086bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5087 // FIXME: Either avoid relying on address space here or change the default
5088 // address space for functions to avoid the explicit check.
5089 return (GV->getValueType()->isFunctionTy() ||
5090 !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5091 !shouldEmitFixup(GV) &&
5092 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5093}
5094
5095bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5096 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5097}
5098
5099bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5100 if (!GV->hasExternalLinkage())
5101 return true;
5102
5103 const auto OS = getTargetMachine().getTargetTriple().getOS();
5104 return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5105}
5106
5107/// This transforms the control flow intrinsics to get the branch destination as
5108/// last parameter, also switches branch target with BR if the need arise
5109SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5110 SelectionDAG &DAG) const {
5111 SDLoc DL(BRCOND);
5112
5113 SDNode *Intr = BRCOND.getOperand(1).getNode();
5114 SDValue Target = BRCOND.getOperand(2);
5115 SDNode *BR = nullptr;
5116 SDNode *SetCC = nullptr;
5117
5118 if (Intr->getOpcode() == ISD::SETCC) {
5119 // As long as we negate the condition everything is fine
5120 SetCC = Intr;
5121 Intr = SetCC->getOperand(0).getNode();
5122
5123 } else {
5124 // Get the target from BR if we don't negate the condition
5125 BR = findUser(BRCOND, ISD::BR);
5126 assert(BR && "brcond missing unconditional branch user")(static_cast <bool> (BR && "brcond missing unconditional branch user"
) ? void (0) : __assert_fail ("BR && \"brcond missing unconditional branch user\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5126, __extension__ __PRETTY_FUNCTION__))
;
5127 Target = BR->getOperand(1);
5128 }
5129
5130 unsigned CFNode = isCFIntrinsic(Intr);
5131 if (CFNode == 0) {
5132 // This is a uniform branch so we don't need to legalize.
5133 return BRCOND;
5134 }
5135
5136 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5137 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5138
5139 assert(!SetCC ||(static_cast <bool> (!SetCC || (SetCC->getConstantOperandVal
(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand
(2).getNode())->get() == ISD::SETNE)) ? void (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5142, __extension__ __PRETTY_FUNCTION__))
5140 (SetCC->getConstantOperandVal(1) == 1 &&(static_cast <bool> (!SetCC || (SetCC->getConstantOperandVal
(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand
(2).getNode())->get() == ISD::SETNE)) ? void (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5142, __extension__ __PRETTY_FUNCTION__))
5141 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==(static_cast <bool> (!SetCC || (SetCC->getConstantOperandVal
(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand
(2).getNode())->get() == ISD::SETNE)) ? void (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5142, __extension__ __PRETTY_FUNCTION__))
5142 ISD::SETNE))(static_cast <bool> (!SetCC || (SetCC->getConstantOperandVal
(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand
(2).getNode())->get() == ISD::SETNE)) ? void (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5142, __extension__ __PRETTY_FUNCTION__))
;
5143
5144 // operands of the new intrinsic call
5145 SmallVector<SDValue, 4> Ops;
5146 if (HaveChain)
5147 Ops.push_back(BRCOND.getOperand(0));
5148
5149 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
5150 Ops.push_back(Target);
5151
5152 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5153
5154 // build the new intrinsic call
5155 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5156
5157 if (!HaveChain) {
5158 SDValue Ops[] = {
5159 SDValue(Result, 0),
5160 BRCOND.getOperand(0)
5161 };
5162
5163 Result = DAG.getMergeValues(Ops, DL).getNode();
5164 }
5165
5166 if (BR) {
5167 // Give the branch instruction our target
5168 SDValue Ops[] = {
5169 BR->getOperand(0),
5170 BRCOND.getOperand(2)
5171 };
5172 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5173 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5174 }
5175
5176 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5177
5178 // Copy the intrinsic results to registers
5179 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5180 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5181 if (!CopyToReg)
5182 continue;
5183
5184 Chain = DAG.getCopyToReg(
5185 Chain, DL,
5186 CopyToReg->getOperand(1),
5187 SDValue(Result, i - 1),
5188 SDValue());
5189
5190 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5191 }
5192
5193 // Remove the old intrinsic from the chain
5194 DAG.ReplaceAllUsesOfValueWith(
5195 SDValue(Intr, Intr->getNumValues() - 1),
5196 Intr->getOperand(0));
5197
5198 return Chain;
5199}
5200
5201SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5202 SelectionDAG &DAG) const {
5203 MVT VT = Op.getSimpleValueType();
5204 SDLoc DL(Op);
5205 // Checking the depth
5206 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5207 return DAG.getConstant(0, DL, VT);
5208
5209 MachineFunction &MF = DAG.getMachineFunction();
5210 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5211 // Check for kernel and shader functions
5212 if (Info->isEntryFunction())
5213 return DAG.getConstant(0, DL, VT);
5214
5215 MachineFrameInfo &MFI = MF.getFrameInfo();
5216 // There is a call to @llvm.returnaddress in this function
5217 MFI.setReturnAddressIsTaken(true);
5218
5219 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5220 // Get the return address reg and mark it as an implicit live-in
5221 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5222
5223 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5224}
5225
5226SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5227 SDValue Op,
5228 const SDLoc &DL,
5229 EVT VT) const {
5230 return Op.getValueType().bitsLE(VT) ?
5231 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5232 DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5233 DAG.getTargetConstant(0, DL, MVT::i32));
5234}
5235
5236SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5237 assert(Op.getValueType() == MVT::f16 &&(static_cast <bool> (Op.getValueType() == MVT::f16 &&
"Do not know how to custom lower FP_ROUND for non-f16 type")
? void (0) : __assert_fail ("Op.getValueType() == MVT::f16 && \"Do not know how to custom lower FP_ROUND for non-f16 type\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5238, __extension__ __PRETTY_FUNCTION__))
5238 "Do not know how to custom lower FP_ROUND for non-f16 type")(static_cast <bool> (Op.getValueType() == MVT::f16 &&
"Do not know how to custom lower FP_ROUND for non-f16 type")
? void (0) : __assert_fail ("Op.getValueType() == MVT::f16 && \"Do not know how to custom lower FP_ROUND for non-f16 type\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5238, __extension__ __PRETTY_FUNCTION__))
;
5239
5240 SDValue Src = Op.getOperand(0);
5241 EVT SrcVT = Src.getValueType();
5242 if (SrcVT != MVT::f64)
5243 return Op;
5244
5245 SDLoc DL(Op);
5246
5247 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5248 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5249 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5250}
5251
5252SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5253 SelectionDAG &DAG) const {
5254 EVT VT = Op.getValueType();
5255 const MachineFunction &MF = DAG.getMachineFunction();
5256 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5257 bool IsIEEEMode = Info->getMode().IEEE;
5258
5259 // FIXME: Assert during selection that this is only selected for
5260 // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5261 // mode functions, but this happens to be OK since it's only done in cases
5262 // where there is known no sNaN.
5263 if (IsIEEEMode)
5264 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5265
5266 if (VT == MVT::v4f16)
5267 return splitBinaryVectorOp(Op, DAG);
5268 return Op;
5269}
5270
5271SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5272 EVT VT = Op.getValueType();
5273 SDLoc SL(Op);
5274 SDValue LHS = Op.getOperand(0);
5275 SDValue RHS = Op.getOperand(1);
5276 bool isSigned = Op.getOpcode() == ISD::SMULO;
5277
5278 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5279 const APInt &C = RHSC->getAPIntValue();
5280 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5281 if (C.isPowerOf2()) {
5282 // smulo(x, signed_min) is same as umulo(x, signed_min).
5283 bool UseArithShift = isSigned && !C.isMinSignedValue();
5284 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5285 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5286 SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5287 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5288 SL, VT, Result, ShiftAmt),
5289 LHS, ISD::SETNE);
5290 return DAG.getMergeValues({ Result, Overflow }, SL);
5291 }
5292 }
5293
5294 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5295 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5296 SL, VT, LHS, RHS);
5297
5298 SDValue Sign = isSigned
5299 ? DAG.getNode(ISD::SRA, SL, VT, Result,
5300 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5301 : DAG.getConstant(0, SL, VT);
5302 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5303
5304 return DAG.getMergeValues({ Result, Overflow }, SL);
5305}
5306
5307SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5308 if (!Subtarget->isTrapHandlerEnabled() ||
5309 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5310 return lowerTrapEndpgm(Op, DAG);
5311
5312 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5313 switch (*HsaAbiVer) {
5314 case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5315 case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5316 return lowerTrapHsaQueuePtr(Op, DAG);
5317 case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5318 return Subtarget->supportsGetDoorbellID() ?
5319 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5320 }
5321 }
5322
5323 llvm_unreachable("Unknown trap handler")::llvm::llvm_unreachable_internal("Unknown trap handler", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5323)
;
5324}
5325
5326SDValue SITargetLowering::lowerTrapEndpgm(
5327 SDValue Op, SelectionDAG &DAG) const {
5328 SDLoc SL(Op);
5329 SDValue Chain = Op.getOperand(0);
5330 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5331}
5332
5333SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5334 SDValue Op, SelectionDAG &DAG) const {
5335 SDLoc SL(Op);
5336 SDValue Chain = Op.getOperand(0);
5337
5338 MachineFunction &MF = DAG.getMachineFunction();
5339 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5340 Register UserSGPR = Info->getQueuePtrUserSGPR();
5341
5342 SDValue QueuePtr;
5343 if (UserSGPR == AMDGPU::NoRegister) {
5344 // We probably are in a function incorrectly marked with
5345 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5346 // so just use a null pointer.
5347 QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5348 } else {
5349 QueuePtr = CreateLiveInRegister(
5350 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5351 }
5352
5353 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5354 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5355 QueuePtr, SDValue());
5356
5357 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5358 SDValue Ops[] = {
5359 ToReg,
5360 DAG.getTargetConstant(TrapID, SL, MVT::i16),
5361 SGPR01,
5362 ToReg.getValue(1)
5363 };
5364 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5365}
5366
5367SDValue SITargetLowering::lowerTrapHsa(
5368 SDValue Op, SelectionDAG &DAG) const {
5369 SDLoc SL(Op);
5370 SDValue Chain = Op.getOperand(0);
5371
5372 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5373 SDValue Ops[] = {
5374 Chain,
5375 DAG.getTargetConstant(TrapID, SL, MVT::i16)
5376 };
5377 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5378}
5379
5380SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5381 SDLoc SL(Op);
5382 SDValue Chain = Op.getOperand(0);
5383 MachineFunction &MF = DAG.getMachineFunction();
5384
5385 if (!Subtarget->isTrapHandlerEnabled() ||
5386 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5387 DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5388 "debugtrap handler not supported",
5389 Op.getDebugLoc(),
5390 DS_Warning);
5391 LLVMContext &Ctx = MF.getFunction().getContext();
5392 Ctx.diagnose(NoTrap);
5393 return Chain;
5394 }
5395
5396 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5397 SDValue Ops[] = {
5398 Chain,
5399 DAG.getTargetConstant(TrapID, SL, MVT::i16)
5400 };
5401 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5402}
5403
5404SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5405 SelectionDAG &DAG) const {
5406 // FIXME: Use inline constants (src_{shared, private}_base) instead.
5407 if (Subtarget->hasApertureRegs()) {
5408 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5409 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5410 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5411 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5412 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5413 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5414 unsigned Encoding =
5415 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5416 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5417 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5418
5419 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5420 SDValue ApertureReg = SDValue(
5421 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5422 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5423 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5424 }
5425
5426 MachineFunction &MF = DAG.getMachineFunction();
5427 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5428 Register UserSGPR = Info->getQueuePtrUserSGPR();
5429 if (UserSGPR == AMDGPU::NoRegister) {
5430 // We probably are in a function incorrectly marked with
5431 // amdgpu-no-queue-ptr. This is undefined.
5432 return DAG.getUNDEF(MVT::i32);
5433 }
5434
5435 SDValue QueuePtr = CreateLiveInRegister(
5436 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5437
5438 // Offset into amd_queue_t for group_segment_aperture_base_hi /
5439 // private_segment_aperture_base_hi.
5440 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5441
5442 SDValue Ptr =
5443 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5444
5445 // TODO: Use custom target PseudoSourceValue.
5446 // TODO: We should use the value from the IR intrinsic call, but it might not
5447 // be available and how do we get it?
5448 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5449 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5450 commonAlignment(Align(64), StructOffset),
5451 MachineMemOperand::MODereferenceable |
5452 MachineMemOperand::MOInvariant);
5453}
5454
5455SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5456 SelectionDAG &DAG) const {
5457 SDLoc SL(Op);
5458 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5459
5460 SDValue Src = ASC->getOperand(0);
5461 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5462
5463 const AMDGPUTargetMachine &TM =
5464 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5465
5466 // flat -> local/private
5467 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5468 unsigned DestAS = ASC->getDestAddressSpace();
5469
5470 if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5471 DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5472 unsigned NullVal = TM.getNullPointerValue(DestAS);
5473 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5474 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5475 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5476
5477 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5478 NonNull, Ptr, SegmentNullPtr);
5479 }
5480 }
5481
5482 // local/private -> flat
5483 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5484 unsigned SrcAS = ASC->getSrcAddressSpace();
5485
5486 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5487 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5488 unsigned NullVal = TM.getNullPointerValue(SrcAS);
5489 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5490
5491 SDValue NonNull
5492 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5493
5494 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5495 SDValue CvtPtr
5496 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5497
5498 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5499 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5500 FlatNullPtr);
5501 }
5502 }
5503
5504 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5505 Src.getValueType() == MVT::i64)
5506 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5507
5508 // global <-> flat are no-ops and never emitted.
5509
5510 const MachineFunction &MF = DAG.getMachineFunction();
5511 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5512 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5513 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5514
5515 return DAG.getUNDEF(ASC->getValueType(0));
5516}
5517
5518// This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5519// the small vector and inserting them into the big vector. That is better than
5520// the default expansion of doing it via a stack slot. Even though the use of
5521// the stack slot would be optimized away afterwards, the stack slot itself
5522// remains.
5523SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5524 SelectionDAG &DAG) const {
5525 SDValue Vec = Op.getOperand(0);
5526 SDValue Ins = Op.getOperand(1);
5527 SDValue Idx = Op.getOperand(2);
5528 EVT VecVT = Vec.getValueType();
5529 EVT InsVT = Ins.getValueType();
5530 EVT EltVT = VecVT.getVectorElementType();
5531 unsigned InsNumElts = InsVT.getVectorNumElements();
5532 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5533 SDLoc SL(Op);
5534
5535 for (unsigned I = 0; I != InsNumElts; ++I) {
5536 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5537 DAG.getConstant(I, SL, MVT::i32));
5538 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5539 DAG.getConstant(IdxVal + I, SL, MVT::i32));
5540 }
5541 return Vec;
5542}
5543
5544SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5545 SelectionDAG &DAG) const {
5546 SDValue Vec = Op.getOperand(0);
5547 SDValue InsVal = Op.getOperand(1);
5548 SDValue Idx = Op.getOperand(2);
5549 EVT VecVT = Vec.getValueType();
5550 EVT EltVT = VecVT.getVectorElementType();
5551 unsigned VecSize = VecVT.getSizeInBits();
5552 unsigned EltSize = EltVT.getSizeInBits();
5553
5554
5555 assert(VecSize <= 64)(static_cast <bool> (VecSize <= 64) ? void (0) : __assert_fail
("VecSize <= 64", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5555, __extension__ __PRETTY_FUNCTION__))
;
5556
5557 unsigned NumElts = VecVT.getVectorNumElements();
5558 SDLoc SL(Op);
5559 auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5560
5561 if (NumElts == 4 && EltSize == 16 && KIdx) {
5562 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5563
5564 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5565 DAG.getConstant(0, SL, MVT::i32));
5566 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5567 DAG.getConstant(1, SL, MVT::i32));
5568
5569 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5570 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5571
5572 unsigned Idx = KIdx->getZExtValue();
5573 bool InsertLo = Idx < 2;
5574 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5575 InsertLo ? LoVec : HiVec,
5576 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5577 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5578
5579 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5580
5581 SDValue Concat = InsertLo ?
5582 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5583 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5584
5585 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5586 }
5587
5588 if (isa<ConstantSDNode>(Idx))
5589 return SDValue();
5590
5591 MVT IntVT = MVT::getIntegerVT(VecSize);
5592
5593 // Avoid stack access for dynamic indexing.
5594 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5595
5596 // Create a congruent vector with the target value in each element so that
5597 // the required element can be masked and ORed into the target vector.
5598 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5599 DAG.getSplatBuildVector(VecVT, SL, InsVal));
5600
5601 assert(isPowerOf2_32(EltSize))(static_cast <bool> (isPowerOf2_32(EltSize)) ? void (0)
: __assert_fail ("isPowerOf2_32(EltSize)", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5601, __extension__ __PRETTY_FUNCTION__))
;
5602 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5603
5604 // Convert vector index to bit-index.
5605 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5606
5607 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5608 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5609 DAG.getConstant(0xffff, SL, IntVT),
5610 ScaledIdx);
5611
5612 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5613 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5614 DAG.getNOT(SL, BFM, IntVT), BCVec);
5615
5616 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5617 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5618}
5619
5620SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5621 SelectionDAG &DAG) const {
5622 SDLoc SL(Op);
5623
5624 EVT ResultVT = Op.getValueType();
5625 SDValue Vec = Op.getOperand(0);
5626 SDValue Idx = Op.getOperand(1);
5627 EVT VecVT = Vec.getValueType();
5628 unsigned VecSize = VecVT.getSizeInBits();
5629 EVT EltVT = VecVT.getVectorElementType();
5630 assert(VecSize <= 64)(static_cast <bool> (VecSize <= 64) ? void (0) : __assert_fail
("VecSize <= 64", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5630, __extension__ __PRETTY_FUNCTION__))
;
5631
5632 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5633
5634 // Make sure we do any optimizations that will make it easier to fold
5635 // source modifiers before obscuring it with bit operations.
5636
5637 // XXX - Why doesn't this get called when vector_shuffle is expanded?
5638 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5639 return Combined;
5640
5641 unsigned EltSize = EltVT.getSizeInBits();
5642 assert(isPowerOf2_32(EltSize))(static_cast <bool> (isPowerOf2_32(EltSize)) ? void (0)
: __assert_fail ("isPowerOf2_32(EltSize)", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5642, __extension__ __PRETTY_FUNCTION__))
;
5643
5644 MVT IntVT = MVT::getIntegerVT(VecSize);
5645 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5646
5647 // Convert vector index to bit-index (* EltSize)
5648 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5649
5650 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5651 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5652
5653 if (ResultVT == MVT::f16) {
5654 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5655 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5656 }
5657
5658 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5659}
5660
5661static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5662 assert(Elt % 2 == 0)(static_cast <bool> (Elt % 2 == 0) ? void (0) : __assert_fail
("Elt % 2 == 0", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5662, __extension__ __PRETTY_FUNCTION__))
;
5663 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5664}
5665
5666SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5667 SelectionDAG &DAG) const {
5668 SDLoc SL(Op);
5669 EVT ResultVT = Op.getValueType();
5670 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5671
5672 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5673 EVT EltVT = PackVT.getVectorElementType();
5674 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5675
5676 // vector_shuffle <0,1,6,7> lhs, rhs
5677 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5678 //
5679 // vector_shuffle <6,7,2,3> lhs, rhs
5680 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5681 //
5682 // vector_shuffle <6,7,0,1> lhs, rhs
5683 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5684
5685 // Avoid scalarizing when both halves are reading from consecutive elements.
5686 SmallVector<SDValue, 4> Pieces;
5687 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5688 if (elementPairIsContiguous(SVN->getMask(), I)) {
5689 const int Idx = SVN->getMaskElt(I);
5690 int VecIdx = Idx < SrcNumElts ? 0 : 1;
5691 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5692 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5693 PackVT, SVN->getOperand(VecIdx),
5694 DAG.getConstant(EltIdx, SL, MVT::i32));
5695 Pieces.push_back(SubVec);
5696 } else {
5697 const int Idx0 = SVN->getMaskElt(I);
5698 const int Idx1 = SVN->getMaskElt(I + 1);
5699 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5700 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5701 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5702 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5703
5704 SDValue Vec0 = SVN->getOperand(VecIdx0);
5705 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5706 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5707
5708 SDValue Vec1 = SVN->getOperand(VecIdx1);
5709 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5710 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5711 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5712 }
5713 }
5714
5715 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5716}
5717
5718SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5719 SelectionDAG &DAG) const {
5720 SDLoc SL(Op);
5721 EVT VT = Op.getValueType();
5722
5723 if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5724 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5725
5726 // Turn into pair of packed build_vectors.
5727 // TODO: Special case for constants that can be materialized with s_mov_b64.
5728 SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5729 { Op.getOperand(0), Op.getOperand(1) });
5730 SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5731 { Op.getOperand(2), Op.getOperand(3) });
5732
5733 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5734 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5735
5736 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5737 return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5738 }
5739
5740 assert(VT == MVT::v2f16 || VT == MVT::v2i16)(static_cast <bool> (VT == MVT::v2f16 || VT == MVT::v2i16
) ? void (0) : __assert_fail ("VT == MVT::v2f16 || VT == MVT::v2i16"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5740, __extension__ __PRETTY_FUNCTION__))
;
5741 assert(!Subtarget->hasVOP3PInsts() && "this should be legal")(static_cast <bool> (!Subtarget->hasVOP3PInsts() &&
"this should be legal") ? void (0) : __assert_fail ("!Subtarget->hasVOP3PInsts() && \"this should be legal\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5741, __extension__ __PRETTY_FUNCTION__))
;
5742
5743 SDValue Lo = Op.getOperand(0);
5744 SDValue Hi = Op.getOperand(1);
5745
5746 // Avoid adding defined bits with the zero_extend.
5747 if (Hi.isUndef()) {
5748 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5749 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5750 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5751 }
5752
5753 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5754 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5755
5756 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5757 DAG.getConstant(16, SL, MVT::i32));
5758 if (Lo.isUndef())
5759 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5760
5761 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5762 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5763
5764 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5765 return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5766}
5767
5768bool
5769SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5770 // We can fold offsets for anything that doesn't require a GOT relocation.
5771 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5772 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5773 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5774 !shouldEmitGOTReloc(GA->getGlobal());
5775}
5776
5777static SDValue
5778buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5779 const SDLoc &DL, int64_t Offset, EVT PtrVT,
5780 unsigned GAFlags = SIInstrInfo::MO_NONE) {
5781 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!")(static_cast <bool> (isInt<32>(Offset + 4) &&
"32-bit offset is expected!") ? void (0) : __assert_fail ("isInt<32>(Offset + 4) && \"32-bit offset is expected!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5781, __extension__ __PRETTY_FUNCTION__))
;
5782 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5783 // lowered to the following code sequence:
5784 //
5785 // For constant address space:
5786 // s_getpc_b64 s[0:1]
5787 // s_add_u32 s0, s0, $symbol
5788 // s_addc_u32 s1, s1, 0
5789 //
5790 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
5791 // a fixup or relocation is emitted to replace $symbol with a literal
5792 // constant, which is a pc-relative offset from the encoding of the $symbol
5793 // operand to the global variable.
5794 //
5795 // For global address space:
5796 // s_getpc_b64 s[0:1]
5797 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5798 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5799 //
5800 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
5801 // fixups or relocations are emitted to replace $symbol@*@lo and
5802 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5803 // which is a 64-bit pc-relative offset from the encoding of the $symbol
5804 // operand to the global variable.
5805 //
5806 // What we want here is an offset from the value returned by s_getpc
5807 // (which is the address of the s_add_u32 instruction) to the global
5808 // variable, but since the encoding of $symbol starts 4 bytes after the start
5809 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5810 // small. This requires us to add 4 to the global variable offset in order to
5811 // compute the correct address. Similarly for the s_addc_u32 instruction, the
5812 // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5813 // instruction.
5814 SDValue PtrLo =
5815 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5816 SDValue PtrHi;
5817 if (GAFlags == SIInstrInfo::MO_NONE) {
5818 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5819 } else {
5820 PtrHi =
5821 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5822 }
5823 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5824}
5825
5826SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5827 SDValue Op,
5828 SelectionDAG &DAG) const {
5829 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5830 SDLoc DL(GSD);
5831 EVT PtrVT = Op.getValueType();
5832
5833 const GlobalValue *GV = GSD->getGlobal();
5834 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5835 shouldUseLDSConstAddress(GV)) ||
5836 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5837 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5838 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5839 GV->hasExternalLinkage()) {
5840 Type *Ty = GV->getValueType();
5841 // HIP uses an unsized array `extern __shared__ T s[]` or similar
5842 // zero-sized type in other languages to declare the dynamic shared
5843 // memory which size is not known at the compile time. They will be
5844 // allocated by the runtime and placed directly after the static
5845 // allocated ones. They all share the same offset.
5846 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5847 assert(PtrVT == MVT::i32 && "32-bit pointer is expected.")(static_cast <bool> (PtrVT == MVT::i32 && "32-bit pointer is expected."
) ? void (0) : __assert_fail ("PtrVT == MVT::i32 && \"32-bit pointer is expected.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5847, __extension__ __PRETTY_FUNCTION__))
;
5848 // Adjust alignment for that dynamic shared memory array.
5849 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5850 return SDValue(
5851 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5852 }
5853 }
5854 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5855 }
5856
5857 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5858 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5859 SIInstrInfo::MO_ABS32_LO);
5860 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5861 }
5862
5863 if (shouldEmitFixup(GV))
5864 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5865 else if (shouldEmitPCReloc(GV))
5866 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5867 SIInstrInfo::MO_REL32);
5868
5869 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5870 SIInstrInfo::MO_GOTPCREL32);
5871
5872 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5873 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5874 const DataLayout &DataLayout = DAG.getDataLayout();
5875 Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5876 MachinePointerInfo PtrInfo
5877 = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5878
5879 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5880 MachineMemOperand::MODereferenceable |
5881 MachineMemOperand::MOInvariant);
5882}
5883
5884SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5885 const SDLoc &DL, SDValue V) const {
5886 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5887 // the destination register.
5888 //
5889 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5890 // so we will end up with redundant moves to m0.
5891 //
5892 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5893
5894 // A Null SDValue creates a glue result.
5895 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5896 V, Chain);
5897 return SDValue(M0, 0);
5898}
5899
5900SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5901 SDValue Op,
5902 MVT VT,
5903 unsigned Offset) const {
5904 SDLoc SL(Op);
5905 SDValue Param = lowerKernargMemParameter(
5906 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5907 // The local size values will have the hi 16-bits as zero.
5908 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5909 DAG.getValueType(VT));
5910}
5911
5912static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5913 EVT VT) {
5914 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5915 "non-hsa intrinsic with hsa target",
5916 DL.getDebugLoc());
5917 DAG.getContext()->diagnose(BadIntrin);
5918 return DAG.getUNDEF(VT);
5919}
5920
5921static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5922 EVT VT) {
5923 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5924 "intrinsic not supported on subtarget",
5925 DL.getDebugLoc());
5926 DAG.getContext()->diagnose(BadIntrin);
5927 return DAG.getUNDEF(VT);
5928}
5929
5930static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5931 ArrayRef<SDValue> Elts) {
5932 assert(!Elts.empty())(static_cast <bool> (!Elts.empty()) ? void (0) : __assert_fail
("!Elts.empty()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5932, __extension__ __PRETTY_FUNCTION__))
;
5933 MVT Type;
5934 unsigned NumElts = Elts.size();
5935
5936 if (NumElts <= 8) {
5937 Type = MVT::getVectorVT(MVT::f32, NumElts);
5938 } else {
5939 assert(Elts.size() <= 16)(static_cast <bool> (Elts.size() <= 16) ? void (0) :
__assert_fail ("Elts.size() <= 16", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5939, __extension__ __PRETTY_FUNCTION__))
;
5940 Type = MVT::v16f32;
5941 NumElts = 16;
5942 }
5943
5944 SmallVector<SDValue, 16> VecElts(NumElts);
5945 for (unsigned i = 0; i < Elts.size(); ++i) {
5946 SDValue Elt = Elts[i];
5947 if (Elt.getValueType() != MVT::f32)
5948 Elt = DAG.getBitcast(MVT::f32, Elt);
5949 VecElts[i] = Elt;
5950 }
5951 for (unsigned i = Elts.size(); i < NumElts; ++i)
5952 VecElts[i] = DAG.getUNDEF(MVT::f32);
5953
5954 if (NumElts == 1)
5955 return VecElts[0];
5956 return DAG.getBuildVector(Type, DL, VecElts);
5957}
5958
5959static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5960 SDValue Src, int ExtraElts) {
5961 EVT SrcVT = Src.getValueType();
5962
5963 SmallVector<SDValue, 8> Elts;
5964
5965 if (SrcVT.isVector())
5966 DAG.ExtractVectorElements(Src, Elts);
5967 else
5968 Elts.push_back(Src);
5969
5970 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5971 while (ExtraElts--)
5972 Elts.push_back(Undef);
5973
5974 return DAG.getBuildVector(CastVT, DL, Elts);
5975}
5976
5977// Re-construct the required return value for a image load intrinsic.
5978// This is more complicated due to the optional use TexFailCtrl which means the required
5979// return type is an aggregate
5980static SDValue constructRetValue(SelectionDAG &DAG,
5981 MachineSDNode *Result,
5982 ArrayRef<EVT> ResultTypes,
5983 bool IsTexFail, bool Unpacked, bool IsD16,
5984 int DMaskPop, int NumVDataDwords,
5985 const SDLoc &DL) {
5986 // Determine the required return type. This is the same regardless of IsTexFail flag
5987 EVT ReqRetVT = ResultTypes[0];
5988 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5989 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5990 ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5991
5992 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5993 DMaskPop : (DMaskPop + 1) / 2;
5994
5995 MVT DataDwordVT = NumDataDwords == 1 ?
5996 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5997
5998 MVT MaskPopVT = MaskPopDwords == 1 ?
5999 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6000
6001 SDValue Data(Result, 0);
6002 SDValue TexFail;
6003
6004 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6005 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6006 if (MaskPopVT.isVector()) {
6007 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6008 SDValue(Result, 0), ZeroIdx);
6009 } else {
6010 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6011 SDValue(Result, 0), ZeroIdx);
6012 }
6013 }
6014
6015 if (DataDwordVT.isVector())
6016 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6017 NumDataDwords - MaskPopDwords);
6018
6019 if (IsD16)
6020 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6021
6022 EVT LegalReqRetVT = ReqRetVT;
6023 if (!ReqRetVT.isVector()) {
6024 if (!Data.getValueType().isInteger())
6025 Data = DAG.getNode(ISD::BITCAST, DL,
6026 Data.getValueType().changeTypeToInteger(), Data);
6027 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6028 } else {
6029 // We need to widen the return vector to a legal type
6030 if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6031 ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6032 LegalReqRetVT =
6033 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6034 ReqRetVT.getVectorNumElements() + 1);
6035 }
6036 }
6037 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6038
6039 if (IsTexFail) {
6040 TexFail =
6041 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6042 DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6043
6044 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6045 }
6046
6047 if (Result->getNumValues() == 1)
6048 return Data;
6049
6050 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6051}
6052
6053static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6054 SDValue *LWE, bool &IsTexFail) {
6055 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6056
6057 uint64_t Value = TexFailCtrlConst->getZExtValue();
6058 if (Value) {
6059 IsTexFail = true;
6060 }
6061
6062 SDLoc DL(TexFailCtrlConst);
6063 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6064 Value &= ~(uint64_t)0x1;
6065 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6066 Value &= ~(uint64_t)0x2;
6067
6068 return Value == 0;
6069}
6070
6071static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6072 MVT PackVectorVT,
6073 SmallVectorImpl<SDValue> &PackedAddrs,
6074 unsigned DimIdx, unsigned EndIdx,
6075 unsigned NumGradients) {
6076 SDLoc DL(Op);
6077 for (unsigned I = DimIdx; I < EndIdx; I++) {
6078 SDValue Addr = Op.getOperand(I);
6079
6080 // Gradients are packed with undef for each coordinate.
6081 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6082 // 1D: undef,dx/dh; undef,dx/dv
6083 // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6084 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6085 if (((I + 1) >= EndIdx) ||
6086 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6087 I == DimIdx + NumGradients - 1))) {
6088 if (Addr.getValueType() != MVT::i16)
6089 Addr = DAG.getBitcast(MVT::i16, Addr);
6090 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6091 } else {
6092 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6093 I++;
6094 }
6095 Addr = DAG.getBitcast(MVT::f32, Addr);
6096 PackedAddrs.push_back(Addr);
6097 }
6098}
6099
6100SDValue SITargetLowering::lowerImage(SDValue Op,
6101 const AMDGPU::ImageDimIntrinsicInfo *Intr,
6102 SelectionDAG &DAG, bool WithChain) const {
6103 SDLoc DL(Op);
6104 MachineFunction &MF = DAG.getMachineFunction();
6105 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6106 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6107 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6108 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6109 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
6110 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
6111 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
6112 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
6113 unsigned IntrOpcode = Intr->BaseOpcode;
6114 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6115
6116 SmallVector<EVT, 3> ResultTypes(Op->values());
6117 SmallVector<EVT, 3> OrigResultTypes(Op->values());
6118 bool IsD16 = false;
6119 bool IsG16 = false;
6120 bool IsA16 = false;
6121 SDValue VData;
6122 int NumVDataDwords;
6123 bool AdjustRetType = false;
6124
6125 // Offset of intrinsic arguments
6126 const unsigned ArgOffset = WithChain ? 2 : 1;
6127
6128 unsigned DMask;
6129 unsigned DMaskLanes = 0;
6130
6131 if (BaseOpcode->Atomic) {
6132 VData = Op.getOperand(2);
6133
6134 bool Is64Bit = VData.getValueType() == MVT::i64;
6135 if (BaseOpcode->AtomicX2) {
6136 SDValue VData2 = Op.getOperand(3);
6137 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6138 {VData, VData2});
6139 if (Is64Bit)
6140 VData = DAG.getBitcast(MVT::v4i32, VData);
6141
6142 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6143 DMask = Is64Bit ? 0xf : 0x3;
6144 NumVDataDwords = Is64Bit ? 4 : 2;
6145 } else {
6146 DMask = Is64Bit ? 0x3 : 0x1;
6147 NumVDataDwords = Is64Bit ? 2 : 1;
6148 }
6149 } else {
6150 auto *DMaskConst =
6151 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6152 DMask = DMaskConst->getZExtValue();
6153 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6154
6155 if (BaseOpcode->Store) {
6156 VData = Op.getOperand(2);
6157
6158 MVT StoreVT = VData.getSimpleValueType();
6159 if (StoreVT.getScalarType() == MVT::f16) {
6160 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6161 return Op; // D16 is unsupported for this instruction
6162
6163 IsD16 = true;
6164 VData = handleD16VData(VData, DAG, true);
6165 }
6166
6167 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6168 } else {
6169 // Work out the num dwords based on the dmask popcount and underlying type
6170 // and whether packing is supported.
6171 MVT LoadVT = ResultTypes[0].getSimpleVT();
6172 if (LoadVT.getScalarType() == MVT::f16) {
6173 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6174 return Op; // D16 is unsupported for this instruction
6175
6176 IsD16 = true;
6177 }
6178
6179 // Confirm that the return type is large enough for the dmask specified
6180 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6181 (!LoadVT.isVector() && DMaskLanes > 1))
6182 return Op;
6183
6184 // The sq block of gfx8 and gfx9 do not estimate register use correctly
6185 // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6186 // instructions.
6187 if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6188 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6189 NumVDataDwords = (DMaskLanes + 1) / 2;
6190 else
6191 NumVDataDwords = DMaskLanes;
6192
6193 AdjustRetType = true;
6194 }
6195 }
6196
6197 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6198 SmallVector<SDValue, 4> VAddrs;
6199
6200 // Optimize _L to _LZ when _L is zero
6201 if (LZMappingInfo) {
6202 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6203 Op.getOperand(ArgOffset + Intr->LodIndex))) {
6204 if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6205 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l
6206 VAddrEnd--; // remove 'lod'
6207 }
6208 }
6209 }
6210
6211 // Optimize _mip away, when 'lod' is zero
6212 if (MIPMappingInfo) {
6213 if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6214 Op.getOperand(ArgOffset + Intr->MipIndex))) {
6215 if (ConstantLod->isZero()) {
6216 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip
6217 VAddrEnd--; // remove 'mip'
6218 }
6219 }
6220 }
6221
6222 // Push back extra arguments.
6223 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6224 VAddrs.push_back(Op.getOperand(ArgOffset + I));
6225
6226 // Check for 16 bit addresses or derivatives and pack if true.
6227 MVT VAddrVT =
6228 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6229 MVT VAddrScalarVT = VAddrVT.getScalarType();
6230 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6231 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6232
6233 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6234 VAddrScalarVT = VAddrVT.getScalarType();
6235 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6236 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6237
6238 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6239 // 16 bit gradients are supported, but are tied to the A16 control
6240 // so both gradients and addresses must be 16 bit
6241 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
"require 16 bit args for both gradients and addresses"; } } while
(false)
6242 dbgs() << "Failed to lower image intrinsic: 16 bit addresses "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
"require 16 bit args for both gradients and addresses"; } } while
(false)
6243 "require 16 bit args for both gradients and addresses")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
"require 16 bit args for both gradients and addresses"; } } while
(false)
;
6244 return Op;
6245 }
6246
6247 if (IsA16) {
6248 if (!ST->hasA16()) {
6249 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: Target does not "
"support 16 bit addresses\n"; } } while (false)
6250 "support 16 bit addresses\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: Target does not "
"support 16 bit addresses\n"; } } while (false)
;
6251 return Op;
6252 }
6253 }
6254
6255 // We've dealt with incorrect input so we know that if IsA16, IsG16
6256 // are set then we have to compress/pack operands (either address,
6257 // gradient or both)
6258 // In the case where a16 and gradients are tied (no G16 support) then we
6259 // have already verified that both IsA16 and IsG16 are true
6260 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6261 // Activate g16
6262 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6263 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6264 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6265 }
6266
6267 // Add gradients (packed or unpacked)
6268 if (IsG16) {
6269 // Pack the gradients
6270 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6271 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6272 ArgOffset + Intr->GradientStart,
6273 ArgOffset + Intr->CoordStart, Intr->NumGradients);
6274 } else {
6275 for (unsigned I = ArgOffset + Intr->GradientStart;
6276 I < ArgOffset + Intr->CoordStart; I++)
6277 VAddrs.push_back(Op.getOperand(I));
6278 }
6279
6280 // Add addresses (packed or unpacked)
6281 if (IsA16) {
6282 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6283 ArgOffset + Intr->CoordStart, VAddrEnd,
6284 0 /* No gradients */);
6285 } else {
6286 // Add uncompressed address
6287 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6288 VAddrs.push_back(Op.getOperand(I));
6289 }
6290
6291 // If the register allocator cannot place the address registers contiguously
6292 // without introducing moves, then using the non-sequential address encoding
6293 // is always preferable, since it saves VALU instructions and is usually a
6294 // wash in terms of code size or even better.
6295 //
6296 // However, we currently have no way of hinting to the register allocator that
6297 // MIMG addresses should be placed contiguously when it is possible to do so,
6298 // so force non-NSA for the common 2-address case as a heuristic.
6299 //
6300 // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6301 // allocation when possible.
6302 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6303 VAddrs.size() >= 3 &&
6304 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6305 SDValue VAddr;
6306 if (!UseNSA)
6307 VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6308
6309 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6310 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6311 SDValue Unorm;
6312 if (!BaseOpcode->Sampler) {
6313 Unorm = True;
6314 } else {
6315 auto UnormConst =
6316 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6317
6318 Unorm = UnormConst->getZExtValue() ? True : False;
6319 }
6320
6321 SDValue TFE;
6322 SDValue LWE;
6323 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6324 bool IsTexFail = false;
6325 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6326 return Op;
6327
6328 if (IsTexFail) {
6329 if (!DMaskLanes) {
6330 // Expecting to get an error flag since TFC is on - and dmask is 0
6331 // Force dmask to be at least 1 otherwise the instruction will fail
6332 DMask = 0x1;
6333 DMaskLanes = 1;
6334 NumVDataDwords = 1;
6335 }
6336 NumVDataDwords += 1;
6337 AdjustRetType = true;
6338 }
6339
6340 // Has something earlier tagged that the return type needs adjusting
6341 // This happens if the instruction is a load or has set TexFailCtrl flags
6342 if (AdjustRetType) {
6343 // NumVDataDwords reflects the true number of dwords required in the return type
6344 if (DMaskLanes == 0 && !BaseOpcode->Store) {
6345 // This is a no-op load. This can be eliminated
6346 SDValue Undef = DAG.getUNDEF(Op.getValueType());
6347 if (isa<MemSDNode>(Op))
6348 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6349 return Undef;
6350 }
6351
6352 EVT NewVT = NumVDataDwords > 1 ?
6353 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6354 : MVT::i32;
6355
6356 ResultTypes[0] = NewVT;
6357 if (ResultTypes.size() == 3) {
6358 // Original result was aggregate type used for TexFailCtrl results
6359 // The actual instruction returns as a vector type which has now been
6360 // created. Remove the aggregate result.
6361 ResultTypes.erase(&ResultTypes[1]);
6362 }
6363 }
6364
6365 unsigned CPol = cast<ConstantSDNode>(
6366 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6367 if (BaseOpcode->Atomic)
6368 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6369 if (CPol & ~AMDGPU::CPol::ALL)
6370 return Op;
6371
6372 SmallVector<SDValue, 26> Ops;
6373 if (BaseOpcode->Store || BaseOpcode->Atomic)
6374 Ops.push_back(VData); // vdata
6375 if (UseNSA)
6376 append_range(Ops, VAddrs);
6377 else
6378 Ops.push_back(VAddr);
6379 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6380 if (BaseOpcode->Sampler)
6381 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6382 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6383 if (IsGFX10Plus)
6384 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6385 Ops.push_back(Unorm);
6386 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6387 Ops.push_back(IsA16 && // r128, a16 for gfx9
6388 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6389 if (IsGFX10Plus)
6390 Ops.push_back(IsA16 ? True : False);
6391 if (!Subtarget->hasGFX90AInsts()) {
6392 Ops.push_back(TFE); //tfe
6393 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6394 report_fatal_error("TFE is not supported on this GPU");
6395 }
6396 Ops.push_back(LWE); // lwe
6397 if (!IsGFX10Plus)
6398 Ops.push_back(DimInfo->DA ? True : False);
6399 if (BaseOpcode->HasD16)
6400 Ops.push_back(IsD16 ? True : False);
6401 if (isa<MemSDNode>(Op))
6402 Ops.push_back(Op.getOperand(0)); // chain
6403
6404 int NumVAddrDwords =
6405 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6406 int Opcode = -1;
6407
6408 if (IsGFX10Plus) {
6409 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6410 UseNSA ? AMDGPU::MIMGEncGfx10NSA
6411 : AMDGPU::MIMGEncGfx10Default,
6412 NumVDataDwords, NumVAddrDwords);
6413 } else {
6414 if (Subtarget->hasGFX90AInsts()) {
6415 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6416 NumVDataDwords, NumVAddrDwords);
6417 if (Opcode == -1)
6418 report_fatal_error(
6419 "requested image instruction is not supported on this GPU");
6420 }
6421 if (Opcode == -1 &&
6422 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6423 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6424 NumVDataDwords, NumVAddrDwords);
6425 if (Opcode == -1)
6426 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6427 NumVDataDwords, NumVAddrDwords);
6428 }
6429 assert(Opcode != -1)(static_cast <bool> (Opcode != -1) ? void (0) : __assert_fail
("Opcode != -1", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6429, __extension__ __PRETTY_FUNCTION__))
;
6430
6431 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6432 if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6433 MachineMemOperand *MemRef = MemOp->getMemOperand();
6434 DAG.setNodeMemRefs(NewNode, {MemRef});
6435 }
6436
6437 if (BaseOpcode->AtomicX2) {
6438 SmallVector<SDValue, 1> Elt;
6439 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6440 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6441 }
6442 if (BaseOpcode->Store)
6443 return SDValue(NewNode, 0);
6444 return constructRetValue(DAG, NewNode,
6445 OrigResultTypes, IsTexFail,
6446 Subtarget->hasUnpackedD16VMem(), IsD16,
6447 DMaskLanes, NumVDataDwords, DL);
6448}
6449
6450SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6451 SDValue Offset, SDValue CachePolicy,
6452 SelectionDAG &DAG) const {
6453 MachineFunction &MF = DAG.getMachineFunction();
6454
6455 const DataLayout &DataLayout = DAG.getDataLayout();
6456 Align Alignment =
6457 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6458
6459 MachineMemOperand *MMO = MF.getMachineMemOperand(
6460 MachinePointerInfo(),
6461 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6462 MachineMemOperand::MOInvariant,
6463 VT.getStoreSize(), Alignment);
6464
6465 if (!Offset->isDivergent()) {
6466 SDValue Ops[] = {
6467 Rsrc,
6468 Offset, // Offset
6469 CachePolicy
6470 };
6471
6472 // Widen vec3 load to vec4.
6473 if (VT.isVector() && VT.getVectorNumElements() == 3) {
6474 EVT WidenedVT =
6475 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6476 auto WidenedOp = DAG.getMemIntrinsicNode(
6477 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6478 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6479 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6480 DAG.getVectorIdxConstant(0, DL));
6481 return Subvector;
6482 }
6483
6484 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6485 DAG.getVTList(VT), Ops, VT, MMO);
6486 }
6487
6488 // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6489 // assume that the buffer is unswizzled.
6490 SmallVector<SDValue, 4> Loads;
6491 unsigned NumLoads = 1;
6492 MVT LoadVT = VT.getSimpleVT();
6493 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6494 assert((LoadVT.getScalarType() == MVT::i32 ||(static_cast <bool> ((LoadVT.getScalarType() == MVT::i32
|| LoadVT.getScalarType() == MVT::f32)) ? void (0) : __assert_fail
("(LoadVT.getScalarType() == MVT::i32 || LoadVT.getScalarType() == MVT::f32)"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6495, __extension__ __PRETTY_FUNCTION__))
6495 LoadVT.getScalarType() == MVT::f32))(static_cast <bool> ((LoadVT.getScalarType() == MVT::i32
|| LoadVT.getScalarType() == MVT::f32)) ? void (0) : __assert_fail
("(LoadVT.getScalarType() == MVT::i32 || LoadVT.getScalarType() == MVT::f32)"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6495, __extension__ __PRETTY_FUNCTION__))
;
6496
6497 if (NumElts == 8 || NumElts == 16) {
6498 NumLoads = NumElts / 4;
6499 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6500 }
6501
6502 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6503 SDValue Ops[] = {
6504 DAG.getEntryNode(), // Chain
6505 Rsrc, // rsrc
6506 DAG.getConstant(0, DL, MVT::i32), // vindex
6507 {}, // voffset
6508 {}, // soffset
6509 {}, // offset
6510 CachePolicy, // cachepolicy
6511 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6512 };
6513
6514 // Use the alignment to ensure that the required offsets will fit into the
6515 // immediate offsets.
6516 setBufferOffsets(Offset, DAG, &Ops[3],
6517 NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6518
6519 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6520 for (unsigned i = 0; i < NumLoads; ++i) {
6521 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6522 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6523 LoadVT, MMO, DAG));
6524 }
6525
6526 if (NumElts == 8 || NumElts == 16)
6527 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6528
6529 return Loads[0];
6530}
6531
6532SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6533 SelectionDAG &DAG) const {
6534 MachineFunction &MF = DAG.getMachineFunction();
6535 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6536
6537 EVT VT = Op.getValueType();
6538 SDLoc DL(Op);
6539 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6540
6541 // TODO: Should this propagate fast-math-flags?
6542
6543 switch (IntrinsicID) {
6544 case Intrinsic::amdgcn_implicit_buffer_ptr: {
6545 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6546 return emitNonHSAIntrinsicError(DAG, DL, VT);
6547 return getPreloadedValue(DAG, *MFI, VT,
6548 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6549 }
6550 case Intrinsic::amdgcn_dispatch_ptr:
6551 case Intrinsic::amdgcn_queue_ptr: {
6552 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6553 DiagnosticInfoUnsupported BadIntrin(
6554 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6555 DL.getDebugLoc());
6556 DAG.getContext()->diagnose(BadIntrin);
6557 return DAG.getUNDEF(VT);
6558 }
6559
6560 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6561 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6562 return getPreloadedValue(DAG, *MFI, VT, RegID);
6563 }
6564 case Intrinsic::amdgcn_implicitarg_ptr: {
6565 if (MFI->isEntryFunction())
6566 return getImplicitArgPtr(DAG, DL);
6567 return getPreloadedValue(DAG, *MFI, VT,
6568 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6569 }
6570 case Intrinsic::amdgcn_kernarg_segment_ptr: {
6571 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6572 // This only makes sense to call in a kernel, so just lower to null.
6573 return DAG.getConstant(0, DL, VT);
6574 }
6575
6576 return getPreloadedValue(DAG, *MFI, VT,
6577 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6578 }
6579 case Intrinsic::amdgcn_dispatch_id: {
6580 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6581 }
6582 case Intrinsic::amdgcn_rcp:
6583 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6584 case Intrinsic::amdgcn_rsq:
6585 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6586 case Intrinsic::amdgcn_rsq_legacy:
6587 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6588 return emitRemovedIntrinsicError(DAG, DL, VT);
6589 return SDValue();
6590 case Intrinsic::amdgcn_rcp_legacy:
6591 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6592 return emitRemovedIntrinsicError(DAG, DL, VT);
6593 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6594 case Intrinsic::amdgcn_rsq_clamp: {
6595 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6596 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6597
6598 Type *Type = VT.getTypeForEVT(*DAG.getContext());
6599 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6600 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6601
6602 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6603 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6604 DAG.getConstantFP(Max, DL, VT));
6605 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6606 DAG.getConstantFP(Min, DL, VT));
6607 }
6608 case Intrinsic::r600_read_ngroups_x:
6609 if (Subtarget->isAmdHsaOS())
6610 return emitNonHSAIntrinsicError(DAG, DL, VT);
6611
6612 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6613 SI::KernelInputOffsets::NGROUPS_X, Align(4),
6614 false);
6615 case Intrinsic::r600_read_ngroups_y:
6616 if (Subtarget->isAmdHsaOS())
6617 return emitNonHSAIntrinsicError(DAG, DL, VT);
6618
6619 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6620 SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6621 false);
6622 case Intrinsic::r600_read_ngroups_z:
6623 if (Subtarget->isAmdHsaOS())
6624 return emitNonHSAIntrinsicError(DAG, DL, VT);
6625
6626 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6627 SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6628 false);
6629 case Intrinsic::r600_read_global_size_x:
6630 if (Subtarget->isAmdHsaOS())
6631 return emitNonHSAIntrinsicError(DAG, DL, VT);
6632
6633 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6634 SI::KernelInputOffsets::GLOBAL_SIZE_X,
6635 Align(4), false);
6636 case Intrinsic::r600_read_global_size_y:
6637 if (Subtarget->isAmdHsaOS())
6638 return emitNonHSAIntrinsicError(DAG, DL, VT);
6639
6640 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6641 SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6642 Align(4), false);
6643 case Intrinsic::r600_read_global_size_z:
6644 if (Subtarget->isAmdHsaOS())
6645 return emitNonHSAIntrinsicError(DAG, DL, VT);
6646
6647 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6648 SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6649 Align(4), false);
6650 case Intrinsic::r600_read_local_size_x:
6651 if (Subtarget->isAmdHsaOS())
6652 return emitNonHSAIntrinsicError(DAG, DL, VT);
6653
6654 return lowerImplicitZextParam(DAG, Op, MVT::i16,
6655 SI::KernelInputOffsets::LOCAL_SIZE_X);
6656 case Intrinsic::r600_read_local_size_y:
6657 if (Subtarget->isAmdHsaOS())
6658 return emitNonHSAIntrinsicError(DAG, DL, VT);
6659
6660 return lowerImplicitZextParam(DAG, Op, MVT::i16,
6661 SI::KernelInputOffsets::LOCAL_SIZE_Y);
6662 case Intrinsic::r600_read_local_size_z:
6663 if (Subtarget->isAmdHsaOS())
6664 return emitNonHSAIntrinsicError(DAG, DL, VT);
6665
6666 return lowerImplicitZextParam(DAG, Op, MVT::i16,
6667 SI::KernelInputOffsets::LOCAL_SIZE_Z);
6668 case Intrinsic::amdgcn_workgroup_id_x:
6669 return getPreloadedValue(DAG, *MFI, VT,
6670 AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6671 case Intrinsic::amdgcn_workgroup_id_y:
6672 return getPreloadedValue(DAG, *MFI, VT,
6673 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6674 case Intrinsic::amdgcn_workgroup_id_z:
6675 return getPreloadedValue(DAG, *MFI, VT,
6676 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6677 case Intrinsic::amdgcn_workitem_id_x:
6678 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6679 SDLoc(DAG.getEntryNode()),
6680 MFI->getArgInfo().WorkItemIDX);
6681 case Intrinsic::amdgcn_workitem_id_y:
6682 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6683 SDLoc(DAG.getEntryNode()),
6684 MFI->getArgInfo().WorkItemIDY);
6685 case Intrinsic::amdgcn_workitem_id_z:
6686 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6687 SDLoc(DAG.getEntryNode()),
6688 MFI->getArgInfo().WorkItemIDZ);
6689 case Intrinsic::amdgcn_wavefrontsize:
6690 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6691 SDLoc(Op), MVT::i32);
6692 case Intrinsic::amdgcn_s_buffer_load: {
6693 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6694 if (CPol & ~AMDGPU::CPol::ALL)
6695 return Op;
6696 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6697 DAG);
6698 }
6699 case Intrinsic::amdgcn_fdiv_fast:
6700 return lowerFDIV_FAST(Op, DAG);
6701 case Intrinsic::amdgcn_sin:
6702 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6703
6704 case Intrinsic::amdgcn_cos:
6705 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6706
6707 case Intrinsic::amdgcn_mul_u24:
6708 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6709 case Intrinsic::amdgcn_mul_i24:
6710 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6711
6712 case Intrinsic::amdgcn_log_clamp: {
6713 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6714 return SDValue();
6715
6716 return emitRemovedIntrinsicError(DAG, DL, VT);
6717 }
6718 case Intrinsic::amdgcn_ldexp:
6719 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6720 Op.getOperand(1), Op.getOperand(2));
6721
6722 case Intrinsic::amdgcn_fract:
6723 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6724
6725 case Intrinsic::amdgcn_class:
6726 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6727 Op.getOperand(1), Op.getOperand(2));
6728 case Intrinsic::amdgcn_div_fmas:
6729 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6730 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6731 Op.getOperand(4));
6732
6733 case Intrinsic::amdgcn_div_fixup:
6734 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6735 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6736
6737 case Intrinsic::amdgcn_div_scale: {
6738 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6739
6740 // Translate to the operands expected by the machine instruction. The
6741 // first parameter must be the same as the first instruction.
6742 SDValue Numerator = Op.getOperand(1);
6743 SDValue Denominator = Op.getOperand(2);
6744
6745 // Note this order is opposite of the machine instruction's operations,
6746 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6747 // intrinsic has the numerator as the first operand to match a normal
6748 // division operation.
6749
6750 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6751
6752 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6753 Denominator, Numerator);
6754 }
6755 case Intrinsic::amdgcn_icmp: {
6756 // There is a Pat that handles this variant, so return it as-is.
6757 if (Op.getOperand(1).getValueType() == MVT::i1 &&
6758 Op.getConstantOperandVal(2) == 0 &&
6759 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6760 return Op;
6761 return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6762 }
6763 case Intrinsic::amdgcn_fcmp: {
6764 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6765 }
6766 case Intrinsic::amdgcn_ballot:
6767 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6768 case Intrinsic::amdgcn_fmed3:
6769 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6770 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6771 case Intrinsic::amdgcn_fdot2:
6772 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6773 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6774 Op.getOperand(4));
6775 case Intrinsic::amdgcn_fmul_legacy:
6776 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6777 Op.getOperand(1), Op.getOperand(2));
6778 case Intrinsic::amdgcn_sffbh:
6779 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6780 case Intrinsic::amdgcn_sbfe:
6781 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6782 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6783 case Intrinsic::amdgcn_ubfe:
6784 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6785 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6786 case Intrinsic::amdgcn_cvt_pkrtz:
6787 case Intrinsic::amdgcn_cvt_pknorm_i16:
6788 case Intrinsic::amdgcn_cvt_pknorm_u16:
6789 case Intrinsic::amdgcn_cvt_pk_i16:
6790 case Intrinsic::amdgcn_cvt_pk_u16: {
6791 // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6792 EVT VT = Op.getValueType();
6793 unsigned Opcode;
6794
6795 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6796 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6797 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6798 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6799 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6800 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6801 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6802 Opcode = AMDGPUISD::CVT_PK_I16_I32;
6803 else
6804 Opcode = AMDGPUISD::CVT_PK_U16_U32;
6805
6806 if (isTypeLegal(VT))
6807 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6808
6809 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6810 Op.getOperand(1), Op.getOperand(2));
6811 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6812 }
6813 case Intrinsic::amdgcn_fmad_ftz:
6814 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6815 Op.getOperand(2), Op.getOperand(3));
6816
6817 case Intrinsic::amdgcn_if_break:
6818 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6819 Op->getOperand(1), Op->getOperand(2)), 0);
6820
6821 case Intrinsic::amdgcn_groupstaticsize: {
6822 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6823 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6824 return Op;
6825
6826 const Module *M = MF.getFunction().getParent();
6827 const GlobalValue *GV =
6828 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6829 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6830 SIInstrInfo::MO_ABS32_LO);
6831 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6832 }
6833 case Intrinsic::amdgcn_is_shared:
6834 case Intrinsic::amdgcn_is_private: {
6835 SDLoc SL(Op);
6836 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6837 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6838 SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6839 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6840 Op.getOperand(1));
6841
6842 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6843 DAG.getConstant(1, SL, MVT::i32));
6844 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6845 }
6846 case Intrinsic::amdgcn_alignbit:
6847 return DAG.getNode(ISD::FSHR, DL, VT,
6848 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6849 case Intrinsic::amdgcn_perm:
6850 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6851 Op.getOperand(2), Op.getOperand(3));
6852 case Intrinsic::amdgcn_reloc_constant: {
6853 Module *M = const_cast<Module *>(MF.getFunction().getParent());
6854 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6855 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6856 auto RelocSymbol = cast<GlobalVariable>(
6857 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6858 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6859 SIInstrInfo::MO_ABS32_LO);
6860 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6861 }
6862 default:
6863 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6864 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6865 return lowerImage(Op, ImageDimIntr, DAG, false);
6866
6867 return Op;
6868 }
6869}
6870
6871/// Update \p MMO based on the offset inputs to an intrinsic.
6872static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
6873 SDValue SOffset, SDValue Offset,
6874 SDValue VIndex = SDValue()) {
6875 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6876 !isa<ConstantSDNode>(Offset)) {
6877 // The combined offset is not known to be constant, so we cannot represent
6878 // it in the MMO. Give up.
6879 MMO->setValue((Value *)nullptr);
6880 return;
6881 }
6882
6883 if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
6884 !cast<ConstantSDNode>(VIndex)->isZero())) {
6885 // The strided index component of the address is not known to be zero, so we
6886 // cannot represent it in the MMO. Give up.
6887 MMO->setValue((Value *)nullptr);
6888 return;
6889 }
6890
6891 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
6892 cast<ConstantSDNode>(SOffset)->getSExtValue() +
6893 cast<ConstantSDNode>(Offset)->getSExtValue());
6894}
6895
6896SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6897 SelectionDAG &DAG,
6898 unsigned NewOpcode) const {
6899 SDLoc DL(Op);
6900
6901 SDValue VData = Op.getOperand(2);
6902 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6903 SDValue Ops[] = {
6904 Op.getOperand(0), // Chain
6905 VData, // vdata
6906 Op.getOperand(3), // rsrc
6907 DAG.getConstant(0, DL, MVT::i32), // vindex
6908 Offsets.first, // voffset
6909 Op.getOperand(5), // soffset
6910 Offsets.second, // offset
6911 Op.getOperand(6), // cachepolicy
6912 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6913 };
6914
6915 auto *M = cast<MemSDNode>(Op);
6916 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
6917
6918 EVT MemVT = VData.getValueType();
6919 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6920 M->getMemOperand());
6921}
6922
6923// Return a value to use for the idxen operand by examining the vindex operand.
6924static unsigned getIdxEn(SDValue VIndex) {
6925 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
6926 // No need to set idxen if vindex is known to be zero.
6927 return VIndexC->getZExtValue() != 0;
6928 return 1;
6929}
6930
6931SDValue
6932SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6933 unsigned NewOpcode) const {
6934 SDLoc DL(Op);
6935
6936 SDValue VData = Op.getOperand(2);
6937 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6938 SDValue Ops[] = {
6939 Op.getOperand(0), // Chain
6940 VData, // vdata
6941 Op.getOperand(3), // rsrc
6942 Op.getOperand(4), // vindex
6943 Offsets.first, // voffset
6944 Op.getOperand(6), // soffset
6945 Offsets.second, // offset
6946 Op.getOperand(7), // cachepolicy
6947 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6948 };
6949
6950 auto *M = cast<MemSDNode>(Op);
6951 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
6952
6953 EVT MemVT = VData.getValueType();
6954 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6955 M->getMemOperand());
6956}
6957
6958SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6959 SelectionDAG &DAG) const {
6960 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6961 SDLoc DL(Op);
6962
6963 switch (IntrID) {
6964 case Intrinsic::amdgcn_ds_ordered_add:
6965 case Intrinsic::amdgcn_ds_ordered_swap: {
6966 MemSDNode *M = cast<MemSDNode>(Op);
6967 SDValue Chain = M->getOperand(0);
6968 SDValue M0 = M->getOperand(2);
6969 SDValue Value = M->getOperand(3);
6970 unsigned IndexOperand = M->getConstantOperandVal(7);
6971 unsigned WaveRelease = M->getConstantOperandVal(8);
6972 unsigned WaveDone = M->getConstantOperandVal(9);
6973
6974 unsigned OrderedCountIndex = IndexOperand & 0x3f;
6975 IndexOperand &= ~0x3f;
6976 unsigned CountDw = 0;
6977
6978 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6979 CountDw = (IndexOperand >> 24) & 0xf;
6980 IndexOperand &= ~(0xf << 24);
6981
6982 if (CountDw < 1 || CountDw > 4) {
6983 report_fatal_error(
6984 "ds_ordered_count: dword count must be between 1 and 4");
6985 }
6986 }
6987
6988 if (IndexOperand)
6989 report_fatal_error("ds_ordered_count: bad index operand");
6990
6991 if (WaveDone && !WaveRelease)
6992 report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6993
6994 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6995 unsigned ShaderType =
6996 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6997 unsigned Offset0 = OrderedCountIndex << 2;
6998 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6999 (Instruction << 4);
7000
7001 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7002 Offset1 |= (CountDw - 1) << 6;
7003
7004 unsigned Offset = Offset0 | (Offset1 << 8);
7005
7006 SDValue Ops[] = {
7007 Chain,
7008 Value,
7009 DAG.getTargetConstant(Offset, DL, MVT::i16),
7010 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7011 };
7012 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7013 M->getVTList(), Ops, M->getMemoryVT(),
7014 M->getMemOperand());
7015 }
7016 case Intrinsic::amdgcn_ds_fadd: {
7017 MemSDNode *M = cast<MemSDNode>(Op);
7018 unsigned Opc;
7019 switch (IntrID) {
7020 case Intrinsic::amdgcn_ds_fadd:
7021 Opc = ISD::ATOMIC_LOAD_FADD;
7022 break;
7023 }
7024
7025 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7026 M->getOperand(0), M->getOperand(2), M->getOperand(3),
7027 M->getMemOperand());
7028 }
7029 case Intrinsic::amdgcn_atomic_inc:
7030 case Intrinsic::amdgcn_atomic_dec:
7031 case Intrinsic::amdgcn_ds_fmin:
7032 case Intrinsic::amdgcn_ds_fmax: {
7033 MemSDNode *M = cast<MemSDNode>(Op);
7034 unsigned Opc;
7035 switch (IntrID) {
7036 case Intrinsic::amdgcn_atomic_inc:
7037 Opc = AMDGPUISD::ATOMIC_INC;
7038 break;
7039 case Intrinsic::amdgcn_atomic_dec:
7040 Opc = AMDGPUISD::ATOMIC_DEC;
7041 break;
7042 case Intrinsic::amdgcn_ds_fmin:
7043 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7044 break;
7045 case Intrinsic::amdgcn_ds_fmax:
7046 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7047 break;
7048 default:
7049 llvm_unreachable("Unknown intrinsic!")::llvm::llvm_unreachable_internal("Unknown intrinsic!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7049)
;
7050 }
7051 SDValue Ops[] = {
7052 M->getOperand(0), // Chain
7053 M->getOperand(2), // Ptr
7054 M->getOperand(3) // Value
7055 };
7056
7057 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7058 M->getMemoryVT(), M->getMemOperand());
7059 }
7060 case Intrinsic::amdgcn_buffer_load:
7061 case Intrinsic::amdgcn_buffer_load_format: {
7062 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7063 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7064 unsigned IdxEn = getIdxEn(Op.getOperand(3));
7065 SDValue Ops[] = {
7066 Op.getOperand(0), // Chain
7067 Op.getOperand(2), // rsrc
7068 Op.getOperand(3), // vindex
7069 SDValue(), // voffset -- will be set by setBufferOffsets
7070 SDValue(), // soffset -- will be set by setBufferOffsets
7071 SDValue(), // offset -- will be set by setBufferOffsets
7072 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7073 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7074 };
7075 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7076
7077 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7078 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7079
7080 EVT VT = Op.getValueType();
7081 EVT IntVT = VT.changeTypeToInteger();
7082 auto *M = cast<MemSDNode>(Op);
7083 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7084 EVT LoadVT = Op.getValueType();
7085
7086 if (LoadVT.getScalarType() == MVT::f16)
7087 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7088 M, DAG, Ops);
7089
7090 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7091 if (LoadVT.getScalarType() == MVT::i8 ||
7092 LoadVT.getScalarType() == MVT::i16)
7093 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7094
7095 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7096 M->getMemOperand(), DAG);
7097 }
7098 case Intrinsic::amdgcn_raw_buffer_load:
7099 case Intrinsic::amdgcn_raw_buffer_load_format: {
7100 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7101
7102 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7103 SDValue Ops[] = {
7104 Op.getOperand(0), // Chain
7105 Op.getOperand(2), // rsrc
7106 DAG.getConstant(0, DL, MVT::i32), // vindex
7107 Offsets.first, // voffset
7108 Op.getOperand(4), // soffset
7109 Offsets.second, // offset
7110 Op.getOperand(5), // cachepolicy, swizzled buffer
7111 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7112 };
7113
7114 auto *M = cast<MemSDNode>(Op);
7115 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7116 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7117 }
7118 case Intrinsic::amdgcn_struct_buffer_load:
7119 case Intrinsic::amdgcn_struct_buffer_load_format: {
7120 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7121
7122 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7123 SDValue Ops[] = {
7124 Op.getOperand(0), // Chain
7125 Op.getOperand(2), // rsrc
7126 Op.getOperand(3), // vindex
7127 Offsets.first, // voffset
7128 Op.getOperand(5), // soffset
7129 Offsets.second, // offset
7130 Op.getOperand(6), // cachepolicy, swizzled buffer
7131 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7132 };
7133
7134 auto *M = cast<MemSDNode>(Op);
7135 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7136 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7137 }
7138 case Intrinsic::amdgcn_tbuffer_load: {
7139 MemSDNode *M = cast<MemSDNode>(Op);
7140 EVT LoadVT = Op.getValueType();
7141
7142 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7143 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7144 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7145 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7146 unsigned IdxEn = getIdxEn(Op.getOperand(3));
7147 SDValue Ops[] = {
7148 Op.getOperand(0), // Chain
7149 Op.getOperand(2), // rsrc
7150 Op.getOperand(3), // vindex
7151 Op.getOperand(4), // voffset
7152 Op.getOperand(5), // soffset
7153 Op.getOperand(6), // offset
7154 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7155 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7156 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7157 };
7158
7159 if (LoadVT.getScalarType() == MVT::f16)
7160 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7161 M, DAG, Ops);
7162 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7163 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7164 DAG);
7165 }
7166 case Intrinsic::amdgcn_raw_tbuffer_load: {
7167 MemSDNode *M = cast<MemSDNode>(Op);
7168 EVT LoadVT = Op.getValueType();
7169 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7170
7171 SDValue Ops[] = {
7172 Op.getOperand(0), // Chain
7173 Op.getOperand(2), // rsrc
7174 DAG.getConstant(0, DL, MVT::i32), // vindex
7175 Offsets.first, // voffset
7176 Op.getOperand(4), // soffset
7177 Offsets.second, // offset
7178 Op.getOperand(5), // format
7179 Op.getOperand(6), // cachepolicy, swizzled buffer
7180 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7181 };
7182
7183 if (LoadVT.getScalarType() == MVT::f16)
7184 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7185 M, DAG, Ops);
7186 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7187 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7188 DAG);
7189 }
7190 case Intrinsic::amdgcn_struct_tbuffer_load: {
7191 MemSDNode *M = cast<MemSDNode>(Op);
7192 EVT LoadVT = Op.getValueType();
7193 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7194
7195 SDValue Ops[] = {
7196 Op.getOperand(0), // Chain
7197 Op.getOperand(2), // rsrc
7198 Op.getOperand(3), // vindex
7199 Offsets.first, // voffset
7200 Op.getOperand(5), // soffset
7201 Offsets.second, // offset
7202 Op.getOperand(6), // format
7203 Op.getOperand(7), // cachepolicy, swizzled buffer
7204 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7205 };
7206
7207 if (LoadVT.getScalarType() == MVT::f16)
7208 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7209 M, DAG, Ops);
7210 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7211 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7212 DAG);
7213 }
7214 case Intrinsic::amdgcn_buffer_atomic_swap:
7215 case Intrinsic::amdgcn_buffer_atomic_add:
7216 case Intrinsic::amdgcn_buffer_atomic_sub:
7217 case Intrinsic::amdgcn_buffer_atomic_csub:
7218 case Intrinsic::amdgcn_buffer_atomic_smin:
7219 case Intrinsic::amdgcn_buffer_atomic_umin:
7220 case Intrinsic::amdgcn_buffer_atomic_smax:
7221 case Intrinsic::amdgcn_buffer_atomic_umax:
7222 case Intrinsic::amdgcn_buffer_atomic_and:
7223 case Intrinsic::amdgcn_buffer_atomic_or:
7224 case Intrinsic::amdgcn_buffer_atomic_xor:
7225 case Intrinsic::amdgcn_buffer_atomic_fadd: {
7226 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7227 unsigned IdxEn = getIdxEn(Op.getOperand(4));
7228 SDValue Ops[] = {
7229 Op.getOperand(0), // Chain
7230 Op.getOperand(2), // vdata
7231 Op.getOperand(3), // rsrc
7232 Op.getOperand(4), // vindex
7233 SDValue(), // voffset -- will be set by setBufferOffsets
7234 SDValue(), // soffset -- will be set by setBufferOffsets
7235 SDValue(), // offset -- will be set by setBufferOffsets
7236 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7237 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7238 };
7239 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7240
7241 EVT VT = Op.getValueType();
7242
7243 auto *M = cast<MemSDNode>(Op);
7244 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7245 unsigned Opcode = 0;
7246
7247 switch (IntrID) {
7248 case Intrinsic::amdgcn_buffer_atomic_swap:
7249 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7250 break;
7251 case Intrinsic::amdgcn_buffer_atomic_add:
7252 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7253 break;
7254 case Intrinsic::amdgcn_buffer_atomic_sub:
7255 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7256 break;
7257 case Intrinsic::amdgcn_buffer_atomic_csub:
7258 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7259 break;
7260 case Intrinsic::amdgcn_buffer_atomic_smin:
7261 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7262 break;
7263 case Intrinsic::amdgcn_buffer_atomic_umin:
7264 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7265 break;
7266 case Intrinsic::amdgcn_buffer_atomic_smax:
7267 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7268 break;
7269 case Intrinsic::amdgcn_buffer_atomic_umax:
7270 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7271 break;
7272 case Intrinsic::amdgcn_buffer_atomic_and:
7273 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7274 break;
7275 case Intrinsic::amdgcn_buffer_atomic_or:
7276 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7277 break;
7278 case Intrinsic::amdgcn_buffer_atomic_xor:
7279 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7280 break;
7281 case Intrinsic::amdgcn_buffer_atomic_fadd:
7282 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7283 DiagnosticInfoUnsupported
7284 NoFpRet(DAG.getMachineFunction().getFunction(),
7285 "return versions of fp atomics not supported",
7286 DL.getDebugLoc(), DS_Error);
7287 DAG.getContext()->diagnose(NoFpRet);
7288 return SDValue();
7289 }
7290 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7291 break;
7292 default:
7293 llvm_unreachable("unhandled atomic opcode")::llvm::llvm_unreachable_internal("unhandled atomic opcode", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7293)
;
7294 }
7295
7296 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7297 M->getMemOperand());
7298 }
7299 case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7300 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7301 case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7302 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7303 case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7304 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7305 case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7306 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7307 case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7308 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7309 case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7310 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7311 case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7312 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7313 case Intrinsic::amdgcn_raw_buffer_atomic_add:
7314 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7315 case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7316 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7317 case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7318 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7319 case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7320 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7321 case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7322 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7323 case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7324 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7325 case Intrinsic::amdgcn_raw_buffer_atomic_and:
7326 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7327 case Intrinsic::amdgcn_raw_buffer_atomic_or:
7328 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7329 case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7330 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7331 case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7332 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7333 case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7334 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7335 case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7336 return lowerStructBufferAtomicIntrin(Op, DAG,
7337 AMDGPUISD::BUFFER_ATOMIC_SWAP);
7338 case Intrinsic::amdgcn_struct_buffer_atomic_add:
7339 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7340 case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7341 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7342 case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7343 return lowerStructBufferAtomicIntrin(Op, DAG,
7344 AMDGPUISD::BUFFER_ATOMIC_SMIN);
7345 case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7346 return lowerStructBufferAtomicIntrin(Op, DAG,
7347 AMDGPUISD::BUFFER_ATOMIC_UMIN);
7348 case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7349 return lowerStructBufferAtomicIntrin(Op, DAG,
7350 AMDGPUISD::BUFFER_ATOMIC_SMAX);
7351 case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7352 return lowerStructBufferAtomicIntrin(Op, DAG,
7353 AMDGPUISD::BUFFER_ATOMIC_UMAX);
7354 case Intrinsic::amdgcn_struct_buffer_atomic_and:
7355 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7356 case Intrinsic::amdgcn_struct_buffer_atomic_or:
7357 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7358 case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7359 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7360 case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7361 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7362 case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7363 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7364
7365 case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7366 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7367 unsigned IdxEn = getIdxEn(Op.getOperand(5));
7368 SDValue Ops[] = {
7369 Op.getOperand(0), // Chain
7370 Op.getOperand(2), // src
7371 Op.getOperand(3), // cmp
7372 Op.getOperand(4), // rsrc
7373 Op.getOperand(5), // vindex
7374 SDValue(), // voffset -- will be set by setBufferOffsets
7375 SDValue(), // soffset -- will be set by setBufferOffsets
7376 SDValue(), // offset -- will be set by setBufferOffsets
7377 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7378 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7379 };
7380 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7381
7382 EVT VT = Op.getValueType();
7383 auto *M = cast<MemSDNode>(Op);
7384 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7385
7386 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7387 Op->getVTList(), Ops, VT, M->getMemOperand());
7388 }
7389 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7390 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7391 SDValue Ops[] = {
7392 Op.getOperand(0), // Chain
7393 Op.getOperand(2), // src
7394 Op.getOperand(3), // cmp
7395 Op.getOperand(4), // rsrc
7396 DAG.getConstant(0, DL, MVT::i32), // vindex
7397 Offsets.first, // voffset
7398 Op.getOperand(6), // soffset
7399 Offsets.second, // offset
7400 Op.getOperand(7), // cachepolicy
7401 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7402 };
7403 EVT VT = Op.getValueType();
7404 auto *M = cast<MemSDNode>(Op);
7405 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7406
7407 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7408 Op->getVTList(), Ops, VT, M->getMemOperand());
7409 }
7410 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7411 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7412 SDValue Ops[] = {
7413 Op.getOperand(0), // Chain
7414 Op.getOperand(2), // src
7415 Op.getOperand(3), // cmp
7416 Op.getOperand(4), // rsrc
7417 Op.getOperand(5), // vindex
7418 Offsets.first, // voffset
7419 Op.getOperand(7), // soffset
7420 Offsets.second, // offset
7421 Op.getOperand(8), // cachepolicy
7422 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7423 };
7424 EVT VT = Op.getValueType();
7425 auto *M = cast<MemSDNode>(Op);
7426 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7427
7428 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7429 Op->getVTList(), Ops, VT, M->getMemOperand());
7430 }
7431 case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7432 MemSDNode *M = cast<MemSDNode>(Op);
7433 SDValue NodePtr = M->getOperand(2);
7434 SDValue RayExtent = M->getOperand(3);
7435 SDValue RayOrigin = M->getOperand(4);
7436 SDValue RayDir = M->getOperand(5);
7437 SDValue RayInvDir = M->getOperand(6);
7438 SDValue TDescr = M->getOperand(7);
7439
7440 assert(NodePtr.getValueType() == MVT::i32 ||(static_cast <bool> (NodePtr.getValueType() == MVT::i32
|| NodePtr.getValueType() == MVT::i64) ? void (0) : __assert_fail
("NodePtr.getValueType() == MVT::i32 || NodePtr.getValueType() == MVT::i64"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7441, __extension__ __PRETTY_FUNCTION__))
7441 NodePtr.getValueType() == MVT::i64)(static_cast <bool> (NodePtr.getValueType() == MVT::i32
|| NodePtr.getValueType() == MVT::i64) ? void (0) : __assert_fail
("NodePtr.getValueType() == MVT::i32 || NodePtr.getValueType() == MVT::i64"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7441, __extension__ __PRETTY_FUNCTION__))
;
7442 assert(RayDir.getValueType() == MVT::v4f16 ||(static_cast <bool> (RayDir.getValueType() == MVT::v4f16
|| RayDir.getValueType() == MVT::v4f32) ? void (0) : __assert_fail
("RayDir.getValueType() == MVT::v4f16 || RayDir.getValueType() == MVT::v4f32"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7443, __extension__ __PRETTY_FUNCTION__))
7443 RayDir.getValueType() == MVT::v4f32)(static_cast <bool> (RayDir.getValueType() == MVT::v4f16
|| RayDir.getValueType() == MVT::v4f32) ? void (0) : __assert_fail
("RayDir.getValueType() == MVT::v4f16 || RayDir.getValueType() == MVT::v4f32"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7443, __extension__ __PRETTY_FUNCTION__))
;
7444
7445 if (!Subtarget->hasGFX10_AEncoding()) {
7446 emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7447 return SDValue();
7448 }
7449
7450 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7451 const bool Is64 = NodePtr.getValueType() == MVT::i64;
7452 const unsigned NumVDataDwords = 4;
7453 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7454 const bool UseNSA = Subtarget->hasNSAEncoding() &&
7455 NumVAddrDwords <= Subtarget->getNSAMaxSize();
7456 const unsigned BaseOpcodes[2][2] = {
7457 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7458 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7459 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7460 int Opcode;
7461 if (UseNSA) {
7462 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7463 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7464 NumVAddrDwords);
7465 } else {
7466 Opcode = AMDGPU::getMIMGOpcode(
7467 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7468 PowerOf2Ceil(NumVAddrDwords));
7469 }
7470 assert(Opcode != -1)(static_cast <bool> (Opcode != -1) ? void (0) : __assert_fail
("Opcode != -1", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7470, __extension__ __PRETTY_FUNCTION__))
;
7471
7472 SmallVector<SDValue, 16> Ops;
7473
7474 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7475 SmallVector<SDValue, 3> Lanes;
7476 DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7477 if (Lanes[0].getValueSizeInBits() == 32) {
7478 for (unsigned I = 0; I < 3; ++I)
7479 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7480 } else {
7481 if (IsAligned) {
7482 Ops.push_back(
7483 DAG.getBitcast(MVT::i32,
7484 DAG.getBuildVector(MVT::v2f16, DL,
7485 { Lanes[0], Lanes[1] })));
7486 Ops.push_back(Lanes[2]);
7487 } else {
7488 SDValue Elt0 = Ops.pop_back_val();
7489 Ops.push_back(
7490 DAG.getBitcast(MVT::i32,
7491 DAG.getBuildVector(MVT::v2f16, DL,
7492 { Elt0, Lanes[0] })));
7493 Ops.push_back(
7494 DAG.getBitcast(MVT::i32,
7495 DAG.getBuildVector(MVT::v2f16, DL,
7496 { Lanes[1], Lanes[2] })));
7497 }
7498 }
7499 };
7500
7501 if (Is64)
7502 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7503 else
7504 Ops.push_back(NodePtr);
7505
7506 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7507 packLanes(RayOrigin, true);
7508 packLanes(RayDir, true);
7509 packLanes(RayInvDir, false);
7510
7511 if (!UseNSA) {
7512 // Build a single vector containing all the operands so far prepared.
7513 if (NumVAddrDwords > 8) {
7514 SDValue Undef = DAG.getUNDEF(MVT::i32);
7515 Ops.append(16 - Ops.size(), Undef);
7516 }
7517 assert(Ops.size() == 8 || Ops.size() == 16)(static_cast <bool> (Ops.size() == 8 || Ops.size() == 16
) ? void (0) : __assert_fail ("Ops.size() == 8 || Ops.size() == 16"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7517, __extension__ __PRETTY_FUNCTION__))
;
7518 SDValue MergedOps = DAG.getBuildVector(
7519 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7520 Ops.clear();
7521 Ops.push_back(MergedOps);
7522 }
7523
7524 Ops.push_back(TDescr);
7525 if (IsA16)
7526 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7527 Ops.push_back(M->getChain());
7528
7529 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7530 MachineMemOperand *MemRef = M->getMemOperand();
7531 DAG.setNodeMemRefs(NewNode, {MemRef});
7532 return SDValue(NewNode, 0);
7533 }
7534 case Intrinsic::amdgcn_global_atomic_fadd:
7535 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7536 DiagnosticInfoUnsupported
7537 NoFpRet(DAG.getMachineFunction().getFunction(),
7538 "return versions of fp atomics not supported",
7539 DL.getDebugLoc(), DS_Error);
7540 DAG.getContext()->diagnose(NoFpRet);
7541 return SDValue();
7542 }
7543 LLVM_FALLTHROUGH[[gnu::fallthrough]];
7544 case Intrinsic::amdgcn_global_atomic_fmin:
7545 case Intrinsic::amdgcn_global_atomic_fmax:
7546 case Intrinsic::amdgcn_flat_atomic_fadd:
7547 case Intrinsic::amdgcn_flat_atomic_fmin:
7548 case Intrinsic::amdgcn_flat_atomic_fmax: {
7549 MemSDNode *M = cast<MemSDNode>(Op);
7550 SDValue Ops[] = {
7551 M->getOperand(0), // Chain
7552 M->getOperand(2), // Ptr
7553 M->getOperand(3) // Value
7554 };
7555 unsigned Opcode = 0;
7556 switch (IntrID) {
7557 case Intrinsic::amdgcn_global_atomic_fadd:
7558 case Intrinsic::amdgcn_flat_atomic_fadd: {
7559 EVT VT = Op.getOperand(3).getValueType();
7560 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7561 DAG.getVTList(VT, MVT::Other), Ops,
7562 M->getMemOperand());
7563 }
7564 case Intrinsic::amdgcn_global_atomic_fmin:
7565 case Intrinsic::amdgcn_flat_atomic_fmin: {
7566 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7567 break;
7568 }
7569 case Intrinsic::amdgcn_global_atomic_fmax:
7570 case Intrinsic::amdgcn_flat_atomic_fmax: {
7571 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7572 break;
7573 }
7574 default:
7575 llvm_unreachable("unhandled atomic opcode")::llvm::llvm_unreachable_internal("unhandled atomic opcode", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7575)
;
7576 }
7577 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7578 M->getVTList(), Ops, M->getMemoryVT(),
7579 M->getMemOperand());
7580 }
7581 default:
7582
7583 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7584 AMDGPU::getImageDimIntrinsicInfo(IntrID))
7585 return lowerImage(Op, ImageDimIntr, DAG, true);
7586
7587 return SDValue();
7588 }
7589}
7590
7591// Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7592// dwordx4 if on SI.
7593SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7594 SDVTList VTList,
7595 ArrayRef<SDValue> Ops, EVT MemVT,
7596 MachineMemOperand *MMO,
7597 SelectionDAG &DAG) const {
7598 EVT VT = VTList.VTs[0];
7599 EVT WidenedVT = VT;
7600 EVT WidenedMemVT = MemVT;
7601 if (!Subtarget->hasDwordx3LoadStores() &&
7602 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7603 WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7604 WidenedVT.getVectorElementType(), 4);
7605 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7606 WidenedMemVT.getVectorElementType(), 4);
7607 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7608 }
7609
7610 assert(VTList.NumVTs == 2)(static_cast <bool> (VTList.NumVTs == 2) ? void (0) : __assert_fail
("VTList.NumVTs == 2", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7610, __extension__ __PRETTY_FUNCTION__))
;
7611 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7612
7613 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7614 WidenedMemVT, MMO);
7615 if (WidenedVT != VT) {
7616 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7617 DAG.getVectorIdxConstant(0, DL));
7618 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7619 }
7620 return NewOp;
7621}
7622
7623SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7624 bool ImageStore) const {
7625 EVT StoreVT = VData.getValueType();
7626
7627 // No change for f16 and legal vector D16 types.
7628 if (!StoreVT.isVector())
7629 return VData;
7630
7631 SDLoc DL(VData);
7632 unsigned NumElements = StoreVT.getVectorNumElements();
7633
7634 if (Subtarget->hasUnpackedD16VMem()) {
7635 // We need to unpack the packed data to store.
7636 EVT IntStoreVT = StoreVT.changeTypeToInteger();
7637 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7638
7639 EVT EquivStoreVT =
7640 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7641 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7642 return DAG.UnrollVectorOp(ZExt.getNode());
7643 }
7644
7645 // The sq block of gfx8.1 does not estimate register use correctly for d16
7646 // image store instructions. The data operand is computed as if it were not a
7647 // d16 image instruction.
7648 if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7649 // Bitcast to i16
7650 EVT IntStoreVT = StoreVT.changeTypeToInteger();
7651 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7652
7653 // Decompose into scalars
7654 SmallVector<SDValue, 4> Elts;
7655 DAG.ExtractVectorElements(IntVData, Elts);
7656
7657 // Group pairs of i16 into v2i16 and bitcast to i32
7658 SmallVector<SDValue, 4> PackedElts;
7659 for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7660 SDValue Pair =
7661 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7662 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7663 PackedElts.push_back(IntPair);
7664 }
7665 if ((NumElements % 2) == 1) {
7666 // Handle v3i16
7667 unsigned I = Elts.size() / 2;
7668 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7669 {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7670 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7671 PackedElts.push_back(IntPair);
7672 }
7673
7674 // Pad using UNDEF
7675 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7676
7677 // Build final vector
7678 EVT VecVT =
7679 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7680 return DAG.getBuildVector(VecVT, DL, PackedElts);
7681 }
7682
7683 if (NumElements == 3) {
7684 EVT IntStoreVT =
7685 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7686 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7687
7688 EVT WidenedStoreVT = EVT::getVectorVT(
7689 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7690 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7691 WidenedStoreVT.getStoreSizeInBits());
7692 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7693 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7694 }
7695
7696 assert(isTypeLegal(StoreVT))(static_cast <bool> (isTypeLegal(StoreVT)) ? void (0) :
__assert_fail ("isTypeLegal(StoreVT)", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7696, __extension__ __PRETTY_FUNCTION__))
;
7697 return VData;
7698}
7699
7700SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7701 SelectionDAG &DAG) const {
7702 SDLoc DL(Op);
7703 SDValue Chain = Op.getOperand(0);
7704 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7705 MachineFunction &MF = DAG.getMachineFunction();
7706
7707 switch (IntrinsicID) {
7708 case Intrinsic::amdgcn_exp_compr: {
7709 SDValue Src0 = Op.getOperand(4);
7710 SDValue Src1 = Op.getOperand(5);
7711 // Hack around illegal type on SI by directly selecting it.
7712 if (isTypeLegal(Src0.getValueType()))
7713 return SDValue();
7714
7715 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7716 SDValue Undef = DAG.getUNDEF(MVT::f32);
7717 const SDValue Ops[] = {
7718 Op.getOperand(2), // tgt
7719 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7720 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7721 Undef, // src2
7722 Undef, // src3
7723 Op.getOperand(7), // vm
7724 DAG.getTargetConstant(1, DL, MVT::i1), // compr
7725 Op.getOperand(3), // en
7726 Op.getOperand(0) // Chain
7727 };
7728
7729 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7730 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7731 }
7732 case Intrinsic::amdgcn_s_barrier: {
7733 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7734 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7735 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7736 if (WGSize <= ST.getWavefrontSize())
7737 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7738 Op.getOperand(0)), 0);
7739 }
7740 return SDValue();
7741 };
7742 case Intrinsic::amdgcn_tbuffer_store: {
7743 SDValue VData = Op.getOperand(2);
7744 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7745 if (IsD16)
7746 VData = handleD16VData(VData, DAG);
7747 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7748 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7749 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7750 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7751 unsigned IdxEn = getIdxEn(Op.getOperand(4));
7752 SDValue Ops[] = {
7753 Chain,
7754 VData, // vdata
7755 Op.getOperand(3), // rsrc
7756 Op.getOperand(4), // vindex
7757 Op.getOperand(5), // voffset
7758 Op.getOperand(6), // soffset
7759 Op.getOperand(7), // offset
7760 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7761 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7762 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7763 };
7764 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7765 AMDGPUISD::TBUFFER_STORE_FORMAT;
7766 MemSDNode *M = cast<MemSDNode>(Op);
7767 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7768 M->getMemoryVT(), M->getMemOperand());
7769 }
7770
7771 case Intrinsic::amdgcn_struct_tbuffer_store: {
7772 SDValue VData = Op.getOperand(2);
7773 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7774 if (IsD16)
7775 VData = handleD16VData(VData, DAG);
7776 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7777 SDValue Ops[] = {
7778 Chain,
7779 VData, // vdata
7780 Op.getOperand(3), // rsrc
7781 Op.getOperand(4), // vindex
7782 Offsets.first, // voffset
7783 Op.getOperand(6), // soffset
7784 Offsets.second, // offset
7785 Op.getOperand(7), // format
7786 Op.getOperand(8), // cachepolicy, swizzled buffer
7787 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7788 };
7789 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7790 AMDGPUISD::TBUFFER_STORE_FORMAT;
7791 MemSDNode *M = cast<MemSDNode>(Op);
7792 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7793 M->getMemoryVT(), M->getMemOperand());
7794 }
7795
7796 case Intrinsic::amdgcn_raw_tbuffer_store: {
7797 SDValue VData = Op.getOperand(2);
7798 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7799 if (IsD16)
7800 VData = handleD16VData(VData, DAG);
7801 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7802 SDValue Ops[] = {
7803 Chain,
7804 VData, // vdata
7805 Op.getOperand(3), // rsrc
7806 DAG.getConstant(0, DL, MVT::i32), // vindex
7807 Offsets.first, // voffset
7808 Op.getOperand(5), // soffset
7809 Offsets.second, // offset
7810 Op.getOperand(6), // format
7811 Op.getOperand(7), // cachepolicy, swizzled buffer
7812 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7813 };
7814 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7815 AMDGPUISD::TBUFFER_STORE_FORMAT;
7816 MemSDNode *M = cast<MemSDNode>(Op);
7817 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7818 M->getMemoryVT(), M->getMemOperand());
7819 }
7820
7821 case Intrinsic::amdgcn_buffer_store:
7822 case Intrinsic::amdgcn_buffer_store_format: {
7823 SDValue VData = Op.getOperand(2);
7824 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7825 if (IsD16)
7826 VData = handleD16VData(VData, DAG);
7827 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7828 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7829 unsigned IdxEn = getIdxEn(Op.getOperand(4));
7830 SDValue Ops[] = {
7831 Chain,
7832 VData,
7833 Op.getOperand(3), // rsrc
7834 Op.getOperand(4), // vindex
7835 SDValue(), // voffset -- will be set by setBufferOffsets
7836 SDValue(), // soffset -- will be set by setBufferOffsets
7837 SDValue(), // offset -- will be set by setBufferOffsets
7838 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7839 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7840 };
7841 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7842
7843 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7844 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7845 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7846 MemSDNode *M = cast<MemSDNode>(Op);
7847 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7848
7849 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7850 EVT VDataType = VData.getValueType().getScalarType();
7851 if (VDataType == MVT::i8 || VDataType == MVT::i16)
7852 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7853
7854 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7855 M->getMemoryVT(), M->getMemOperand());
7856 }
7857
7858 case Intrinsic::amdgcn_raw_buffer_store:
7859 case Intrinsic::amdgcn_raw_buffer_store_format: {
7860 const bool IsFormat =
7861 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7862
7863 SDValue VData = Op.getOperand(2);
7864 EVT VDataVT = VData.getValueType();
7865 EVT EltType = VDataVT.getScalarType();
7866 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7867 if (IsD16) {
7868 VData = handleD16VData(VData, DAG);
7869 VDataVT = VData.getValueType();
7870 }
7871
7872 if (!isTypeLegal(VDataVT)) {
7873 VData =
7874 DAG.getNode(ISD::BITCAST, DL,
7875 getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7876 }
7877
7878 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7879 SDValue Ops[] = {
7880 Chain,
7881 VData,
7882 Op.getOperand(3), // rsrc
7883 DAG.getConstant(0, DL, MVT::i32), // vindex
7884 Offsets.first, // voffset
7885 Op.getOperand(5), // soffset
7886 Offsets.second, // offset
7887 Op.getOperand(6), // cachepolicy, swizzled buffer
7888 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7889 };
7890 unsigned Opc =
7891 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7892 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7893 MemSDNode *M = cast<MemSDNode>(Op);
7894 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7895
7896 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7897 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7898 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7899
7900 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7901 M->getMemoryVT(), M->getMemOperand());
7902 }
7903
7904 case Intrinsic::amdgcn_struct_buffer_store:
7905 case Intrinsic::amdgcn_struct_buffer_store_format: {
7906 const bool IsFormat =
7907 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7908
7909 SDValue VData = Op.getOperand(2);
7910 EVT VDataVT = VData.getValueType();
7911 EVT EltType = VDataVT.getScalarType();
7912 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7913
7914 if (IsD16) {
7915 VData = handleD16VData(VData, DAG);
7916 VDataVT = VData.getValueType();
7917 }
7918
7919 if (!isTypeLegal(VDataVT)) {
7920 VData =
7921 DAG.getNode(ISD::BITCAST, DL,
7922 getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7923 }
7924
7925 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7926 SDValue Ops[] = {
7927 Chain,
7928 VData,
7929 Op.getOperand(3), // rsrc
7930 Op.getOperand(4), // vindex
7931 Offsets.first, // voffset
7932 Op.getOperand(6), // soffset
7933 Offsets.second, // offset
7934 Op.getOperand(7), // cachepolicy, swizzled buffer
7935 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7936 };
7937 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7938 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7939 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7940 MemSDNode *M = cast<MemSDNode>(Op);
7941 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7942
7943 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7944 EVT VDataType = VData.getValueType().getScalarType();
7945 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7946 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7947
7948 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7949 M->getMemoryVT(), M->getMemOperand());
7950 }
7951 case Intrinsic::amdgcn_end_cf:
7952 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7953 Op->getOperand(2), Chain), 0);
7954
7955 default: {
7956 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7957 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7958 return lowerImage(Op, ImageDimIntr, DAG, true);
7959
7960 return Op;
7961 }
7962 }
7963}
7964
7965// The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7966// offset (the offset that is included in bounds checking and swizzling, to be
7967// split between the instruction's voffset and immoffset fields) and soffset
7968// (the offset that is excluded from bounds checking and swizzling, to go in
7969// the instruction's soffset field). This function takes the first kind of
7970// offset and figures out how to split it between voffset and immoffset.
7971std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7972 SDValue Offset, SelectionDAG &DAG) const {
7973 SDLoc DL(Offset);
7974 const unsigned MaxImm = 4095;
7975 SDValue N0 = Offset;
7976 ConstantSDNode *C1 = nullptr;
7977
7978 if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7979 N0 = SDValue();
7980 else if (DAG.isBaseWithConstantOffset(N0)) {
7981 C1 = cast<ConstantSDNode>(N0.getOperand(1));
7982 N0 = N0.getOperand(0);
7983 }
7984
7985 if (C1) {
7986 unsigned ImmOffset = C1->getZExtValue();
7987 // If the immediate value is too big for the immoffset field, put the value
7988 // and -4096 into the immoffset field so that the value that is copied/added
7989 // for the voffset field is a multiple of 4096, and it stands more chance
7990 // of being CSEd with the copy/add for another similar load/store.
7991 // However, do not do that rounding down to a multiple of 4096 if that is a
7992 // negative number, as it appears to be illegal to have a negative offset
7993 // in the vgpr, even if adding the immediate offset makes it positive.
7994 unsigned Overflow = ImmOffset & ~MaxImm;
7995 ImmOffset -= Overflow;
7996 if ((int32_t)Overflow < 0) {
7997 Overflow += ImmOffset;
7998 ImmOffset = 0;
7999 }
8000 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8001 if (Overflow) {
8002 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8003 if (!N0)
8004 N0 = OverflowVal;
8005 else {
8006 SDValue Ops[] = { N0, OverflowVal };
8007 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8008 }
8009 }
8010 }
8011 if (!N0)
8012 N0 = DAG.getConstant(0, DL, MVT::i32);
8013 if (!C1)
8014 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8015 return {N0, SDValue(C1, 0)};
8016}
8017
8018// Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8019// three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8020// pointed to by Offsets.
8021void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8022 SelectionDAG &DAG, SDValue *Offsets,
8023 Align Alignment) const {
8024 SDLoc DL(CombinedOffset);
8025 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8026 uint32_t Imm = C->getZExtValue();
8027 uint32_t SOffset, ImmOffset;
8028 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8029 Alignment)) {
8030 Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8031 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8032 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8033 return;
8034 }
8035 }
8036 if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8037 SDValue N0 = CombinedOffset.getOperand(0);
8038 SDValue N1 = CombinedOffset.getOperand(1);
8039 uint32_t SOffset, ImmOffset;
8040 int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8041 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8042 Subtarget, Alignment)) {
8043 Offsets[0] = N0;
8044 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8045 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8046 return;
8047 }
8048 }
8049 Offsets[0] = CombinedOffset;
8050 Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8051 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8052}
8053
8054// Handle 8 bit and 16 bit buffer loads
8055SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8056 EVT LoadVT, SDLoc DL,
8057 ArrayRef<SDValue> Ops,
8058 MemSDNode *M) const {
8059 EVT IntVT = LoadVT.changeTypeToInteger();
8060 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8061 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8062
8063 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8064 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8065 Ops, IntVT,
8066 M->getMemOperand());
8067 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8068 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8069
8070 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8071}
8072
8073// Handle 8 bit and 16 bit buffer stores
8074SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8075 EVT VDataType, SDLoc DL,
8076 SDValue Ops[],
8077 MemSDNode *M) const {
8078 if (VDataType == MVT::f16)
8079 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8080
8081 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8082 Ops[1] = BufferStoreExt;
8083 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8084 AMDGPUISD::BUFFER_STORE_SHORT;
8085 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8086 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8087 M->getMemOperand());
8088}
8089
8090static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8091 ISD::LoadExtType ExtType, SDValue Op,
8092 const SDLoc &SL, EVT VT) {
8093 if (VT.bitsLT(Op.getValueType()))
8094 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8095
8096 switch (ExtType) {
8097 case ISD::SEXTLOAD:
8098 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8099 case ISD::ZEXTLOAD:
8100 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8101 case ISD::EXTLOAD:
8102 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8103 case ISD::NON_EXTLOAD:
8104 return Op;
8105 }
8106
8107 llvm_unreachable("invalid ext type")::llvm::llvm_unreachable_internal("invalid ext type", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8107)
;
8108}
8109
8110SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8111 SelectionDAG &DAG = DCI.DAG;
8112 if (Ld->getAlignment() < 4 || Ld->isDivergent())
8113 return SDValue();
8114
8115 // FIXME: Constant loads should all be marked invariant.
8116 unsigned AS = Ld->getAddressSpace();
8117 if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8118 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8119 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8120 return SDValue();
8121
8122 // Don't do this early, since it may interfere with adjacent load merging for
8123 // illegal types. We can avoid losing alignment information for exotic types
8124 // pre-legalize.
8125 EVT MemVT = Ld->getMemoryVT();
8126 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8127 MemVT.getSizeInBits() >= 32)
8128 return SDValue();
8129
8130 SDLoc SL(Ld);
8131
8132 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&(static_cast <bool> ((!MemVT.isVector() || Ld->getExtensionType
() == ISD::NON_EXTLOAD) && "unexpected vector extload"
) ? void (0) : __assert_fail ("(!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && \"unexpected vector extload\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8133, __extension__ __PRETTY_FUNCTION__))
8133 "unexpected vector extload")(static_cast <bool> ((!MemVT.isVector() || Ld->getExtensionType
() == ISD::NON_EXTLOAD) && "unexpected vector extload"
) ? void (0) : __assert_fail ("(!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && \"unexpected vector extload\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8133, __extension__ __PRETTY_FUNCTION__))
;
8134
8135 // TODO: Drop only high part of range.
8136 SDValue Ptr = Ld->getBasePtr();
8137 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8138 MVT::i32, SL, Ld->getChain(), Ptr,
8139 Ld->getOffset(),
8140 Ld->getPointerInfo(), MVT::i32,
8141 Ld->getAlignment(),
8142 Ld->getMemOperand()->getFlags(),
8143 Ld->getAAInfo(),
8144 nullptr); // Drop ranges
8145
8146 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8147 if (MemVT.isFloatingPoint()) {
8148 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&(static_cast <bool> (Ld->getExtensionType() == ISD::
NON_EXTLOAD && "unexpected fp extload") ? void (0) : __assert_fail
("Ld->getExtensionType() == ISD::NON_EXTLOAD && \"unexpected fp extload\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8149, __extension__ __PRETTY_FUNCTION__))
8149 "unexpected fp extload")(static_cast <bool> (Ld->getExtensionType() == ISD::
NON_EXTLOAD && "unexpected fp extload") ? void (0) : __assert_fail
("Ld->getExtensionType() == ISD::NON_EXTLOAD && \"unexpected fp extload\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8149, __extension__ __PRETTY_FUNCTION__))
;
8150 TruncVT = MemVT.changeTypeToInteger();
8151 }
8152
8153 SDValue Cvt = NewLoad;
8154 if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8155 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8156 DAG.getValueType(TruncVT));
8157 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8158 Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8159 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8160 } else {
8161 assert(Ld->getExtensionType() == ISD::EXTLOAD)(static_cast <bool> (Ld->getExtensionType() == ISD::
EXTLOAD) ? void (0) : __assert_fail ("Ld->getExtensionType() == ISD::EXTLOAD"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8161, __extension__ __PRETTY_FUNCTION__))
;
8162 }
8163
8164 EVT VT = Ld->getValueType(0);
8165 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8166
8167 DCI.AddToWorklist(Cvt.getNode());
8168
8169 // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8170 // the appropriate extension from the 32-bit load.
8171 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8172 DCI.AddToWorklist(Cvt.getNode());
8173
8174 // Handle conversion back to floating point if necessary.
8175 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8176
8177 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8178}
8179
8180SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8181 SDLoc DL(Op);
8182 LoadSDNode *Load = cast<LoadSDNode>(Op);
8183 ISD::LoadExtType ExtType = Load->getExtensionType();
8184 EVT MemVT = Load->getMemoryVT();
8185
8186 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8187 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8188 return SDValue();
8189
8190 // FIXME: Copied from PPC
8191 // First, load into 32 bits, then truncate to 1 bit.
8192
8193 SDValue Chain = Load->getChain();
8194 SDValue BasePtr = Load->getBasePtr();
8195 MachineMemOperand *MMO = Load->getMemOperand();
8196
8197 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8198
8199 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8200 BasePtr, RealMemVT, MMO);
8201
8202 if (!MemVT.isVector()) {
8203 SDValue Ops[] = {
8204 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8205 NewLD.getValue(1)
8206 };
8207
8208 return DAG.getMergeValues(Ops, DL);
8209 }
8210
8211 SmallVector<SDValue, 3> Elts;
8212 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8213 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8214 DAG.getConstant(I, DL, MVT::i32));
8215
8216 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8217 }
8218
8219 SDValue Ops[] = {
8220 DAG.getBuildVector(MemVT, DL, Elts),
8221 NewLD.getValue(1)
8222 };
8223
8224 return DAG.getMergeValues(Ops, DL);
8225 }
8226
8227 if (!MemVT.isVector())
8228 return SDValue();
8229
8230 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&(static_cast <bool> (Op.getValueType().getVectorElementType
() == MVT::i32 && "Custom lowering for non-i32 vectors hasn't been implemented."
) ? void (0) : __assert_fail ("Op.getValueType().getVectorElementType() == MVT::i32 && \"Custom lowering for non-i32 vectors hasn't been implemented.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8231, __extension__ __PRETTY_FUNCTION__))
8231 "Custom lowering for non-i32 vectors hasn't been implemented.")(static_cast <bool> (Op.getValueType().getVectorElementType
() == MVT::i32 && "Custom lowering for non-i32 vectors hasn't been implemented."
) ? void (0) : __assert_fail ("Op.getValueType().getVectorElementType() == MVT::i32 && \"Custom lowering for non-i32 vectors hasn't been implemented.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8231, __extension__ __PRETTY_FUNCTION__))
;
8232
8233 unsigned Alignment = Load->getAlignment();
8234 unsigned AS = Load->getAddressSpace();
8235 if (Subtarget->hasLDSMisalignedBug() &&
8236 AS == AMDGPUAS::FLAT_ADDRESS &&
8237 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8238 return SplitVectorLoad(Op, DAG);
8239 }
8240
8241 MachineFunction &MF = DAG.getMachineFunction();
8242 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8243 // If there is a possibilty that flat instruction access scratch memory
8244 // then we need to use the same legalization rules we use for private.
8245 if (AS == AMDGPUAS::FLAT_ADDRESS &&
8246 !Subtarget->hasMultiDwordFlatScratchAddressing())
8247 AS = MFI->hasFlatScratchInit() ?
8248 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8249
8250 unsigned NumElements = MemVT.getVectorNumElements();
8251
8252 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8253 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8254 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8255 if (MemVT.isPow2VectorType())
8256 return SDValue();
8257 return WidenOrSplitVectorLoad(Op, DAG);
8258 }
8259 // Non-uniform loads will be selected to MUBUF instructions, so they
8260 // have the same legalization requirements as global and private
8261 // loads.
8262 //
8263 }
8264
8265 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8266 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8267 AS == AMDGPUAS::GLOBAL_ADDRESS) {
8268 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8269 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8270 Alignment >= 4 && NumElements < 32) {
8271 if (MemVT.isPow2VectorType())
8272 return SDValue();
8273 return WidenOrSplitVectorLoad(Op, DAG);
8274 }
8275 // Non-uniform loads will be selected to MUBUF instructions, so they
8276 // have the same legalization requirements as global and private
8277 // loads.
8278 //
8279 }
8280 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8281 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8282 AS == AMDGPUAS::GLOBAL_ADDRESS ||
8283 AS == AMDGPUAS::FLAT_ADDRESS) {
8284 if (NumElements > 4)
8285 return SplitVectorLoad(Op, DAG);
8286 // v3 loads not supported on SI.
8287 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8288 return WidenOrSplitVectorLoad(Op, DAG);
8289
8290 // v3 and v4 loads are supported for private and global memory.
8291 return SDValue();
8292 }
8293 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8294 // Depending on the setting of the private_element_size field in the
8295 // resource descriptor, we can only make private accesses up to a certain
8296 // size.
8297 switch (Subtarget->getMaxPrivateElementSize()) {
8298 case 4: {
8299 SDValue Ops[2];
8300 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8301 return DAG.getMergeValues(Ops, DL);
8302 }
8303 case 8:
8304 if (NumElements > 2)
8305 return SplitVectorLoad(Op, DAG);
8306 return SDValue();
8307 case 16:
8308 // Same as global/flat
8309 if (NumElements > 4)
8310 return SplitVectorLoad(Op, DAG);
8311 // v3 loads not supported on SI.
8312 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8313 return WidenOrSplitVectorLoad(Op, DAG);
8314
8315 return SDValue();
8316 default:
8317 llvm_unreachable("unsupported private_element_size")::llvm::llvm_unreachable_internal("unsupported private_element_size"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8317)
;
8318 }
8319 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8320 // Use ds_read_b128 or ds_read_b96 when possible.
8321 if (Subtarget->hasDS96AndDS128() &&
8322 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8323 MemVT.getStoreSize() == 12) &&
8324 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8325 Load->getAlign()))
8326 return SDValue();
8327
8328 if (NumElements > 2)
8329 return SplitVectorLoad(Op, DAG);
8330
8331 // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8332 // address is negative, then the instruction is incorrectly treated as
8333 // out-of-bounds even if base + offsets is in bounds. Split vectorized
8334 // loads here to avoid emitting ds_read2_b32. We may re-combine the
8335 // load later in the SILoadStoreOptimizer.
8336 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8337 NumElements == 2 && MemVT.getStoreSize() == 8 &&
8338 Load->getAlignment() < 8) {
8339 return SplitVectorLoad(Op, DAG);
8340 }
8341 }
8342
8343 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8344 MemVT, *Load->getMemOperand())) {
8345 SDValue Ops[2];
8346 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8347 return DAG.getMergeValues(Ops, DL);
8348 }
8349
8350 return SDValue();
8351}
8352
8353SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8354 EVT VT = Op.getValueType();
8355 assert(VT.getSizeInBits() == 64)(static_cast <bool> (VT.getSizeInBits() == 64) ? void (
0) : __assert_fail ("VT.getSizeInBits() == 64", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8355, __extension__ __PRETTY_FUNCTION__))
;
8356
8357 SDLoc DL(Op);
8358 SDValue Cond = Op.getOperand(0);
8359
8360 if (Subtarget->hasScalarCompareEq64() && Op->getOperand(0)->hasOneUse() &&
8361 !Op->isDivergent()) {
8362 if (VT == MVT::i64)
8363 return Op;
8364 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(1));
8365 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(2));
8366 return DAG.getNode(ISD::BITCAST, DL, VT,
8367 DAG.getSelect(DL, MVT::i64, Cond, LHS, RHS));
8368 }
8369
8370 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8371 SDValue One = DAG.getConstant(1, DL, MVT::i32);
8372
8373 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8374 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8375
8376 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8377 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8378
8379 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8380
8381 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8382 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8383
8384 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8385
8386 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8387 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8388}
8389
8390// Catch division cases where we can use shortcuts with rcp and rsq
8391// instructions.
8392SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8393 SelectionDAG &DAG) const {
8394 SDLoc SL(Op);
8395 SDValue LHS = Op.getOperand(0);
8396 SDValue RHS = Op.getOperand(1);
8397 EVT VT = Op.getValueType();
8398 const SDNodeFlags Flags = Op->getFlags();
8399
8400 bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8401
8402 // Without !fpmath accuracy information, we can't do more because we don't
8403 // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8404 if (!AllowInaccurateRcp)
8405 return SDValue();
8406
8407 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8408 if (CLHS->isExactlyValue(1.0)) {
8409 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8410 // the CI documentation has a worst case error of 1 ulp.
8411 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8412 // use it as long as we aren't trying to use denormals.
8413 //
8414 // v_rcp_f16 and v_rsq_f16 DO support denormals.
8415
8416 // 1.0 / sqrt(x) -> rsq(x)
8417
8418 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8419 // error seems really high at 2^29 ULP.
8420 if (RHS.getOpcode() == ISD::FSQRT)
8421 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8422
8423 // 1.0 / x -> rcp(x)
8424 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8425 }
8426
8427 // Same as for 1.0, but expand the sign out of the constant.
8428 if (CLHS->isExactlyValue(-1.0)) {
8429 // -1.0 / x -> rcp (fneg x)
8430 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8431 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8432 }
8433 }
8434
8435 // Turn into multiply by the reciprocal.
8436 // x / y -> x * (1.0 / y)
8437 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8438 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8439}
8440
8441SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8442 SelectionDAG &DAG) const {
8443 SDLoc SL(Op);
8444 SDValue X = Op.getOperand(0);
8445 SDValue Y = Op.getOperand(1);
8446 EVT VT = Op.getValueType();
8447 const SDNodeFlags Flags = Op->getFlags();
8448
8449 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8450 DAG.getTarget().Options.UnsafeFPMath;
8451 if (!AllowInaccurateDiv)
8452 return SDValue();
8453
8454 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8455 SDValue One = DAG.getConstantFP(1.0, SL, VT);
8456
8457 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8458 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8459
8460 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8461 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8462 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8463 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8464 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8465 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8466}
8467
8468static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8469 EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8470 SDNodeFlags Flags) {
8471 if (GlueChain->getNumValues() <= 1) {
8472 return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8473 }
8474
8475 assert(GlueChain->getNumValues() == 3)(static_cast <bool> (GlueChain->getNumValues() == 3)
? void (0) : __assert_fail ("GlueChain->getNumValues() == 3"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8475, __extension__ __PRETTY_FUNCTION__))
;
8476
8477 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8478 switch (Opcode) {
8479 default: llvm_unreachable("no chain equivalent for opcode")::llvm::llvm_unreachable_internal("no chain equivalent for opcode"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8479)
;
8480 case ISD::FMUL:
8481 Opcode = AMDGPUISD::FMUL_W_CHAIN;
8482 break;
8483 }
8484
8485 return DAG.getNode(Opcode, SL, VTList,
8486 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8487 Flags);
8488}
8489
8490static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8491 EVT VT, SDValue A, SDValue B, SDValue C,
8492 SDValue GlueChain, SDNodeFlags Flags) {
8493 if (GlueChain->getNumValues() <= 1) {
8494 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8495 }
8496
8497 assert(GlueChain->getNumValues() == 3)(static_cast <bool> (GlueChain->getNumValues() == 3)
? void (0) : __assert_fail ("GlueChain->getNumValues() == 3"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8497, __extension__ __PRETTY_FUNCTION__))
;
8498
8499 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8500 switch (Opcode) {
8501 default: llvm_unreachable("no chain equivalent for opcode")::llvm::llvm_unreachable_internal("no chain equivalent for opcode"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8501)
;
8502 case ISD::FMA:
8503 Opcode = AMDGPUISD::FMA_W_CHAIN;
8504 break;
8505 }
8506
8507 return DAG.getNode(Opcode, SL, VTList,
8508 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8509 Flags);
8510}
8511
8512SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8513 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8514 return FastLowered;
8515
8516 SDLoc SL(Op);
8517 SDValue Src0 = Op.getOperand(0);
8518 SDValue Src1 = Op.getOperand(1);
8519
8520 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8521 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8522
8523 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8524 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8525
8526 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8527 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8528
8529 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8530}
8531
8532// Faster 2.5 ULP division that does not support denormals.
8533SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8534 SDLoc SL(Op);
8535 SDValue LHS = Op.getOperand(1);
8536 SDValue RHS = Op.getOperand(2);
8537
8538 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8539
8540 const APFloat K0Val(BitsToFloat(0x6f800000));
8541 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8542
8543 const APFloat K1Val(BitsToFloat(0x2f800000));
8544 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8545
8546 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8547
8548 EVT SetCCVT =
8549 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8550
8551 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8552
8553 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8554
8555 // TODO: Should this propagate fast-math-flags?
8556 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8557
8558 // rcp does not support denormals.
8559 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8560
8561 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8562
8563 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8564}
8565
8566// Returns immediate value for setting the F32 denorm mode when using the
8567// S_DENORM_MODE instruction.
8568static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8569 const SDLoc &SL, const GCNSubtarget *ST) {
8570 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE")(static_cast <bool> (ST->hasDenormModeInst() &&
"Requires S_DENORM_MODE") ? void (0) : __assert_fail ("ST->hasDenormModeInst() && \"Requires S_DENORM_MODE\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8570, __extension__ __PRETTY_FUNCTION__))
;
8571 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8572 ? FP_DENORM_FLUSH_NONE3
8573 : FP_DENORM_FLUSH_IN_FLUSH_OUT0;
8574
8575 int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8576 return DAG.getTargetConstant(Mode, SL, MVT::i32);
8577}
8578
8579SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8580 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8581 return FastLowered;
8582
8583 // The selection matcher assumes anything with a chain selecting to a
8584 // mayRaiseFPException machine instruction. Since we're introducing a chain
8585 // here, we need to explicitly report nofpexcept for the regular fdiv
8586 // lowering.
8587 SDNodeFlags Flags = Op->getFlags();
8588 Flags.setNoFPExcept(true);
8589
8590 SDLoc SL(Op);
8591 SDValue LHS = Op.getOperand(0);
8592 SDValue RHS = Op.getOperand(1);
8593
8594 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8595
8596 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8597
8598 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8599 {RHS, RHS, LHS}, Flags);
8600 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8601 {LHS, RHS, LHS}, Flags);
8602
8603 // Denominator is scaled to not be denormal, so using rcp is ok.
8604 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8605 DenominatorScaled, Flags);
8606 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8607 DenominatorScaled, Flags);
8608
8609 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8610 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8611 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8612 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8613
8614 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8615
8616 if (!HasFP32Denormals) {
8617 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8618 // lowering. The chain dependence is insufficient, and we need glue. We do
8619 // not need the glue variants in a strictfp function.
8620
8621 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8622
8623 SDNode *EnableDenorm;
8624 if (Subtarget->hasDenormModeInst()) {
8625 const SDValue EnableDenormValue =
8626 getSPDenormModeValue(FP_DENORM_FLUSH_NONE3, DAG, SL, Subtarget);
8627
8628 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8629 DAG.getEntryNode(), EnableDenormValue).getNode();
8630 } else {
8631 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE3,
8632 SL, MVT::i32);
8633 EnableDenorm =
8634 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8635 {EnableDenormValue, BitField, DAG.getEntryNode()});
8636 }
8637
8638 SDValue Ops[3] = {
8639 NegDivScale0,
8640 SDValue(EnableDenorm, 0),
8641 SDValue(EnableDenorm, 1)
8642 };
8643
8644 NegDivScale0 = DAG.getMergeValues(Ops, SL);
8645 }
8646
8647 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8648 ApproxRcp, One, NegDivScale0, Flags);
8649
8650 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8651 ApproxRcp, Fma0, Flags);
8652
8653 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8654 Fma1, Fma1, Flags);
8655
8656 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8657 NumeratorScaled, Mul, Flags);
8658
8659 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8660 Fma2, Fma1, Mul, Fma2, Flags);
8661
8662 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8663 NumeratorScaled, Fma3, Flags);
8664
8665 if (!HasFP32Denormals) {
8666 SDNode *DisableDenorm;
8667 if (Subtarget->hasDenormModeInst()) {
8668 const SDValue DisableDenormValue =
8669 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT0, DAG, SL, Subtarget);
8670
8671 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8672 Fma4.getValue(1), DisableDenormValue,
8673 Fma4.getValue(2)).getNode();
8674 } else {
8675 const SDValue DisableDenormValue =
8676 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT0, SL, MVT::i32);
8677
8678 DisableDenorm = DAG.getMachineNode(
8679 AMDGPU::S_SETREG_B32, SL, MVT::Other,
8680 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8681 }
8682
8683 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8684 SDValue(DisableDenorm, 0), DAG.getRoot());
8685 DAG.setRoot(OutputChain);
8686 }
8687
8688 SDValue Scale = NumeratorScaled.getValue(1);
8689 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8690 {Fma4, Fma1, Fma3, Scale}, Flags);
8691
8692 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8693}
8694
8695SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8696 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8697 return FastLowered;
8698
8699 SDLoc SL(Op);
8700 SDValue X = Op.getOperand(0);
8701 SDValue Y = Op.getOperand(1);
8702
8703 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8704
8705 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8706
8707 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8708
8709 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8710
8711 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8712
8713 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8714
8715 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8716
8717 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8718
8719 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8720
8721 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8722 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8723
8724 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8725 NegDivScale0, Mul, DivScale1);
8726
8727 SDValue Scale;
8728
8729 if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8730 // Workaround a hardware bug on SI where the condition output from div_scale
8731 // is not usable.
8732
8733 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8734
8735 // Figure out if the scale to use for div_fmas.
8736 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8737 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8738 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8739 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8740
8741 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8742 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8743
8744 SDValue Scale0Hi
8745 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8746 SDValue Scale1Hi
8747 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8748
8749 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8750 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8751 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8752 } else {
8753 Scale = DivScale1.getValue(1);
8754 }
8755
8756 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8757 Fma4, Fma3, Mul, Scale);
8758
8759 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8760}
8761
8762SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8763 EVT VT = Op.getValueType();
8764
8765 if (VT == MVT::f32)
8766 return LowerFDIV32(Op, DAG);
8767
8768 if (VT == MVT::f64)
8769 return LowerFDIV64(Op, DAG);
8770
8771 if (VT == MVT::f16)
8772 return LowerFDIV16(Op, DAG);
8773
8774 llvm_unreachable("Unexpected type for fdiv")::llvm::llvm_unreachable_internal("Unexpected type for fdiv",
"/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8774)
;
8775}
8776
8777SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8778 SDLoc DL(Op);
8779 StoreSDNode *Store = cast<StoreSDNode>(Op);
8780 EVT VT = Store->getMemoryVT();
8781
8782 if (VT == MVT::i1) {
8783 return DAG.getTruncStore(Store->getChain(), DL,
8784 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8785 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8786 }
8787
8788 assert(VT.isVector() &&(static_cast <bool> (VT.isVector() && Store->
getValue().getValueType().getScalarType() == MVT::i32) ? void
(0) : __assert_fail ("VT.isVector() && Store->getValue().getValueType().getScalarType() == MVT::i32"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8789, __extension__ __PRETTY_FUNCTION__))
8789 Store->getValue().getValueType().getScalarType() == MVT::i32)(static_cast <bool> (VT.isVector() && Store->
getValue().getValueType().getScalarType() == MVT::i32) ? void
(0) : __assert_fail ("VT.isVector() && Store->getValue().getValueType().getScalarType() == MVT::i32"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8789, __extension__ __PRETTY_FUNCTION__))
;
8790
8791 unsigned AS = Store->getAddressSpace();
8792 if (Subtarget->hasLDSMisalignedBug() &&
8793 AS == AMDGPUAS::FLAT_ADDRESS &&
8794 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8795 return SplitVectorStore(Op, DAG);
8796 }
8797
8798 MachineFunction &MF = DAG.getMachineFunction();
8799 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8800 // If there is a possibilty that flat instruction access scratch memory
8801 // then we need to use the same legalization rules we use for private.
8802 if (AS == AMDGPUAS::FLAT_ADDRESS &&
8803 !Subtarget->hasMultiDwordFlatScratchAddressing())
8804 AS = MFI->hasFlatScratchInit() ?
8805 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8806
8807 unsigned NumElements = VT.getVectorNumElements();
8808 if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8809 AS == AMDGPUAS::FLAT_ADDRESS) {
8810 if (NumElements > 4)
8811 return SplitVectorStore(Op, DAG);
8812 // v3 stores not supported on SI.
8813 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8814 return SplitVectorStore(Op, DAG);
8815
8816 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8817 VT, *Store->getMemOperand()))
8818 return expandUnalignedStore(Store, DAG);
8819
8820 return SDValue();
8821 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8822 switch (Subtarget->getMaxPrivateElementSize()) {
8823 case 4:
8824 return scalarizeVectorStore(Store, DAG);
8825 case 8:
8826 if (NumElements > 2)
8827 return SplitVectorStore(Op, DAG);
8828 return SDValue();
8829 case 16:
8830 if (NumElements > 4 ||
8831 (NumElements == 3 && !Subtarget->enableFlatScratch()))
8832 return SplitVectorStore(Op, DAG);
8833 return SDValue();
8834 default:
8835 llvm_unreachable("unsupported private_element_size")::llvm::llvm_unreachable_internal("unsupported private_element_size"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8835)
;
8836 }
8837 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8838 // Use ds_write_b128 or ds_write_b96 when possible.
8839 if (Subtarget->hasDS96AndDS128() &&
8840 ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8841 (VT.getStoreSize() == 12)) &&
8842 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8843 Store->getAlign()))
8844 return SDValue();
8845
8846 if (NumElements > 2)
8847 return SplitVectorStore(Op, DAG);
8848
8849 // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8850 // address is negative, then the instruction is incorrectly treated as
8851 // out-of-bounds even if base + offsets is in bounds. Split vectorized
8852 // stores here to avoid emitting ds_write2_b32. We may re-combine the
8853 // store later in the SILoadStoreOptimizer.
8854 if (!Subtarget->hasUsableDSOffset() &&
8855 NumElements == 2 && VT.getStoreSize() == 8 &&
8856 Store->getAlignment() < 8) {
8857 return SplitVectorStore(Op, DAG);
8858 }
8859
8860 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8861 VT, *Store->getMemOperand())) {
8862 if (VT.isVector())
8863 return SplitVectorStore(Op, DAG);
8864 return expandUnalignedStore(Store, DAG);
8865 }
8866
8867 return SDValue();
8868 } else {
8869 llvm_unreachable("unhandled address space")::llvm::llvm_unreachable_internal("unhandled address space", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8869)
;
8870 }
8871}
8872
8873SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8874 SDLoc DL(Op);
8875 EVT VT = Op.getValueType();
8876 SDValue Arg = Op.getOperand(0);
8877 SDValue TrigVal;
8878
8879 // Propagate fast-math flags so that the multiply we introduce can be folded
8880 // if Arg is already the result of a multiply by constant.
8881 auto Flags = Op->getFlags();
8882
8883 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8884
8885 if (Subtarget->hasTrigReducedRange()) {
8886 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8887 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8888 } else {
8889 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8890 }
8891
8892 switch (Op.getOpcode()) {
8893 case ISD::FCOS:
8894 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8895 case ISD::FSIN:
8896 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8897 default:
8898 llvm_unreachable("Wrong trig opcode")::llvm::llvm_unreachable_internal("Wrong trig opcode", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8898)
;
8899 }
8900}
8901
8902SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8903 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8904 assert(AtomicNode->isCompareAndSwap())(static_cast <bool> (AtomicNode->isCompareAndSwap())
? void (0) : __assert_fail ("AtomicNode->isCompareAndSwap()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8904, __extension__ __PRETTY_FUNCTION__))
;
8905 unsigned AS = AtomicNode->getAddressSpace();
8906
8907 // No custom lowering required for local address space
8908 if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8909 return Op;
8910
8911 // Non-local address space requires custom lowering for atomic compare
8912 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8913 SDLoc DL(Op);
8914 SDValue ChainIn = Op.getOperand(0);
8915 SDValue Addr = Op.getOperand(1);
8916 SDValue Old = Op.getOperand(2);
8917 SDValue New = Op.getOperand(3);
8918 EVT VT = Op.getValueType();
8919 MVT SimpleVT = VT.getSimpleVT();
8920 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8921
8922 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8923 SDValue Ops[] = { ChainIn, Addr, NewOld };
8924
8925 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8926 Ops, VT, AtomicNode->getMemOperand());
8927}
8928
8929//===----------------------------------------------------------------------===//
8930// Custom DAG optimizations
8931//===----------------------------------------------------------------------===//
8932
8933SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8934 DAGCombinerInfo &DCI) const {
8935 EVT VT = N->getValueType(0);
8936 EVT ScalarVT = VT.getScalarType();
8937 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8938 return SDValue();
8939
8940 SelectionDAG &DAG = DCI.DAG;
8941 SDLoc DL(N);
8942
8943 SDValue Src = N->getOperand(0);
8944 EVT SrcVT = Src.getValueType();
8945
8946 // TODO: We could try to match extracting the higher bytes, which would be
8947 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8948 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8949 // about in practice.
8950 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8951 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8952 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8953 DCI.AddToWorklist(Cvt.getNode());
8954
8955 // For the f16 case, fold to a cast to f32 and then cast back to f16.
8956 if (ScalarVT != MVT::f32) {
8957 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8958 DAG.getTargetConstant(0, DL, MVT::i32));
8959 }
8960 return Cvt;
8961 }
8962 }
8963
8964 return SDValue();
8965}
8966
8967// (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8968
8969// This is a variant of
8970// (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8971//
8972// The normal DAG combiner will do this, but only if the add has one use since
8973// that would increase the number of instructions.
8974//
8975// This prevents us from seeing a constant offset that can be folded into a
8976// memory instruction's addressing mode. If we know the resulting add offset of
8977// a pointer can be folded into an addressing offset, we can replace the pointer
8978// operand with the add of new constant offset. This eliminates one of the uses,
8979// and may allow the remaining use to also be simplified.
8980//
8981SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8982 unsigned AddrSpace,
8983 EVT MemVT,
8984 DAGCombinerInfo &DCI) const {
8985 SDValue N0 = N->getOperand(0);
8986 SDValue N1 = N->getOperand(1);
8987
8988 // We only do this to handle cases where it's profitable when there are
8989 // multiple uses of the add, so defer to the standard combine.
8990 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8991 N0->hasOneUse())
8992 return SDValue();
8993
8994 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8995 if (!CN1)
8996 return SDValue();
8997
8998 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8999 if (!CAdd)
9000 return SDValue();
9001
9002 // If the resulting offset is too large, we can't fold it into the addressing
9003 // mode offset.
9004 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9005 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9006
9007 AddrMode AM;
9008 AM.HasBaseReg = true;
9009 AM.BaseOffs = Offset.getSExtValue();
9010 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9011 return SDValue();
9012
9013 SelectionDAG &DAG = DCI.DAG;
9014 SDLoc SL(N);
9015 EVT VT = N->getValueType(0);
9016
9017 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9018 SDValue COffset = DAG.getConstant(Offset, SL, VT);
9019
9020 SDNodeFlags Flags;
9021 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9022 (N0.getOpcode() == ISD::OR ||
9023 N0->getFlags().hasNoUnsignedWrap()));
9024
9025 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9026}
9027
9028/// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9029/// by the chain and intrinsic ID. Theoretically we would also need to check the
9030/// specific intrinsic, but they all place the pointer operand first.
9031static unsigned getBasePtrIndex(const MemSDNode *N) {
9032 switch (N->getOpcode()) {
9033 case ISD::STORE:
9034 case ISD::INTRINSIC_W_CHAIN:
9035 case ISD::INTRINSIC_VOID:
9036 return 2;
9037 default:
9038 return 1;
9039 }
9040}
9041
9042SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9043 DAGCombinerInfo &DCI) const {
9044 SelectionDAG &DAG = DCI.DAG;
9045 SDLoc SL(N);
9046
9047 unsigned PtrIdx = getBasePtrIndex(N);
9048 SDValue Ptr = N->getOperand(PtrIdx);
9049
9050 // TODO: We could also do this for multiplies.
9051 if (Ptr.getOpcode() == ISD::SHL) {
9052 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
9053 N->getMemoryVT(), DCI);
9054 if (NewPtr) {
9055 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9056
9057 NewOps[PtrIdx] = NewPtr;
9058 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9059 }
9060 }
9061
9062 return SDValue();
9063}
9064
9065static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9066 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9067 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9068 (Opc == ISD::XOR && Val == 0);
9069}
9070
9071// Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9072// will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9073// integer combine opportunities since most 64-bit operations are decomposed
9074// this way. TODO: We won't want this for SALU especially if it is an inline
9075// immediate.
9076SDValue SITargetLowering::splitBinaryBitConstantOp(
9077 DAGCombinerInfo &DCI,
9078 const SDLoc &SL,
9079 unsigned Opc, SDValue LHS,
9080 const ConstantSDNode *CRHS) const {
9081 uint64_t Val = CRHS->getZExtValue();
9082 uint32_t ValLo = Lo_32(Val);
9083 uint32_t ValHi = Hi_32(Val);
9084 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9085
9086 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9087 bitOpWithConstantIsReducible(Opc, ValHi)) ||
9088 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9089 // If we need to materialize a 64-bit immediate, it will be split up later
9090 // anyway. Avoid creating the harder to understand 64-bit immediate
9091 // materialization.
9092 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9093 }
9094
9095 return SDValue();
9096}
9097
9098// Returns true if argument is a boolean value which is not serialized into
9099// memory or argument and does not require v_cndmask_b32 to be deserialized.
9100static bool isBoolSGPR(SDValue V) {
9101 if (V.getValueType() != MVT::i1)
9102 return false;
9103 switch (V.getOpcode()) {
9104 default:
9105 break;
9106 case ISD::SETCC:
9107 case AMDGPUISD::FP_CLASS:
9108 return true;
9109 case ISD::AND:
9110 case ISD::OR:
9111 case ISD::XOR:
9112 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9113 }
9114 return false;
9115}
9116
9117// If a constant has all zeroes or all ones within each byte return it.
9118// Otherwise return 0.
9119static uint32_t getConstantPermuteMask(uint32_t C) {
9120 // 0xff for any zero byte in the mask
9121 uint32_t ZeroByteMask = 0;
9122 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9123 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9124 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9125 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9126 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9127 if ((NonZeroByteMask & C) != NonZeroByteMask)
9128 return 0; // Partial bytes selected.
9129 return C;
9130}
9131
9132// Check if a node selects whole bytes from its operand 0 starting at a byte
9133// boundary while masking the rest. Returns select mask as in the v_perm_b32
9134// or -1 if not succeeded.
9135// Note byte select encoding:
9136// value 0-3 selects corresponding source byte;
9137// value 0xc selects zero;
9138// value 0xff selects 0xff.
9139static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9140 assert(V.getValueSizeInBits() == 32)(static_cast <bool> (V.getValueSizeInBits() == 32) ? void
(0) : __assert_fail ("V.getValueSizeInBits() == 32", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 9140, __extension__ __PRETTY_FUNCTION__))
;
9141
9142 if (V.getNumOperands() != 2)
9143 return ~0;
9144
9145 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9146 if (!N1)
9147 return ~0;
9148
9149 uint32_t C = N1->getZExtValue();
9150
9151 switch (V.getOpcode()) {
9152 default:
9153 break;
9154 case ISD::AND:
9155 if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9156 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9157 }
9158 break;
9159
9160 case ISD::OR:
9161 if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9162 return (0x03020100 & ~ConstMask) | ConstMask;
9163 }
9164 break;
9165
9166 case ISD::SHL:
9167 if (C % 8)
9168 return ~0;
9169
9170 return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9171
9172 case ISD::SRL:
9173 if (C % 8)
9174 return ~0;
9175
9176 return uint32_t(0x0c0c0c0c03020100ull >> C);
9177 }
9178
9179 return ~0;
9180}
9181
9182SDValue SITargetLowering::performAndCombine(SDNode *N,
9183 DAGCombinerInfo &DCI) const {
9184 if (DCI.isBeforeLegalize())
9185 return SDValue();
9186
9187 SelectionDAG &DAG = DCI.DAG;
9188 EVT VT = N->getValueType(0);
9189 SDValue LHS = N->getOperand(0);
9190 SDValue RHS = N->getOperand(1);
9191
9192
9193 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9194 if (VT == MVT::i64 && CRHS) {
9195 if (SDValue Split
9196 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9197 return Split;
9198 }
9199
9200 if (CRHS && VT == MVT::i32) {
9201 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9202 // nb = number of trailing zeroes in mask
9203 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9204 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9205 uint64_t Mask = CRHS->getZExtValue();
9206 unsigned Bits = countPopulation(Mask);
9207 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9208 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9209 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9210 unsigned Shift = CShift->getZExtValue();
9211 unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9212 unsigned Offset = NB + Shift;
9213 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9214 SDLoc SL(N);
9215 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9216 LHS->getOperand(0),
9217 DAG.getConstant(Offset, SL, MVT::i32),
9218 DAG.getConstant(Bits, SL, MVT::i32));
9219 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9220 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9221 DAG.getValueType(NarrowVT));
9222 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9223 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9224 return Shl;
9225 }
9226 }
9227 }
9228
9229 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9230 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9231 isa<ConstantSDNode>(LHS.getOperand(2))) {
9232 uint32_t Sel = getConstantPermuteMask(Mask);
9233 if (!Sel)
9234 return SDValue();
9235
9236 // Select 0xc for all zero bytes
9237 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9238 SDLoc DL(N);
9239 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9240 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9241 }
9242 }
9243
9244 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9245 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9246 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9247 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9248 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9249
9250 SDValue X = LHS.getOperand(0);
9251 SDValue Y = RHS.getOperand(0);
9252 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9253 return SDValue();
9254
9255 if (LCC == ISD::SETO) {
9256 if (X != LHS.getOperand(1))
9257 return SDValue();
9258
9259 if (RCC == ISD::SETUNE) {
9260 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9261 if (!C1 || !C1->isInfinity() || C1->isNegative())
9262 return SDValue();
9263
9264 const uint32_t Mask = SIInstrFlags::N_NORMAL |
9265 SIInstrFlags::N_SUBNORMAL |
9266 SIInstrFlags::N_ZERO |
9267 SIInstrFlags::P_ZERO |
9268 SIInstrFlags::P_SUBNORMAL |
9269 SIInstrFlags::P_NORMAL;
9270
9271 static_assert(((~(SIInstrFlags::S_NAN |
9272 SIInstrFlags::Q_NAN |
9273 SIInstrFlags::N_INFINITY |
9274 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9275 "mask not equal");
9276
9277 SDLoc DL(N);
9278 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9279 X, DAG.getConstant(Mask, DL, MVT::i32));
9280 }
9281 }
9282 }
9283
9284 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9285 std::swap(LHS, RHS);
9286
9287 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9288 RHS.hasOneUse()) {
9289 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9290 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9291 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9292 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9293 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9294 (RHS.getOperand(0) == LHS.getOperand(0) &&
9295 LHS.getOperand(0) == LHS.getOperand(1))) {
9296 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9297 unsigned NewMask = LCC == ISD::SETO ?
9298 Mask->getZExtValue() & ~OrdMask :
9299 Mask->getZExtValue() & OrdMask;
9300
9301 SDLoc DL(N);
9302 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9303 DAG.getConstant(NewMask, DL, MVT::i32));
9304 }
9305 }
9306
9307 if (VT == MVT::i32 &&
9308 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9309 // and x, (sext cc from i1) => select cc, x, 0
9310 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9311 std::swap(LHS, RHS);
9312 if (isBoolSGPR(RHS.getOperand(0)))
9313 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9314 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9315 }
9316
9317 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9318 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9319 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9320 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9321 uint32_t LHSMask = getPermuteMask(DAG, LHS);
9322 uint32_t RHSMask = getPermuteMask(DAG, RHS);
9323 if (LHSMask != ~0u && RHSMask != ~0u) {
9324 // Canonicalize the expression in an attempt to have fewer unique masks
9325 // and therefore fewer registers used to hold the masks.
9326 if (LHSMask > RHSMask) {
9327 std::swap(LHSMask, RHSMask);
9328 std::swap(LHS, RHS);
9329 }
9330
9331 // Select 0xc for each lane used from source operand. Zero has 0xc mask
9332 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9333 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9334 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9335
9336 // Check of we need to combine values from two sources within a byte.
9337 if (!(LHSUsedLanes & RHSUsedLanes) &&
9338 // If we select high and lower word keep it for SDWA.
9339 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9340 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9341 // Each byte in each mask is either selector mask 0-3, or has higher
9342 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9343 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9344 // mask which is not 0xff wins. By anding both masks we have a correct
9345 // result except that 0x0c shall be corrected to give 0x0c only.
9346 uint32_t Mask = LHSMask & RHSMask;
9347 for (unsigned I = 0; I < 32; I += 8) {
9348 uint32_t ByteSel = 0xff << I;
9349 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9350 Mask &= (0x0c << I) & 0xffffffff;
9351 }
9352
9353 // Add 4 to each active LHS lane. It will not affect any existing 0xff
9354 // or 0x0c.
9355 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9356 SDLoc DL(N);
9357
9358 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9359 LHS.getOperand(0), RHS.getOperand(0),
9360 DAG.getConstant(Sel, DL, MVT::i32));
9361 }
9362 }
9363 }
9364
9365 return SDValue();
9366}
9367
9368SDValue SITargetLowering::performOrCombine(SDNode *N,
9369 DAGCombinerInfo &DCI) const {
9370 SelectionDAG &DAG = DCI.DAG;
9371 SDValue LHS = N->getOperand(0);
9372 SDValue RHS = N->getOperand(1);
9373
9374 EVT VT = N->getValueType(0);
9375 if (VT == MVT::i1) {
9376 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9377 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9378 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9379 SDValue Src = LHS.getOperand(0);
9380 if (Src != RHS.getOperand(0))
9381 return SDValue();
9382
9383 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9384 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9385 if (!CLHS || !CRHS)
9386 return SDValue();
9387
9388 // Only 10 bits are used.
9389 static const uint32_t MaxMask = 0x3ff;
9390
9391 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9392 SDLoc DL(N);
9393 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9394 Src, DAG.getConstant(NewMask, DL, MVT::i32));
9395 }
9396
9397 return SDValue();
9398 }
9399
9400 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9401 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9402 LHS.getOpcode() == AMDGPUISD::PERM &&
9403 isa<ConstantSDNode>(LHS.getOperand(2))) {
9404 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9405 if (!Sel)
9406 return SDValue();
9407
9408 Sel |= LHS.getConstantOperandVal(2);
9409 SDLoc DL(N);
9410 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9411 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9412 }
9413
9414 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9415 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9416 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9417 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9418 uint32_t LHSMask = getPermuteMask(DAG, LHS);
9419 uint32_t RHSMask = getPermuteMask(DAG, RHS);
9420 if (LHSMask != ~0u && RHSMask != ~0u) {
9421 // Canonicalize the expression in an attempt to have fewer unique masks
9422 // and therefore fewer registers used to hold the masks.
9423 if (LHSMask > RHSMask) {
9424 std::swap(LHSMask, RHSMask);
9425 std::swap(LHS, RHS);
9426 }
9427
9428 // Select 0xc for each lane used from source operand. Zero has 0xc mask
9429 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9430 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9431 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9432
9433 // Check of we need to combine values from two sources within a byte.
9434 if (!(LHSUsedLanes & RHSUsedLanes) &&
9435 // If we select high and lower word keep it for SDWA.
9436 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9437 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9438 // Kill zero bytes selected by other mask. Zero value is 0xc.
9439 LHSMask &= ~RHSUsedLanes;
9440 RHSMask &= ~LHSUsedLanes;
9441 // Add 4 to each active LHS lane
9442 LHSMask |= LHSUsedLanes & 0x04040404;
9443 // Combine masks
9444 uint32_t Sel = LHSMask | RHSMask;
9445 SDLoc DL(N);
9446
9447 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9448 LHS.getOperand(0), RHS.getOperand(0),
9449 DAG.getConstant(Sel, DL, MVT::i32));
9450 }
9451 }
9452 }
9453
9454 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9455 return SDValue();
9456
9457 // TODO: This could be a generic combine with a predicate for extracting the
9458 // high half of an integer being free.
9459
9460 // (or i64:x, (zero_extend i32:y)) ->
9461 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9462 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9463 RHS.getOpcode() != ISD::ZERO_EXTEND)
9464 std::swap(LHS, RHS);
9465
9466 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9467 SDValue ExtSrc = RHS.getOperand(0);
9468 EVT SrcVT = ExtSrc.getValueType();
9469 if (SrcVT == MVT::i32) {
9470 SDLoc SL(N);
9471 SDValue LowLHS, HiBits;
9472 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9473 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9474
9475 DCI.AddToWorklist(LowOr.getNode());
9476 DCI.AddToWorklist(HiBits.getNode());
9477
9478 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9479 LowOr, HiBits);
9480 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9481 }
9482 }
9483
9484 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9485 if (CRHS) {
9486 if (SDValue Split
9487 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9488 return Split;
9489 }
9490
9491 return SDValue();
9492}
9493
9494SDValue SITargetLowering::performXorCombine(SDNode *N,
9495 DAGCombinerInfo &DCI) const {
9496 EVT VT = N->getValueType(0);
9497 if (VT != MVT::i64)
9498 return SDValue();
9499
9500 SDValue LHS = N->getOperand(0);
9501 SDValue RHS = N->getOperand(1);
9502
9503 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9504 if (CRHS) {
9505 if (SDValue Split
9506 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9507 return Split;
9508 }
9509
9510 return SDValue();
9511}
9512
9513SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9514 DAGCombinerInfo &DCI) const {
9515 if (!Subtarget->has16BitInsts() ||
9516 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9517 return SDValue();
9518
9519 EVT VT = N->getValueType(0);
9520 if (VT != MVT::i32)
9521 return SDValue();
9522
9523 SDValue Src = N->getOperand(0);
9524 if (Src.getValueType() != MVT::i16)
9525 return SDValue();
9526
9527 return SDValue();
9528}
9529
9530SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9531 DAGCombinerInfo &DCI)
9532 const {
9533 SDValue Src = N->getOperand(0);
9534 auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9535
9536 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9537 VTSign->getVT() == MVT::i8) ||
9538 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9539 VTSign->getVT() == MVT::i16)) &&
9540 Src.hasOneUse()) {
9541 auto *M = cast<MemSDNode>(Src);
9542 SDValue Ops[] = {
9543 Src.getOperand(0), // Chain
9544 Src.getOperand(1), // rsrc
9545 Src.getOperand(2), // vindex
9546 Src.getOperand(3), // voffset
9547 Src.getOperand(4), // soffset
9548 Src.getOperand(5), // offset
9549 Src.getOperand(6),
9550 Src.getOperand(7)
9551 };
9552 // replace with BUFFER_LOAD_BYTE/SHORT
9553 SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9554 Src.getOperand(0).getValueType());
9555 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9556 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9557 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9558 ResList,
9559 Ops, M->getMemoryVT(),
9560 M->getMemOperand());
9561 return DCI.DAG.getMergeValues({BufferLoadSignExt,
9562 BufferLoadSignExt.getValue(1)}, SDLoc(N));
9563 }
9564 return SDValue();
9565}
9566
9567SDValue SITargetLowering::performClassCombine(SDNode *N,
9568 DAGCombinerInfo &DCI) const {
9569 SelectionDAG &DAG = DCI.DAG;
9570 SDValue Mask = N->getOperand(1);
9571
9572 // fp_class x, 0 -> false
9573 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9574 if (CMask->isZero())
9575 return DAG.getConstant(0, SDLoc(N), MVT::i1);
9576 }
9577
9578 if (N->getOperand(0).isUndef())
9579 return DAG.getUNDEF(MVT::i1);
9580
9581 return SDValue();
9582}
9583
9584SDValue SITargetLowering::performRcpCombine(SDNode *N,
9585 DAGCombinerInfo &DCI) const {
9586 EVT VT = N->getValueType(0);
9587 SDValue N0 = N->getOperand(0);
9588
9589 if (N0.isUndef())
9590 return N0;
9591
9592 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9593 N0.getOpcode() == ISD::SINT_TO_FP)) {
9594 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9595 N->getFlags());
9596 }
9597
9598 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9599 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9600 N0.getOperand(0), N->getFlags());
9601 }
9602
9603 return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9604}
9605
9606bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9607 unsigned MaxDepth) const {
9608 unsigned Opcode = Op.getOpcode();
9609 if (Opcode == ISD::FCANONICALIZE)
9610 return true;
9611
9612 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9613 auto F = CFP->getValueAPF();
9614 if (F.isNaN() && F.isSignaling())
9615 return false;
9616 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9617 }
9618
9619 // If source is a result of another standard FP operation it is already in
9620 // canonical form.
9621 if (MaxDepth == 0)
9622 return false;
9623
9624 switch (Opcode) {
9625 // These will flush denorms if required.
9626 case ISD::FADD:
9627 case ISD::FSUB:
9628 case ISD::FMUL:
9629 case ISD::FCEIL:
9630 case ISD::FFLOOR:
9631 case ISD::FMA:
9632 case ISD::FMAD:
9633 case ISD::FSQRT:
9634 case ISD::FDIV:
9635 case ISD::FREM:
9636 case ISD::FP_ROUND:
9637 case ISD::FP_EXTEND:
9638 case AMDGPUISD::FMUL_LEGACY:
9639 case AMDGPUISD::FMAD_FTZ:
9640 case AMDGPUISD::RCP:
9641 case AMDGPUISD::RSQ:
9642 case AMDGPUISD::RSQ_CLAMP:
9643 case AMDGPUISD::RCP_LEGACY:
9644 case AMDGPUISD::RCP_IFLAG:
9645 case AMDGPUISD::DIV_SCALE:
9646 case AMDGPUISD::DIV_FMAS:
9647 case AMDGPUISD::DIV_FIXUP:
9648 case AMDGPUISD::FRACT:
9649 case AMDGPUISD::LDEXP:
9650 case AMDGPUISD::CVT_PKRTZ_F16_F32:
9651 case AMDGPUISD::CVT_F32_UBYTE0:
9652 case AMDGPUISD::CVT_F32_UBYTE1:
9653 case AMDGPUISD::CVT_F32_UBYTE2:
9654 case AMDGPUISD::CVT_F32_UBYTE3:
9655 return true;
9656
9657 // It can/will be lowered or combined as a bit operation.
9658 // Need to check their input recursively to handle.
9659 case ISD::FNEG:
9660 case ISD::FABS:
9661 case ISD::FCOPYSIGN:
9662 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9663
9664 case ISD::FSIN:
9665 case ISD::FCOS:
9666 case ISD::FSINCOS:
9667 return Op.getValueType().getScalarType() != MVT::f16;
9668
9669 case ISD::FMINNUM:
9670 case ISD::FMAXNUM:
9671 case ISD::FMINNUM_IEEE:
9672 case ISD::FMAXNUM_IEEE:
9673 case AMDGPUISD::CLAMP:
9674 case AMDGPUISD::FMED3:
9675 case AMDGPUISD::FMAX3:
9676 case AMDGPUISD::FMIN3: {
9677 // FIXME: Shouldn't treat the generic operations different based these.
9678 // However, we aren't really required to flush the result from
9679 // minnum/maxnum..
9680
9681 // snans will be quieted, so we only need to worry about denormals.
9682 if (Subtarget->supportsMinMaxDenormModes() ||
9683 denormalsEnabledForType(DAG, Op.getValueType()))
9684 return true;
9685
9686 // Flushing may be required.
9687 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9688 // targets need to check their input recursively.
9689
9690 // FIXME: Does this apply with clamp? It's implemented with max.
9691 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9692 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9693 return false;
9694 }
9695
9696 return true;
9697 }
9698 case ISD::SELECT: {
9699 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9700 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9701 }
9702 case ISD::BUILD_VECTOR: {
9703 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9704 SDValue SrcOp = Op.getOperand(i);
9705 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9706 return false;
9707 }
9708
9709 return true;
9710 }
9711 case ISD::EXTRACT_VECTOR_ELT:
9712 case ISD::EXTRACT_SUBVECTOR: {
9713 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9714 }
9715 case ISD::INSERT_VECTOR_ELT: {
9716 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9717 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9718 }
9719 case ISD::UNDEF:
9720 // Could be anything.
9721 return false;
9722
9723 case ISD::BITCAST:
9724 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9725 case ISD::TRUNCATE: {
9726 // Hack round the mess we make when legalizing extract_vector_elt
9727 if (Op.getValueType() == MVT::i16) {
9728 SDValue TruncSrc = Op.getOperand(0);
9729 if (TruncSrc.getValueType() == MVT::i32 &&
9730 TruncSrc.getOpcode() == ISD::BITCAST &&
9731 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9732 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9733 }
9734 }
9735 return false;
9736 }
9737 case ISD::INTRINSIC_WO_CHAIN: {
9738 unsigned IntrinsicID
9739 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9740 // TODO: Handle more intrinsics
9741 switch (IntrinsicID) {
9742 case Intrinsic::amdgcn_cvt_pkrtz:
9743 case Intrinsic::amdgcn_cubeid:
9744 case Intrinsic::amdgcn_frexp_mant:
9745 case Intrinsic::amdgcn_fdot2:
9746 case Intrinsic::amdgcn_rcp:
9747 case Intrinsic::amdgcn_rsq:
9748 case Intrinsic::amdgcn_rsq_clamp:
9749 case Intrinsic::amdgcn_rcp_legacy:
9750 case Intrinsic::amdgcn_rsq_legacy:
9751 case Intrinsic::amdgcn_trig_preop:
9752 return true;
9753 default:
9754 break;
9755 }
9756
9757 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9758 }
9759 default:
9760 return denormalsEnabledForType(DAG, Op.getValueType()) &&
9761 DAG.isKnownNeverSNaN(Op);
9762 }
9763
9764 llvm_unreachable("invalid operation")::llvm::llvm_unreachable_internal("invalid operation", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 9764)
;
9765}
9766
9767bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9768 unsigned MaxDepth) const {
9769 MachineRegisterInfo &MRI = MF.getRegInfo();
9770 MachineInstr *MI = MRI.getVRegDef(Reg);
9771 unsigned Opcode = MI->getOpcode();
9772
9773 if (Opcode == AMDGPU::G_FCANONICALIZE)
9774 return true;
9775
9776 if (Opcode == AMDGPU::G_FCONSTANT) {
9777 auto F = MI->getOperand(1).getFPImm()->getValueAPF();
9778 if (F.isNaN() && F.isSignaling())
9779 return false;
9780 return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF);
9781 }
9782
9783 if (MaxDepth == 0)
9784 return false;
9785
9786 switch (Opcode) {
9787 case AMDGPU::G_FMINNUM_IEEE:
9788 case AMDGPU::G_FMAXNUM_IEEE: {
9789 if (Subtarget->supportsMinMaxDenormModes() ||
9790 denormalsEnabledForType(MRI.getType(Reg), MF))
9791 return true;
9792 for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) {
9793 if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1))
9794 return false;
9795 }
9796 return true;
9797 }
9798 default:
9799 return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9800 isKnownNeverSNaN(Reg, MRI);
9801 }
9802
9803 llvm_unreachable("invalid operation")::llvm::llvm_unreachable_internal("invalid operation", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 9803)
;
9804}
9805
9806// Constant fold canonicalize.
9807SDValue SITargetLowering::getCanonicalConstantFP(
9808 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9809 // Flush denormals to 0 if not enabled.
9810 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9811 return DAG.getConstantFP(0.0, SL, VT);
9812
9813 if (C.isNaN()) {
9814 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9815 if (C.isSignaling()) {
9816 // Quiet a signaling NaN.
9817 // FIXME: Is this supposed to preserve payload bits?
9818 return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9819 }
9820
9821 // Make sure it is the canonical NaN bitpattern.
9822 //
9823 // TODO: Can we use -1 as the canonical NaN value since it's an inline
9824 // immediate?
9825 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9826 return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9827 }
9828
9829 // Already canonical.
9830 return DAG.getConstantFP(C, SL, VT);
9831}
9832
9833static bool vectorEltWillFoldAway(SDValue Op) {
9834 return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9835}
9836
9837SDValue SITargetLowering::performFCanonicalizeCombine(
9838 SDNode *N,
9839 DAGCombinerInfo &DCI) const {
9840 SelectionDAG &DAG = DCI.DAG;
9841 SDValue N0 = N->getOperand(0);
9842 EVT VT = N->getValueType(0);
9843
9844 // fcanonicalize undef -> qnan
9845 if (N0.isUndef()) {
9846 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9847 return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9848 }
9849
9850 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9851 EVT VT = N->getValueType(0);
9852 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9853 }
9854
9855 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9856 // (fcanonicalize k)
9857 //
9858 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9859
9860 // TODO: This could be better with wider vectors that will be split to v2f16,
9861 // and to consider uses since there aren't that many packed operations.
9862 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9863 isTypeLegal(MVT::v2f16)) {
9864 SDLoc SL(N);
9865 SDValue NewElts[2];
9866 SDValue Lo = N0.getOperand(0);
9867 SDValue Hi = N0.getOperand(1);
9868 EVT EltVT = Lo.getValueType();
9869
9870 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9871 for (unsigned I = 0; I != 2; ++I) {
9872 SDValue Op = N0.getOperand(I);
9873 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9874 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9875 CFP->getValueAPF());
9876 } else if (Op.isUndef()) {
9877 // Handled below based on what the other operand is.
9878 NewElts[I] = Op;
9879 } else {
9880 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9881 }
9882 }
9883
9884 // If one half is undef, and one is constant, perfer a splat vector rather
9885 // than the normal qNaN. If it's a register, prefer 0.0 since that's
9886 // cheaper to use and may be free with a packed operation.
9887 if (NewElts[0].isUndef()) {
9888 if (isa<ConstantFPSDNode>(NewElts[1]))
9889 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9890 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9891 }
9892
9893 if (NewElts[1].isUndef()) {
9894 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9895 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9896 }
9897
9898 return DAG.getBuildVector(VT, SL, NewElts);
9899 }
9900 }
9901
9902 unsigned SrcOpc = N0.getOpcode();
9903
9904 // If it's free to do so, push canonicalizes further up the source, which may
9905 // find a canonical source.
9906 //
9907 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9908 // sNaNs.
9909 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9910 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9911 if (CRHS && N0.hasOneUse()) {
9912 SDLoc SL(N);
9913 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9914 N0.getOperand(0));
9915 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9916 DCI.AddToWorklist(Canon0.getNode());
9917
9918 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9919 }
9920 }
9921
9922 return isCanonicalized(DAG, N0) ? N0 : SDValue();
9923}
9924
9925static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9926 switch (Opc) {
9927 case ISD::FMAXNUM:
9928 case ISD::FMAXNUM_IEEE:
9929 return AMDGPUISD::FMAX3;
9930 case ISD::SMAX:
9931 return AMDGPUISD::SMAX3;
9932 case ISD::UMAX:
9933 return AMDGPUISD::UMAX3;
9934 case ISD::FMINNUM:
9935 case ISD::FMINNUM_IEEE:
9936 return AMDGPUISD::FMIN3;
9937 case ISD::SMIN:
9938 return AMDGPUISD::SMIN3;
9939 case ISD::UMIN:
9940 return AMDGPUISD::UMIN3;
9941 default:
9942 llvm_unreachable("Not a min/max opcode")::llvm::llvm_unreachable_internal("Not a min/max opcode", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 9942)
;
9943 }
9944}
9945
9946SDValue SITargetLowering::performIntMed3ImmCombine(
9947 SelectionDAG &DAG, const SDLoc &SL,
9948 SDValue Op0, SDValue Op1, bool Signed) const {
9949 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9950 if (!K1)
9951 return SDValue();
9952
9953 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9954 if (!K0)
9955 return SDValue();
9956
9957 if (Signed) {
9958 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9959 return SDValue();
9960 } else {
9961 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9962 return SDValue();
9963 }
9964
9965 EVT VT = K0->getValueType(0);
9966 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9967 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9968 return DAG.getNode(Med3Opc, SL, VT,
9969 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9970 }
9971
9972 // If there isn't a 16-bit med3 operation, convert to 32-bit.
9973 if (VT == MVT::i16) {
9974 MVT NVT = MVT::i32;
9975 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9976
9977 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9978 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9979 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9980
9981 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9982 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9983 }
9984
9985 return SDValue();
9986}
9987
9988static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9989 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9990 return C;
9991
9992 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9993 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9994 return C;
9995 }
9996
9997 return nullptr;
9998}
9999
10000SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10001 const SDLoc &SL,
10002 SDValue Op0,
10003 SDValue Op1) const {
10004 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10005 if (!K1)
10006 return SDValue();
10007
10008 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10009 if (!K0)
10010 return SDValue();
10011
10012 // Ordered >= (although NaN inputs should have folded away by now).
10013 if (K0->getValueAPF() > K1->getValueAPF())
10014 return SDValue();
10015
10016 const MachineFunction &MF = DAG.getMachineFunction();
10017 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10018
10019 // TODO: Check IEEE bit enabled?
10020 EVT VT = Op0.getValueType();
10021 if (Info->getMode().DX10Clamp) {
10022 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10023 // hardware fmed3 behavior converting to a min.
10024 // FIXME: Should this be allowing -0.0?
10025 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10026 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10027 }
10028
10029 // med3 for f16 is only available on gfx9+, and not available for v2f16.
10030 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10031 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10032 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10033 // then give the other result, which is different from med3 with a NaN
10034 // input.
10035 SDValue Var = Op0.getOperand(0);
10036 if (!DAG.isKnownNeverSNaN(Var))
10037 return SDValue();
10038
10039 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10040
10041 if ((!K0->hasOneUse() ||
10042 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10043 (!K1->hasOneUse() ||
10044 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10045 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10046 Var, SDValue(K0, 0), SDValue(K1, 0));
10047 }
10048 }
10049
10050 return SDValue();
10051}
10052
10053SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10054 DAGCombinerInfo &DCI) const {
10055 SelectionDAG &DAG = DCI.DAG;
10056
10057 EVT VT = N->getValueType(0);
10058 unsigned Opc = N->getOpcode();
10059 SDValue Op0 = N->getOperand(0);
10060 SDValue Op1 = N->getOperand(1);
10061
10062 // Only do this if the inner op has one use since this will just increases
10063 // register pressure for no benefit.
10064
10065 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10066 !VT.isVector() &&
10067 (VT == MVT::i32 || VT == MVT::f32 ||
10068 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10069 // max(max(a, b), c) -> max3(a, b, c)
10070 // min(min(a, b), c) -> min3(a, b, c)
10071 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10072 SDLoc DL(N);
10073 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10074 DL,
10075 N->getValueType(0),
10076 Op0.getOperand(0),
10077 Op0.getOperand(1),
10078 Op1);
10079 }
10080
10081 // Try commuted.
10082 // max(a, max(b, c)) -> max3(a, b, c)
10083 // min(a, min(b, c)) -> min3(a, b, c)
10084 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10085 SDLoc DL(N);
10086 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10087 DL,
10088 N->getValueType(0),
10089 Op0,
10090 Op1.getOperand(0),
10091 Op1.getOperand(1));
10092 }
10093 }
10094
10095 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10096 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10097 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10098 return Med3;
10099 }
10100
10101 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10102 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10103 return Med3;
10104 }
10105
10106 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10107 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10108 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10109 (Opc == AMDGPUISD::FMIN_LEGACY &&
10110 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10111 (VT == MVT::f32 || VT == MVT::f64 ||
10112 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10113 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10114 Op0.hasOneUse()) {
10115 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10116 return Res;
10117 }
10118
10119 return SDValue();
10120}
10121
10122static bool isClampZeroToOne(SDValue A, SDValue B) {
10123 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10124 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10125 // FIXME: Should this be allowing -0.0?
10126 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10127 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10128 }
10129 }
10130
10131 return false;
10132}
10133
10134// FIXME: Should only worry about snans for version with chain.
10135SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10136 DAGCombinerInfo &DCI) const {
10137 EVT VT = N->getValueType(0);
10138 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10139 // NaNs. With a NaN input, the order of the operands may change the result.
10140
10141 SelectionDAG &DAG = DCI.DAG;
10142 SDLoc SL(N);
10143
10144 SDValue Src0 = N->getOperand(0);
10145 SDValue Src1 = N->getOperand(1);
10146 SDValue Src2 = N->getOperand(2);
10147
10148 if (isClampZeroToOne(Src0, Src1)) {
10149 // const_a, const_b, x -> clamp is safe in all cases including signaling
10150 // nans.
10151 // FIXME: Should this be allowing -0.0?
10152 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10153 }
10154
10155 const MachineFunction &MF = DAG.getMachineFunction();
10156 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10157
10158 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10159 // handling no dx10-clamp?
10160 if (Info->getMode().DX10Clamp) {
10161 // If NaNs is clamped to 0, we are free to reorder the inputs.
10162
10163 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10164 std::swap(Src0, Src1);
10165
10166 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10167 std::swap(Src1, Src2);
10168
10169 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10170 std::swap(Src0, Src1);
10171
10172 if (isClampZeroToOne(Src1, Src2))
10173 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10174 }
10175
10176 return SDValue();
10177}
10178
10179SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10180 DAGCombinerInfo &DCI) const {
10181 SDValue Src0 = N->getOperand(0);
10182 SDValue Src1 = N->getOperand(1);
10183 if (Src0.isUndef() && Src1.isUndef())
10184 return DCI.DAG.getUNDEF(N->getValueType(0));
10185 return SDValue();
10186}
10187
10188// Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10189// expanded into a set of cmp/select instructions.
10190bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10191 unsigned NumElem,
10192 bool IsDivergentIdx) {
10193 if (UseDivergentRegisterIndexing)
10194 return false;
10195
10196 unsigned VecSize = EltSize * NumElem;
10197
10198 // Sub-dword vectors of size 2 dword or less have better implementation.
10199 if (VecSize <= 64 && EltSize < 32)
10200 return false;
10201
10202 // Always expand the rest of sub-dword instructions, otherwise it will be
10203 // lowered via memory.
10204 if (EltSize < 32)
10205 return true;
10206
10207 // Always do this if var-idx is divergent, otherwise it will become a loop.
10208 if (IsDivergentIdx)
10209 return true;
10210
10211 // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10212 unsigned NumInsts = NumElem /* Number of compares */ +
10213 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10214 return NumInsts <= 16;
10215}
10216
10217static bool shouldExpandVectorDynExt(SDNode *N) {
10218 SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10219 if (isa<ConstantSDNode>(Idx))
10220 return false;
10221
10222 SDValue Vec = N->getOperand(0);
10223 EVT VecVT = Vec.getValueType();
10224 EVT EltVT = VecVT.getVectorElementType();
10225 unsigned EltSize = EltVT.getSizeInBits();
10226 unsigned NumElem = VecVT.getVectorNumElements();
10227
10228 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10229 Idx->isDivergent());
10230}
10231
10232SDValue SITargetLowering::performExtractVectorEltCombine(
10233 SDNode *N, DAGCombinerInfo &DCI) const {
10234 SDValue Vec = N->getOperand(0);
10235 SelectionDAG &DAG = DCI.DAG;
10236
10237 EVT VecVT = Vec.getValueType();
10238 EVT EltVT = VecVT.getVectorElementType();
10239
10240 if ((Vec.getOpcode() == ISD::FNEG ||
10241 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10242 SDLoc SL(N);
10243 EVT EltVT = N->getValueType(0);
10244 SDValue Idx = N->getOperand(1);
10245 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10246 Vec.getOperand(0), Idx);
10247 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10248 }
10249
10250 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10251 // =>
10252 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10253 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10254 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10255 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10256 SDLoc SL(N);
10257 EVT EltVT = N->getValueType(0);
10258 SDValue Idx = N->getOperand(1);
10259 unsigned Opc = Vec.getOpcode();
10260
10261 switch(Opc) {
10262 default:
10263 break;
10264 // TODO: Support other binary operations.
10265 case ISD::FADD:
10266 case ISD::FSUB:
10267 case ISD::FMUL:
10268 case ISD::ADD:
10269 case ISD::UMIN:
10270 case ISD::UMAX:
10271 case ISD::SMIN:
10272 case ISD::SMAX:
10273 case ISD::FMAXNUM:
10274 case ISD::FMINNUM:
10275 case ISD::FMAXNUM_IEEE:
10276 case ISD::FMINNUM_IEEE: {
10277 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10278 Vec.getOperand(0), Idx);
10279 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10280 Vec.getOperand(1), Idx);
10281
10282 DCI.AddToWorklist(Elt0.getNode());
10283 DCI.AddToWorklist(Elt1.getNode());
10284 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10285 }
10286 }
10287 }
10288
10289 unsigned VecSize = VecVT.getSizeInBits();
10290 unsigned EltSize = EltVT.getSizeInBits();
10291
10292 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10293 if (::shouldExpandVectorDynExt(N)) {
10294 SDLoc SL(N);
10295 SDValue Idx = N->getOperand(1);
10296 SDValue V;
10297 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10298 SDValue IC = DAG.getVectorIdxConstant(I, SL);
10299 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10300 if (I == 0)
10301 V = Elt;
10302 else
10303 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10304 }
10305 return V;
10306 }
10307
10308 if (!DCI.isBeforeLegalize())
10309 return SDValue();
10310
10311 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10312 // elements. This exposes more load reduction opportunities by replacing
10313 // multiple small extract_vector_elements with a single 32-bit extract.
10314 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10315 if (isa<MemSDNode>(Vec) &&
10316 EltSize <= 16 &&
10317 EltVT.isByteSized() &&
10318 VecSize > 32 &&
10319 VecSize % 32 == 0 &&
10320 Idx) {
10321 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10322
10323 unsigned BitIndex = Idx->getZExtValue() * EltSize;
10324 unsigned EltIdx = BitIndex / 32;
10325 unsigned LeftoverBitIdx = BitIndex % 32;
10326 SDLoc SL(N);
10327
10328 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10329 DCI.AddToWorklist(Cast.getNode());
10330
10331 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10332 DAG.getConstant(EltIdx, SL, MVT::i32));
10333 DCI.AddToWorklist(Elt.getNode());
10334 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10335 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10336 DCI.AddToWorklist(Srl.getNode());
10337
10338 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10339 DCI.AddToWorklist(Trunc.getNode());
10340 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10341 }
10342
10343 return SDValue();
10344}
10345
10346SDValue
10347SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10348 DAGCombinerInfo &DCI) const {
10349 SDValue Vec = N->getOperand(0);
10350 SDValue Idx = N->getOperand(2);
10351 EVT VecVT = Vec.getValueType();
10352 EVT EltVT = VecVT.getVectorElementType();
10353
10354 // INSERT_VECTOR_ELT (<n x e>, var-idx)
10355 // => BUILD_VECTOR n x select (e, const-idx)
10356 if (!::shouldExpandVectorDynExt(N))
10357 return SDValue();
10358
10359 SelectionDAG &DAG = DCI.DAG;
10360 SDLoc SL(N);
10361 SDValue Ins = N->getOperand(1);
10362 EVT IdxVT = Idx.getValueType();
10363
10364 SmallVector<SDValue, 16> Ops;
10365 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10366 SDValue IC = DAG.getConstant(I, SL, IdxVT);
10367 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10368 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10369 Ops.push_back(V);
10370 }
10371
10372 return DAG.getBuildVector(VecVT, SL, Ops);
10373}
10374
10375unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10376 const SDNode *N0,
10377 const SDNode *N1) const {
10378 EVT VT = N0->getValueType(0);
10379
10380 // Only do this if we are not trying to support denormals. v_mad_f32 does not
10381 // support denormals ever.
10382 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10383 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10384 getSubtarget()->hasMadF16())) &&
10385 isOperationLegal(ISD::FMAD, VT))
10386 return ISD::FMAD;
10387
10388 const TargetOptions &Options = DAG.getTarget().Options;
10389 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10390 (N0->getFlags().hasAllowContract() &&
10391 N1->getFlags().hasAllowContract())) &&
10392 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10393 return ISD::FMA;
10394 }
10395
10396 return 0;
10397}
10398
10399// For a reassociatable opcode perform:
10400// op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10401SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10402 SelectionDAG &DAG) const {
10403 EVT VT = N->getValueType(0);
10404 if (VT != MVT::i32 && VT != MVT::i64)
10405 return SDValue();
10406
10407 unsigned Opc = N->getOpcode();
10408 SDValue Op0 = N->getOperand(0);
10409 SDValue Op1 = N->getOperand(1);
10410
10411 if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10412 return SDValue();
10413
10414 if (Op0->isDivergent())
10415 std::swap(Op0, Op1);
10416
10417 if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10418 return SDValue();
10419
10420 SDValue Op2 = Op1.getOperand(1);
10421 Op1 = Op1.getOperand(0);
10422 if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10423 return SDValue();
10424
10425 if (Op1->isDivergent())
10426 std::swap(Op1, Op2);
10427
10428 // If either operand is constant this will conflict with
10429 // DAGCombiner::ReassociateOps().
10430 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10431 DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10432 return SDValue();
10433
10434 SDLoc SL(N);
10435 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10436 return DAG.getNode(Opc, SL, VT, Add1, Op2);
10437}
10438
10439static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10440 EVT VT,
10441 SDValue N0, SDValue N1, SDValue N2,
10442 bool Signed) {
10443 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10444 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10445 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10446 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10447}
10448
10449SDValue SITargetLowering::performAddCombine(SDNode *N,
10450 DAGCombinerInfo &DCI) const {
10451 SelectionDAG &DAG = DCI.DAG;
10452 EVT VT = N->getValueType(0);
10453 SDLoc SL(N);
10454 SDValue LHS = N->getOperand(0);
10455 SDValue RHS = N->getOperand(1);
10456
10457 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10458 && Subtarget->hasMad64_32() &&
10459 !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10460 VT.getScalarSizeInBits() <= 64) {
10461 if (LHS.getOpcode() != ISD::MUL)
10462 std::swap(LHS, RHS);
10463
10464 SDValue MulLHS = LHS.getOperand(0);
10465 SDValue MulRHS = LHS.getOperand(1);
10466 SDValue AddRHS = RHS;
10467
10468 // TODO: Maybe restrict if SGPR inputs.
10469 if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10470 numBitsUnsigned(MulRHS, DAG) <= 32) {
10471 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10472 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10473 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10474 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10475 }
10476
10477 if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10478 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10479 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10480 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10481 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10482 }
10483
10484 return SDValue();
10485 }
10486
10487 if (SDValue V = reassociateScalarOps(N, DAG)) {
10488 return V;
10489 }
10490
10491 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10492 return SDValue();
10493
10494 // add x, zext (setcc) => addcarry x, 0, setcc
10495 // add x, sext (setcc) => subcarry x, 0, setcc
10496 unsigned Opc = LHS.getOpcode();
10497 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10498 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10499 std::swap(RHS, LHS);
10500
10501 Opc = RHS.getOpcode();
10502 switch (Opc) {
10503 default: break;
10504 case ISD::ZERO_EXTEND:
10505 case ISD::SIGN_EXTEND:
10506 case ISD::ANY_EXTEND: {
10507 auto Cond = RHS.getOperand(0);
10508 // If this won't be a real VOPC output, we would still need to insert an
10509 // extra instruction anyway.
10510 if (!isBoolSGPR(Cond))
10511 break;
10512 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10513 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10514 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10515 return DAG.getNode(Opc, SL, VTList, Args);
10516 }
10517 case ISD::ADDCARRY: {
10518 // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10519 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10520 if (!C || C->getZExtValue() != 0) break;
10521 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10522 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10523 }
10524 }
10525 return SDValue();
10526}
10527
10528SDValue SITargetLowering::performSubCombine(SDNode *N,
10529 DAGCombinerInfo &DCI) const {
10530 SelectionDAG &DAG = DCI.DAG;
10531 EVT VT = N->getValueType(0);
10532
10533 if (VT != MVT::i32)
10534 return SDValue();
10535
10536 SDLoc SL(N);
10537 SDValue LHS = N->getOperand(0);
10538 SDValue RHS = N->getOperand(1);
10539
10540 // sub x, zext (setcc) => subcarry x, 0, setcc
10541 // sub x, sext (setcc) => addcarry x, 0, setcc
10542 unsigned Opc = RHS.getOpcode();
10543 switch (Opc) {
10544 default: break;
10545 case ISD::ZERO_EXTEND:
10546 case ISD::SIGN_EXTEND:
10547 case ISD::ANY_EXTEND: {
10548 auto Cond = RHS.getOperand(0);
10549 // If this won't be a real VOPC output, we would still need to insert an
10550 // extra instruction anyway.
10551 if (!isBoolSGPR(Cond))
10552 break;
10553 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10554 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10555 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10556 return DAG.getNode(Opc, SL, VTList, Args);
10557 }
10558 }
10559
10560 if (LHS.getOpcode() == ISD::SUBCARRY) {
10561 // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10562 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10563 if (!C || !C->isZero())
10564 return SDValue();
10565 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10566 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10567 }
10568 return SDValue();
10569}
10570
10571SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10572 DAGCombinerInfo &DCI) const {
10573
10574 if (N->getValueType(0) != MVT::i32)
10575 return SDValue();
10576
10577 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10578 if (!C || C->getZExtValue() != 0)
10579 return SDValue();
10580
10581 SelectionDAG &DAG = DCI.DAG;
10582 SDValue LHS = N->getOperand(0);
10583
10584 // addcarry (add x, y), 0, cc => addcarry x, y, cc
10585 // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10586 unsigned LHSOpc = LHS.getOpcode();
10587 unsigned Opc = N->getOpcode();
10588 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10589 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10590 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10591 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10592 }
10593 return SDValue();
10594}
10595
10596SDValue SITargetLowering::performFAddCombine(SDNode *N,
10597 DAGCombinerInfo &DCI) const {
10598 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10599 return SDValue();
10600
10601 SelectionDAG &DAG = DCI.DAG;
10602 EVT VT = N->getValueType(0);
10603
10604 SDLoc SL(N);
10605 SDValue LHS = N->getOperand(0);
10606 SDValue RHS = N->getOperand(1);
10607
10608 // These should really be instruction patterns, but writing patterns with
10609 // source modiifiers is a pain.
10610
10611 // fadd (fadd (a, a), b) -> mad 2.0, a, b
10612 if (LHS.getOpcode() == ISD::FADD) {
10613 SDValue A = LHS.getOperand(0);
10614 if (A == LHS.getOperand(1)) {
10615 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10616 if (FusedOp != 0) {
10617 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10618 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10619 }
10620 }
10621 }
10622
10623 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10624 if (RHS.getOpcode() == ISD::FADD) {
10625 SDValue A = RHS.getOperand(0);
10626 if (A == RHS.getOperand(1)) {
10627 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10628 if (FusedOp != 0) {
10629 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10630 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10631 }
10632 }
10633 }
10634
10635 return SDValue();
10636}
10637
10638SDValue SITargetLowering::performFSubCombine(SDNode *N,
10639 DAGCombinerInfo &DCI) const {
10640 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10641 return SDValue();
10642
10643 SelectionDAG &DAG = DCI.DAG;
10644 SDLoc SL(N);
10645 EVT VT = N->getValueType(0);
10646 assert(!VT.isVector())(static_cast <bool> (!VT.isVector()) ? void (0) : __assert_fail
("!VT.isVector()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 10646, __extension__ __PRETTY_FUNCTION__))
;
10647
10648 // Try to get the fneg to fold into the source modifier. This undoes generic
10649 // DAG combines and folds them into the mad.
10650 //
10651 // Only do this if we are not trying to support denormals. v_mad_f32 does
10652 // not support denormals ever.
10653 SDValue LHS = N->getOperand(0);
10654 SDValue RHS = N->getOperand(1);
10655 if (LHS.getOpcode() == ISD::FADD) {
10656 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10657 SDValue A = LHS.getOperand(0);
10658 if (A == LHS.getOperand(1)) {
10659 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10660 if (FusedOp != 0){
10661 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10662 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10663
10664 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10665 }
10666 }
10667 }
10668
10669 if (RHS.getOpcode() == ISD::FADD) {
10670 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10671
10672 SDValue A = RHS.getOperand(0);
10673 if (A == RHS.getOperand(1)) {
10674 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10675 if (FusedOp != 0){
10676 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10677 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10678 }
10679 }
10680 }
10681
10682 return SDValue();
10683}
10684
10685SDValue SITargetLowering::performFMACombine(SDNode *N,
10686 DAGCombinerInfo &DCI) const {
10687 SelectionDAG &DAG = DCI.DAG;
10688 EVT VT = N->getValueType(0);
10689 SDLoc SL(N);
10690
10691 if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10692 return SDValue();
10693
10694 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10695 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10696 SDValue Op1 = N->getOperand(0);
10697 SDValue Op2 = N->getOperand(1);
10698 SDValue FMA = N->getOperand(2);
10699
10700 if (FMA.getOpcode() != ISD::FMA ||
10701 Op1.getOpcode() != ISD::FP_EXTEND ||
10702 Op2.getOpcode() != ISD::FP_EXTEND)
10703 return SDValue();
10704
10705 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10706 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10707 // is sufficient to allow generaing fdot2.
10708 const TargetOptions &Options = DAG.getTarget().Options;
10709 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10710 (N->getFlags().hasAllowContract() &&
10711 FMA->getFlags().hasAllowContract())) {
10712 Op1 = Op1.getOperand(0);
10713 Op2 = Op2.getOperand(0);
10714 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10715 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10716 return SDValue();
10717
10718 SDValue Vec1 = Op1.getOperand(0);
10719 SDValue Idx1 = Op1.getOperand(1);
10720 SDValue Vec2 = Op2.getOperand(0);
10721
10722 SDValue FMAOp1 = FMA.getOperand(0);
10723 SDValue FMAOp2 = FMA.getOperand(1);
10724 SDValue FMAAcc = FMA.getOperand(2);
10725
10726 if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10727 FMAOp2.getOpcode() != ISD::FP_EXTEND)
10728 return SDValue();
10729
10730 FMAOp1 = FMAOp1.getOperand(0);
10731 FMAOp2 = FMAOp2.getOperand(0);
10732 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10733 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10734 return SDValue();
10735
10736 SDValue Vec3 = FMAOp1.getOperand(0);
10737 SDValue Vec4 = FMAOp2.getOperand(0);
10738 SDValue Idx2 = FMAOp1.getOperand(1);
10739
10740 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10741 // Idx1 and Idx2 cannot be the same.
10742 Idx1 == Idx2)
10743 return SDValue();
10744
10745 if (Vec1 == Vec2 || Vec3 == Vec4)
10746 return SDValue();
10747
10748 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10749 return SDValue();
10750
10751 if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10752 (Vec1 == Vec4 && Vec2 == Vec3)) {
10753 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10754 DAG.getTargetConstant(0, SL, MVT::i1));
10755 }
10756 }
10757 return SDValue();
10758}
10759
10760SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10761 DAGCombinerInfo &DCI) const {
10762 SelectionDAG &DAG = DCI.DAG;
10763 SDLoc SL(N);
10764
10765 SDValue LHS = N->getOperand(0);
10766 SDValue RHS = N->getOperand(1);
10767 EVT VT = LHS.getValueType();
10768 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10769
10770 auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10771 if (!CRHS) {
10772 CRHS = dyn_cast<ConstantSDNode>(LHS);
10773 if (CRHS) {
10774 std::swap(LHS, RHS);
10775 CC = getSetCCSwappedOperands(CC);
10776 }
10777 }
10778
10779 if (CRHS) {
10780 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10781 isBoolSGPR(LHS.getOperand(0))) {
10782 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10783 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10784 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
10785 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
10786 if ((CRHS->isAllOnes() &&
10787 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10788 (CRHS->isZero() &&
10789 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10790 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10791 DAG.getConstant(-1, SL, MVT::i1));
10792 if ((CRHS->isAllOnes() &&
10793 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10794 (CRHS->isZero() &&
10795 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10796 return LHS.getOperand(0);
10797 }
10798
10799 const APInt &CRHSVal = CRHS->getAPIntValue();
10800 if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10801 LHS.getOpcode() == ISD::SELECT &&
10802 isa<ConstantSDNode>(LHS.getOperand(1)) &&
10803 isa<ConstantSDNode>(LHS.getOperand(2)) &&
10804 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10805 isBoolSGPR(LHS.getOperand(0))) {
10806 // Given CT != FT:
10807 // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10808 // setcc (select cc, CT, CF), CF, ne => cc
10809 // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10810 // setcc (select cc, CT, CF), CT, eq => cc
10811 const APInt &CT = LHS.getConstantOperandAPInt(1);
10812 const APInt &CF = LHS.getConstantOperandAPInt(2);
10813
10814 if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10815 (CT == CRHSVal && CC == ISD::SETNE))
10816 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10817 DAG.getConstant(-1, SL, MVT::i1));
10818 if ((CF == CRHSVal && CC == ISD::SETNE) ||
10819 (CT == CRHSVal && CC == ISD::SETEQ))
10820 return LHS.getOperand(0);
10821 }
10822 }
10823
10824 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10825 VT != MVT::f16))
10826 return SDValue();
10827
10828 // Match isinf/isfinite pattern
10829 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10830 // (fcmp one (fabs x), inf) -> (fp_class x,
10831 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10832 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10833 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10834 if (!CRHS)
10835 return SDValue();
10836
10837 const APFloat &APF = CRHS->getValueAPF();
10838 if (APF.isInfinity() && !APF.isNegative()) {
10839 const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10840 SIInstrFlags::N_INFINITY;
10841 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10842 SIInstrFlags::P_ZERO |
10843 SIInstrFlags::N_NORMAL |
10844 SIInstrFlags::P_NORMAL |
10845 SIInstrFlags::N_SUBNORMAL |
10846 SIInstrFlags::P_SUBNORMAL;
10847 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10848 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10849 DAG.getConstant(Mask, SL, MVT::i32));
10850 }
10851 }
10852
10853 return SDValue();
10854}
10855
10856SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10857 DAGCombinerInfo &DCI) const {
10858 SelectionDAG &DAG = DCI.DAG;
10859 SDLoc SL(N);
10860 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10861
10862 SDValue Src = N->getOperand(0);
10863 SDValue Shift = N->getOperand(0);
10864
10865 // TODO: Extend type shouldn't matter (assuming legal types).
10866 if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10867 Shift = Shift.getOperand(0);
10868
10869 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10870 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x
10871 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10872 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10873 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10874 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
10875 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10876 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
10877 SDLoc(Shift.getOperand(0)), MVT::i32);
10878
10879 unsigned ShiftOffset = 8 * Offset;
10880 if (Shift.getOpcode() == ISD::SHL)
10881 ShiftOffset -= C->getZExtValue();
10882 else
10883 ShiftOffset += C->getZExtValue();
10884
10885 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10886 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10887 MVT::f32, Shifted);
10888 }
10889 }
10890 }
10891
10892 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10893 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10894 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10895 // We simplified Src. If this node is not dead, visit it again so it is
10896 // folded properly.
10897 if (N->getOpcode() != ISD::DELETED_NODE)
10898 DCI.AddToWorklist(N);
10899 return SDValue(N, 0);
10900 }
10901
10902 // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10903 if (SDValue DemandedSrc =
10904 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10905 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10906
10907 return SDValue();
10908}
10909
10910SDValue SITargetLowering::performClampCombine(SDNode *N,
10911 DAGCombinerInfo &DCI) const {
10912 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10913 if (!CSrc)
10914 return SDValue();
10915
10916 const MachineFunction &MF = DCI.DAG.getMachineFunction();
10917 const APFloat &F = CSrc->getValueAPF();
10918 APFloat Zero = APFloat::getZero(F.getSemantics());
10919 if (F < Zero ||
10920 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10921 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10922 }
10923
10924 APFloat One(F.getSemantics(), "1.0");
10925 if (F > One)
10926 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10927
10928 return SDValue(CSrc, 0);
10929}
10930
10931
10932SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10933 DAGCombinerInfo &DCI) const {
10934 if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10935 return SDValue();
10936 switch (N->getOpcode()) {
10937 case ISD::ADD:
10938 return performAddCombine(N, DCI);
10939 case ISD::SUB:
10940 return performSubCombine(N, DCI);
10941 case ISD::ADDCARRY:
10942 case ISD::SUBCARRY:
10943 return performAddCarrySubCarryCombine(N, DCI);
10944 case ISD::FADD:
10945 return performFAddCombine(N, DCI);
10946 case ISD::FSUB:
10947 return performFSubCombine(N, DCI);
10948 case ISD::SETCC:
10949 return performSetCCCombine(N, DCI);
10950 case ISD::FMAXNUM:
10951 case ISD::FMINNUM:
10952 case ISD::FMAXNUM_IEEE:
10953 case ISD::FMINNUM_IEEE:
10954 case ISD::SMAX:
10955 case ISD::SMIN:
10956 case ISD::UMAX:
10957 case ISD::UMIN:
10958 case AMDGPUISD::FMIN_LEGACY:
10959 case AMDGPUISD::FMAX_LEGACY:
10960 return performMinMaxCombine(N, DCI);
10961 case ISD::FMA:
10962 return performFMACombine(N, DCI);
10963 case ISD::AND:
10964 return performAndCombine(N, DCI);
10965 case ISD::OR:
10966 return performOrCombine(N, DCI);
10967 case ISD::XOR:
10968 return performXorCombine(N, DCI);
10969 case ISD::ZERO_EXTEND:
10970 return performZeroExtendCombine(N, DCI);
10971 case ISD::SIGN_EXTEND_INREG:
10972 return performSignExtendInRegCombine(N , DCI);
10973 case AMDGPUISD::FP_CLASS:
10974 return performClassCombine(N, DCI);
10975 case ISD::FCANONICALIZE:
10976 return performFCanonicalizeCombine(N, DCI);
10977 case AMDGPUISD::RCP:
10978 return performRcpCombine(N, DCI);
10979 case AMDGPUISD::FRACT:
10980 case AMDGPUISD::RSQ:
10981 case AMDGPUISD::RCP_LEGACY:
10982 case AMDGPUISD::RCP_IFLAG:
10983 case AMDGPUISD::RSQ_CLAMP:
10984 case AMDGPUISD::LDEXP: {
10985 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10986 SDValue Src = N->getOperand(0);
10987 if (Src.isUndef())
10988 return Src;
10989 break;
10990 }
10991 case ISD::SINT_TO_FP:
10992 case ISD::UINT_TO_FP:
10993 return performUCharToFloatCombine(N, DCI);
10994 case AMDGPUISD::CVT_F32_UBYTE0:
10995 case AMDGPUISD::CVT_F32_UBYTE1:
10996 case AMDGPUISD::CVT_F32_UBYTE2:
10997 case AMDGPUISD::CVT_F32_UBYTE3:
10998 return performCvtF32UByteNCombine(N, DCI);
10999 case AMDGPUISD::FMED3:
11000 return performFMed3Combine(N, DCI);
11001 case AMDGPUISD::CVT_PKRTZ_F16_F32:
11002 return performCvtPkRTZCombine(N, DCI);
11003 case AMDGPUISD::CLAMP:
11004 return performClampCombine(N, DCI);
11005 case ISD::SCALAR_TO_VECTOR: {
11006 SelectionDAG &DAG = DCI.DAG;
11007 EVT VT = N->getValueType(0);
11008
11009 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11010 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11011 SDLoc SL(N);
11012 SDValue Src = N->getOperand(0);
11013 EVT EltVT = Src.getValueType();
11014 if (EltVT == MVT::f16)
11015 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11016
11017 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11018 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11019 }
11020
11021 break;
11022 }
11023 case ISD::EXTRACT_VECTOR_ELT:
11024 return performExtractVectorEltCombine(N, DCI);
11025 case ISD::INSERT_VECTOR_ELT:
11026 return performInsertVectorEltCombine(N, DCI);
11027 case ISD::LOAD: {
11028 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11029 return Widended;
11030 LLVM_FALLTHROUGH[[gnu::fallthrough]];
11031 }
11032 default: {
11033 if (!DCI.isBeforeLegalize()) {
11034 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11035 return performMemSDNodeCombine(MemNode, DCI);
11036 }
11037
11038 break;
11039 }
11040 }
11041
11042 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11043}
11044
11045/// Helper function for adjustWritemask
11046static unsigned SubIdx2Lane(unsigned Idx) {
11047 switch (Idx) {
11048 default: return ~0u;
11049 case AMDGPU::sub0: return 0;
11050 case AMDGPU::sub1: return 1;
11051 case AMDGPU::sub2: return 2;
11052 case AMDGPU::sub3: return 3;
11053 case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11054 }
11055}
11056
11057/// Adjust the writemask of MIMG instructions
11058SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11059 SelectionDAG &DAG) const {
11060 unsigned Opcode = Node->getMachineOpcode();
11061
11062 // Subtract 1 because the vdata output is not a MachineSDNode operand.
11063 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11064 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
7
Assuming 'D16Idx' is < 0
11065 return Node; // not implemented for D16
11066
11067 SDNode *Users[5] = { nullptr };
8
Initializing to a null pointer value
11068 unsigned Lane = 0;
9
'Lane' initialized to 0
11069 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11070 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11071 unsigned NewDmask = 0;
11072 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11073 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11074 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
10
Assuming 'TFEIdx' is >= 0
11
Assuming the condition is true
11075 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
11076 unsigned TFCLane = 0;
11077 bool HasChain = Node->getNumValues() > 1;
12
Assuming the condition is false
11078
11079 if (OldDmask == 0) {
13
Assuming 'OldDmask' is not equal to 0
14
Taking false branch
11080 // These are folded out, but on the chance it happens don't assert.
11081 return Node;
11082 }
11083
11084 unsigned OldBitsSet = countPopulation(OldDmask);
11085 // Work out which is the TFE/LWE lane if that is enabled.
11086 if (UsesTFC
14.1
'UsesTFC' is true
) {
15
Taking true branch
11087 TFCLane = OldBitsSet;
11088 }
11089
11090 // Try to figure out the used register components
11091 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
16
Loop condition is false. Execution continues on line 11132
11092 I != E; ++I) {
11093
11094 // Don't look at users of the chain.
11095 if (I.getUse().getResNo() != 0)
11096 continue;
11097
11098 // Abort if we can't understand the usage
11099 if (!I->isMachineOpcode() ||
11100 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11101 return Node;
11102
11103 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11104 // Note that subregs are packed, i.e. Lane==0 is the first bit set
11105 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11106 // set, etc.
11107 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11108 if (Lane == ~0u)
11109 return Node;
11110
11111 // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11112 if (UsesTFC && Lane == TFCLane) {
11113 Users[Lane] = *I;
11114 } else {
11115 // Set which texture component corresponds to the lane.
11116 unsigned Comp;
11117 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11118 Comp = countTrailingZeros(Dmask);
11119 Dmask &= ~(1 << Comp);
11120 }
11121
11122 // Abort if we have more than one user per component.
11123 if (Users[Lane])
11124 return Node;
11125
11126 Users[Lane] = *I;
11127 NewDmask |= 1 << Comp;
11128 }
11129 }
11130
11131 // Don't allow 0 dmask, as hardware assumes one channel enabled.
11132 bool NoChannels = !NewDmask;
11133 if (NoChannels
16.1
'NoChannels' is true
) {
17
Taking true branch
11134 if (!UsesTFC
17.1
'UsesTFC' is true
) {
18
Taking false branch
11135 // No uses of the result and not using TFC. Then do nothing.
11136 return Node;
11137 }
11138 // If the original dmask has one channel - then nothing to do
11139 if (OldBitsSet == 1)
19
Assuming 'OldBitsSet' is not equal to 1
20
Taking false branch
11140 return Node;
11141 // Use an arbitrary dmask - required for the instruction to work
11142 NewDmask = 1;
11143 }
11144 // Abort if there's no change
11145 if (NewDmask == OldDmask)
21
Assuming 'NewDmask' is not equal to 'OldDmask'
22
Taking false branch
11146 return Node;
11147
11148 unsigned BitsSet = countPopulation(NewDmask);
11149
11150 // Check for TFE or LWE - increase the number of channels by one to account
11151 // for the extra return value
11152 // This will need adjustment for D16 if this is also included in
11153 // adjustWriteMask (this function) but at present D16 are excluded.
11154 unsigned NewChannels = BitsSet + UsesTFC;
11155
11156 int NewOpcode =
11157 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11158 assert(NewOpcode != -1 &&(static_cast <bool> (NewOpcode != -1 && NewOpcode
!= static_cast<int>(Node->getMachineOpcode()) &&
"failed to find equivalent MIMG op") ? void (0) : __assert_fail
("NewOpcode != -1 && NewOpcode != static_cast<int>(Node->getMachineOpcode()) && \"failed to find equivalent MIMG op\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11160, __extension__ __PRETTY_FUNCTION__))
23
Assuming the condition is true
24
Assuming the condition is true
25
'?' condition is true
11159 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&(static_cast <bool> (NewOpcode != -1 && NewOpcode
!= static_cast<int>(Node->getMachineOpcode()) &&
"failed to find equivalent MIMG op") ? void (0) : __assert_fail
("NewOpcode != -1 && NewOpcode != static_cast<int>(Node->getMachineOpcode()) && \"failed to find equivalent MIMG op\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11160, __extension__ __PRETTY_FUNCTION__))
11160 "failed to find equivalent MIMG op")(static_cast <bool> (NewOpcode != -1 && NewOpcode
!= static_cast<int>(Node->getMachineOpcode()) &&
"failed to find equivalent MIMG op") ? void (0) : __assert_fail
("NewOpcode != -1 && NewOpcode != static_cast<int>(Node->getMachineOpcode()) && \"failed to find equivalent MIMG op\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11160, __extension__ __PRETTY_FUNCTION__))
;
11161
11162 // Adjust the writemask in the node
11163 SmallVector<SDValue, 12> Ops;
11164 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11165 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11166 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11167
11168 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11169
11170 MVT ResultVT = NewChannels == 1 ?
26
Assuming 'NewChannels' is equal to 1
27
'?' condition is true
11171 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11172 NewChannels == 5 ? 8 : NewChannels);
11173 SDVTList NewVTList = HasChain
27.1
'HasChain' is false
?
28
'?' condition is false
11174 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11175
11176
11177 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11178 NewVTList, Ops);
11179
11180 if (HasChain
28.1
'HasChain' is false
) {
29
Taking false branch
11181 // Update chain.
11182 DAG.setNodeMemRefs(NewNode, Node->memoperands());
11183 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11184 }
11185
11186 if (NewChannels
29.1
'NewChannels' is equal to 1
== 1) {
30
Taking true branch
11187 assert(Node->hasNUsesOfValue(1, 0))(static_cast <bool> (Node->hasNUsesOfValue(1, 0)) ? void
(0) : __assert_fail ("Node->hasNUsesOfValue(1, 0)", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11187, __extension__ __PRETTY_FUNCTION__))
;
31
Assuming the condition is true
32
'?' condition is true
11188 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11189 SDLoc(Node), Users[Lane]->getValueType(0),
33
Called C++ object pointer is null
11190 SDValue(NewNode, 0));
11191 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11192 return nullptr;
11193 }
11194
11195 // Update the users of the node with the new indices
11196 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11197 SDNode *User = Users[i];
11198 if (!User) {
11199 // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11200 // Users[0] is still nullptr because channel 0 doesn't really have a use.
11201 if (i || !NoChannels)
11202 continue;
11203 } else {
11204 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11205 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11206 }
11207
11208 switch (Idx) {
11209 default: break;
11210 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11211 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11212 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11213 case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11214 }
11215 }
11216
11217 DAG.RemoveDeadNode(Node);
11218 return nullptr;
11219}
11220
11221static bool isFrameIndexOp(SDValue Op) {
11222 if (Op.getOpcode() == ISD::AssertZext)
11223 Op = Op.getOperand(0);
11224
11225 return isa<FrameIndexSDNode>(Op);
11226}
11227
11228/// Legalize target independent instructions (e.g. INSERT_SUBREG)
11229/// with frame index operands.
11230/// LLVM assumes that inputs are to these instructions are registers.
11231SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11232 SelectionDAG &DAG) const {
11233 if (Node->getOpcode() == ISD::CopyToReg) {
11234 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11235 SDValue SrcVal = Node->getOperand(2);
11236
11237 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11238 // to try understanding copies to physical registers.
11239 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11240 SDLoc SL(Node);
11241 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11242 SDValue VReg = DAG.getRegister(
11243 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11244
11245 SDNode *Glued = Node->getGluedNode();
11246 SDValue ToVReg
11247 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11248 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11249 SDValue ToResultReg
11250 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11251 VReg, ToVReg.getValue(1));
11252 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11253 DAG.RemoveDeadNode(Node);
11254 return ToResultReg.getNode();
11255 }
11256 }
11257
11258 SmallVector<SDValue, 8> Ops;
11259 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11260 if (!isFrameIndexOp(Node->getOperand(i))) {
11261 Ops.push_back(Node->getOperand(i));
11262 continue;
11263 }
11264
11265 SDLoc DL(Node);
11266 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11267 Node->getOperand(i).getValueType(),
11268 Node->getOperand(i)), 0));
11269 }
11270
11271 return DAG.UpdateNodeOperands(Node, Ops);
11272}
11273
11274/// Fold the instructions after selecting them.
11275/// Returns null if users were already updated.
11276SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11277 SelectionDAG &DAG) const {
11278 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11279 unsigned Opcode = Node->getMachineOpcode();
11280
11281 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
1
Assuming the condition is true
2
Assuming the condition is true
5
Taking true branch
11282 !TII->isGather4(Opcode) &&
3
Assuming the condition is true
11283 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
4
Assuming the condition is true
11284 return adjustWritemask(Node, DAG);
6
Calling 'SITargetLowering::adjustWritemask'
11285 }
11286
11287 if (Opcode == AMDGPU::INSERT_SUBREG ||
11288 Opcode == AMDGPU::REG_SEQUENCE) {
11289 legalizeTargetIndependentNode(Node, DAG);
11290 return Node;
11291 }
11292
11293 switch (Opcode) {
11294 case AMDGPU::V_DIV_SCALE_F32_e64:
11295 case AMDGPU::V_DIV_SCALE_F64_e64: {
11296 // Satisfy the operand register constraint when one of the inputs is
11297 // undefined. Ordinarily each undef value will have its own implicit_def of
11298 // a vreg, so force these to use a single register.
11299 SDValue Src0 = Node->getOperand(1);
11300 SDValue Src1 = Node->getOperand(3);
11301 SDValue Src2 = Node->getOperand(5);
11302
11303 if ((Src0.isMachineOpcode() &&
11304 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11305 (Src0 == Src1 || Src0 == Src2))
11306 break;
11307
11308 MVT VT = Src0.getValueType().getSimpleVT();
11309 const TargetRegisterClass *RC =
11310 getRegClassFor(VT, Src0.getNode()->isDivergent());
11311
11312 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11313 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11314
11315 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11316 UndefReg, Src0, SDValue());
11317
11318 // src0 must be the same register as src1 or src2, even if the value is
11319 // undefined, so make sure we don't violate this constraint.
11320 if (Src0.isMachineOpcode() &&
11321 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11322 if (Src1.isMachineOpcode() &&
11323 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11324 Src0 = Src1;
11325 else if (Src2.isMachineOpcode() &&
11326 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11327 Src0 = Src2;
11328 else {
11329 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF)(static_cast <bool> (Src1.getMachineOpcode() == AMDGPU::
IMPLICIT_DEF) ? void (0) : __assert_fail ("Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11329, __extension__ __PRETTY_FUNCTION__))
;
11330 Src0 = UndefReg;
11331 Src1 = UndefReg;
11332 }
11333 } else
11334 break;
11335
11336 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11337 Ops[1] = Src0;
11338 Ops[3] = Src1;
11339 Ops[5] = Src2;
11340 Ops.push_back(ImpDef.getValue(1));
11341 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11342 }
11343 default:
11344 break;
11345 }
11346
11347 return Node;
11348}
11349
11350// Any MIMG instructions that use tfe or lwe require an initialization of the
11351// result register that will be written in the case of a memory access failure.
11352// The required code is also added to tie this init code to the result of the
11353// img instruction.
11354void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11355 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11356 const SIRegisterInfo &TRI = TII->getRegisterInfo();
11357 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11358 MachineBasicBlock &MBB = *MI.getParent();
11359
11360 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11361 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11362 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11363
11364 if (!TFE && !LWE) // intersect_ray
11365 return;
11366
11367 unsigned TFEVal = TFE ? TFE->getImm() : 0;
11368 unsigned LWEVal = LWE->getImm();
11369 unsigned D16Val = D16 ? D16->getImm() : 0;
11370
11371 if (!TFEVal && !LWEVal)
11372 return;
11373
11374 // At least one of TFE or LWE are non-zero
11375 // We have to insert a suitable initialization of the result value and
11376 // tie this to the dest of the image instruction.
11377
11378 const DebugLoc &DL = MI.getDebugLoc();
11379
11380 int DstIdx =
11381 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11382
11383 // Calculate which dword we have to initialize to 0.
11384 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11385
11386 // check that dmask operand is found.
11387 assert(MO_Dmask && "Expected dmask operand in instruction")(static_cast <bool> (MO_Dmask && "Expected dmask operand in instruction"
) ? void (0) : __assert_fail ("MO_Dmask && \"Expected dmask operand in instruction\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11387, __extension__ __PRETTY_FUNCTION__))
;
11388
11389 unsigned dmask = MO_Dmask->getImm();
11390 // Determine the number of active lanes taking into account the
11391 // Gather4 special case
11392 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11393
11394 bool Packed = !Subtarget->hasUnpackedD16VMem();
11395
11396 unsigned InitIdx =
11397 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11398
11399 // Abandon attempt if the dst size isn't large enough
11400 // - this is in fact an error but this is picked up elsewhere and
11401 // reported correctly.
11402 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11403 if (DstSize < InitIdx)
11404 return;
11405
11406 // Create a register for the intialization value.
11407 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11408 unsigned NewDst = 0; // Final initialized value will be in here
11409
11410 // If PRTStrictNull feature is enabled (the default) then initialize
11411 // all the result registers to 0, otherwise just the error indication
11412 // register (VGPRn+1)
11413 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11414 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11415
11416 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11417 for (; SizeLeft; SizeLeft--, CurrIdx++) {
11418 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11419 // Initialize dword
11420 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11421 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11422 .addImm(0);
11423 // Insert into the super-reg
11424 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11425 .addReg(PrevDst)
11426 .addReg(SubReg)
11427 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11428
11429 PrevDst = NewDst;
11430 }
11431
11432 // Add as an implicit operand
11433 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11434
11435 // Tie the just added implicit operand to the dst
11436 MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11437}
11438
11439/// Assign the register class depending on the number of
11440/// bits set in the writemask
11441void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11442 SDNode *Node) const {
11443 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11444
11445 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11446
11447 if (TII->isVOP3(MI.getOpcode())) {
11448 // Make sure constant bus requirements are respected.
11449 TII->legalizeOperandsVOP3(MRI, MI);
11450
11451 // Prefer VGPRs over AGPRs in mAI instructions where possible.
11452 // This saves a chain-copy of registers and better ballance register
11453 // use between vgpr and agpr as agpr tuples tend to be big.
11454 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11455 unsigned Opc = MI.getOpcode();
11456 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11457 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11458 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11459 if (I == -1)
11460 break;
11461 MachineOperand &Op = MI.getOperand(I);
11462 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11463 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11464 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11465 continue;
11466 auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11467 if (!Src || !Src->isCopy() ||
11468 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11469 continue;
11470 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11471 auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11472 // All uses of agpr64 and agpr32 can also accept vgpr except for
11473 // v_accvgpr_read, but we do not produce agpr reads during selection,
11474 // so no use checks are needed.
11475 MRI.setRegClass(Op.getReg(), NewRC);
11476 }
11477 }
11478
11479 return;
11480 }
11481
11482 // Replace unused atomics with the no return version.
11483 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11484 if (NoRetAtomicOp != -1) {
11485 if (!Node->hasAnyUseOfValue(0)) {
11486 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11487 AMDGPU::OpName::cpol);
11488 if (CPolIdx != -1) {
11489 MachineOperand &CPol = MI.getOperand(CPolIdx);
11490 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11491 }
11492 MI.RemoveOperand(0);
11493 MI.setDesc(TII->get(NoRetAtomicOp));
11494 return;
11495 }
11496
11497 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11498 // instruction, because the return type of these instructions is a vec2 of
11499 // the memory type, so it can be tied to the input operand.
11500 // This means these instructions always have a use, so we need to add a
11501 // special case to check if the atomic has only one extract_subreg use,
11502 // which itself has no uses.
11503 if ((Node->hasNUsesOfValue(1, 0) &&
11504 Node->use_begin()->isMachineOpcode() &&
11505 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11506 !Node->use_begin()->hasAnyUseOfValue(0))) {
11507 Register Def = MI.getOperand(0).getReg();
11508
11509 // Change this into a noret atomic.
11510 MI.setDesc(TII->get(NoRetAtomicOp));
11511 MI.RemoveOperand(0);
11512
11513 // If we only remove the def operand from the atomic instruction, the
11514 // extract_subreg will be left with a use of a vreg without a def.
11515 // So we need to insert an implicit_def to avoid machine verifier
11516 // errors.
11517 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11518 TII->get(AMDGPU::IMPLICIT_DEF), Def);
11519 }
11520 return;
11521 }
11522
11523 if (TII->isMIMG(MI) && !MI.mayStore())
11524 AddIMGInit(MI);
11525}
11526
11527static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11528 uint64_t Val) {
11529 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11530 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11531}
11532
11533MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11534 const SDLoc &DL,
11535 SDValue Ptr) const {
11536 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11537
11538 // Build the half of the subregister with the constants before building the
11539 // full 128-bit register. If we are building multiple resource descriptors,
11540 // this will allow CSEing of the 2-component register.
11541 const SDValue Ops0[] = {
11542 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11543 buildSMovImm32(DAG, DL, 0),
11544 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11545 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11546 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11547 };
11548
11549 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11550 MVT::v2i32, Ops0), 0);
11551
11552 // Combine the constants and the pointer.
11553 const SDValue Ops1[] = {
11554 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11555 Ptr,
11556 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11557 SubRegHi,
11558 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11559 };
11560
11561 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11562}
11563
11564/// Return a resource descriptor with the 'Add TID' bit enabled
11565/// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11566/// of the resource descriptor) to create an offset, which is added to
11567/// the resource pointer.
11568MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11569 SDValue Ptr, uint32_t RsrcDword1,
11570 uint64_t RsrcDword2And3) const {
11571 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11572 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11573 if (RsrcDword1) {
11574 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11575 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11576 0);
11577 }
11578
11579 SDValue DataLo = buildSMovImm32(DAG, DL,
11580 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)0xFFFFFFFFUL);
11581 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11582
11583 const SDValue Ops[] = {
11584 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11585 PtrLo,
11586 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11587 PtrHi,
11588 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11589 DataLo,
11590 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11591 DataHi,
11592 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11593 };
11594
11595 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11596}
11597
11598//===----------------------------------------------------------------------===//
11599// SI Inline Assembly Support
11600//===----------------------------------------------------------------------===//
11601
11602std::pair<unsigned, const TargetRegisterClass *>
11603SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11604 StringRef Constraint,
11605 MVT VT) const {
11606 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11607
11608 const TargetRegisterClass *RC = nullptr;
11609 if (Constraint.size() == 1) {
11610 const unsigned BitWidth = VT.getSizeInBits();
11611 switch (Constraint[0]) {
11612 default:
11613 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11614 case 's':
11615 case 'r':
11616 switch (BitWidth) {
11617 case 16:
11618 RC = &AMDGPU::SReg_32RegClass;
11619 break;
11620 case 64:
11621 RC = &AMDGPU::SGPR_64RegClass;
11622 break;
11623 default:
11624 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11625 if (!RC)
11626 return std::make_pair(0U, nullptr);
11627 break;
11628 }
11629 break;
11630 case 'v':
11631 switch (BitWidth) {
11632 case 16:
11633 RC = &AMDGPU::VGPR_32RegClass;
11634 break;
11635 default:
11636 RC = TRI->getVGPRClassForBitWidth(BitWidth);
11637 if (!RC)
11638 return std::make_pair(0U, nullptr);
11639 break;
11640 }
11641 break;
11642 case 'a':
11643 if (!Subtarget->hasMAIInsts())
11644 break;
11645 switch (BitWidth) {
11646 case 16:
11647 RC = &AMDGPU::AGPR_32RegClass;
11648 break;
11649 default:
11650 RC = TRI->getAGPRClassForBitWidth(BitWidth);
11651 if (!RC)
11652 return std::make_pair(0U, nullptr);
11653 break;
11654 }
11655 break;
11656 }
11657 // We actually support i128, i16 and f16 as inline parameters
11658 // even if they are not reported as legal
11659 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11660 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11661 return std::make_pair(0U, RC);
11662 }
11663
11664 if (Constraint.size() > 1) {
11665 if (Constraint[1] == 'v') {
11666 RC = &AMDGPU::VGPR_32RegClass;
11667 } else if (Constraint[1] == 's') {
11668 RC = &AMDGPU::SGPR_32RegClass;
11669 } else if (Constraint[1] == 'a') {
11670 RC = &AMDGPU::AGPR_32RegClass;
11671 }
11672
11673 if (RC) {
11674 uint32_t Idx;
11675 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11676 if (!Failed && Idx < RC->getNumRegs())
11677 return std::make_pair(RC->getRegister(Idx), RC);
11678 }
11679 }
11680
11681 // FIXME: Returns VS_32 for physical SGPR constraints
11682 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11683}
11684
11685static bool isImmConstraint(StringRef Constraint) {
11686 if (Constraint.size() == 1) {
11687 switch (Constraint[0]) {
11688 default: break;
11689 case 'I':
11690 case 'J':
11691 case 'A':
11692 case 'B':
11693 case 'C':
11694 return true;
11695 }
11696 } else if (Constraint == "DA" ||
11697 Constraint == "DB") {
11698 return true;
11699 }
11700 return false;
11701}
11702
11703SITargetLowering::ConstraintType
11704SITargetLowering::getConstraintType(StringRef Constraint) const {
11705 if (Constraint.size() == 1) {
11706 switch (Constraint[0]) {
11707 default: break;
11708 case 's':
11709 case 'v':
11710 case 'a':
11711 return C_RegisterClass;
11712 }
11713 }
11714 if (isImmConstraint(Constraint)) {
11715 return C_Other;
11716 }
11717 return TargetLowering::getConstraintType(Constraint);
11718}
11719
11720static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11721 if (!AMDGPU::isInlinableIntLiteral(Val)) {
11722 Val = Val & maskTrailingOnes<uint64_t>(Size);
11723 }
11724 return Val;
11725}
11726
11727void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11728 std::string &Constraint,
11729 std::vector<SDValue> &Ops,
11730 SelectionDAG &DAG) const {
11731 if (isImmConstraint(Constraint)) {
11732 uint64_t Val;
11733 if (getAsmOperandConstVal(Op, Val) &&
11734 checkAsmConstraintVal(Op, Constraint, Val)) {
11735 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11736 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11737 }
11738 } else {
11739 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11740 }
11741}
11742
11743bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11744 unsigned Size = Op.getScalarValueSizeInBits();
11745 if (Size > 64)
11746 return false;
11747
11748 if (Size == 16 && !Subtarget->has16BitInsts())
11749 return false;
11750
11751 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11752 Val = C->getSExtValue();
11753 return true;
11754 }
11755 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11756 Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11757 return true;
11758 }
11759 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11760 if (Size != 16 || Op.getNumOperands() != 2)
11761 return false;
11762 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11763 return false;
11764 if (ConstantSDNode *C = V->getConstantSplatNode()) {
11765 Val = C->getSExtValue();
11766 return true;
11767 }
11768 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11769 Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11770 return true;
11771 }
11772 }
11773
11774 return false;
11775}
11776
11777bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11778 const std::string &Constraint,
11779 uint64_t Val) const {
11780 if (Constraint.size() == 1) {
11781 switch (Constraint[0]) {
11782 case 'I':
11783 return AMDGPU::isInlinableIntLiteral(Val);
11784 case 'J':
11785 return isInt<16>(Val);
11786 case 'A':
11787 return checkAsmConstraintValA(Op, Val);
11788 case 'B':
11789 return isInt<32>(Val);
11790 case 'C':
11791 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11792 AMDGPU::isInlinableIntLiteral(Val);
11793 default:
11794 break;
11795 }
11796 } else if (Constraint.size() == 2) {
11797 if (Constraint == "DA") {
11798 int64_t HiBits = static_cast<int32_t>(Val >> 32);
11799 int64_t LoBits = static_cast<int32_t>(Val);
11800 return checkAsmConstraintValA(Op, HiBits, 32) &&
11801 checkAsmConstraintValA(Op, LoBits, 32);
11802 }
11803 if (Constraint == "DB") {
11804 return true;
11805 }
11806 }
11807 llvm_unreachable("Invalid asm constraint")::llvm::llvm_unreachable_internal("Invalid asm constraint", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11807)
;
11808}
11809
11810bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11811 uint64_t Val,
11812 unsigned MaxSize) const {
11813 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11814 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11815 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11816 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11817 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11818 return true;
11819 }
11820 return false;
11821}
11822
11823static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11824 switch (UnalignedClassID) {
11825 case AMDGPU::VReg_64RegClassID:
11826 return AMDGPU::VReg_64_Align2RegClassID;
11827 case AMDGPU::VReg_96RegClassID:
11828 return AMDGPU::VReg_96_Align2RegClassID;
11829 case AMDGPU::VReg_128RegClassID:
11830 return AMDGPU::VReg_128_Align2RegClassID;
11831 case AMDGPU::VReg_160RegClassID:
11832 return AMDGPU::VReg_160_Align2RegClassID;
11833 case AMDGPU::VReg_192RegClassID:
11834 return AMDGPU::VReg_192_Align2RegClassID;
11835 case AMDGPU::VReg_224RegClassID:
11836 return AMDGPU::VReg_224_Align2RegClassID;
11837 case AMDGPU::VReg_256RegClassID:
11838 return AMDGPU::VReg_256_Align2RegClassID;
11839 case AMDGPU::VReg_512RegClassID:
11840 return AMDGPU::VReg_512_Align2RegClassID;
11841 case AMDGPU::VReg_1024RegClassID:
11842 return AMDGPU::VReg_1024_Align2RegClassID;
11843 case AMDGPU::AReg_64RegClassID:
11844 return AMDGPU::AReg_64_Align2RegClassID;
11845 case AMDGPU::AReg_96RegClassID:
11846 return AMDGPU::AReg_96_Align2RegClassID;
11847 case AMDGPU::AReg_128RegClassID:
11848 return AMDGPU::AReg_128_Align2RegClassID;
11849 case AMDGPU::AReg_160RegClassID:
11850 return AMDGPU::AReg_160_Align2RegClassID;
11851 case AMDGPU::AReg_192RegClassID:
11852 return AMDGPU::AReg_192_Align2RegClassID;
11853 case AMDGPU::AReg_256RegClassID:
11854 return AMDGPU::AReg_256_Align2RegClassID;
11855 case AMDGPU::AReg_512RegClassID:
11856 return AMDGPU::AReg_512_Align2RegClassID;
11857 case AMDGPU::AReg_1024RegClassID:
11858 return AMDGPU::AReg_1024_Align2RegClassID;
11859 default:
11860 return -1;
11861 }
11862}
11863
11864// Figure out which registers should be reserved for stack access. Only after
11865// the function is legalized do we know all of the non-spill stack objects or if
11866// calls are present.
11867void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11868 MachineRegisterInfo &MRI = MF.getRegInfo();
11869 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11870 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11871 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11872 const SIInstrInfo *TII = ST.getInstrInfo();
11873
11874 if (Info->isEntryFunction()) {
11875 // Callable functions have fixed registers used for stack access.
11876 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11877 }
11878
11879 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),(static_cast <bool> (!TRI->isSubRegister(Info->getScratchRSrcReg
(), Info->getStackPtrOffsetReg())) ? void (0) : __assert_fail
("!TRI->isSubRegister(Info->getScratchRSrcReg(), Info->getStackPtrOffsetReg())"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11880, __extension__ __PRETTY_FUNCTION__))
11880 Info->getStackPtrOffsetReg()))(static_cast <bool> (!TRI->isSubRegister(Info->getScratchRSrcReg
(), Info->getStackPtrOffsetReg())) ? void (0) : __assert_fail
("!TRI->isSubRegister(Info->getScratchRSrcReg(), Info->getStackPtrOffsetReg())"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11880, __extension__ __PRETTY_FUNCTION__))
;
11881 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11882 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11883
11884 // We need to worry about replacing the default register with itself in case
11885 // of MIR testcases missing the MFI.
11886 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11887 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11888
11889 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11890 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11891
11892 Info->limitOccupancy(MF);
11893
11894 if (ST.isWave32() && !MF.empty()) {
11895 for (auto &MBB : MF) {
11896 for (auto &MI : MBB) {
11897 TII->fixImplicitOperands(MI);
11898 }
11899 }
11900 }
11901
11902 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
11903 // classes if required. Ideally the register class constraints would differ
11904 // per-subtarget, but there's no easy way to achieve that right now. This is
11905 // not a problem for VGPRs because the correctly aligned VGPR class is implied
11906 // from using them as the register class for legal types.
11907 if (ST.needsAlignedVGPRs()) {
11908 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
11909 const Register Reg = Register::index2VirtReg(I);
11910 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
11911 if (!RC)
11912 continue;
11913 int NewClassID = getAlignedAGPRClassID(RC->getID());
11914 if (NewClassID != -1)
11915 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
11916 }
11917 }
11918
11919 TargetLoweringBase::finalizeLowering(MF);
11920
11921 // Allocate a VGPR for future SGPR Spill if
11922 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11923 // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11924 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() &&
11925 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction())
11926 Info->reserveVGPRforSGPRSpills(MF);
11927}
11928
11929void SITargetLowering::computeKnownBitsForFrameIndex(
11930 const int FI, KnownBits &Known, const MachineFunction &MF) const {
11931 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11932
11933 // Set the high bits to zero based on the maximum allowed scratch size per
11934 // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11935 // calculation won't overflow, so assume the sign bit is never set.
11936 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11937}
11938
11939static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11940 KnownBits &Known, unsigned Dim) {
11941 unsigned MaxValue =
11942 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11943 Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11944}
11945
11946void SITargetLowering::computeKnownBitsForTargetInstr(
11947 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11948 const MachineRegisterInfo &MRI, unsigned Depth) const {
11949 const MachineInstr *MI = MRI.getVRegDef(R);
11950 switch (MI->getOpcode()) {
11951 case AMDGPU::G_INTRINSIC: {
11952 switch (MI->getIntrinsicID()) {
11953 case Intrinsic::amdgcn_workitem_id_x:
11954 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11955 break;
11956 case Intrinsic::amdgcn_workitem_id_y:
11957 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11958 break;
11959 case Intrinsic::amdgcn_workitem_id_z:
11960 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11961 break;
11962 case Intrinsic::amdgcn_mbcnt_lo:
11963 case Intrinsic::amdgcn_mbcnt_hi: {
11964 // These return at most the wavefront size - 1.
11965 unsigned Size = MRI.getType(R).getSizeInBits();
11966 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11967 break;
11968 }
11969 case Intrinsic::amdgcn_groupstaticsize: {
11970 // We can report everything over the maximum size as 0. We can't report
11971 // based on the actual size because we don't know if it's accurate or not
11972 // at any given point.
11973 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11974 break;
11975 }
11976 }
11977 break;
11978 }
11979 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11980 Known.Zero.setHighBits(24);
11981 break;
11982 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11983 Known.Zero.setHighBits(16);
11984 break;
11985 }
11986}
11987
11988Align SITargetLowering::computeKnownAlignForTargetInstr(
11989 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11990 unsigned Depth) const {
11991 const MachineInstr *MI = MRI.getVRegDef(R);
11992 switch (MI->getOpcode()) {
11993 case AMDGPU::G_INTRINSIC:
11994 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11995 // FIXME: Can this move to generic code? What about the case where the call
11996 // site specifies a lower alignment?
11997 Intrinsic::ID IID = MI->getIntrinsicID();
11998 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11999 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12000 if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12001 return *RetAlign;
12002 return Align(1);
12003 }
12004 default:
12005 return Align(1);
12006 }
12007}
12008
12009Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12010 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12011 const Align CacheLineAlign = Align(64);
12012
12013 // Pre-GFX10 target did not benefit from loop alignment
12014 if (!ML || DisableLoopAlignment ||
12015 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12016 getSubtarget()->hasInstFwdPrefetchBug())
12017 return PrefAlign;
12018
12019 // On GFX10 I$ is 4 x 64 bytes cache lines.
12020 // By default prefetcher keeps one cache line behind and reads two ahead.
12021 // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12022 // behind and one ahead.
12023 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12024 // If loop fits 64 bytes it always spans no more than two cache lines and
12025 // does not need an alignment.
12026 // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12027 // Else if loop is less or equal 192 bytes we need two lines behind.
12028
12029 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12030 const MachineBasicBlock *Header = ML->getHeader();
12031 if (Header->getAlignment() != PrefAlign)
12032 return Header->getAlignment(); // Already processed.
12033
12034 unsigned LoopSize = 0;
12035 for (const MachineBasicBlock *MBB : ML->blocks()) {
12036 // If inner loop block is aligned assume in average half of the alignment
12037 // size to be added as nops.
12038 if (MBB != Header)
12039 LoopSize += MBB->getAlignment().value() / 2;
12040
12041 for (const MachineInstr &MI : *MBB) {
12042 LoopSize += TII->getInstSizeInBytes(MI);
12043 if (LoopSize > 192)
12044 return PrefAlign;
12045 }
12046 }
12047
12048 if (LoopSize <= 64)
12049 return PrefAlign;
12050
12051 if (LoopSize <= 128)
12052 return CacheLineAlign;
12053
12054 // If any of parent loops is surrounded by prefetch instructions do not
12055 // insert new for inner loop, which would reset parent's settings.
12056 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12057 if (MachineBasicBlock *Exit = P->getExitBlock()) {
12058 auto I = Exit->getFirstNonDebugInstr();
12059 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12060 return CacheLineAlign;
12061 }
12062 }
12063
12064 MachineBasicBlock *Pre = ML->getLoopPreheader();
12065 MachineBasicBlock *Exit = ML->getExitBlock();
12066
12067 if (Pre && Exit) {
12068 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12069 TII->get(AMDGPU::S_INST_PREFETCH))
12070 .addImm(1); // prefetch 2 lines behind PC
12071
12072 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12073 TII->get(AMDGPU::S_INST_PREFETCH))
12074 .addImm(2); // prefetch 1 line behind PC
12075 }
12076
12077 return CacheLineAlign;
12078}
12079
12080LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__))
12081static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12082 assert(N->getOpcode() == ISD::CopyFromReg)(static_cast <bool> (N->getOpcode() == ISD::CopyFromReg
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::CopyFromReg"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 12082, __extension__ __PRETTY_FUNCTION__))
;
12083 do {
12084 // Follow the chain until we find an INLINEASM node.
12085 N = N->getOperand(0).getNode();
12086 if (N->getOpcode() == ISD::INLINEASM ||
12087 N->getOpcode() == ISD::INLINEASM_BR)
12088 return true;
12089 } while (N->getOpcode() == ISD::CopyFromReg);
12090 return false;
12091}
12092
12093bool SITargetLowering::isSDNodeSourceOfDivergence(
12094 const SDNode *N, FunctionLoweringInfo *FLI,
12095 LegacyDivergenceAnalysis *KDA) const {
12096 switch (N->getOpcode()) {
12097 case ISD::CopyFromReg: {
12098 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12099 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12100 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12101 Register Reg = R->getReg();
12102
12103 // FIXME: Why does this need to consider isLiveIn?
12104 if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12105 return !TRI->isSGPRReg(MRI, Reg);
12106
12107 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12108 return KDA->isDivergent(V);
12109
12110 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N))(static_cast <bool> (Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm
(N)) ? void (0) : __assert_fail ("Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 12110, __extension__ __PRETTY_FUNCTION__))
;
12111 return !TRI->isSGPRReg(MRI, Reg);
12112 }
12113 case ISD::LOAD: {
12114 const LoadSDNode *L = cast<LoadSDNode>(N);
12115 unsigned AS = L->getAddressSpace();
12116 // A flat load may access private memory.
12117 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12118 }
12119 case ISD::CALLSEQ_END:
12120 return true;
12121 case ISD::INTRINSIC_WO_CHAIN:
12122 return AMDGPU::isIntrinsicSourceOfDivergence(
12123 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12124 case ISD::INTRINSIC_W_CHAIN:
12125 return AMDGPU::isIntrinsicSourceOfDivergence(
12126 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12127 case AMDGPUISD::ATOMIC_CMP_SWAP:
12128 case AMDGPUISD::ATOMIC_INC:
12129 case AMDGPUISD::ATOMIC_DEC:
12130 case AMDGPUISD::ATOMIC_LOAD_FMIN:
12131 case AMDGPUISD::ATOMIC_LOAD_FMAX:
12132 case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12133 case AMDGPUISD::BUFFER_ATOMIC_ADD:
12134 case AMDGPUISD::BUFFER_ATOMIC_SUB:
12135 case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12136 case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12137 case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12138 case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12139 case AMDGPUISD::BUFFER_ATOMIC_AND:
12140 case AMDGPUISD::BUFFER_ATOMIC_OR:
12141 case AMDGPUISD::BUFFER_ATOMIC_XOR:
12142 case AMDGPUISD::BUFFER_ATOMIC_INC:
12143 case AMDGPUISD::BUFFER_ATOMIC_DEC:
12144 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12145 case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12146 case AMDGPUISD::BUFFER_ATOMIC_FADD:
12147 case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12148 case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12149 // Target-specific read-modify-write atomics are sources of divergence.
12150 return true;
12151 default:
12152 if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12153 // Generic read-modify-write atomics are sources of divergence.
12154 return A->readMem() && A->writeMem();
12155 }
12156 return false;
12157 }
12158}
12159
12160bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12161 EVT VT) const {
12162 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12163 case MVT::f32:
12164 return hasFP32Denormals(DAG.getMachineFunction());
12165 case MVT::f64:
12166 case MVT::f16:
12167 return hasFP64FP16Denormals(DAG.getMachineFunction());
12168 default:
12169 return false;
12170 }
12171}
12172
12173bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12174 MachineFunction &MF) const {
12175 switch (Ty.getScalarSizeInBits()) {
12176 case 32:
12177 return hasFP32Denormals(MF);
12178 case 64:
12179 case 16:
12180 return hasFP64FP16Denormals(MF);
12181 default:
12182 return false;
12183 }
12184}
12185
12186bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12187 const SelectionDAG &DAG,
12188 bool SNaN,
12189 unsigned Depth) const {
12190 if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12191 const MachineFunction &MF = DAG.getMachineFunction();
12192 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12193
12194 if (Info->getMode().DX10Clamp)
12195 return true; // Clamped to 0.
12196 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12197 }
12198
12199 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12200 SNaN, Depth);
12201}
12202
12203// Global FP atomic instructions have a hardcoded FP mode and do not support
12204// FP32 denormals, and only support v2f16 denormals.
12205static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12206 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12207 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12208 if (&Flt == &APFloat::IEEEsingle())
12209 return DenormMode == DenormalMode::getPreserveSign();
12210 return DenormMode == DenormalMode::getIEEE();
12211}
12212
12213TargetLowering::AtomicExpansionKind
12214SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12215
12216 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12217 OptimizationRemarkEmitter ORE(RMW->getFunction());
12218 LLVMContext &Ctx = RMW->getFunction()->getContext();
12219 SmallVector<StringRef> SSNs;
12220 Ctx.getSyncScopeNames(SSNs);
12221 auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12222 ? "system"
12223 : SSNs[RMW->getSyncScopeID()];
12224 ORE.emit([&]() {
12225 return OptimizationRemark(DEBUG_TYPE"si-lower", "Passed", RMW)
12226 << "Hardware instruction generated for atomic "
12227 << RMW->getOperationName(RMW->getOperation())
12228 << " operation at memory scope " << MemScope
12229 << " due to an unsafe request.";
12230 });
12231 return Kind;
12232 };
12233
12234 switch (RMW->getOperation()) {
12235 case AtomicRMWInst::FAdd: {
12236 Type *Ty = RMW->getType();
12237
12238 // We don't have a way to support 16-bit atomics now, so just leave them
12239 // as-is.
12240 if (Ty->isHalfTy())
12241 return AtomicExpansionKind::None;
12242
12243 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12244 return AtomicExpansionKind::CmpXChg;
12245
12246 unsigned AS = RMW->getPointerAddressSpace();
12247
12248 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12249 Subtarget->hasAtomicFaddInsts()) {
12250 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12251 // floating point atomic instructions. May generate more efficient code,
12252 // but may not respect rounding and denormal modes, and may give incorrect
12253 // results for certain memory destinations.
12254 if (RMW->getFunction()
12255 ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12256 .getValueAsString() != "true")
12257 return AtomicExpansionKind::CmpXChg;
12258
12259 if (Subtarget->hasGFX90AInsts()) {
12260 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12261 return AtomicExpansionKind::CmpXChg;
12262
12263 auto SSID = RMW->getSyncScopeID();
12264 if (SSID == SyncScope::System ||
12265 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12266 return AtomicExpansionKind::CmpXChg;
12267
12268 return ReportUnsafeHWInst(AtomicExpansionKind::None);
12269 }
12270
12271 if (AS == AMDGPUAS::FLAT_ADDRESS)
12272 return AtomicExpansionKind::CmpXChg;
12273
12274 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12275 : AtomicExpansionKind::CmpXChg;
12276 }
12277
12278 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12279 // to round-to-nearest-even.
12280 // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12281 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12282 if (!Ty->isDoubleTy())
12283 return AtomicExpansionKind::None;
12284
12285 if (fpModeMatchesGlobalFPAtomicMode(RMW))
12286 return AtomicExpansionKind::None;
12287
12288 return RMW->getFunction()
12289 ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12290 .getValueAsString() == "true"
12291 ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12292 : AtomicExpansionKind::CmpXChg;
12293 }
12294
12295 return AtomicExpansionKind::CmpXChg;
12296 }
12297 default:
12298 break;
12299 }
12300
12301 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12302}
12303
12304const TargetRegisterClass *
12305SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12306 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12307 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12308 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12309 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12310 : &AMDGPU::SReg_32RegClass;
12311 if (!TRI->isSGPRClass(RC) && !isDivergent)
12312 return TRI->getEquivalentSGPRClass(RC);
12313 else if (TRI->isSGPRClass(RC) && isDivergent)
12314 return TRI->getEquivalentVGPRClass(RC);
12315
12316 return RC;
12317}
12318
12319// FIXME: This is a workaround for DivergenceAnalysis not understanding always
12320// uniform values (as produced by the mask results of control flow intrinsics)
12321// used outside of divergent blocks. The phi users need to also be treated as
12322// always uniform.
12323static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12324 unsigned WaveSize) {
12325 // FIXME: We asssume we never cast the mask results of a control flow
12326 // intrinsic.
12327 // Early exit if the type won't be consistent as a compile time hack.
12328 IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12329 if (!IT || IT->getBitWidth() != WaveSize)
12330 return false;
12331
12332 if (!isa<Instruction>(V))
12333 return false;
12334 if (!Visited.insert(V).second)
12335 return false;
12336 bool Result = false;
12337 for (auto U : V->users()) {
12338 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12339 if (V == U->getOperand(1)) {
12340 switch (Intrinsic->getIntrinsicID()) {
12341 default:
12342 Result = false;
12343 break;
12344 case Intrinsic::amdgcn_if_break:
12345 case Intrinsic::amdgcn_if:
12346 case Intrinsic::amdgcn_else:
12347 Result = true;
12348 break;
12349 }
12350 }
12351 if (V == U->getOperand(0)) {
12352 switch (Intrinsic->getIntrinsicID()) {
12353 default:
12354 Result = false;
12355 break;
12356 case Intrinsic::amdgcn_end_cf:
12357 case Intrinsic::amdgcn_loop:
12358 Result = true;
12359 break;
12360 }
12361 }
12362 } else {
12363 Result = hasCFUser(U, Visited, WaveSize);
12364 }
12365 if (Result)
12366 break;
12367 }
12368 return Result;
12369}
12370
12371bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12372 const Value *V) const {
12373 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12374 if (CI->isInlineAsm()) {
12375 // FIXME: This cannot give a correct answer. This should only trigger in
12376 // the case where inline asm returns mixed SGPR and VGPR results, used
12377 // outside the defining block. We don't have a specific result to
12378 // consider, so this assumes if any value is SGPR, the overall register
12379 // also needs to be SGPR.
12380 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12381 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12382 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12383 for (auto &TC : TargetConstraints) {
12384 if (TC.Type == InlineAsm::isOutput) {
12385 ComputeConstraintToUse(TC, SDValue());
12386 unsigned AssignedReg;
12387 const TargetRegisterClass *RC;
12388 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
12389 SIRI, TC.ConstraintCode, TC.ConstraintVT);
12390 if (RC) {
12391 MachineRegisterInfo &MRI = MF.getRegInfo();
12392 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
12393 return true;
12394 else if (SIRI->isSGPRClass(RC))
12395 return true;
12396 }
12397 }
12398 }
12399 }
12400 }
12401 SmallPtrSet<const Value *, 16> Visited;
12402 return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12403}
12404
12405std::pair<InstructionCost, MVT>
12406SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12407 Type *Ty) const {
12408 std::pair<InstructionCost, MVT> Cost =
12409 TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12410 auto Size = DL.getTypeSizeInBits(Ty);
12411 // Maximum load or store can handle 8 dwords for scalar and 4 for
12412 // vector ALU. Let's assume anything above 8 dwords is expensive
12413 // even if legal.
12414 if (Size <= 256)
12415 return Cost;
12416
12417 Cost.first = (Size + 255) / 256;
12418 return Cost;
12419}