Bug Summary

File:llvm/include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1199, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -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 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/Target/AMDGPU -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/Target/AMDGPU -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-09-002921-48462-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/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#if defined(_MSC_VER) || defined(__MINGW32__)
15// Provide M_PI.
16#define _USE_MATH_DEFINES
17#endif
18
19#include "SIISelLowering.h"
20#include "AMDGPU.h"
21#include "AMDGPUSubtarget.h"
22#include "AMDGPUTargetMachine.h"
23#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
24#include "SIDefines.h"
25#include "SIInstrInfo.h"
26#include "SIMachineFunctionInfo.h"
27#include "SIRegisterInfo.h"
28#include "Utils/AMDGPUBaseInfo.h"
29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/APInt.h"
31#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/StringRef.h"
36#include "llvm/ADT/StringSwitch.h"
37#include "llvm/ADT/Twine.h"
38#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
39#include "llvm/CodeGen/Analysis.h"
40#include "llvm/CodeGen/CallingConvLower.h"
41#include "llvm/CodeGen/DAGCombine.h"
42#include "llvm/CodeGen/ISDOpcodes.h"
43#include "llvm/CodeGen/MachineBasicBlock.h"
44#include "llvm/CodeGen/MachineFrameInfo.h"
45#include "llvm/CodeGen/MachineFunction.h"
46#include "llvm/CodeGen/MachineInstr.h"
47#include "llvm/CodeGen/MachineInstrBuilder.h"
48#include "llvm/CodeGen/MachineLoopInfo.h"
49#include "llvm/CodeGen/MachineMemOperand.h"
50#include "llvm/CodeGen/MachineModuleInfo.h"
51#include "llvm/CodeGen/MachineOperand.h"
52#include "llvm/CodeGen/MachineRegisterInfo.h"
53#include "llvm/CodeGen/SelectionDAG.h"
54#include "llvm/CodeGen/SelectionDAGNodes.h"
55#include "llvm/CodeGen/TargetCallingConv.h"
56#include "llvm/CodeGen/TargetRegisterInfo.h"
57#include "llvm/CodeGen/ValueTypes.h"
58#include "llvm/IR/Constants.h"
59#include "llvm/IR/DataLayout.h"
60#include "llvm/IR/DebugLoc.h"
61#include "llvm/IR/DerivedTypes.h"
62#include "llvm/IR/DiagnosticInfo.h"
63#include "llvm/IR/Function.h"
64#include "llvm/IR/GlobalValue.h"
65#include "llvm/IR/InstrTypes.h"
66#include "llvm/IR/Instruction.h"
67#include "llvm/IR/Instructions.h"
68#include "llvm/IR/IntrinsicInst.h"
69#include "llvm/IR/Type.h"
70#include "llvm/Support/Casting.h"
71#include "llvm/Support/CodeGen.h"
72#include "llvm/Support/CommandLine.h"
73#include "llvm/Support/Compiler.h"
74#include "llvm/Support/ErrorHandling.h"
75#include "llvm/Support/KnownBits.h"
76#include "llvm/Support/MachineValueType.h"
77#include "llvm/Support/MathExtras.h"
78#include "llvm/Target/TargetOptions.h"
79#include <cassert>
80#include <cmath>
81#include <cstdint>
82#include <iterator>
83#include <tuple>
84#include <utility>
85#include <vector>
86
87using namespace llvm;
88
89#define DEBUG_TYPE"si-lower" "si-lower"
90
91STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"si-lower", "NumTailCalls"
, "Number of tail calls"}
;
92
93static cl::opt<bool> EnableVGPRIndexMode(
94 "amdgpu-vgpr-index-mode",
95 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
96 cl::init(false));
97
98static cl::opt<bool> DisableLoopAlignment(
99 "amdgpu-disable-loop-alignment",
100 cl::desc("Do not align and prefetch loops"),
101 cl::init(false));
102
103static unsigned findFirstFreeSGPR(CCState &CCInfo) {
104 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
105 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
106 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
107 return AMDGPU::SGPR0 + Reg;
108 }
109 }
110 llvm_unreachable("Cannot allocate sgpr")::llvm::llvm_unreachable_internal("Cannot allocate sgpr", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 110)
;
111}
112
113SITargetLowering::SITargetLowering(const TargetMachine &TM,
114 const GCNSubtarget &STI)
115 : AMDGPUTargetLowering(TM, STI),
116 Subtarget(&STI) {
117 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
118 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
119
120 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
121 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
122
123 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
124 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
125 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
126
127 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
128 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
129
130 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
131 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
132
133 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
134 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
135
136 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
137 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
138
139 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
140 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
141
142 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
143 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
144
145 if (Subtarget->has16BitInsts()) {
146 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
147 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
148
149 // Unless there are also VOP3P operations, not operations are really legal.
150 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
151 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
152 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
153 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
154 }
155
156 if (Subtarget->hasMAIInsts()) {
157 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
158 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
159 }
160
161 computeRegisterProperties(Subtarget->getRegisterInfo());
162
163 // We need to custom lower vector stores from local memory
164 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
165 setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
166 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
167 setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
168 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
169 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
170 setOperationAction(ISD::LOAD, MVT::i1, Custom);
171 setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
172
173 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
174 setOperationAction(ISD::STORE, MVT::v3i32, Custom);
175 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
176 setOperationAction(ISD::STORE, MVT::v5i32, Custom);
177 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
178 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
179 setOperationAction(ISD::STORE, MVT::i1, Custom);
180 setOperationAction(ISD::STORE, MVT::v32i32, Custom);
181
182 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
183 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
184 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
185 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
186 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
187 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
188 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
189 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
190 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
191 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
192 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
193
194 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
195 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
196
197 setOperationAction(ISD::SELECT, MVT::i1, Promote);
198 setOperationAction(ISD::SELECT, MVT::i64, Custom);
199 setOperationAction(ISD::SELECT, MVT::f64, Promote);
200 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
201
202 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
203 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
204 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
205 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
206 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
207
208 setOperationAction(ISD::SETCC, MVT::i1, Promote);
209 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
210 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
211 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
212
213 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
214 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
215
216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
218 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
219 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
220 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
221 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
222 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
223 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
224
225 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
226 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
227 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
228 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
229 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
230 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
231
232 setOperationAction(ISD::UADDO, MVT::i32, Legal);
233 setOperationAction(ISD::USUBO, MVT::i32, Legal);
234
235 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
236 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
237
238 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
239 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
240 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
241
242#if 0
243 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
244 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
245#endif
246
247 // We only support LOAD/STORE and vector manipulation ops for vectors
248 // with > 4 elements.
249 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
250 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
251 MVT::v32i32, MVT::v32f32 }) {
252 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
253 switch (Op) {
254 case ISD::LOAD:
255 case ISD::STORE:
256 case ISD::BUILD_VECTOR:
257 case ISD::BITCAST:
258 case ISD::EXTRACT_VECTOR_ELT:
259 case ISD::INSERT_VECTOR_ELT:
260 case ISD::INSERT_SUBVECTOR:
261 case ISD::EXTRACT_SUBVECTOR:
262 case ISD::SCALAR_TO_VECTOR:
263 break;
264 case ISD::CONCAT_VECTORS:
265 setOperationAction(Op, VT, Custom);
266 break;
267 default:
268 setOperationAction(Op, VT, Expand);
269 break;
270 }
271 }
272 }
273
274 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
275
276 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
277 // is expanded to avoid having two separate loops in case the index is a VGPR.
278
279 // Most operations are naturally 32-bit vector operations. We only support
280 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
281 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
282 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
283 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
284
285 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
286 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
287
288 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
289 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
290
291 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
292 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
293 }
294
295 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
296 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
297 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
298 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
299
300 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
301 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
302
303 // Avoid stack access for these.
304 // TODO: Generalize to more vector types.
305 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
306 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
307 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
308 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
309
310 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
311 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
312 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
313 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
314 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
315
316 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
317 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
318 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
319
320 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
321 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
322 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
323 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
324
325 // Deal with vec3 vector operations when widened to vec4.
326 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
327 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
328 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
329 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
330
331 // Deal with vec5 vector operations when widened to vec8.
332 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
333 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
334 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
335 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
336
337 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
338 // and output demarshalling
339 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
340 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
341
342 // We can't return success/failure, only the old value,
343 // let LLVM add the comparison
344 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
345 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
346
347 if (Subtarget->hasFlatAddressSpace()) {
348 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
349 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
350 }
351
352 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
353 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
354
355 // On SI this is s_memtime and s_memrealtime on VI.
356 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
357 setOperationAction(ISD::TRAP, MVT::Other, Custom);
358 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
359
360 if (Subtarget->has16BitInsts()) {
361 setOperationAction(ISD::FLOG, MVT::f16, Custom);
362 setOperationAction(ISD::FEXP, MVT::f16, Custom);
363 setOperationAction(ISD::FLOG10, MVT::f16, Custom);
364 }
365
366 // v_mad_f32 does not support denormals according to some sources.
367 if (!Subtarget->hasFP32Denormals())
368 setOperationAction(ISD::FMAD, MVT::f32, Legal);
369
370 if (!Subtarget->hasBFI()) {
371 // fcopysign can be done in a single instruction with BFI.
372 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
373 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
374 }
375
376 if (!Subtarget->hasBCNT(32))
377 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
378
379 if (!Subtarget->hasBCNT(64))
380 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
381
382 if (Subtarget->hasFFBH())
383 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
384
385 if (Subtarget->hasFFBL())
386 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
387
388 // We only really have 32-bit BFE instructions (and 16-bit on VI).
389 //
390 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
391 // effort to match them now. We want this to be false for i64 cases when the
392 // extraction isn't restricted to the upper or lower half. Ideally we would
393 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
394 // span the midpoint are probably relatively rare, so don't worry about them
395 // for now.
396 if (Subtarget->hasBFE())
397 setHasExtractBitsInsn(true);
398
399 setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
400 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
401 setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
402 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
403
404
405 // These are really only legal for ieee_mode functions. We should be avoiding
406 // them for functions that don't have ieee_mode enabled, so just say they are
407 // legal.
408 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
409 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
410 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
411 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
412
413
414 if (Subtarget->haveRoundOpsF64()) {
415 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
416 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
417 setOperationAction(ISD::FRINT, MVT::f64, Legal);
418 } else {
419 setOperationAction(ISD::FCEIL, MVT::f64, Custom);
420 setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
421 setOperationAction(ISD::FRINT, MVT::f64, Custom);
422 setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
423 }
424
425 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
426
427 setOperationAction(ISD::FSIN, MVT::f32, Custom);
428 setOperationAction(ISD::FCOS, MVT::f32, Custom);
429 setOperationAction(ISD::FDIV, MVT::f32, Custom);
430 setOperationAction(ISD::FDIV, MVT::f64, Custom);
431
432 if (Subtarget->has16BitInsts()) {
433 setOperationAction(ISD::Constant, MVT::i16, Legal);
434
435 setOperationAction(ISD::SMIN, MVT::i16, Legal);
436 setOperationAction(ISD::SMAX, MVT::i16, Legal);
437
438 setOperationAction(ISD::UMIN, MVT::i16, Legal);
439 setOperationAction(ISD::UMAX, MVT::i16, Legal);
440
441 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
442 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
443
444 setOperationAction(ISD::ROTR, MVT::i16, Promote);
445 setOperationAction(ISD::ROTL, MVT::i16, Promote);
446
447 setOperationAction(ISD::SDIV, MVT::i16, Promote);
448 setOperationAction(ISD::UDIV, MVT::i16, Promote);
449 setOperationAction(ISD::SREM, MVT::i16, Promote);
450 setOperationAction(ISD::UREM, MVT::i16, Promote);
451
452 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
453 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
454
455 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
456 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
457 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
458 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
459 setOperationAction(ISD::CTPOP, MVT::i16, Promote);
460
461 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
462
463 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
464
465 setOperationAction(ISD::LOAD, MVT::i16, Custom);
466
467 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
468
469 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
470 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
471 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
472 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
473
474 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
475 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
476 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
477 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
478
479 // F16 - Constant Actions.
480 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
481
482 // F16 - Load/Store Actions.
483 setOperationAction(ISD::LOAD, MVT::f16, Promote);
484 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
485 setOperationAction(ISD::STORE, MVT::f16, Promote);
486 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
487
488 // F16 - VOP1 Actions.
489 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
490 setOperationAction(ISD::FCOS, MVT::f16, Promote);
491 setOperationAction(ISD::FSIN, MVT::f16, Promote);
492 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
493 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
494 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
495 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
496 setOperationAction(ISD::FROUND, MVT::f16, Custom);
497
498 // F16 - VOP2 Actions.
499 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
500 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
501
502 setOperationAction(ISD::FDIV, MVT::f16, Custom);
503
504 // F16 - VOP3 Actions.
505 setOperationAction(ISD::FMA, MVT::f16, Legal);
506 if (!Subtarget->hasFP16Denormals() && STI.hasMadF16())
507 setOperationAction(ISD::FMAD, MVT::f16, Legal);
508
509 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
510 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
511 switch (Op) {
512 case ISD::LOAD:
513 case ISD::STORE:
514 case ISD::BUILD_VECTOR:
515 case ISD::BITCAST:
516 case ISD::EXTRACT_VECTOR_ELT:
517 case ISD::INSERT_VECTOR_ELT:
518 case ISD::INSERT_SUBVECTOR:
519 case ISD::EXTRACT_SUBVECTOR:
520 case ISD::SCALAR_TO_VECTOR:
521 break;
522 case ISD::CONCAT_VECTORS:
523 setOperationAction(Op, VT, Custom);
524 break;
525 default:
526 setOperationAction(Op, VT, Expand);
527 break;
528 }
529 }
530 }
531
532 // XXX - Do these do anything? Vector constants turn into build_vector.
533 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
534 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
535
536 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
537 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
538
539 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
540 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
541 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
542 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
543
544 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
545 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
546 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
547 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
548
549 setOperationAction(ISD::AND, MVT::v2i16, Promote);
550 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
551 setOperationAction(ISD::OR, MVT::v2i16, Promote);
552 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
553 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
554 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
555
556 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
557 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
558 setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
559 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
560
561 setOperationAction(ISD::STORE, MVT::v4i16, Promote);
562 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
563 setOperationAction(ISD::STORE, MVT::v4f16, Promote);
564 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
565
566 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
567 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
568 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
569 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
570
571 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
572 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
573 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
574
575 if (!Subtarget->hasVOP3PInsts()) {
576 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
577 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
578 }
579
580 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
581 // This isn't really legal, but this avoids the legalizer unrolling it (and
582 // allows matching fneg (fabs x) patterns)
583 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
584
585 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
586 setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
587 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
588 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
589
590 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
591 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
592
593 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
594 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
595 }
596
597 if (Subtarget->hasVOP3PInsts()) {
598 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
599 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
600 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
601 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
602 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
603 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
604 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
605 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
606 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
607 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
608
609 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
610 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
611 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
612
613 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
614 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
615
616 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
617
618 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
619 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
620
621 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
622 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
623
624 setOperationAction(ISD::SHL, MVT::v4i16, Custom);
625 setOperationAction(ISD::SRA, MVT::v4i16, Custom);
626 setOperationAction(ISD::SRL, MVT::v4i16, Custom);
627 setOperationAction(ISD::ADD, MVT::v4i16, Custom);
628 setOperationAction(ISD::SUB, MVT::v4i16, Custom);
629 setOperationAction(ISD::MUL, MVT::v4i16, Custom);
630
631 setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
632 setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
633 setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
634 setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
635
636 setOperationAction(ISD::FADD, MVT::v4f16, Custom);
637 setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
638 setOperationAction(ISD::FMA, MVT::v4f16, Custom);
639
640 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
641 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
642
643 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
644 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
645 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
646
647 setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
648 setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
649 setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
650 }
651
652 setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
653 setOperationAction(ISD::FABS, MVT::v4f16, Custom);
654
655 if (Subtarget->has16BitInsts()) {
656 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
657 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
658 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
659 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
660 } else {
661 // Legalization hack.
662 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
663 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
664
665 setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
666 setOperationAction(ISD::FABS, MVT::v2f16, Custom);
667 }
668
669 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
670 setOperationAction(ISD::SELECT, VT, Custom);
671 }
672
673 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
674 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
675 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
676 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
677 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
678 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
679 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
680
681 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
682 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
683 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
684 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
685 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
686 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
687 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
688 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
689 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
690
691 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
692 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
693 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
694 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
695 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
696 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
697 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
698 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
699
700 setTargetDAGCombine(ISD::ADD);
701 setTargetDAGCombine(ISD::ADDCARRY);
702 setTargetDAGCombine(ISD::SUB);
703 setTargetDAGCombine(ISD::SUBCARRY);
704 setTargetDAGCombine(ISD::FADD);
705 setTargetDAGCombine(ISD::FSUB);
706 setTargetDAGCombine(ISD::FMINNUM);
707 setTargetDAGCombine(ISD::FMAXNUM);
708 setTargetDAGCombine(ISD::FMINNUM_IEEE);
709 setTargetDAGCombine(ISD::FMAXNUM_IEEE);
710 setTargetDAGCombine(ISD::FMA);
711 setTargetDAGCombine(ISD::SMIN);
712 setTargetDAGCombine(ISD::SMAX);
713 setTargetDAGCombine(ISD::UMIN);
714 setTargetDAGCombine(ISD::UMAX);
715 setTargetDAGCombine(ISD::SETCC);
716 setTargetDAGCombine(ISD::AND);
717 setTargetDAGCombine(ISD::OR);
718 setTargetDAGCombine(ISD::XOR);
719 setTargetDAGCombine(ISD::SINT_TO_FP);
720 setTargetDAGCombine(ISD::UINT_TO_FP);
721 setTargetDAGCombine(ISD::FCANONICALIZE);
722 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
723 setTargetDAGCombine(ISD::ZERO_EXTEND);
724 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
725 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
726 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
727
728 // All memory operations. Some folding on the pointer operand is done to help
729 // matching the constant offsets in the addressing modes.
730 setTargetDAGCombine(ISD::LOAD);
731 setTargetDAGCombine(ISD::STORE);
732 setTargetDAGCombine(ISD::ATOMIC_LOAD);
733 setTargetDAGCombine(ISD::ATOMIC_STORE);
734 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
735 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
736 setTargetDAGCombine(ISD::ATOMIC_SWAP);
737 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
738 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
739 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
740 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
741 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
742 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
743 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
744 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
745 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
746 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
747 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
748
749 setSchedulingPreference(Sched::RegPressure);
750}
751
752const GCNSubtarget *SITargetLowering::getSubtarget() const {
753 return Subtarget;
754}
755
756//===----------------------------------------------------------------------===//
757// TargetLowering queries
758//===----------------------------------------------------------------------===//
759
760// v_mad_mix* support a conversion from f16 to f32.
761//
762// There is only one special case when denormals are enabled we don't currently,
763// where this is OK to use.
764bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
765 EVT DestVT, EVT SrcVT) const {
766 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
767 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
768 DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
769 SrcVT.getScalarType() == MVT::f16;
770}
771
772bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
773 // SI has some legal vector types, but no legal vector operations. Say no
774 // shuffles are legal in order to prefer scalarizing some vector operations.
775 return false;
776}
777
778MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
779 CallingConv::ID CC,
780 EVT VT) const {
781 if (CC == CallingConv::AMDGPU_KERNEL)
782 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
783
784 if (VT.isVector()) {
785 EVT ScalarVT = VT.getScalarType();
786 unsigned Size = ScalarVT.getSizeInBits();
787 if (Size == 32)
788 return ScalarVT.getSimpleVT();
789
790 if (Size > 32)
791 return MVT::i32;
792
793 if (Size == 16 && Subtarget->has16BitInsts())
794 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
795 } else if (VT.getSizeInBits() > 32)
796 return MVT::i32;
797
798 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
799}
800
801unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
802 CallingConv::ID CC,
803 EVT VT) const {
804 if (CC == CallingConv::AMDGPU_KERNEL)
805 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
806
807 if (VT.isVector()) {
808 unsigned NumElts = VT.getVectorNumElements();
809 EVT ScalarVT = VT.getScalarType();
810 unsigned Size = ScalarVT.getSizeInBits();
811
812 if (Size == 32)
813 return NumElts;
814
815 if (Size > 32)
816 return NumElts * ((Size + 31) / 32);
817
818 if (Size == 16 && Subtarget->has16BitInsts())
819 return (NumElts + 1) / 2;
820 } else if (VT.getSizeInBits() > 32)
821 return (VT.getSizeInBits() + 31) / 32;
822
823 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
824}
825
826unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
827 LLVMContext &Context, CallingConv::ID CC,
828 EVT VT, EVT &IntermediateVT,
829 unsigned &NumIntermediates, MVT &RegisterVT) const {
830 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
831 unsigned NumElts = VT.getVectorNumElements();
832 EVT ScalarVT = VT.getScalarType();
833 unsigned Size = ScalarVT.getSizeInBits();
834 if (Size == 32) {
835 RegisterVT = ScalarVT.getSimpleVT();
836 IntermediateVT = RegisterVT;
837 NumIntermediates = NumElts;
838 return NumIntermediates;
839 }
840
841 if (Size > 32) {
842 RegisterVT = MVT::i32;
843 IntermediateVT = RegisterVT;
844 NumIntermediates = NumElts * ((Size + 31) / 32);
845 return NumIntermediates;
846 }
847
848 // FIXME: We should fix the ABI to be the same on targets without 16-bit
849 // support, but unless we can properly handle 3-vectors, it will be still be
850 // inconsistent.
851 if (Size == 16 && Subtarget->has16BitInsts()) {
852 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
853 IntermediateVT = RegisterVT;
854 NumIntermediates = (NumElts + 1) / 2;
855 return NumIntermediates;
856 }
857 }
858
859 return TargetLowering::getVectorTypeBreakdownForCallingConv(
860 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
861}
862
863static MVT memVTFromAggregate(Type *Ty) {
864 // Only limited forms of aggregate type currently expected.
865 assert(Ty->isStructTy() && "Expected struct type")((Ty->isStructTy() && "Expected struct type") ? static_cast
<void> (0) : __assert_fail ("Ty->isStructTy() && \"Expected struct type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 865, __PRETTY_FUNCTION__))
;
866
867
868 Type *ElementType = nullptr;
869 unsigned NumElts;
870 if (Ty->getContainedType(0)->isVectorTy()) {
871 VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0));
872 ElementType = VecComponent->getElementType();
873 NumElts = VecComponent->getNumElements();
874 } else {
875 ElementType = Ty->getContainedType(0);
876 NumElts = 1;
877 }
878
879 assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type")(((Ty->getContainedType(1) && Ty->getContainedType
(1)->isIntegerTy(32)) && "Expected int32 type") ? static_cast
<void> (0) : __assert_fail ("(Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && \"Expected int32 type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 879, __PRETTY_FUNCTION__))
;
880
881 // Calculate the size of the memVT type from the aggregate
882 unsigned Pow2Elts = 0;
883 unsigned ElementSize;
884 switch (ElementType->getTypeID()) {
885 default:
886 llvm_unreachable("Unknown type!")::llvm::llvm_unreachable_internal("Unknown type!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 886)
;
887 case Type::IntegerTyID:
888 ElementSize = cast<IntegerType>(ElementType)->getBitWidth();
889 break;
890 case Type::HalfTyID:
891 ElementSize = 16;
892 break;
893 case Type::FloatTyID:
894 ElementSize = 32;
895 break;
896 }
897 unsigned AdditionalElts = ElementSize == 16 ? 2 : 1;
898 Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts);
899
900 return MVT::getVectorVT(MVT::getVT(ElementType, false),
901 Pow2Elts);
902}
903
904bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
905 const CallInst &CI,
906 MachineFunction &MF,
907 unsigned IntrID) const {
908 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
909 AMDGPU::lookupRsrcIntrinsic(IntrID)) {
910 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
911 (Intrinsic::ID)IntrID);
912 if (Attr.hasFnAttribute(Attribute::ReadNone))
913 return false;
914
915 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
916
917 if (RsrcIntr->IsImage) {
918 Info.ptrVal = MFI->getImagePSV(
919 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
920 CI.getArgOperand(RsrcIntr->RsrcArg));
921 Info.align.reset();
922 } else {
923 Info.ptrVal = MFI->getBufferPSV(
924 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
925 CI.getArgOperand(RsrcIntr->RsrcArg));
926 }
927
928 Info.flags = MachineMemOperand::MODereferenceable;
929 if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
930 Info.opc = ISD::INTRINSIC_W_CHAIN;
931 Info.memVT = MVT::getVT(CI.getType(), true);
932 if (Info.memVT == MVT::Other) {
933 // Some intrinsics return an aggregate type - special case to work out
934 // the correct memVT
935 Info.memVT = memVTFromAggregate(CI.getType());
936 }
937 Info.flags |= MachineMemOperand::MOLoad;
938 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
939 Info.opc = ISD::INTRINSIC_VOID;
940 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
941 Info.flags |= MachineMemOperand::MOStore;
942 } else {
943 // Atomic
944 Info.opc = ISD::INTRINSIC_W_CHAIN;
945 Info.memVT = MVT::getVT(CI.getType());
946 Info.flags = MachineMemOperand::MOLoad |
947 MachineMemOperand::MOStore |
948 MachineMemOperand::MODereferenceable;
949
950 // XXX - Should this be volatile without known ordering?
951 Info.flags |= MachineMemOperand::MOVolatile;
952 }
953 return true;
954 }
955
956 switch (IntrID) {
957 case Intrinsic::amdgcn_atomic_inc:
958 case Intrinsic::amdgcn_atomic_dec:
959 case Intrinsic::amdgcn_ds_ordered_add:
960 case Intrinsic::amdgcn_ds_ordered_swap:
961 case Intrinsic::amdgcn_ds_fadd:
962 case Intrinsic::amdgcn_ds_fmin:
963 case Intrinsic::amdgcn_ds_fmax: {
964 Info.opc = ISD::INTRINSIC_W_CHAIN;
965 Info.memVT = MVT::getVT(CI.getType());
966 Info.ptrVal = CI.getOperand(0);
967 Info.align.reset();
968 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
969
970 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
971 if (!Vol->isZero())
972 Info.flags |= MachineMemOperand::MOVolatile;
973
974 return true;
975 }
976 case Intrinsic::amdgcn_buffer_atomic_fadd: {
977 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
978
979 Info.opc = ISD::INTRINSIC_VOID;
980 Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
981 Info.ptrVal = MFI->getBufferPSV(
982 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
983 CI.getArgOperand(1));
984 Info.align.reset();
985 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
986
987 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
988 if (!Vol || !Vol->isZero())
989 Info.flags |= MachineMemOperand::MOVolatile;
990
991 return true;
992 }
993 case Intrinsic::amdgcn_global_atomic_fadd: {
994 Info.opc = ISD::INTRINSIC_VOID;
995 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
996 ->getPointerElementType());
997 Info.ptrVal = CI.getOperand(0);
998 Info.align.reset();
999 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1000
1001 return true;
1002 }
1003 case Intrinsic::amdgcn_ds_append:
1004 case Intrinsic::amdgcn_ds_consume: {
1005 Info.opc = ISD::INTRINSIC_W_CHAIN;
1006 Info.memVT = MVT::getVT(CI.getType());
1007 Info.ptrVal = CI.getOperand(0);
1008 Info.align.reset();
1009 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1010
1011 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1012 if (!Vol->isZero())
1013 Info.flags |= MachineMemOperand::MOVolatile;
1014
1015 return true;
1016 }
1017 case Intrinsic::amdgcn_ds_gws_init:
1018 case Intrinsic::amdgcn_ds_gws_barrier:
1019 case Intrinsic::amdgcn_ds_gws_sema_v:
1020 case Intrinsic::amdgcn_ds_gws_sema_br:
1021 case Intrinsic::amdgcn_ds_gws_sema_p:
1022 case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1023 Info.opc = ISD::INTRINSIC_VOID;
1024
1025 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1026 Info.ptrVal =
1027 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1028
1029 // This is an abstract access, but we need to specify a type and size.
1030 Info.memVT = MVT::i32;
1031 Info.size = 4;
1032 Info.align = Align(4);
1033
1034 Info.flags = MachineMemOperand::MOStore;
1035 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1036 Info.flags = MachineMemOperand::MOLoad;
1037 return true;
1038 }
1039 default:
1040 return false;
1041 }
1042}
1043
1044bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1045 SmallVectorImpl<Value*> &Ops,
1046 Type *&AccessTy) const {
1047 switch (II->getIntrinsicID()) {
1048 case Intrinsic::amdgcn_atomic_inc:
1049 case Intrinsic::amdgcn_atomic_dec:
1050 case Intrinsic::amdgcn_ds_ordered_add:
1051 case Intrinsic::amdgcn_ds_ordered_swap:
1052 case Intrinsic::amdgcn_ds_fadd:
1053 case Intrinsic::amdgcn_ds_fmin:
1054 case Intrinsic::amdgcn_ds_fmax: {
1055 Value *Ptr = II->getArgOperand(0);
1056 AccessTy = II->getType();
1057 Ops.push_back(Ptr);
1058 return true;
1059 }
1060 default:
1061 return false;
1062 }
1063}
1064
1065bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1066 if (!Subtarget->hasFlatInstOffsets()) {
1067 // Flat instructions do not have offsets, and only have the register
1068 // address.
1069 return AM.BaseOffs == 0 && AM.Scale == 0;
1070 }
1071
1072 // GFX9 added a 13-bit signed offset. When using regular flat instructions,
1073 // the sign bit is ignored and is treated as a 12-bit unsigned offset.
1074
1075 // GFX10 shrinked signed offset to 12 bits. When using regular flat
1076 // instructions, the sign bit is also ignored and is treated as 11-bit
1077 // unsigned offset.
1078
1079 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
1080 return isUInt<11>(AM.BaseOffs) && AM.Scale == 0;
1081
1082 // Just r + i
1083 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
1084}
1085
1086bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1087 if (Subtarget->hasFlatGlobalInsts())
1088 return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
1089
1090 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1091 // Assume the we will use FLAT for all global memory accesses
1092 // on VI.
1093 // FIXME: This assumption is currently wrong. On VI we still use
1094 // MUBUF instructions for the r + i addressing mode. As currently
1095 // implemented, the MUBUF instructions only work on buffer < 4GB.
1096 // It may be possible to support > 4GB buffers with MUBUF instructions,
1097 // by setting the stride value in the resource descriptor which would
1098 // increase the size limit to (stride * 4GB). However, this is risky,
1099 // because it has never been validated.
1100 return isLegalFlatAddressingMode(AM);
1101 }
1102
1103 return isLegalMUBUFAddressingMode(AM);
1104}
1105
1106bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1107 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1108 // additionally can do r + r + i with addr64. 32-bit has more addressing
1109 // mode options. Depending on the resource constant, it can also do
1110 // (i64 r0) + (i32 r1) * (i14 i).
1111 //
1112 // Private arrays end up using a scratch buffer most of the time, so also
1113 // assume those use MUBUF instructions. Scratch loads / stores are currently
1114 // implemented as mubuf instructions with offen bit set, so slightly
1115 // different than the normal addr64.
1116 if (!isUInt<12>(AM.BaseOffs))
1117 return false;
1118
1119 // FIXME: Since we can split immediate into soffset and immediate offset,
1120 // would it make sense to allow any immediate?
1121
1122 switch (AM.Scale) {
1123 case 0: // r + i or just i, depending on HasBaseReg.
1124 return true;
1125 case 1:
1126 return true; // We have r + r or r + i.
1127 case 2:
1128 if (AM.HasBaseReg) {
1129 // Reject 2 * r + r.
1130 return false;
1131 }
1132
1133 // Allow 2 * r as r + r
1134 // Or 2 * r + i is allowed as r + r + i.
1135 return true;
1136 default: // Don't allow n * r
1137 return false;
1138 }
1139}
1140
1141bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1142 const AddrMode &AM, Type *Ty,
1143 unsigned AS, Instruction *I) const {
1144 // No global is ever allowed as a base.
1145 if (AM.BaseGV)
1146 return false;
1147
1148 if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1149 return isLegalGlobalAddressingMode(AM);
1150
1151 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1152 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1153 AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1154 // If the offset isn't a multiple of 4, it probably isn't going to be
1155 // correctly aligned.
1156 // FIXME: Can we get the real alignment here?
1157 if (AM.BaseOffs % 4 != 0)
1158 return isLegalMUBUFAddressingMode(AM);
1159
1160 // There are no SMRD extloads, so if we have to do a small type access we
1161 // will use a MUBUF load.
1162 // FIXME?: We also need to do this if unaligned, but we don't know the
1163 // alignment here.
1164 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1165 return isLegalGlobalAddressingMode(AM);
1166
1167 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1168 // SMRD instructions have an 8-bit, dword offset on SI.
1169 if (!isUInt<8>(AM.BaseOffs / 4))
1170 return false;
1171 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1172 // On CI+, this can also be a 32-bit literal constant offset. If it fits
1173 // in 8-bits, it can use a smaller encoding.
1174 if (!isUInt<32>(AM.BaseOffs / 4))
1175 return false;
1176 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1177 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1178 if (!isUInt<20>(AM.BaseOffs))
1179 return false;
1180 } else
1181 llvm_unreachable("unhandled generation")::llvm::llvm_unreachable_internal("unhandled generation", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1181)
;
1182
1183 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1184 return true;
1185
1186 if (AM.Scale == 1 && AM.HasBaseReg)
1187 return true;
1188
1189 return false;
1190
1191 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1192 return isLegalMUBUFAddressingMode(AM);
1193 } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1194 AS == AMDGPUAS::REGION_ADDRESS) {
1195 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1196 // field.
1197 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1198 // an 8-bit dword offset but we don't know the alignment here.
1199 if (!isUInt<16>(AM.BaseOffs))
1200 return false;
1201
1202 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1203 return true;
1204
1205 if (AM.Scale == 1 && AM.HasBaseReg)
1206 return true;
1207
1208 return false;
1209 } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1210 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1211 // For an unknown address space, this usually means that this is for some
1212 // reason being used for pure arithmetic, and not based on some addressing
1213 // computation. We don't have instructions that compute pointers with any
1214 // addressing modes, so treat them as having no offset like flat
1215 // instructions.
1216 return isLegalFlatAddressingMode(AM);
1217 } else {
1218 llvm_unreachable("unhandled address space")::llvm::llvm_unreachable_internal("unhandled address space", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1218)
;
1219 }
1220}
1221
1222bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1223 const SelectionDAG &DAG) const {
1224 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1225 return (MemVT.getSizeInBits() <= 4 * 32);
1226 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1227 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1228 return (MemVT.getSizeInBits() <= MaxPrivateBits);
1229 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1230 return (MemVT.getSizeInBits() <= 2 * 32);
1231 }
1232 return true;
1233}
1234
1235bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1236 unsigned Size, unsigned AddrSpace, unsigned Align,
1237 MachineMemOperand::Flags Flags, bool *IsFast) const {
1238 if (IsFast)
1239 *IsFast = false;
1240
1241 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1242 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1243 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1244 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1245 // with adjacent offsets.
1246 bool AlignedBy4 = (Align % 4 == 0);
1247 if (IsFast)
1248 *IsFast = AlignedBy4;
1249
1250 return AlignedBy4;
1251 }
1252
1253 // FIXME: We have to be conservative here and assume that flat operations
1254 // will access scratch. If we had access to the IR function, then we
1255 // could determine if any private memory was used in the function.
1256 if (!Subtarget->hasUnalignedScratchAccess() &&
1257 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1258 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1259 bool AlignedBy4 = Align >= 4;
1260 if (IsFast)
1261 *IsFast = AlignedBy4;
1262
1263 return AlignedBy4;
1264 }
1265
1266 if (Subtarget->hasUnalignedBufferAccess()) {
1267 // If we have an uniform constant load, it still requires using a slow
1268 // buffer instruction if unaligned.
1269 if (IsFast) {
1270 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1271 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1272 (Align % 4 == 0) : true;
1273 }
1274
1275 return true;
1276 }
1277
1278 // Smaller than dword value must be aligned.
1279 if (Size < 32)
1280 return false;
1281
1282 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1283 // byte-address are ignored, thus forcing Dword alignment.
1284 // This applies to private, global, and constant memory.
1285 if (IsFast)
1286 *IsFast = true;
1287
1288 return Size >= 32 && Align >= 4;
1289}
1290
1291bool SITargetLowering::allowsMisalignedMemoryAccesses(
1292 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1293 bool *IsFast) const {
1294 if (IsFast)
1295 *IsFast = false;
1296
1297 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1298 // which isn't a simple VT.
1299 // Until MVT is extended to handle this, simply check for the size and
1300 // rely on the condition below: allow accesses if the size is a multiple of 4.
1301 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1302 VT.getStoreSize() > 16)) {
1303 return false;
1304 }
1305
1306 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1307 Align, Flags, IsFast);
1308}
1309
1310EVT SITargetLowering::getOptimalMemOpType(
1311 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
1312 bool ZeroMemset, bool MemcpyStrSrc,
1313 const AttributeList &FuncAttributes) const {
1314 // FIXME: Should account for address space here.
1315
1316 // The default fallback uses the private pointer size as a guess for a type to
1317 // use. Make sure we switch these to 64-bit accesses.
1318
1319 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1320 return MVT::v4i32;
1321
1322 if (Size >= 8 && DstAlign >= 4)
1323 return MVT::v2i32;
1324
1325 // Use the default.
1326 return MVT::Other;
1327}
1328
1329bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1330 unsigned DestAS) const {
1331 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1332}
1333
1334bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1335 const MemSDNode *MemNode = cast<MemSDNode>(N);
1336 const Value *Ptr = MemNode->getMemOperand()->getValue();
1337 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1338 return I && I->getMetadata("amdgpu.noclobber");
1339}
1340
1341bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1342 unsigned DestAS) const {
1343 // Flat -> private/local is a simple truncate.
1344 // Flat -> global is no-op
1345 if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1346 return true;
1347
1348 return isNoopAddrSpaceCast(SrcAS, DestAS);
1349}
1350
1351bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1352 const MemSDNode *MemNode = cast<MemSDNode>(N);
1353
1354 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1355}
1356
1357TargetLoweringBase::LegalizeTypeAction
1358SITargetLowering::getPreferredVectorAction(MVT VT) const {
1359 int NumElts = VT.getVectorNumElements();
1360 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1361 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1362 return TargetLoweringBase::getPreferredVectorAction(VT);
1363}
1364
1365bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1366 Type *Ty) const {
1367 // FIXME: Could be smarter if called for vector constants.
1368 return true;
1369}
1370
1371bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1372 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1373 switch (Op) {
1374 case ISD::LOAD:
1375 case ISD::STORE:
1376
1377 // These operations are done with 32-bit instructions anyway.
1378 case ISD::AND:
1379 case ISD::OR:
1380 case ISD::XOR:
1381 case ISD::SELECT:
1382 // TODO: Extensions?
1383 return true;
1384 default:
1385 return false;
1386 }
1387 }
1388
1389 // SimplifySetCC uses this function to determine whether or not it should
1390 // create setcc with i1 operands. We don't have instructions for i1 setcc.
1391 if (VT == MVT::i1 && Op == ISD::SETCC)
1392 return false;
1393
1394 return TargetLowering::isTypeDesirableForOp(Op, VT);
1395}
1396
1397SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1398 const SDLoc &SL,
1399 SDValue Chain,
1400 uint64_t Offset) const {
1401 const DataLayout &DL = DAG.getDataLayout();
1402 MachineFunction &MF = DAG.getMachineFunction();
1403 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1404
1405 const ArgDescriptor *InputPtrReg;
1406 const TargetRegisterClass *RC;
1407
1408 std::tie(InputPtrReg, RC)
1409 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1410
1411 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1412 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1413 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1414 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1415
1416 return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1417}
1418
1419SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1420 const SDLoc &SL) const {
1421 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1422 FIRST_IMPLICIT);
1423 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1424}
1425
1426SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1427 const SDLoc &SL, SDValue Val,
1428 bool Signed,
1429 const ISD::InputArg *Arg) const {
1430 // First, if it is a widened vector, narrow it.
1431 if (VT.isVector() &&
1432 VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1433 EVT NarrowedVT =
1434 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1435 VT.getVectorNumElements());
1436 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1437 DAG.getConstant(0, SL, MVT::i32));
1438 }
1439
1440 // Then convert the vector elements or scalar value.
1441 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1442 VT.bitsLT(MemVT)) {
1443 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1444 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1445 }
1446
1447 if (MemVT.isFloatingPoint())
1448 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1449 else if (Signed)
1450 Val = DAG.getSExtOrTrunc(Val, SL, VT);
1451 else
1452 Val = DAG.getZExtOrTrunc(Val, SL, VT);
1453
1454 return Val;
1455}
1456
1457SDValue SITargetLowering::lowerKernargMemParameter(
1458 SelectionDAG &DAG, EVT VT, EVT MemVT,
1459 const SDLoc &SL, SDValue Chain,
1460 uint64_t Offset, unsigned Align, bool Signed,
1461 const ISD::InputArg *Arg) const {
1462 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1463 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
1464 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1465
1466 // Try to avoid using an extload by loading earlier than the argument address,
1467 // and extracting the relevant bits. The load should hopefully be merged with
1468 // the previous argument.
1469 if (MemVT.getStoreSize() < 4 && Align < 4) {
1470 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1471 int64_t AlignDownOffset = alignDown(Offset, 4);
1472 int64_t OffsetDiff = Offset - AlignDownOffset;
1473
1474 EVT IntVT = MemVT.changeTypeToInteger();
1475
1476 // TODO: If we passed in the base kernel offset we could have a better
1477 // alignment than 4, but we don't really need it.
1478 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1479 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1480 MachineMemOperand::MODereferenceable |
1481 MachineMemOperand::MOInvariant);
1482
1483 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1484 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1485
1486 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1487 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1488 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1489
1490
1491 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1492 }
1493
1494 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1495 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1496 MachineMemOperand::MODereferenceable |
1497 MachineMemOperand::MOInvariant);
1498
1499 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1500 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1501}
1502
1503SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1504 const SDLoc &SL, SDValue Chain,
1505 const ISD::InputArg &Arg) const {
1506 MachineFunction &MF = DAG.getMachineFunction();
1507 MachineFrameInfo &MFI = MF.getFrameInfo();
1508
1509 if (Arg.Flags.isByVal()) {
1510 unsigned Size = Arg.Flags.getByValSize();
1511 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1512 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1513 }
1514
1515 unsigned ArgOffset = VA.getLocMemOffset();
1516 unsigned ArgSize = VA.getValVT().getStoreSize();
1517
1518 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1519
1520 // Create load nodes to retrieve arguments from the stack.
1521 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1522 SDValue ArgValue;
1523
1524 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1525 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1526 MVT MemVT = VA.getValVT();
1527
1528 switch (VA.getLocInfo()) {
1529 default:
1530 break;
1531 case CCValAssign::BCvt:
1532 MemVT = VA.getLocVT();
1533 break;
1534 case CCValAssign::SExt:
1535 ExtType = ISD::SEXTLOAD;
1536 break;
1537 case CCValAssign::ZExt:
1538 ExtType = ISD::ZEXTLOAD;
1539 break;
1540 case CCValAssign::AExt:
1541 ExtType = ISD::EXTLOAD;
1542 break;
1543 }
1544
1545 ArgValue = DAG.getExtLoad(
1546 ExtType, SL, VA.getLocVT(), Chain, FIN,
1547 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1548 MemVT);
1549 return ArgValue;
1550}
1551
1552SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1553 const SIMachineFunctionInfo &MFI,
1554 EVT VT,
1555 AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1556 const ArgDescriptor *Reg;
1557 const TargetRegisterClass *RC;
1558
1559 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1560 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1561}
1562
1563static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1564 CallingConv::ID CallConv,
1565 ArrayRef<ISD::InputArg> Ins,
1566 BitVector &Skipped,
1567 FunctionType *FType,
1568 SIMachineFunctionInfo *Info) {
1569 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1570 const ISD::InputArg *Arg = &Ins[I];
1571
1572 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&(((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits()
== 16) && "vector type argument should have been split"
) ? static_cast<void> (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"vector type argument should have been split\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1573, __PRETTY_FUNCTION__))
1573 "vector type argument should have been split")(((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits()
== 16) && "vector type argument should have been split"
) ? static_cast<void> (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"vector type argument should have been split\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1573, __PRETTY_FUNCTION__))
;
1574
1575 // First check if it's a PS input addr.
1576 if (CallConv == CallingConv::AMDGPU_PS &&
1577 !Arg->Flags.isInReg() && PSInputNum <= 15) {
1578 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1579
1580 // Inconveniently only the first part of the split is marked as isSplit,
1581 // so skip to the end. We only want to increment PSInputNum once for the
1582 // entire split argument.
1583 if (Arg->Flags.isSplit()) {
1584 while (!Arg->Flags.isSplitEnd()) {
1585 assert((!Arg->VT.isVector() ||(((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits()
== 16) && "unexpected vector split in ps argument type"
) ? static_cast<void> (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"unexpected vector split in ps argument type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1587, __PRETTY_FUNCTION__))
1586 Arg->VT.getScalarSizeInBits() == 16) &&(((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits()
== 16) && "unexpected vector split in ps argument type"
) ? static_cast<void> (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"unexpected vector split in ps argument type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1587, __PRETTY_FUNCTION__))
1587 "unexpected vector split in ps argument type")(((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits()
== 16) && "unexpected vector split in ps argument type"
) ? static_cast<void> (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"unexpected vector split in ps argument type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1587, __PRETTY_FUNCTION__))
;
1588 if (!SkipArg)
1589 Splits.push_back(*Arg);
1590 Arg = &Ins[++I];
1591 }
1592 }
1593
1594 if (SkipArg) {
1595 // We can safely skip PS inputs.
1596 Skipped.set(Arg->getOrigArgIndex());
1597 ++PSInputNum;
1598 continue;
1599 }
1600
1601 Info->markPSInputAllocated(PSInputNum);
1602 if (Arg->Used)
1603 Info->markPSInputEnabled(PSInputNum);
1604
1605 ++PSInputNum;
1606 }
1607
1608 Splits.push_back(*Arg);
1609 }
1610}
1611
1612// Allocate special inputs passed in VGPRs.
1613void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1614 MachineFunction &MF,
1615 const SIRegisterInfo &TRI,
1616 SIMachineFunctionInfo &Info) const {
1617 const LLT S32 = LLT::scalar(32);
1618 MachineRegisterInfo &MRI = MF.getRegInfo();
1619
1620 if (Info.hasWorkItemIDX()) {
1621 Register Reg = AMDGPU::VGPR0;
1622 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1623
1624 CCInfo.AllocateReg(Reg);
1625 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1626 }
1627
1628 if (Info.hasWorkItemIDY()) {
1629 Register Reg = AMDGPU::VGPR1;
1630 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1631
1632 CCInfo.AllocateReg(Reg);
1633 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1634 }
1635
1636 if (Info.hasWorkItemIDZ()) {
1637 Register Reg = AMDGPU::VGPR2;
1638 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1639
1640 CCInfo.AllocateReg(Reg);
1641 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1642 }
1643}
1644
1645// Try to allocate a VGPR at the end of the argument list, or if no argument
1646// VGPRs are left allocating a stack slot.
1647// If \p Mask is is given it indicates bitfield position in the register.
1648// If \p Arg is given use it with new ]p Mask instead of allocating new.
1649static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1650 ArgDescriptor Arg = ArgDescriptor()) {
1651 if (Arg.isSet())
1652 return ArgDescriptor::createArg(Arg, Mask);
1653
1654 ArrayRef<MCPhysReg> ArgVGPRs
1655 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1656 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1657 if (RegIdx == ArgVGPRs.size()) {
1658 // Spill to stack required.
1659 int64_t Offset = CCInfo.AllocateStack(4, 4);
1660
1661 return ArgDescriptor::createStack(Offset, Mask);
1662 }
1663
1664 unsigned Reg = ArgVGPRs[RegIdx];
1665 Reg = CCInfo.AllocateReg(Reg);
1666 assert(Reg != AMDGPU::NoRegister)((Reg != AMDGPU::NoRegister) ? static_cast<void> (0) : __assert_fail
("Reg != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1666, __PRETTY_FUNCTION__))
;
1667
1668 MachineFunction &MF = CCInfo.getMachineFunction();
1669 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1670 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1671 return ArgDescriptor::createRegister(Reg, Mask);
1672}
1673
1674static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1675 const TargetRegisterClass *RC,
1676 unsigned NumArgRegs) {
1677 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1678 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1679 if (RegIdx == ArgSGPRs.size())
1680 report_fatal_error("ran out of SGPRs for arguments");
1681
1682 unsigned Reg = ArgSGPRs[RegIdx];
1683 Reg = CCInfo.AllocateReg(Reg);
1684 assert(Reg != AMDGPU::NoRegister)((Reg != AMDGPU::NoRegister) ? static_cast<void> (0) : __assert_fail
("Reg != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1684, __PRETTY_FUNCTION__))
;
1685
1686 MachineFunction &MF = CCInfo.getMachineFunction();
1687 MF.addLiveIn(Reg, RC);
1688 return ArgDescriptor::createRegister(Reg);
1689}
1690
1691static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1692 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1693}
1694
1695static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1696 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1697}
1698
1699void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo,
1700 MachineFunction &MF,
1701 const SIRegisterInfo &TRI,
1702 SIMachineFunctionInfo &Info) const {
1703 const unsigned Mask = 0x3ff;
1704 ArgDescriptor Arg;
1705
1706 if (Info.hasWorkItemIDX()) {
1707 Arg = allocateVGPR32Input(CCInfo, Mask);
1708 Info.setWorkItemIDX(Arg);
1709 }
1710
1711 if (Info.hasWorkItemIDY()) {
1712 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1713 Info.setWorkItemIDY(Arg);
1714 }
1715
1716 if (Info.hasWorkItemIDZ())
1717 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1718}
1719
1720void SITargetLowering::allocateSpecialInputSGPRs(
1721 CCState &CCInfo,
1722 MachineFunction &MF,
1723 const SIRegisterInfo &TRI,
1724 SIMachineFunctionInfo &Info) const {
1725 auto &ArgInfo = Info.getArgInfo();
1726
1727 // TODO: Unify handling with private memory pointers.
1728
1729 if (Info.hasDispatchPtr())
1730 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1731
1732 if (Info.hasQueuePtr())
1733 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1734
1735 if (Info.hasKernargSegmentPtr())
1736 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1737
1738 if (Info.hasDispatchID())
1739 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1740
1741 // flat_scratch_init is not applicable for non-kernel functions.
1742
1743 if (Info.hasWorkGroupIDX())
1744 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1745
1746 if (Info.hasWorkGroupIDY())
1747 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1748
1749 if (Info.hasWorkGroupIDZ())
1750 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1751
1752 if (Info.hasImplicitArgPtr())
1753 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1754}
1755
1756// Allocate special inputs passed in user SGPRs.
1757void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1758 MachineFunction &MF,
1759 const SIRegisterInfo &TRI,
1760 SIMachineFunctionInfo &Info) const {
1761 if (Info.hasImplicitBufferPtr()) {
1762 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1763 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1764 CCInfo.AllocateReg(ImplicitBufferPtrReg);
1765 }
1766
1767 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1768 if (Info.hasPrivateSegmentBuffer()) {
1769 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1770 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1771 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1772 }
1773
1774 if (Info.hasDispatchPtr()) {
1775 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1776 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1777 CCInfo.AllocateReg(DispatchPtrReg);
1778 }
1779
1780 if (Info.hasQueuePtr()) {
1781 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1782 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1783 CCInfo.AllocateReg(QueuePtrReg);
1784 }
1785
1786 if (Info.hasKernargSegmentPtr()) {
1787 MachineRegisterInfo &MRI = MF.getRegInfo();
1788 Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1789 CCInfo.AllocateReg(InputPtrReg);
1790
1791 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1792 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1793 }
1794
1795 if (Info.hasDispatchID()) {
1796 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1797 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1798 CCInfo.AllocateReg(DispatchIDReg);
1799 }
1800
1801 if (Info.hasFlatScratchInit()) {
1802 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1803 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1804 CCInfo.AllocateReg(FlatScratchInitReg);
1805 }
1806
1807 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1808 // these from the dispatch pointer.
1809}
1810
1811// Allocate special input registers that are initialized per-wave.
1812void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1813 MachineFunction &MF,
1814 SIMachineFunctionInfo &Info,
1815 CallingConv::ID CallConv,
1816 bool IsShader) const {
1817 if (Info.hasWorkGroupIDX()) {
1818 unsigned Reg = Info.addWorkGroupIDX();
1819 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1820 CCInfo.AllocateReg(Reg);
1821 }
1822
1823 if (Info.hasWorkGroupIDY()) {
1824 unsigned Reg = Info.addWorkGroupIDY();
1825 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1826 CCInfo.AllocateReg(Reg);
1827 }
1828
1829 if (Info.hasWorkGroupIDZ()) {
1830 unsigned Reg = Info.addWorkGroupIDZ();
1831 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1832 CCInfo.AllocateReg(Reg);
1833 }
1834
1835 if (Info.hasWorkGroupInfo()) {
1836 unsigned Reg = Info.addWorkGroupInfo();
1837 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1838 CCInfo.AllocateReg(Reg);
1839 }
1840
1841 if (Info.hasPrivateSegmentWaveByteOffset()) {
1842 // Scratch wave offset passed in system SGPR.
1843 unsigned PrivateSegmentWaveByteOffsetReg;
1844
1845 if (IsShader) {
1846 PrivateSegmentWaveByteOffsetReg =
1847 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1848
1849 // This is true if the scratch wave byte offset doesn't have a fixed
1850 // location.
1851 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1852 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1853 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1854 }
1855 } else
1856 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1857
1858 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1859 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1860 }
1861}
1862
1863static void reservePrivateMemoryRegs(const TargetMachine &TM,
1864 MachineFunction &MF,
1865 const SIRegisterInfo &TRI,
1866 SIMachineFunctionInfo &Info) {
1867 // Now that we've figured out where the scratch register inputs are, see if
1868 // should reserve the arguments and use them directly.
1869 MachineFrameInfo &MFI = MF.getFrameInfo();
1870 bool HasStackObjects = MFI.hasStackObjects();
1871 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1872
1873 // Record that we know we have non-spill stack objects so we don't need to
1874 // check all stack objects later.
1875 if (HasStackObjects)
1876 Info.setHasNonSpillStackObjects(true);
1877
1878 // Everything live out of a block is spilled with fast regalloc, so it's
1879 // almost certain that spilling will be required.
1880 if (TM.getOptLevel() == CodeGenOpt::None)
1881 HasStackObjects = true;
1882
1883 // For now assume stack access is needed in any callee functions, so we need
1884 // the scratch registers to pass in.
1885 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1886
1887 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1888 // If we have stack objects, we unquestionably need the private buffer
1889 // resource. For the Code Object V2 ABI, this will be the first 4 user
1890 // SGPR inputs. We can reserve those and use them directly.
1891
1892 Register PrivateSegmentBufferReg =
1893 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1894 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1895 } else {
1896 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1897 // We tentatively reserve the last registers (skipping the last registers
1898 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1899 // we'll replace these with the ones immediately after those which were
1900 // really allocated. In the prologue copies will be inserted from the
1901 // argument to these reserved registers.
1902
1903 // Without HSA, relocations are used for the scratch pointer and the
1904 // buffer resource setup is always inserted in the prologue. Scratch wave
1905 // offset is still in an input SGPR.
1906 Info.setScratchRSrcReg(ReservedBufferReg);
1907 }
1908
1909 // hasFP should be accurate for kernels even before the frame is finalized.
1910 if (ST.getFrameLowering()->hasFP(MF)) {
1911 MachineRegisterInfo &MRI = MF.getRegInfo();
1912
1913 // Try to use s32 as the SP, but move it if it would interfere with input
1914 // arguments. This won't work with calls though.
1915 //
1916 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1917 // registers.
1918 if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1919 Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1920 } else {
1921 assert(AMDGPU::isShader(MF.getFunction().getCallingConv()))((AMDGPU::isShader(MF.getFunction().getCallingConv())) ? static_cast
<void> (0) : __assert_fail ("AMDGPU::isShader(MF.getFunction().getCallingConv())"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1921, __PRETTY_FUNCTION__))
;
1922
1923 if (MFI.hasCalls())
1924 report_fatal_error("call in graphics shader with too many input SGPRs");
1925
1926 for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1927 if (!MRI.isLiveIn(Reg)) {
1928 Info.setStackPtrOffsetReg(Reg);
1929 break;
1930 }
1931 }
1932
1933 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1934 report_fatal_error("failed to find register for SP");
1935 }
1936
1937 if (MFI.hasCalls()) {
1938 Info.setScratchWaveOffsetReg(AMDGPU::SGPR33);
1939 Info.setFrameOffsetReg(AMDGPU::SGPR33);
1940 } else {
1941 unsigned ReservedOffsetReg =
1942 TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1943 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1944 Info.setFrameOffsetReg(ReservedOffsetReg);
1945 }
1946 } else if (RequiresStackAccess) {
1947 assert(!MFI.hasCalls())((!MFI.hasCalls()) ? static_cast<void> (0) : __assert_fail
("!MFI.hasCalls()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1947, __PRETTY_FUNCTION__))
;
1948 // We know there are accesses and they will be done relative to SP, so just
1949 // pin it to the input.
1950 //
1951 // FIXME: Should not do this if inline asm is reading/writing these
1952 // registers.
1953 Register PreloadedSP = Info.getPreloadedReg(
1954 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1955
1956 Info.setStackPtrOffsetReg(PreloadedSP);
1957 Info.setScratchWaveOffsetReg(PreloadedSP);
1958 Info.setFrameOffsetReg(PreloadedSP);
1959 } else {
1960 assert(!MFI.hasCalls())((!MFI.hasCalls()) ? static_cast<void> (0) : __assert_fail
("!MFI.hasCalls()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1960, __PRETTY_FUNCTION__))
;
1961
1962 // There may not be stack access at all. There may still be spills, or
1963 // access of a constant pointer (in which cases an extra copy will be
1964 // emitted in the prolog).
1965 unsigned ReservedOffsetReg
1966 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1967 Info.setStackPtrOffsetReg(ReservedOffsetReg);
1968 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1969 Info.setFrameOffsetReg(ReservedOffsetReg);
1970 }
1971}
1972
1973bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1974 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1975 return !Info->isEntryFunction();
1976}
1977
1978void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1979
1980}
1981
1982void SITargetLowering::insertCopiesSplitCSR(
1983 MachineBasicBlock *Entry,
1984 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1985 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1986
1987 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1988 if (!IStart)
1989 return;
1990
1991 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1992 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1993 MachineBasicBlock::iterator MBBI = Entry->begin();
1994 for (const MCPhysReg *I = IStart; *I; ++I) {
1995 const TargetRegisterClass *RC = nullptr;
1996 if (AMDGPU::SReg_64RegClass.contains(*I))
1997 RC = &AMDGPU::SGPR_64RegClass;
1998 else if (AMDGPU::SReg_32RegClass.contains(*I))
1999 RC = &AMDGPU::SGPR_32RegClass;
2000 else
2001 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2001)
;
2002
2003 Register NewVR = MRI->createVirtualRegister(RC);
2004 // Create copy from CSR to a virtual register.
2005 Entry->addLiveIn(*I);
2006 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2007 .addReg(*I);
2008
2009 // Insert the copy-back instructions right before the terminator.
2010 for (auto *Exit : Exits)
2011 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2012 TII->get(TargetOpcode::COPY), *I)
2013 .addReg(NewVR);
2014 }
2015}
2016
2017SDValue SITargetLowering::LowerFormalArguments(
2018 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2019 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2020 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2021 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2022
2023 MachineFunction &MF = DAG.getMachineFunction();
2024 const Function &Fn = MF.getFunction();
2025 FunctionType *FType = MF.getFunction().getFunctionType();
2026 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2027
2028 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2029 DiagnosticInfoUnsupported NoGraphicsHSA(
2030 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2031 DAG.getContext()->diagnose(NoGraphicsHSA);
2032 return DAG.getEntryNode();
2033 }
2034
2035 SmallVector<ISD::InputArg, 16> Splits;
2036 SmallVector<CCValAssign, 16> ArgLocs;
2037 BitVector Skipped(Ins.size());
2038 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2039 *DAG.getContext());
2040
2041 bool IsShader = AMDGPU::isShader(CallConv);
2042 bool IsKernel = AMDGPU::isKernel(CallConv);
2043 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2044
2045 if (IsShader) {
2046 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2047
2048 // At least one interpolation mode must be enabled or else the GPU will
2049 // hang.
2050 //
2051 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2052 // set PSInputAddr, the user wants to enable some bits after the compilation
2053 // based on run-time states. Since we can't know what the final PSInputEna
2054 // will look like, so we shouldn't do anything here and the user should take
2055 // responsibility for the correct programming.
2056 //
2057 // Otherwise, the following restrictions apply:
2058 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2059 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2060 // enabled too.
2061 if (CallConv == CallingConv::AMDGPU_PS) {
2062 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2063 ((Info->getPSInputAddr() & 0xF) == 0 &&
2064 Info->isPSInputAllocated(11))) {
2065 CCInfo.AllocateReg(AMDGPU::VGPR0);
2066 CCInfo.AllocateReg(AMDGPU::VGPR1);
2067 Info->markPSInputAllocated(0);
2068 Info->markPSInputEnabled(0);
2069 }
2070 if (Subtarget->isAmdPalOS()) {
2071 // For isAmdPalOS, the user does not enable some bits after compilation
2072 // based on run-time states; the register values being generated here are
2073 // the final ones set in hardware. Therefore we need to apply the
2074 // workaround to PSInputAddr and PSInputEnable together. (The case where
2075 // a bit is set in PSInputAddr but not PSInputEnable is where the
2076 // frontend set up an input arg for a particular interpolation mode, but
2077 // nothing uses that input arg. Really we should have an earlier pass
2078 // that removes such an arg.)
2079 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2080 if ((PsInputBits & 0x7F) == 0 ||
2081 ((PsInputBits & 0xF) == 0 &&
2082 (PsInputBits >> 11 & 1)))
2083 Info->markPSInputEnabled(
2084 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2085 }
2086 }
2087
2088 assert(!Info->hasDispatchPtr() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && !Info->hasFlatScratchInit() && !Info
->hasWorkGroupIDX() && !Info->hasWorkGroupIDY()
&& !Info->hasWorkGroupIDZ() && !Info->
hasWorkGroupInfo() && !Info->hasWorkItemIDX() &&
!Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ
()) ? static_cast<void> (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2093, __PRETTY_FUNCTION__))
2089 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && !Info->hasFlatScratchInit() && !Info
->hasWorkGroupIDX() && !Info->hasWorkGroupIDY()
&& !Info->hasWorkGroupIDZ() && !Info->
hasWorkGroupInfo() && !Info->hasWorkItemIDX() &&
!Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ
()) ? static_cast<void> (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2093, __PRETTY_FUNCTION__))
2090 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && !Info->hasFlatScratchInit() && !Info
->hasWorkGroupIDX() && !Info->hasWorkGroupIDY()
&& !Info->hasWorkGroupIDZ() && !Info->
hasWorkGroupInfo() && !Info->hasWorkItemIDX() &&
!Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ
()) ? static_cast<void> (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2093, __PRETTY_FUNCTION__))
2091 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && !Info->hasFlatScratchInit() && !Info
->hasWorkGroupIDX() && !Info->hasWorkGroupIDY()
&& !Info->hasWorkGroupIDZ() && !Info->
hasWorkGroupInfo() && !Info->hasWorkItemIDX() &&
!Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ
()) ? static_cast<void> (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2093, __PRETTY_FUNCTION__))
2092 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && !Info->hasFlatScratchInit() && !Info
->hasWorkGroupIDX() && !Info->hasWorkGroupIDY()
&& !Info->hasWorkGroupIDZ() && !Info->
hasWorkGroupInfo() && !Info->hasWorkItemIDX() &&
!Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ
()) ? static_cast<void> (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2093, __PRETTY_FUNCTION__))
2093 !Info->hasWorkItemIDZ())((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && !Info->hasFlatScratchInit() && !Info
->hasWorkGroupIDX() && !Info->hasWorkGroupIDY()
&& !Info->hasWorkGroupIDZ() && !Info->
hasWorkGroupInfo() && !Info->hasWorkItemIDX() &&
!Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ
()) ? static_cast<void> (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2093, __PRETTY_FUNCTION__))
;
2094 } else if (IsKernel) {
2095 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX())((Info->hasWorkGroupIDX() && Info->hasWorkItemIDX
()) ? static_cast<void> (0) : __assert_fail ("Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2095, __PRETTY_FUNCTION__))
;
2096 } else {
2097 Splits.append(Ins.begin(), Ins.end());
2098 }
2099
2100 if (IsEntryFunc) {
2101 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2102 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2103 }
2104
2105 if (IsKernel) {
2106 analyzeFormalArgumentsCompute(CCInfo, Ins);
2107 } else {
2108 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2109 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2110 }
2111
2112 SmallVector<SDValue, 16> Chains;
2113
2114 // FIXME: This is the minimum kernel argument alignment. We should improve
2115 // this to the maximum alignment of the arguments.
2116 //
2117 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2118 // kern arg offset.
2119 const unsigned KernelArgBaseAlign = 16;
2120
2121 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2122 const ISD::InputArg &Arg = Ins[i];
2123 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2124 InVals.push_back(DAG.getUNDEF(Arg.VT));
2125 continue;
2126 }
2127
2128 CCValAssign &VA = ArgLocs[ArgIdx++];
2129 MVT VT = VA.getLocVT();
2130
2131 if (IsEntryFunc && VA.isMemLoc()) {
2132 VT = Ins[i].VT;
2133 EVT MemVT = VA.getLocVT();
2134
2135 const uint64_t Offset = VA.getLocMemOffset();
2136 unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2137
2138 SDValue Arg = lowerKernargMemParameter(
2139 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2140 Chains.push_back(Arg.getValue(1));
2141
2142 auto *ParamTy =
2143 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2144 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2145 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2146 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2147 // On SI local pointers are just offsets into LDS, so they are always
2148 // less than 16-bits. On CI and newer they could potentially be
2149 // real pointers, so we can't guarantee their size.
2150 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2151 DAG.getValueType(MVT::i16));
2152 }
2153
2154 InVals.push_back(Arg);
2155 continue;
2156 } else if (!IsEntryFunc && VA.isMemLoc()) {
2157 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2158 InVals.push_back(Val);
2159 if (!Arg.Flags.isByVal())
2160 Chains.push_back(Val.getValue(1));
2161 continue;
2162 }
2163
2164 assert(VA.isRegLoc() && "Parameter must be in a register!")((VA.isRegLoc() && "Parameter must be in a register!"
) ? static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && \"Parameter must be in a register!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2164, __PRETTY_FUNCTION__))
;
2165
2166 Register Reg = VA.getLocReg();
2167 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2168 EVT ValVT = VA.getValVT();
2169
2170 Reg = MF.addLiveIn(Reg, RC);
2171 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2172
2173 if (Arg.Flags.isSRet()) {
2174 // The return object should be reasonably addressable.
2175
2176 // FIXME: This helps when the return is a real sret. If it is a
2177 // automatically inserted sret (i.e. CanLowerReturn returns false), an
2178 // extra copy is inserted in SelectionDAGBuilder which obscures this.
2179 unsigned NumBits
2180 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2181 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2182 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2183 }
2184
2185 // If this is an 8 or 16-bit value, it is really passed promoted
2186 // to 32 bits. Insert an assert[sz]ext to capture this, then
2187 // truncate to the right size.
2188 switch (VA.getLocInfo()) {
2189 case CCValAssign::Full:
2190 break;
2191 case CCValAssign::BCvt:
2192 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2193 break;
2194 case CCValAssign::SExt:
2195 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2196 DAG.getValueType(ValVT));
2197 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2198 break;
2199 case CCValAssign::ZExt:
2200 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2201 DAG.getValueType(ValVT));
2202 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2203 break;
2204 case CCValAssign::AExt:
2205 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2206 break;
2207 default:
2208 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2208)
;
2209 }
2210
2211 InVals.push_back(Val);
2212 }
2213
2214 if (!IsEntryFunc) {
2215 // Special inputs come after user arguments.
2216 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2217 }
2218
2219 // Start adding system SGPRs.
2220 if (IsEntryFunc) {
2221 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2222 } else {
2223 CCInfo.AllocateReg(Info->getScratchRSrcReg());
2224 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2225 CCInfo.AllocateReg(Info->getFrameOffsetReg());
2226 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2227 }
2228
2229 auto &ArgUsageInfo =
2230 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2231 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2232
2233 unsigned StackArgSize = CCInfo.getNextStackOffset();
2234 Info->setBytesInStackArgArea(StackArgSize);
2235
2236 return Chains.empty() ? Chain :
2237 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2238}
2239
2240// TODO: If return values can't fit in registers, we should return as many as
2241// possible in registers before passing on stack.
2242bool SITargetLowering::CanLowerReturn(
2243 CallingConv::ID CallConv,
2244 MachineFunction &MF, bool IsVarArg,
2245 const SmallVectorImpl<ISD::OutputArg> &Outs,
2246 LLVMContext &Context) const {
2247 // Replacing returns with sret/stack usage doesn't make sense for shaders.
2248 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2249 // for shaders. Vector types should be explicitly handled by CC.
2250 if (AMDGPU::isEntryFunctionCC(CallConv))
2251 return true;
2252
2253 SmallVector<CCValAssign, 16> RVLocs;
2254 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2255 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2256}
2257
2258SDValue
2259SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2260 bool isVarArg,
2261 const SmallVectorImpl<ISD::OutputArg> &Outs,
2262 const SmallVectorImpl<SDValue> &OutVals,
2263 const SDLoc &DL, SelectionDAG &DAG) const {
2264 MachineFunction &MF = DAG.getMachineFunction();
2265 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2266
2267 if (AMDGPU::isKernel(CallConv)) {
2268 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2269 OutVals, DL, DAG);
2270 }
2271
2272 bool IsShader = AMDGPU::isShader(CallConv);
2273
2274 Info->setIfReturnsVoid(Outs.empty());
2275 bool IsWaveEnd = Info->returnsVoid() && IsShader;
2276
2277 // CCValAssign - represent the assignment of the return value to a location.
2278 SmallVector<CCValAssign, 48> RVLocs;
2279 SmallVector<ISD::OutputArg, 48> Splits;
2280
2281 // CCState - Info about the registers and stack slots.
2282 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2283 *DAG.getContext());
2284
2285 // Analyze outgoing return values.
2286 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2287
2288 SDValue Flag;
2289 SmallVector<SDValue, 48> RetOps;
2290 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2291
2292 // Add return address for callable functions.
2293 if (!Info->isEntryFunction()) {
2294 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2295 SDValue ReturnAddrReg = CreateLiveInRegister(
2296 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2297
2298 SDValue ReturnAddrVirtualReg = DAG.getRegister(
2299 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2300 MVT::i64);
2301 Chain =
2302 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2303 Flag = Chain.getValue(1);
2304 RetOps.push_back(ReturnAddrVirtualReg);
2305 }
2306
2307 // Copy the result values into the output registers.
2308 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2309 ++I, ++RealRVLocIdx) {
2310 CCValAssign &VA = RVLocs[I];
2311 assert(VA.isRegLoc() && "Can only return in registers!")((VA.isRegLoc() && "Can only return in registers!") ?
static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2311, __PRETTY_FUNCTION__))
;
2312 // TODO: Partially return in registers if return values don't fit.
2313 SDValue Arg = OutVals[RealRVLocIdx];
2314
2315 // Copied from other backends.
2316 switch (VA.getLocInfo()) {
2317 case CCValAssign::Full:
2318 break;
2319 case CCValAssign::BCvt:
2320 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2321 break;
2322 case CCValAssign::SExt:
2323 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2324 break;
2325 case CCValAssign::ZExt:
2326 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2327 break;
2328 case CCValAssign::AExt:
2329 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2330 break;
2331 default:
2332 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2332)
;
2333 }
2334
2335 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2336 Flag = Chain.getValue(1);
2337 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2338 }
2339
2340 // FIXME: Does sret work properly?
2341 if (!Info->isEntryFunction()) {
2342 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2343 const MCPhysReg *I =
2344 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2345 if (I) {
2346 for (; *I; ++I) {
2347 if (AMDGPU::SReg_64RegClass.contains(*I))
2348 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2349 else if (AMDGPU::SReg_32RegClass.contains(*I))
2350 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2351 else
2352 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2352)
;
2353 }
2354 }
2355 }
2356
2357 // Update chain and glue.
2358 RetOps[0] = Chain;
2359 if (Flag.getNode())
2360 RetOps.push_back(Flag);
2361
2362 unsigned Opc = AMDGPUISD::ENDPGM;
2363 if (!IsWaveEnd)
2364 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2365 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2366}
2367
2368SDValue SITargetLowering::LowerCallResult(
2369 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2370 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2371 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2372 SDValue ThisVal) const {
2373 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2374
2375 // Assign locations to each value returned by this call.
2376 SmallVector<CCValAssign, 16> RVLocs;
2377 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2378 *DAG.getContext());
2379 CCInfo.AnalyzeCallResult(Ins, RetCC);
2380
2381 // Copy all of the result registers out of their specified physreg.
2382 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2383 CCValAssign VA = RVLocs[i];
2384 SDValue Val;
2385
2386 if (VA.isRegLoc()) {
2387 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2388 Chain = Val.getValue(1);
2389 InFlag = Val.getValue(2);
2390 } else if (VA.isMemLoc()) {
2391 report_fatal_error("TODO: return values in memory");
2392 } else
2393 llvm_unreachable("unknown argument location type")::llvm::llvm_unreachable_internal("unknown argument location type"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2393)
;
2394
2395 switch (VA.getLocInfo()) {
2396 case CCValAssign::Full:
2397 break;
2398 case CCValAssign::BCvt:
2399 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2400 break;
2401 case CCValAssign::ZExt:
2402 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2403 DAG.getValueType(VA.getValVT()));
2404 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2405 break;
2406 case CCValAssign::SExt:
2407 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2408 DAG.getValueType(VA.getValVT()));
2409 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2410 break;
2411 case CCValAssign::AExt:
2412 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2413 break;
2414 default:
2415 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2415)
;
2416 }
2417
2418 InVals.push_back(Val);
2419 }
2420
2421 return Chain;
2422}
2423
2424// Add code to pass special inputs required depending on used features separate
2425// from the explicit user arguments present in the IR.
2426void SITargetLowering::passSpecialInputs(
2427 CallLoweringInfo &CLI,
2428 CCState &CCInfo,
2429 const SIMachineFunctionInfo &Info,
2430 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2431 SmallVectorImpl<SDValue> &MemOpChains,
2432 SDValue Chain) const {
2433 // If we don't have a call site, this was a call inserted by
2434 // legalization. These can never use special inputs.
2435 if (!CLI.CS)
2436 return;
2437
2438 const Function *CalleeFunc = CLI.CS.getCalledFunction();
2439 assert(CalleeFunc)((CalleeFunc) ? static_cast<void> (0) : __assert_fail (
"CalleeFunc", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2439, __PRETTY_FUNCTION__))
;
2440
2441 SelectionDAG &DAG = CLI.DAG;
2442 const SDLoc &DL = CLI.DL;
2443
2444 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2445
2446 auto &ArgUsageInfo =
2447 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2448 const AMDGPUFunctionArgInfo &CalleeArgInfo
2449 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2450
2451 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2452
2453 // TODO: Unify with private memory register handling. This is complicated by
2454 // the fact that at least in kernels, the input argument is not necessarily
2455 // in the same location as the input.
2456 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2457 AMDGPUFunctionArgInfo::DISPATCH_PTR,
2458 AMDGPUFunctionArgInfo::QUEUE_PTR,
2459 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2460 AMDGPUFunctionArgInfo::DISPATCH_ID,
2461 AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2462 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2463 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2464 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2465 };
2466
2467 for (auto InputID : InputRegs) {
2468 const ArgDescriptor *OutgoingArg;
2469 const TargetRegisterClass *ArgRC;
2470
2471 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2472 if (!OutgoingArg)
2473 continue;
2474
2475 const ArgDescriptor *IncomingArg;
2476 const TargetRegisterClass *IncomingArgRC;
2477 std::tie(IncomingArg, IncomingArgRC)
2478 = CallerArgInfo.getPreloadedValue(InputID);
2479 assert(IncomingArgRC == ArgRC)((IncomingArgRC == ArgRC) ? static_cast<void> (0) : __assert_fail
("IncomingArgRC == ArgRC", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2479, __PRETTY_FUNCTION__))
;
2480
2481 // All special arguments are ints for now.
2482 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2483 SDValue InputReg;
2484
2485 if (IncomingArg) {
2486 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2487 } else {
2488 // The implicit arg ptr is special because it doesn't have a corresponding
2489 // input for kernels, and is computed from the kernarg segment pointer.
2490 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR)((InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) ? static_cast
<void> (0) : __assert_fail ("InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2490, __PRETTY_FUNCTION__))
;
2491 InputReg = getImplicitArgPtr(DAG, DL);
2492 }
2493
2494 if (OutgoingArg->isRegister()) {
2495 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2496 } else {
2497 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2498 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2499 SpecialArgOffset);
2500 MemOpChains.push_back(ArgStore);
2501 }
2502 }
2503
2504 // Pack workitem IDs into a single register or pass it as is if already
2505 // packed.
2506 const ArgDescriptor *OutgoingArg;
2507 const TargetRegisterClass *ArgRC;
2508
2509 std::tie(OutgoingArg, ArgRC) =
2510 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2511 if (!OutgoingArg)
2512 std::tie(OutgoingArg, ArgRC) =
2513 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2514 if (!OutgoingArg)
2515 std::tie(OutgoingArg, ArgRC) =
2516 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2517 if (!OutgoingArg)
2518 return;
2519
2520 const ArgDescriptor *IncomingArgX
2521 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2522 const ArgDescriptor *IncomingArgY
2523 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2524 const ArgDescriptor *IncomingArgZ
2525 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2526
2527 SDValue InputReg;
2528 SDLoc SL;
2529
2530 // If incoming ids are not packed we need to pack them.
2531 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX)
2532 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2533
2534 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) {
2535 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2536 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2537 DAG.getShiftAmountConstant(10, MVT::i32, SL));
2538 InputReg = InputReg.getNode() ?
2539 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2540 }
2541
2542 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) {
2543 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2544 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2545 DAG.getShiftAmountConstant(20, MVT::i32, SL));
2546 InputReg = InputReg.getNode() ?
2547 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2548 }
2549
2550 if (!InputReg.getNode()) {
2551 // Workitem ids are already packed, any of present incoming arguments
2552 // will carry all required fields.
2553 ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2554 IncomingArgX ? *IncomingArgX :
2555 IncomingArgY ? *IncomingArgY :
2556 *IncomingArgZ, ~0u);
2557 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2558 }
2559
2560 if (OutgoingArg->isRegister()) {
2561 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2562 } else {
2563 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2564 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2565 SpecialArgOffset);
2566 MemOpChains.push_back(ArgStore);
2567 }
2568}
2569
2570static bool canGuaranteeTCO(CallingConv::ID CC) {
2571 return CC == CallingConv::Fast;
2572}
2573
2574/// Return true if we might ever do TCO for calls with this calling convention.
2575static bool mayTailCallThisCC(CallingConv::ID CC) {
2576 switch (CC) {
2577 case CallingConv::C:
2578 return true;
2579 default:
2580 return canGuaranteeTCO(CC);
2581 }
2582}
2583
2584bool SITargetLowering::isEligibleForTailCallOptimization(
2585 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2586 const SmallVectorImpl<ISD::OutputArg> &Outs,
2587 const SmallVectorImpl<SDValue> &OutVals,
2588 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2589 if (!mayTailCallThisCC(CalleeCC))
2590 return false;
2591
2592 MachineFunction &MF = DAG.getMachineFunction();
2593 const Function &CallerF = MF.getFunction();
2594 CallingConv::ID CallerCC = CallerF.getCallingConv();
2595 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2596 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2597
2598 // Kernels aren't callable, and don't have a live in return address so it
2599 // doesn't make sense to do a tail call with entry functions.
2600 if (!CallerPreserved)
2601 return false;
2602
2603 bool CCMatch = CallerCC == CalleeCC;
2604
2605 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2606 if (canGuaranteeTCO(CalleeCC) && CCMatch)
2607 return true;
2608 return false;
2609 }
2610
2611 // TODO: Can we handle var args?
2612 if (IsVarArg)
2613 return false;
2614
2615 for (const Argument &Arg : CallerF.args()) {
2616 if (Arg.hasByValAttr())
2617 return false;
2618 }
2619
2620 LLVMContext &Ctx = *DAG.getContext();
2621
2622 // Check that the call results are passed in the same way.
2623 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2624 CCAssignFnForCall(CalleeCC, IsVarArg),
2625 CCAssignFnForCall(CallerCC, IsVarArg)))
2626 return false;
2627
2628 // The callee has to preserve all registers the caller needs to preserve.
2629 if (!CCMatch) {
2630 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2631 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2632 return false;
2633 }
2634
2635 // Nothing more to check if the callee is taking no arguments.
2636 if (Outs.empty())
2637 return true;
2638
2639 SmallVector<CCValAssign, 16> ArgLocs;
2640 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2641
2642 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2643
2644 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2645 // If the stack arguments for this call do not fit into our own save area then
2646 // the call cannot be made tail.
2647 // TODO: Is this really necessary?
2648 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2649 return false;
2650
2651 const MachineRegisterInfo &MRI = MF.getRegInfo();
2652 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2653}
2654
2655bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2656 if (!CI->isTailCall())
2657 return false;
2658
2659 const Function *ParentFn = CI->getParent()->getParent();
2660 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2661 return false;
2662
2663 auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2664 return (Attr.getValueAsString() != "true");
2665}
2666
2667// The wave scratch offset register is used as the global base pointer.
2668SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2669 SmallVectorImpl<SDValue> &InVals) const {
2670 SelectionDAG &DAG = CLI.DAG;
2671 const SDLoc &DL = CLI.DL;
2672 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2673 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2674 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2675 SDValue Chain = CLI.Chain;
2676 SDValue Callee = CLI.Callee;
2677 bool &IsTailCall = CLI.IsTailCall;
2678 CallingConv::ID CallConv = CLI.CallConv;
2679 bool IsVarArg = CLI.IsVarArg;
2680 bool IsSibCall = false;
2681 bool IsThisReturn = false;
2682 MachineFunction &MF = DAG.getMachineFunction();
2683
2684 if (Callee.isUndef() || isNullConstant(Callee)) {
2685 if (!CLI.IsTailCall) {
2686 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2687 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2688 }
2689
2690 return Chain;
2691 }
2692
2693 if (IsVarArg) {
2694 return lowerUnhandledCall(CLI, InVals,
2695 "unsupported call to variadic function ");
2696 }
2697
2698 if (!CLI.CS.getInstruction())
2699 report_fatal_error("unsupported libcall legalization");
2700
2701 if (!CLI.CS.getCalledFunction()) {
2702 return lowerUnhandledCall(CLI, InVals,
2703 "unsupported indirect call to function ");
2704 }
2705
2706 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2707 return lowerUnhandledCall(CLI, InVals,
2708 "unsupported required tail call to function ");
2709 }
2710
2711 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2712 // Note the issue is with the CC of the calling function, not of the call
2713 // itself.
2714 return lowerUnhandledCall(CLI, InVals,
2715 "unsupported call from graphics shader of function ");
2716 }
2717
2718 if (IsTailCall) {
2719 IsTailCall = isEligibleForTailCallOptimization(
2720 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2721 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2722 report_fatal_error("failed to perform tail call elimination on a call "
2723 "site marked musttail");
2724 }
2725
2726 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2727
2728 // A sibling call is one where we're under the usual C ABI and not planning
2729 // to change that but can still do a tail call:
2730 if (!TailCallOpt && IsTailCall)
2731 IsSibCall = true;
2732
2733 if (IsTailCall)
2734 ++NumTailCalls;
2735 }
2736
2737 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2738
2739 // Analyze operands of the call, assigning locations to each operand.
2740 SmallVector<CCValAssign, 16> ArgLocs;
2741 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2742 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2743
2744 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2745
2746 // Get a count of how many bytes are to be pushed on the stack.
2747 unsigned NumBytes = CCInfo.getNextStackOffset();
2748
2749 if (IsSibCall) {
2750 // Since we're not changing the ABI to make this a tail call, the memory
2751 // operands are already available in the caller's incoming argument space.
2752 NumBytes = 0;
2753 }
2754
2755 // FPDiff is the byte offset of the call's argument area from the callee's.
2756 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2757 // by this amount for a tail call. In a sibling call it must be 0 because the
2758 // caller will deallocate the entire stack and the callee still expects its
2759 // arguments to begin at SP+0. Completely unused for non-tail calls.
2760 int32_t FPDiff = 0;
2761 MachineFrameInfo &MFI = MF.getFrameInfo();
2762 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2763
2764 // Adjust the stack pointer for the new arguments...
2765 // These operations are automatically eliminated by the prolog/epilog pass
2766 if (!IsSibCall) {
2767 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2768
2769 SmallVector<SDValue, 4> CopyFromChains;
2770
2771 // In the HSA case, this should be an identity copy.
2772 SDValue ScratchRSrcReg
2773 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2774 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2775 CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2776 Chain = DAG.getTokenFactor(DL, CopyFromChains);
2777 }
2778
2779 SmallVector<SDValue, 8> MemOpChains;
2780 MVT PtrVT = MVT::i32;
2781
2782 // Walk the register/memloc assignments, inserting copies/loads.
2783 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2784 ++i, ++realArgIdx) {
2785 CCValAssign &VA = ArgLocs[i];
2786 SDValue Arg = OutVals[realArgIdx];
2787
2788 // Promote the value if needed.
2789 switch (VA.getLocInfo()) {
2790 case CCValAssign::Full:
2791 break;
2792 case CCValAssign::BCvt:
2793 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2794 break;
2795 case CCValAssign::ZExt:
2796 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2797 break;
2798 case CCValAssign::SExt:
2799 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2800 break;
2801 case CCValAssign::AExt:
2802 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2803 break;
2804 case CCValAssign::FPExt:
2805 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2806 break;
2807 default:
2808 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2808)
;
2809 }
2810
2811 if (VA.isRegLoc()) {
2812 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2813 } else {
2814 assert(VA.isMemLoc())((VA.isMemLoc()) ? static_cast<void> (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2814, __PRETTY_FUNCTION__))
;
2815
2816 SDValue DstAddr;
2817 MachinePointerInfo DstInfo;
2818
2819 unsigned LocMemOffset = VA.getLocMemOffset();
2820 int32_t Offset = LocMemOffset;
2821
2822 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2823 MaybeAlign Alignment;
2824
2825 if (IsTailCall) {
2826 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2827 unsigned OpSize = Flags.isByVal() ?
2828 Flags.getByValSize() : VA.getValVT().getStoreSize();
2829
2830 // FIXME: We can have better than the minimum byval required alignment.
2831 Alignment =
2832 Flags.isByVal()
2833 ? MaybeAlign(Flags.getByValAlign())
2834 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2835
2836 Offset = Offset + FPDiff;
2837 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2838
2839 DstAddr = DAG.getFrameIndex(FI, PtrVT);
2840 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2841
2842 // Make sure any stack arguments overlapping with where we're storing
2843 // are loaded before this eventual operation. Otherwise they'll be
2844 // clobbered.
2845
2846 // FIXME: Why is this really necessary? This seems to just result in a
2847 // lot of code to copy the stack and write them back to the same
2848 // locations, which are supposed to be immutable?
2849 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2850 } else {
2851 DstAddr = PtrOff;
2852 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2853 Alignment =
2854 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2855 }
2856
2857 if (Outs[i].Flags.isByVal()) {
2858 SDValue SizeNode =
2859 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2860 SDValue Cpy = DAG.getMemcpy(
2861 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2862 /*isVol = */ false, /*AlwaysInline = */ true,
2863 /*isTailCall = */ false, DstInfo,
2864 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2865 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS))));
2866
2867 MemOpChains.push_back(Cpy);
2868 } else {
2869 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2870 Alignment ? Alignment->value() : 0);
2871 MemOpChains.push_back(Store);
2872 }
2873 }
2874 }
2875
2876 // Copy special input registers after user input arguments.
2877 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2878
2879 if (!MemOpChains.empty())
2880 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2881
2882 // Build a sequence of copy-to-reg nodes chained together with token chain
2883 // and flag operands which copy the outgoing args into the appropriate regs.
2884 SDValue InFlag;
2885 for (auto &RegToPass : RegsToPass) {
2886 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2887 RegToPass.second, InFlag);
2888 InFlag = Chain.getValue(1);
2889 }
2890
2891
2892 SDValue PhysReturnAddrReg;
2893 if (IsTailCall) {
2894 // Since the return is being combined with the call, we need to pass on the
2895 // return address.
2896
2897 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2898 SDValue ReturnAddrReg = CreateLiveInRegister(
2899 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2900
2901 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2902 MVT::i64);
2903 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2904 InFlag = Chain.getValue(1);
2905 }
2906
2907 // We don't usually want to end the call-sequence here because we would tidy
2908 // the frame up *after* the call, however in the ABI-changing tail-call case
2909 // we've carefully laid out the parameters so that when sp is reset they'll be
2910 // in the correct location.
2911 if (IsTailCall && !IsSibCall) {
2912 Chain = DAG.getCALLSEQ_END(Chain,
2913 DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2914 DAG.getTargetConstant(0, DL, MVT::i32),
2915 InFlag, DL);
2916 InFlag = Chain.getValue(1);
2917 }
2918
2919 std::vector<SDValue> Ops;
2920 Ops.push_back(Chain);
2921 Ops.push_back(Callee);
2922 // Add a redundant copy of the callee global which will not be legalized, as
2923 // we need direct access to the callee later.
2924 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee);
2925 const GlobalValue *GV = GSD->getGlobal();
2926 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2927
2928 if (IsTailCall) {
2929 // Each tail call may have to adjust the stack by a different amount, so
2930 // this information must travel along with the operation for eventual
2931 // consumption by emitEpilogue.
2932 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2933
2934 Ops.push_back(PhysReturnAddrReg);
2935 }
2936
2937 // Add argument registers to the end of the list so that they are known live
2938 // into the call.
2939 for (auto &RegToPass : RegsToPass) {
2940 Ops.push_back(DAG.getRegister(RegToPass.first,
2941 RegToPass.second.getValueType()));
2942 }
2943
2944 // Add a register mask operand representing the call-preserved registers.
2945
2946 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2947 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2948 assert(Mask && "Missing call preserved mask for calling convention")((Mask && "Missing call preserved mask for calling convention"
) ? static_cast<void> (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2948, __PRETTY_FUNCTION__))
;
2949 Ops.push_back(DAG.getRegisterMask(Mask));
2950
2951 if (InFlag.getNode())
2952 Ops.push_back(InFlag);
2953
2954 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2955
2956 // If we're doing a tall call, use a TC_RETURN here rather than an
2957 // actual call instruction.
2958 if (IsTailCall) {
2959 MFI.setHasTailCall();
2960 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2961 }
2962
2963 // Returns a chain and a flag for retval copy to use.
2964 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2965 Chain = Call.getValue(0);
2966 InFlag = Call.getValue(1);
2967
2968 uint64_t CalleePopBytes = NumBytes;
2969 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2970 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2971 InFlag, DL);
2972 if (!Ins.empty())
2973 InFlag = Chain.getValue(1);
2974
2975 // Handle result values, copying them out of physregs into vregs that we
2976 // return.
2977 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2978 InVals, IsThisReturn,
2979 IsThisReturn ? OutVals[0] : SDValue());
2980}
2981
2982Register SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2983 const MachineFunction &MF) const {
2984 Register Reg = StringSwitch<Register>(RegName)
2985 .Case("m0", AMDGPU::M0)
2986 .Case("exec", AMDGPU::EXEC)
2987 .Case("exec_lo", AMDGPU::EXEC_LO)
2988 .Case("exec_hi", AMDGPU::EXEC_HI)
2989 .Case("flat_scratch", AMDGPU::FLAT_SCR)
2990 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2991 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2992 .Default(Register());
2993
2994 if (Reg == AMDGPU::NoRegister) {
2995 report_fatal_error(Twine("invalid register name \""
2996 + StringRef(RegName) + "\"."));
2997
2998 }
2999
3000 if (!Subtarget->hasFlatScrRegister() &&
3001 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3002 report_fatal_error(Twine("invalid register \""
3003 + StringRef(RegName) + "\" for subtarget."));
3004 }
3005
3006 switch (Reg) {
3007 case AMDGPU::M0:
3008 case AMDGPU::EXEC_LO:
3009 case AMDGPU::EXEC_HI:
3010 case AMDGPU::FLAT_SCR_LO:
3011 case AMDGPU::FLAT_SCR_HI:
3012 if (VT.getSizeInBits() == 32)
3013 return Reg;
3014 break;
3015 case AMDGPU::EXEC:
3016 case AMDGPU::FLAT_SCR:
3017 if (VT.getSizeInBits() == 64)
3018 return Reg;
3019 break;
3020 default:
3021 llvm_unreachable("missing register type checking")::llvm::llvm_unreachable_internal("missing register type checking"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3021)
;
3022 }
3023
3024 report_fatal_error(Twine("invalid type for register \""
3025 + StringRef(RegName) + "\"."));
3026}
3027
3028// If kill is not the last instruction, split the block so kill is always a
3029// proper terminator.
3030MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3031 MachineBasicBlock *BB) const {
3032 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3033
3034 MachineBasicBlock::iterator SplitPoint(&MI);
3035 ++SplitPoint;
3036
3037 if (SplitPoint == BB->end()) {
3038 // Don't bother with a new block.
3039 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3040 return BB;
3041 }
3042
3043 MachineFunction *MF = BB->getParent();
3044 MachineBasicBlock *SplitBB
3045 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3046
3047 MF->insert(++MachineFunction::iterator(BB), SplitBB);
3048 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3049
3050 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3051 BB->addSuccessor(SplitBB);
3052
3053 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3054 return SplitBB;
3055}
3056
3057// Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3058// \p MI will be the only instruction in the loop body block. Otherwise, it will
3059// be the first instruction in the remainder block.
3060//
3061/// \returns { LoopBody, Remainder }
3062static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3063splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3064 MachineFunction *MF = MBB.getParent();
3065 MachineBasicBlock::iterator I(&MI);
3066
3067 // To insert the loop we need to split the block. Move everything after this
3068 // point to a new block, and insert a new empty block between the two.
3069 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3070 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3071 MachineFunction::iterator MBBI(MBB);
3072 ++MBBI;
3073
3074 MF->insert(MBBI, LoopBB);
3075 MF->insert(MBBI, RemainderBB);
3076
3077 LoopBB->addSuccessor(LoopBB);
3078 LoopBB->addSuccessor(RemainderBB);
3079
3080 // Move the rest of the block into a new block.
3081 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3082
3083 if (InstInLoop) {
3084 auto Next = std::next(I);
3085
3086 // Move instruction to loop body.
3087 LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3088
3089 // Move the rest of the block.
3090 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3091 } else {
3092 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3093 }
3094
3095 MBB.addSuccessor(LoopBB);
3096
3097 return std::make_pair(LoopBB, RemainderBB);
3098}
3099
3100/// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3101void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3102 MachineBasicBlock *MBB = MI.getParent();
3103 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3104 auto I = MI.getIterator();
3105 auto E = std::next(I);
3106
3107 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3108 .addImm(0);
3109
3110 MIBundleBuilder Bundler(*MBB, I, E);
3111 finalizeBundle(*MBB, Bundler.begin());
3112}
3113
3114MachineBasicBlock *
3115SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3116 MachineBasicBlock *BB) const {
3117 const DebugLoc &DL = MI.getDebugLoc();
3118
3119 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3120
3121 MachineBasicBlock *LoopBB;
3122 MachineBasicBlock *RemainderBB;
3123 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3124
3125 // Apparently kill flags are only valid if the def is in the same block?
3126 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3127 Src->setIsKill(false);
3128
3129 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3130
3131 MachineBasicBlock::iterator I = LoopBB->end();
3132
3133 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3134 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3135
3136 // Clear TRAP_STS.MEM_VIOL
3137 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3138 .addImm(0)
3139 .addImm(EncodedReg);
3140
3141 bundleInstWithWaitcnt(MI);
3142
3143 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3144
3145 // Load and check TRAP_STS.MEM_VIOL
3146 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3147 .addImm(EncodedReg);
3148
3149 // FIXME: Do we need to use an isel pseudo that may clobber scc?
3150 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3151 .addReg(Reg, RegState::Kill)
3152 .addImm(0);
3153 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3154 .addMBB(LoopBB);
3155
3156 return RemainderBB;
3157}
3158
3159// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3160// wavefront. If the value is uniform and just happens to be in a VGPR, this
3161// will only do one iteration. In the worst case, this will loop 64 times.
3162//
3163// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3164static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3165 const SIInstrInfo *TII,
3166 MachineRegisterInfo &MRI,
3167 MachineBasicBlock &OrigBB,
3168 MachineBasicBlock &LoopBB,
3169 const DebugLoc &DL,
3170 const MachineOperand &IdxReg,
3171 unsigned InitReg,
3172 unsigned ResultReg,
3173 unsigned PhiReg,
3174 unsigned InitSaveExecReg,
3175 int Offset,
3176 bool UseGPRIdxMode,
3177 bool IsIndirectSrc) {
3178 MachineFunction *MF = OrigBB.getParent();
3179 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3180 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3181 MachineBasicBlock::iterator I = LoopBB.begin();
3182
3183 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3184 Register PhiExec = MRI.createVirtualRegister(BoolRC);
3185 Register NewExec = MRI.createVirtualRegister(BoolRC);
3186 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3187 Register CondReg = MRI.createVirtualRegister(BoolRC);
3188
3189 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3190 .addReg(InitReg)
3191 .addMBB(&OrigBB)
3192 .addReg(ResultReg)
3193 .addMBB(&LoopBB);
3194
3195 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3196 .addReg(InitSaveExecReg)
3197 .addMBB(&OrigBB)
3198 .addReg(NewExec)
3199 .addMBB(&LoopBB);
3200
3201 // Read the next variant <- also loop target.
3202 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3203 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3204
3205 // Compare the just read M0 value to all possible Idx values.
3206 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3207 .addReg(CurrentIdxReg)
3208 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3209
3210 // Update EXEC, save the original EXEC value to VCC.
3211 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3212 : AMDGPU::S_AND_SAVEEXEC_B64),
3213 NewExec)
3214 .addReg(CondReg, RegState::Kill);
3215
3216 MRI.setSimpleHint(NewExec, CondReg);
3217
3218 if (UseGPRIdxMode) {
3219 unsigned IdxReg;
3220 if (Offset == 0) {
3221 IdxReg = CurrentIdxReg;
3222 } else {
3223 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3224 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3225 .addReg(CurrentIdxReg, RegState::Kill)
3226 .addImm(Offset);
3227 }
3228 unsigned IdxMode = IsIndirectSrc ?
3229 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3230 MachineInstr *SetOn =
3231 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3232 .addReg(IdxReg, RegState::Kill)
3233 .addImm(IdxMode);
3234 SetOn->getOperand(3).setIsUndef();
3235 } else {
3236 // Move index from VCC into M0
3237 if (Offset == 0) {
3238 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3239 .addReg(CurrentIdxReg, RegState::Kill);
3240 } else {
3241 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3242 .addReg(CurrentIdxReg, RegState::Kill)
3243 .addImm(Offset);
3244 }
3245 }
3246
3247 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3248 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3249 MachineInstr *InsertPt =
3250 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3251 : AMDGPU::S_XOR_B64_term), Exec)
3252 .addReg(Exec)
3253 .addReg(NewExec);
3254
3255 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3256 // s_cbranch_scc0?
3257
3258 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3259 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3260 .addMBB(&LoopBB);
3261
3262 return InsertPt->getIterator();
3263}
3264
3265// This has slightly sub-optimal regalloc when the source vector is killed by
3266// the read. The register allocator does not understand that the kill is
3267// per-workitem, so is kept alive for the whole loop so we end up not re-using a
3268// subregister from it, using 1 more VGPR than necessary. This was saved when
3269// this was expanded after register allocation.
3270static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3271 MachineBasicBlock &MBB,
3272 MachineInstr &MI,
3273 unsigned InitResultReg,
3274 unsigned PhiReg,
3275 int Offset,
3276 bool UseGPRIdxMode,
3277 bool IsIndirectSrc) {
3278 MachineFunction *MF = MBB.getParent();
3279 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3280 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3281 MachineRegisterInfo &MRI = MF->getRegInfo();
3282 const DebugLoc &DL = MI.getDebugLoc();
3283 MachineBasicBlock::iterator I(&MI);
3284
3285 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3286 Register DstReg = MI.getOperand(0).getReg();
3287 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3288 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3289 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3290 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3291
3292 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3293
3294 // Save the EXEC mask
3295 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3296 .addReg(Exec);
3297
3298 MachineBasicBlock *LoopBB;
3299 MachineBasicBlock *RemainderBB;
3300 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3301
3302 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3303
3304 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3305 InitResultReg, DstReg, PhiReg, TmpExec,
3306 Offset, UseGPRIdxMode, IsIndirectSrc);
3307
3308 MachineBasicBlock::iterator First = RemainderBB->begin();
3309 BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec)
3310 .addReg(SaveExec);
3311
3312 return InsPt;
3313}
3314
3315// Returns subreg index, offset
3316static std::pair<unsigned, int>
3317computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3318 const TargetRegisterClass *SuperRC,
3319 unsigned VecReg,
3320 int Offset) {
3321 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3322
3323 // Skip out of bounds offsets, or else we would end up using an undefined
3324 // register.
3325 if (Offset >= NumElts || Offset < 0)
3326 return std::make_pair(AMDGPU::sub0, Offset);
3327
3328 return std::make_pair(AMDGPU::sub0 + Offset, 0);
3329}
3330
3331// Return true if the index is an SGPR and was set.
3332static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3333 MachineRegisterInfo &MRI,
3334 MachineInstr &MI,
3335 int Offset,
3336 bool UseGPRIdxMode,
3337 bool IsIndirectSrc) {
3338 MachineBasicBlock *MBB = MI.getParent();
3339 const DebugLoc &DL = MI.getDebugLoc();
3340 MachineBasicBlock::iterator I(&MI);
3341
3342 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3343 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3344
3345 assert(Idx->getReg() != AMDGPU::NoRegister)((Idx->getReg() != AMDGPU::NoRegister) ? static_cast<void
> (0) : __assert_fail ("Idx->getReg() != AMDGPU::NoRegister"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3345, __PRETTY_FUNCTION__))
;
3346
3347 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3348 return false;
3349
3350 if (UseGPRIdxMode) {
3351 unsigned IdxMode = IsIndirectSrc ?
3352 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3353 if (Offset == 0) {
3354 MachineInstr *SetOn =
3355 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3356 .add(*Idx)
3357 .addImm(IdxMode);
3358
3359 SetOn->getOperand(3).setIsUndef();
3360 } else {
3361 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3362 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3363 .add(*Idx)
3364 .addImm(Offset);
3365 MachineInstr *SetOn =
3366 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3367 .addReg(Tmp, RegState::Kill)
3368 .addImm(IdxMode);
3369
3370 SetOn->getOperand(3).setIsUndef();
3371 }
3372
3373 return true;
3374 }
3375
3376 if (Offset == 0) {
3377 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3378 .add(*Idx);
3379 } else {
3380 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3381 .add(*Idx)
3382 .addImm(Offset);
3383 }
3384
3385 return true;
3386}
3387
3388// Control flow needs to be inserted if indexing with a VGPR.
3389static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3390 MachineBasicBlock &MBB,
3391 const GCNSubtarget &ST) {
3392 const SIInstrInfo *TII = ST.getInstrInfo();
3393 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3394 MachineFunction *MF = MBB.getParent();
3395 MachineRegisterInfo &MRI = MF->getRegInfo();
3396
3397 Register Dst = MI.getOperand(0).getReg();
3398 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3399 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3400
3401 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3402
3403 unsigned SubReg;
3404 std::tie(SubReg, Offset)
3405 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3406
3407 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3408
3409 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3410 MachineBasicBlock::iterator I(&MI);
3411 const DebugLoc &DL = MI.getDebugLoc();
3412
3413 if (UseGPRIdxMode) {
3414 // TODO: Look at the uses to avoid the copy. This may require rescheduling
3415 // to avoid interfering with other uses, so probably requires a new
3416 // optimization pass.
3417 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3418 .addReg(SrcReg, RegState::Undef, SubReg)
3419 .addReg(SrcReg, RegState::Implicit)
3420 .addReg(AMDGPU::M0, RegState::Implicit);
3421 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3422 } else {
3423 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3424 .addReg(SrcReg, RegState::Undef, SubReg)
3425 .addReg(SrcReg, RegState::Implicit);
3426 }
3427
3428 MI.eraseFromParent();
3429
3430 return &MBB;
3431 }
3432
3433 const DebugLoc &DL = MI.getDebugLoc();
3434 MachineBasicBlock::iterator I(&MI);
3435
3436 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3437 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3438
3439 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3440
3441 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3442 Offset, UseGPRIdxMode, true);
3443 MachineBasicBlock *LoopBB = InsPt->getParent();
3444
3445 if (UseGPRIdxMode) {
3446 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3447 .addReg(SrcReg, RegState::Undef, SubReg)
3448 .addReg(SrcReg, RegState::Implicit)
3449 .addReg(AMDGPU::M0, RegState::Implicit);
3450 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3451 } else {
3452 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3453 .addReg(SrcReg, RegState::Undef, SubReg)
3454 .addReg(SrcReg, RegState::Implicit);
3455 }
3456
3457 MI.eraseFromParent();
3458
3459 return LoopBB;
3460}
3461
3462static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3463 const TargetRegisterClass *VecRC) {
3464 switch (TRI.getRegSizeInBits(*VecRC)) {
3465 case 32: // 4 bytes
3466 return AMDGPU::V_MOVRELD_B32_V1;
3467 case 64: // 8 bytes
3468 return AMDGPU::V_MOVRELD_B32_V2;
3469 case 128: // 16 bytes
3470 return AMDGPU::V_MOVRELD_B32_V4;
3471 case 256: // 32 bytes
3472 return AMDGPU::V_MOVRELD_B32_V8;
3473 case 512: // 64 bytes
3474 return AMDGPU::V_MOVRELD_B32_V16;
3475 default:
3476 llvm_unreachable("unsupported size for MOVRELD pseudos")::llvm::llvm_unreachable_internal("unsupported size for MOVRELD pseudos"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3476)
;
3477 }
3478}
3479
3480static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3481 MachineBasicBlock &MBB,
3482 const GCNSubtarget &ST) {
3483 const SIInstrInfo *TII = ST.getInstrInfo();
3484 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3485 MachineFunction *MF = MBB.getParent();
3486 MachineRegisterInfo &MRI = MF->getRegInfo();
3487
3488 Register Dst = MI.getOperand(0).getReg();
3489 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3490 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3491 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3492 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3493 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3494
3495 // This can be an immediate, but will be folded later.
3496 assert(Val->getReg())((Val->getReg()) ? static_cast<void> (0) : __assert_fail
("Val->getReg()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3496, __PRETTY_FUNCTION__))
;
3497
3498 unsigned SubReg;
3499 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3500 SrcVec->getReg(),
3501 Offset);
3502 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3503
3504 if (Idx->getReg() == AMDGPU::NoRegister) {
3505 MachineBasicBlock::iterator I(&MI);
3506 const DebugLoc &DL = MI.getDebugLoc();
3507
3508 assert(Offset == 0)((Offset == 0) ? static_cast<void> (0) : __assert_fail (
"Offset == 0", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3508, __PRETTY_FUNCTION__))
;
3509
3510 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3511 .add(*SrcVec)
3512 .add(*Val)
3513 .addImm(SubReg);
3514
3515 MI.eraseFromParent();
3516 return &MBB;
3517 }
3518
3519 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3520 MachineBasicBlock::iterator I(&MI);
3521 const DebugLoc &DL = MI.getDebugLoc();
3522
3523 if (UseGPRIdxMode) {
3524 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3525 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3526 .add(*Val)
3527 .addReg(Dst, RegState::ImplicitDefine)
3528 .addReg(SrcVec->getReg(), RegState::Implicit)
3529 .addReg(AMDGPU::M0, RegState::Implicit);
3530
3531 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3532 } else {
3533 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3534
3535 BuildMI(MBB, I, DL, MovRelDesc)
3536 .addReg(Dst, RegState::Define)
3537 .addReg(SrcVec->getReg())
3538 .add(*Val)
3539 .addImm(SubReg - AMDGPU::sub0);
3540 }
3541
3542 MI.eraseFromParent();
3543 return &MBB;
3544 }
3545
3546 if (Val->isReg())
3547 MRI.clearKillFlags(Val->getReg());
3548
3549 const DebugLoc &DL = MI.getDebugLoc();
3550
3551 Register PhiReg = MRI.createVirtualRegister(VecRC);
3552
3553 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3554 Offset, UseGPRIdxMode, false);
3555 MachineBasicBlock *LoopBB = InsPt->getParent();
3556
3557 if (UseGPRIdxMode) {
3558 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3559 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3560 .add(*Val) // src0
3561 .addReg(Dst, RegState::ImplicitDefine)
3562 .addReg(PhiReg, RegState::Implicit)
3563 .addReg(AMDGPU::M0, RegState::Implicit);
3564 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3565 } else {
3566 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3567
3568 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3569 .addReg(Dst, RegState::Define)
3570 .addReg(PhiReg)
3571 .add(*Val)
3572 .addImm(SubReg - AMDGPU::sub0);
3573 }
3574
3575 MI.eraseFromParent();
3576
3577 return LoopBB;
3578}
3579
3580MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3581 MachineInstr &MI, MachineBasicBlock *BB) const {
3582
3583 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3584 MachineFunction *MF = BB->getParent();
3585 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3586
3587 if (TII->isMIMG(MI)) {
3588 if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3589 report_fatal_error("missing mem operand from MIMG instruction");
3590 }
3591 // Add a memoperand for mimg instructions so that they aren't assumed to
3592 // be ordered memory instuctions.
3593
3594 return BB;
3595 }
3596
3597 switch (MI.getOpcode()) {
3598 case AMDGPU::S_ADD_U64_PSEUDO:
3599 case AMDGPU::S_SUB_U64_PSEUDO: {
3600 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3601 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3602 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3603 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3604 const DebugLoc &DL = MI.getDebugLoc();
3605
3606 MachineOperand &Dest = MI.getOperand(0);
3607 MachineOperand &Src0 = MI.getOperand(1);
3608 MachineOperand &Src1 = MI.getOperand(2);
3609
3610 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3611 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3612
3613 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3614 Src0, BoolRC, AMDGPU::sub0,
3615 &AMDGPU::SReg_32RegClass);
3616 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3617 Src0, BoolRC, AMDGPU::sub1,
3618 &AMDGPU::SReg_32RegClass);
3619
3620 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3621 Src1, BoolRC, AMDGPU::sub0,
3622 &AMDGPU::SReg_32RegClass);
3623 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3624 Src1, BoolRC, AMDGPU::sub1,
3625 &AMDGPU::SReg_32RegClass);
3626
3627 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3628
3629 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3630 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3631 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3632 .add(Src0Sub0)
3633 .add(Src1Sub0);
3634 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3635 .add(Src0Sub1)
3636 .add(Src1Sub1);
3637 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3638 .addReg(DestSub0)
3639 .addImm(AMDGPU::sub0)
3640 .addReg(DestSub1)
3641 .addImm(AMDGPU::sub1);
3642 MI.eraseFromParent();
3643 return BB;
3644 }
3645 case AMDGPU::SI_INIT_M0: {
3646 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3647 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3648 .add(MI.getOperand(0));
3649 MI.eraseFromParent();
3650 return BB;
3651 }
3652 case AMDGPU::SI_INIT_EXEC:
3653 // This should be before all vector instructions.
3654 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3655 AMDGPU::EXEC)
3656 .addImm(MI.getOperand(0).getImm());
3657 MI.eraseFromParent();
3658 return BB;
3659
3660 case AMDGPU::SI_INIT_EXEC_LO:
3661 // This should be before all vector instructions.
3662 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3663 AMDGPU::EXEC_LO)
3664 .addImm(MI.getOperand(0).getImm());
3665 MI.eraseFromParent();
3666 return BB;
3667
3668 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3669 // Extract the thread count from an SGPR input and set EXEC accordingly.
3670 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3671 //
3672 // S_BFE_U32 count, input, {shift, 7}
3673 // S_BFM_B64 exec, count, 0
3674 // S_CMP_EQ_U32 count, 64
3675 // S_CMOV_B64 exec, -1
3676 MachineInstr *FirstMI = &*BB->begin();
3677 MachineRegisterInfo &MRI = MF->getRegInfo();
3678 Register InputReg = MI.getOperand(0).getReg();
3679 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3680 bool Found = false;
3681
3682 // Move the COPY of the input reg to the beginning, so that we can use it.
3683 for (auto I = BB->begin(); I != &MI; I++) {
3684 if (I->getOpcode() != TargetOpcode::COPY ||
3685 I->getOperand(0).getReg() != InputReg)
3686 continue;
3687
3688 if (I == FirstMI) {
3689 FirstMI = &*++BB->begin();
3690 } else {
3691 I->removeFromParent();
3692 BB->insert(FirstMI, &*I);
3693 }
3694 Found = true;
3695 break;
3696 }
3697 assert(Found)((Found) ? static_cast<void> (0) : __assert_fail ("Found"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3697, __PRETTY_FUNCTION__))
;
3698 (void)Found;
3699
3700 // This should be before all vector instructions.
3701 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3702 bool isWave32 = getSubtarget()->isWave32();
3703 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3704 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3705 .addReg(InputReg)
3706 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3707 BuildMI(*BB, FirstMI, DebugLoc(),
3708 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3709 Exec)
3710 .addReg(CountReg)
3711 .addImm(0);
3712 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3713 .addReg(CountReg, RegState::Kill)
3714 .addImm(getSubtarget()->getWavefrontSize());
3715 BuildMI(*BB, FirstMI, DebugLoc(),
3716 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3717 Exec)
3718 .addImm(-1);
3719 MI.eraseFromParent();
3720 return BB;
3721 }
3722
3723 case AMDGPU::GET_GROUPSTATICSIZE: {
3724 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||((getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA
|| getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL
) ? static_cast<void> (0) : __assert_fail ("getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3725, __PRETTY_FUNCTION__))
3725 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)((getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA
|| getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL
) ? static_cast<void> (0) : __assert_fail ("getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3725, __PRETTY_FUNCTION__))
;
3726 DebugLoc DL = MI.getDebugLoc();
3727 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3728 .add(MI.getOperand(0))
3729 .addImm(MFI->getLDSSize());
3730 MI.eraseFromParent();
3731 return BB;
3732 }
3733 case AMDGPU::SI_INDIRECT_SRC_V1:
3734 case AMDGPU::SI_INDIRECT_SRC_V2:
3735 case AMDGPU::SI_INDIRECT_SRC_V4:
3736 case AMDGPU::SI_INDIRECT_SRC_V8:
3737 case AMDGPU::SI_INDIRECT_SRC_V16:
3738 return emitIndirectSrc(MI, *BB, *getSubtarget());
3739 case AMDGPU::SI_INDIRECT_DST_V1:
3740 case AMDGPU::SI_INDIRECT_DST_V2:
3741 case AMDGPU::SI_INDIRECT_DST_V4:
3742 case AMDGPU::SI_INDIRECT_DST_V8:
3743 case AMDGPU::SI_INDIRECT_DST_V16:
3744 return emitIndirectDst(MI, *BB, *getSubtarget());
3745 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3746 case AMDGPU::SI_KILL_I1_PSEUDO:
3747 return splitKillBlock(MI, BB);
3748 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3749 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3750 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3751 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3752
3753 Register Dst = MI.getOperand(0).getReg();
3754 Register Src0 = MI.getOperand(1).getReg();
3755 Register Src1 = MI.getOperand(2).getReg();
3756 const DebugLoc &DL = MI.getDebugLoc();
3757 Register SrcCond = MI.getOperand(3).getReg();
3758
3759 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3760 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3761 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3762 Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3763
3764 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3765 .addReg(SrcCond);
3766 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3767 .addImm(0)
3768 .addReg(Src0, 0, AMDGPU::sub0)
3769 .addImm(0)
3770 .addReg(Src1, 0, AMDGPU::sub0)
3771 .addReg(SrcCondCopy);
3772 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3773 .addImm(0)
3774 .addReg(Src0, 0, AMDGPU::sub1)
3775 .addImm(0)
3776 .addReg(Src1, 0, AMDGPU::sub1)
3777 .addReg(SrcCondCopy);
3778
3779 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3780 .addReg(DstLo)
3781 .addImm(AMDGPU::sub0)
3782 .addReg(DstHi)
3783 .addImm(AMDGPU::sub1);
3784 MI.eraseFromParent();
3785 return BB;
3786 }
3787 case AMDGPU::SI_BR_UNDEF: {
3788 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3789 const DebugLoc &DL = MI.getDebugLoc();
3790 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3791 .add(MI.getOperand(0));
3792 Br->getOperand(1).setIsUndef(true); // read undef SCC
3793 MI.eraseFromParent();
3794 return BB;
3795 }
3796 case AMDGPU::ADJCALLSTACKUP:
3797 case AMDGPU::ADJCALLSTACKDOWN: {
3798 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3799 MachineInstrBuilder MIB(*MF, &MI);
3800
3801 // Add an implicit use of the frame offset reg to prevent the restore copy
3802 // inserted after the call from being reorderd after stack operations in the
3803 // the caller's frame.
3804 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3805 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3806 .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3807 return BB;
3808 }
3809 case AMDGPU::SI_CALL_ISEL: {
3810 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3811 const DebugLoc &DL = MI.getDebugLoc();
3812
3813 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3814
3815 MachineInstrBuilder MIB;
3816 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3817
3818 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3819 MIB.add(MI.getOperand(I));
3820
3821 MIB.cloneMemRefs(MI);
3822 MI.eraseFromParent();
3823 return BB;
3824 }
3825 case AMDGPU::V_ADD_I32_e32:
3826 case AMDGPU::V_SUB_I32_e32:
3827 case AMDGPU::V_SUBREV_I32_e32: {
3828 // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3829 const DebugLoc &DL = MI.getDebugLoc();
3830 unsigned Opc = MI.getOpcode();
3831
3832 bool NeedClampOperand = false;
3833 if (TII->pseudoToMCOpcode(Opc) == -1) {
3834 Opc = AMDGPU::getVOPe64(Opc);
3835 NeedClampOperand = true;
3836 }
3837
3838 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3839 if (TII->isVOP3(*I)) {
3840 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3841 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3842 I.addReg(TRI->getVCC(), RegState::Define);
3843 }
3844 I.add(MI.getOperand(1))
3845 .add(MI.getOperand(2));
3846 if (NeedClampOperand)
3847 I.addImm(0); // clamp bit for e64 encoding
3848
3849 TII->legalizeOperands(*I);
3850
3851 MI.eraseFromParent();
3852 return BB;
3853 }
3854 case AMDGPU::DS_GWS_INIT:
3855 case AMDGPU::DS_GWS_SEMA_V:
3856 case AMDGPU::DS_GWS_SEMA_BR:
3857 case AMDGPU::DS_GWS_SEMA_P:
3858 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
3859 case AMDGPU::DS_GWS_BARRIER:
3860 // A s_waitcnt 0 is required to be the instruction immediately following.
3861 if (getSubtarget()->hasGWSAutoReplay()) {
3862 bundleInstWithWaitcnt(MI);
3863 return BB;
3864 }
3865
3866 return emitGWSMemViolTestLoop(MI, BB);
3867 default:
3868 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3869 }
3870}
3871
3872bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3873 return isTypeLegal(VT.getScalarType());
3874}
3875
3876bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3877 // This currently forces unfolding various combinations of fsub into fma with
3878 // free fneg'd operands. As long as we have fast FMA (controlled by
3879 // isFMAFasterThanFMulAndFAdd), we should perform these.
3880
3881 // When fma is quarter rate, for f64 where add / sub are at best half rate,
3882 // most of these combines appear to be cycle neutral but save on instruction
3883 // count / code size.
3884 return true;
3885}
3886
3887EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3888 EVT VT) const {
3889 if (!VT.isVector()) {
3890 return MVT::i1;
3891 }
3892 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3893}
3894
3895MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3896 // TODO: Should i16 be used always if legal? For now it would force VALU
3897 // shifts.
3898 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3899}
3900
3901// Answering this is somewhat tricky and depends on the specific device which
3902// have different rates for fma or all f64 operations.
3903//
3904// v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3905// regardless of which device (although the number of cycles differs between
3906// devices), so it is always profitable for f64.
3907//
3908// v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3909// only on full rate devices. Normally, we should prefer selecting v_mad_f32
3910// which we can always do even without fused FP ops since it returns the same
3911// result as the separate operations and since it is always full
3912// rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3913// however does not support denormals, so we do report fma as faster if we have
3914// a fast fma device and require denormals.
3915//
3916bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3917 VT = VT.getScalarType();
3918
3919 switch (VT.getSimpleVT().SimpleTy) {
3920 case MVT::f32: {
3921 // This is as fast on some subtargets. However, we always have full rate f32
3922 // mad available which returns the same result as the separate operations
3923 // which we should prefer over fma. We can't use this if we want to support
3924 // denormals, so only report this in these cases.
3925 if (Subtarget->hasFP32Denormals())
3926 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3927
3928 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3929 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3930 }
3931 case MVT::f64:
3932 return true;
3933 case MVT::f16:
3934 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3935 default:
3936 break;
3937 }
3938
3939 return false;
3940}
3941
3942bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG,
3943 const SDNode *N) const {
3944 // TODO: Check future ftz flag
3945 // v_mad_f32/v_mac_f32 do not support denormals.
3946 EVT VT = N->getValueType(0);
3947 if (VT == MVT::f32)
3948 return !Subtarget->hasFP32Denormals();
3949 if (VT == MVT::f16)
3950 return !Subtarget->hasFP16Denormals() && Subtarget->hasMadF16();
3951
3952 return false;
3953}
3954
3955//===----------------------------------------------------------------------===//
3956// Custom DAG Lowering Operations
3957//===----------------------------------------------------------------------===//
3958
3959// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3960// wider vector type is legal.
3961SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3962 SelectionDAG &DAG) const {
3963 unsigned Opc = Op.getOpcode();
3964 EVT VT = Op.getValueType();
3965 assert(VT == MVT::v4f16)((VT == MVT::v4f16) ? static_cast<void> (0) : __assert_fail
("VT == MVT::v4f16", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3965, __PRETTY_FUNCTION__))
;
3966
3967 SDValue Lo, Hi;
3968 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3969
3970 SDLoc SL(Op);
3971 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3972 Op->getFlags());
3973 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3974 Op->getFlags());
3975
3976 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3977}
3978
3979// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3980// wider vector type is legal.
3981SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3982 SelectionDAG &DAG) const {
3983 unsigned Opc = Op.getOpcode();
3984 EVT VT = Op.getValueType();
3985 assert(VT == MVT::v4i16 || VT == MVT::v4f16)((VT == MVT::v4i16 || VT == MVT::v4f16) ? static_cast<void
> (0) : __assert_fail ("VT == MVT::v4i16 || VT == MVT::v4f16"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3985, __PRETTY_FUNCTION__))
;
3986
3987 SDValue Lo0, Hi0;
3988 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3989 SDValue Lo1, Hi1;
3990 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3991
3992 SDLoc SL(Op);
3993
3994 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3995 Op->getFlags());
3996 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3997 Op->getFlags());
3998
3999 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4000}
4001
4002SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4003 SelectionDAG &DAG) const {
4004 unsigned Opc = Op.getOpcode();
4005 EVT VT = Op.getValueType();
4006 assert(VT == MVT::v4i16 || VT == MVT::v4f16)((VT == MVT::v4i16 || VT == MVT::v4f16) ? static_cast<void
> (0) : __assert_fail ("VT == MVT::v4i16 || VT == MVT::v4f16"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4006, __PRETTY_FUNCTION__))
;
4007
4008 SDValue Lo0, Hi0;
4009 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4010 SDValue Lo1, Hi1;
4011 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4012 SDValue Lo2, Hi2;
4013 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4014
4015 SDLoc SL(Op);
4016
4017 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4018 Op->getFlags());
4019 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4020 Op->getFlags());
4021
4022 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4023}
4024
4025
4026SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4027 switch (Op.getOpcode()) {
4028 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4029 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4030 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4031 case ISD::LOAD: {
4032 SDValue Result = LowerLOAD(Op, DAG);
4033 assert((!Result.getNode() ||(((!Result.getNode() || Result.getNode()->getNumValues() ==
2) && "Load should return a value and a chain") ? static_cast
<void> (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4035, __PRETTY_FUNCTION__))
4034 Result.getNode()->getNumValues() == 2) &&(((!Result.getNode() || Result.getNode()->getNumValues() ==
2) && "Load should return a value and a chain") ? static_cast
<void> (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4035, __PRETTY_FUNCTION__))
4035 "Load should return a value and a chain")(((!Result.getNode() || Result.getNode()->getNumValues() ==
2) && "Load should return a value and a chain") ? static_cast
<void> (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4035, __PRETTY_FUNCTION__))
;
4036 return Result;
4037 }
4038
4039 case ISD::FSIN:
4040 case ISD::FCOS:
4041 return LowerTrig(Op, DAG);
4042 case ISD::SELECT: return LowerSELECT(Op, DAG);
4043 case ISD::FDIV: return LowerFDIV(Op, DAG);
4044 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4045 case ISD::STORE: return LowerSTORE(Op, DAG);
4046 case ISD::GlobalAddress: {
4047 MachineFunction &MF = DAG.getMachineFunction();
4048 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4049 return LowerGlobalAddress(MFI, Op, DAG);
4050 }
4051 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4052 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4053 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4054 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4055 case ISD::INSERT_SUBVECTOR:
4056 return lowerINSERT_SUBVECTOR(Op, DAG);
4057 case ISD::INSERT_VECTOR_ELT:
4058 return lowerINSERT_VECTOR_ELT(Op, DAG);
4059 case ISD::EXTRACT_VECTOR_ELT:
4060 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4061 case ISD::VECTOR_SHUFFLE:
4062 return lowerVECTOR_SHUFFLE(Op, DAG);
4063 case ISD::BUILD_VECTOR:
4064 return lowerBUILD_VECTOR(Op, DAG);
4065 case ISD::FP_ROUND:
4066 return lowerFP_ROUND(Op, DAG);
4067 case ISD::TRAP:
4068 return lowerTRAP(Op, DAG);
4069 case ISD::DEBUGTRAP:
4070 return lowerDEBUGTRAP(Op, DAG);
4071 case ISD::FABS:
4072 case ISD::FNEG:
4073 case ISD::FCANONICALIZE:
4074 return splitUnaryVectorOp(Op, DAG);
4075 case ISD::FMINNUM:
4076 case ISD::FMAXNUM:
4077 return lowerFMINNUM_FMAXNUM(Op, DAG);
4078 case ISD::FMA:
4079 return splitTernaryVectorOp(Op, DAG);
4080 case ISD::SHL:
4081 case ISD::SRA:
4082 case ISD::SRL:
4083 case ISD::ADD:
4084 case ISD::SUB:
4085 case ISD::MUL:
4086 case ISD::SMIN:
4087 case ISD::SMAX:
4088 case ISD::UMIN:
4089 case ISD::UMAX:
4090 case ISD::FADD:
4091 case ISD::FMUL:
4092 case ISD::FMINNUM_IEEE:
4093 case ISD::FMAXNUM_IEEE:
4094 return splitBinaryVectorOp(Op, DAG);
4095 }
4096 return SDValue();
4097}
4098
4099static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4100 const SDLoc &DL,
4101 SelectionDAG &DAG, bool Unpacked) {
4102 if (!LoadVT.isVector())
4103 return Result;
4104
4105 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4106 // Truncate to v2i16/v4i16.
4107 EVT IntLoadVT = LoadVT.changeTypeToInteger();
4108
4109 // Workaround legalizer not scalarizing truncate after vector op
4110 // legalization byt not creating intermediate vector trunc.
4111 SmallVector<SDValue, 4> Elts;
4112 DAG.ExtractVectorElements(Result, Elts);
4113 for (SDValue &Elt : Elts)
4114 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4115
4116 Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4117
4118 // Bitcast to original type (v2f16/v4f16).
4119 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4120 }
4121
4122 // Cast back to the original packed type.
4123 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4124}
4125
4126SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4127 MemSDNode *M,
4128 SelectionDAG &DAG,
4129 ArrayRef<SDValue> Ops,
4130 bool IsIntrinsic) const {
4131 SDLoc DL(M);
4132
4133 bool Unpacked = Subtarget->hasUnpackedD16VMem();
4134 EVT LoadVT = M->getValueType(0);
4135
4136 EVT EquivLoadVT = LoadVT;
4137 if (Unpacked && LoadVT.isVector()) {
4138 EquivLoadVT = LoadVT.isVector() ?
4139 EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4140 LoadVT.getVectorNumElements()) : LoadVT;
4141 }
4142
4143 // Change from v4f16/v2f16 to EquivLoadVT.
4144 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4145
4146 SDValue Load
4147 = DAG.getMemIntrinsicNode(
4148 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4149 VTList, Ops, M->getMemoryVT(),
4150 M->getMemOperand());
4151 if (!Unpacked) // Just adjusted the opcode.
4152 return Load;
4153
4154 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4155
4156 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4157}
4158
4159SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4160 SelectionDAG &DAG,
4161 ArrayRef<SDValue> Ops) const {
4162 SDLoc DL(M);
4163 EVT LoadVT = M->getValueType(0);
4164 EVT EltType = LoadVT.getScalarType();
4165 EVT IntVT = LoadVT.changeTypeToInteger();
4166
4167 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4168
4169 unsigned Opc =
4170 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4171
4172 if (IsD16) {
4173 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4174 }
4175
4176 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4177 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4178 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4179
4180 if (isTypeLegal(LoadVT)) {
4181 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4182 M->getMemOperand(), DAG);
4183 }
4184
4185 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4186 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4187 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4188 M->getMemOperand(), DAG);
4189 return DAG.getMergeValues(
4190 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4191 DL);
4192}
4193
4194static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4195 SDNode *N, SelectionDAG &DAG) {
4196 EVT VT = N->getValueType(0);
4197 const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4198 int CondCode = CD->getSExtValue();
4199 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4200 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4201 return DAG.getUNDEF(VT);
4202
4203 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4204
4205 SDValue LHS = N->getOperand(1);
4206 SDValue RHS = N->getOperand(2);
4207
4208 SDLoc DL(N);
4209
4210 EVT CmpVT = LHS.getValueType();
4211 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4212 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4213 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4214 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4215 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4216 }
4217
4218 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4219
4220 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4221 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4222
4223 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4224 DAG.getCondCode(CCOpcode));
4225 if (VT.bitsEq(CCVT))
4226 return SetCC;
4227 return DAG.getZExtOrTrunc(SetCC, DL, VT);
4228}
4229
4230static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4231 SDNode *N, SelectionDAG &DAG) {
4232 EVT VT = N->getValueType(0);
4233 const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4234
4235 int CondCode = CD->getSExtValue();
4236 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4237 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4238 return DAG.getUNDEF(VT);
4239 }
4240
4241 SDValue Src0 = N->getOperand(1);
4242 SDValue Src1 = N->getOperand(2);
4243 EVT CmpVT = Src0.getValueType();
4244 SDLoc SL(N);
4245
4246 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4247 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4248 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4249 }
4250
4251 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4252 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4253 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4254 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4255 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4256 Src1, DAG.getCondCode(CCOpcode));
4257 if (VT.bitsEq(CCVT))
4258 return SetCC;
4259 return DAG.getZExtOrTrunc(SetCC, SL, VT);
4260}
4261
4262void SITargetLowering::ReplaceNodeResults(SDNode *N,
4263 SmallVectorImpl<SDValue> &Results,
4264 SelectionDAG &DAG) const {
4265 switch (N->getOpcode()) {
4266 case ISD::INSERT_VECTOR_ELT: {
4267 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4268 Results.push_back(Res);
4269 return;
4270 }
4271 case ISD::EXTRACT_VECTOR_ELT: {
4272 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4273 Results.push_back(Res);
4274 return;
4275 }
4276 case ISD::INTRINSIC_WO_CHAIN: {
4277 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4278 switch (IID) {
4279 case Intrinsic::amdgcn_cvt_pkrtz: {
4280 SDValue Src0 = N->getOperand(1);
4281 SDValue Src1 = N->getOperand(2);
4282 SDLoc SL(N);
4283 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4284 Src0, Src1);
4285 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4286 return;
4287 }
4288 case Intrinsic::amdgcn_cvt_pknorm_i16:
4289 case Intrinsic::amdgcn_cvt_pknorm_u16:
4290 case Intrinsic::amdgcn_cvt_pk_i16:
4291 case Intrinsic::amdgcn_cvt_pk_u16: {
4292 SDValue Src0 = N->getOperand(1);
4293 SDValue Src1 = N->getOperand(2);
4294 SDLoc SL(N);
4295 unsigned Opcode;
4296
4297 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4298 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4299 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4300 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4301 else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4302 Opcode = AMDGPUISD::CVT_PK_I16_I32;
4303 else
4304 Opcode = AMDGPUISD::CVT_PK_U16_U32;
4305
4306 EVT VT = N->getValueType(0);
4307 if (isTypeLegal(VT))
4308 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4309 else {
4310 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4311 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4312 }
4313 return;
4314 }
4315 }
4316 break;
4317 }
4318 case ISD::INTRINSIC_W_CHAIN: {
4319 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4320 if (Res.getOpcode() == ISD::MERGE_VALUES) {
4321 // FIXME: Hacky
4322 Results.push_back(Res.getOperand(0));
4323 Results.push_back(Res.getOperand(1));
4324 } else {
4325 Results.push_back(Res);
4326 Results.push_back(Res.getValue(1));
4327 }
4328 return;
4329 }
4330
4331 break;
4332 }
4333 case ISD::SELECT: {
4334 SDLoc SL(N);
4335 EVT VT = N->getValueType(0);
4336 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4337 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4338 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4339
4340 EVT SelectVT = NewVT;
4341 if (NewVT.bitsLT(MVT::i32)) {
4342 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4343 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4344 SelectVT = MVT::i32;
4345 }
4346
4347 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4348 N->getOperand(0), LHS, RHS);
4349
4350 if (NewVT != SelectVT)
4351 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4352 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4353 return;
4354 }
4355 case ISD::FNEG: {
4356 if (N->getValueType(0) != MVT::v2f16)
4357 break;
4358
4359 SDLoc SL(N);
4360 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4361
4362 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4363 BC,
4364 DAG.getConstant(0x80008000, SL, MVT::i32));
4365 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4366 return;
4367 }
4368 case ISD::FABS: {
4369 if (N->getValueType(0) != MVT::v2f16)
4370 break;
4371
4372 SDLoc SL(N);
4373 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4374
4375 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4376 BC,
4377 DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4378 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4379 return;
4380 }
4381 default:
4382 break;
4383 }
4384}
4385
4386/// Helper function for LowerBRCOND
4387static SDNode *findUser(SDValue Value, unsigned Opcode) {
4388
4389 SDNode *Parent = Value.getNode();
4390 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4391 I != E; ++I) {
4392
4393 if (I.getUse().get() != Value)
4394 continue;
4395
4396 if (I->getOpcode() == Opcode)
4397 return *I;
4398 }
4399 return nullptr;
4400}
4401
4402unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4403 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4404 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4405 case Intrinsic::amdgcn_if:
4406 return AMDGPUISD::IF;
4407 case Intrinsic::amdgcn_else:
4408 return AMDGPUISD::ELSE;
4409 case Intrinsic::amdgcn_loop:
4410 return AMDGPUISD::LOOP;
4411 case Intrinsic::amdgcn_end_cf:
4412 llvm_unreachable("should not occur")::llvm::llvm_unreachable_internal("should not occur", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4412)
;
4413 default:
4414 return 0;
4415 }
4416 }
4417
4418 // break, if_break, else_break are all only used as inputs to loop, not
4419 // directly as branch conditions.
4420 return 0;
4421}
4422
4423bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4424 const Triple &TT = getTargetMachine().getTargetTriple();
4425 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4426 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4427 AMDGPU::shouldEmitConstantsToTextSection(TT);
4428}
4429
4430bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4431 // FIXME: Either avoid relying on address space here or change the default
4432 // address space for functions to avoid the explicit check.
4433 return (GV->getValueType()->isFunctionTy() ||
4434 GV->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4435 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4436 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4437 !shouldEmitFixup(GV) &&
4438 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4439}
4440
4441bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4442 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4443}
4444
4445/// This transforms the control flow intrinsics to get the branch destination as
4446/// last parameter, also switches branch target with BR if the need arise
4447SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4448 SelectionDAG &DAG) const {
4449 SDLoc DL(BRCOND);
4450
4451 SDNode *Intr = BRCOND.getOperand(1).getNode();
4452 SDValue Target = BRCOND.getOperand(2);
4453 SDNode *BR = nullptr;
4454 SDNode *SetCC = nullptr;
4455
4456 if (Intr->getOpcode() == ISD::SETCC) {
4457 // As long as we negate the condition everything is fine
4458 SetCC = Intr;
4459 Intr = SetCC->getOperand(0).getNode();
4460
4461 } else {
4462 // Get the target from BR if we don't negate the condition
4463 BR = findUser(BRCOND, ISD::BR);
4464 Target = BR->getOperand(1);
4465 }
4466
4467 // FIXME: This changes the types of the intrinsics instead of introducing new
4468 // nodes with the correct types.
4469 // e.g. llvm.amdgcn.loop
4470
4471 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4472 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4473
4474 unsigned CFNode = isCFIntrinsic(Intr);
4475 if (CFNode == 0) {
4476 // This is a uniform branch so we don't need to legalize.
4477 return BRCOND;
4478 }
4479
4480 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4481 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4482
4483 assert(!SetCC ||((!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode()
)->get() == ISD::SETNE)) ? static_cast<void> (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4486, __PRETTY_FUNCTION__))
4484 (SetCC->getConstantOperandVal(1) == 1 &&((!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode()
)->get() == ISD::SETNE)) ? static_cast<void> (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4486, __PRETTY_FUNCTION__))
4485 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==((!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode()
)->get() == ISD::SETNE)) ? static_cast<void> (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4486, __PRETTY_FUNCTION__))
4486 ISD::SETNE))((!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode()
)->get() == ISD::SETNE)) ? static_cast<void> (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4486, __PRETTY_FUNCTION__))
;
4487
4488 // operands of the new intrinsic call
4489 SmallVector<SDValue, 4> Ops;
4490 if (HaveChain)
4491 Ops.push_back(BRCOND.getOperand(0));
4492
4493 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
4494 Ops.push_back(Target);
4495
4496 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4497
4498 // build the new intrinsic call
4499 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4500
4501 if (!HaveChain) {
4502 SDValue Ops[] = {
4503 SDValue(Result, 0),
4504 BRCOND.getOperand(0)
4505 };
4506
4507 Result = DAG.getMergeValues(Ops, DL).getNode();
4508 }
4509
4510 if (BR) {
4511 // Give the branch instruction our target
4512 SDValue Ops[] = {
4513 BR->getOperand(0),
4514 BRCOND.getOperand(2)
4515 };
4516 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4517 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4518 BR = NewBR.getNode();
4519 }
4520
4521 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4522
4523 // Copy the intrinsic results to registers
4524 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4525 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4526 if (!CopyToReg)
4527 continue;
4528
4529 Chain = DAG.getCopyToReg(
4530 Chain, DL,
4531 CopyToReg->getOperand(1),
4532 SDValue(Result, i - 1),
4533 SDValue());
4534
4535 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4536 }
4537
4538 // Remove the old intrinsic from the chain
4539 DAG.ReplaceAllUsesOfValueWith(
4540 SDValue(Intr, Intr->getNumValues() - 1),
4541 Intr->getOperand(0));
4542
4543 return Chain;
4544}
4545
4546SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4547 SelectionDAG &DAG) const {
4548 MVT VT = Op.getSimpleValueType();
4549 SDLoc DL(Op);
4550 // Checking the depth
4551 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4552 return DAG.getConstant(0, DL, VT);
4553
4554 MachineFunction &MF = DAG.getMachineFunction();
4555 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4556 // Check for kernel and shader functions
4557 if (Info->isEntryFunction())
4558 return DAG.getConstant(0, DL, VT);
4559
4560 MachineFrameInfo &MFI = MF.getFrameInfo();
4561 // There is a call to @llvm.returnaddress in this function
4562 MFI.setReturnAddressIsTaken(true);
4563
4564 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4565 // Get the return address reg and mark it as an implicit live-in
4566 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4567
4568 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4569}
4570
4571SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4572 SDValue Op,
4573 const SDLoc &DL,
4574 EVT VT) const {
4575 return Op.getValueType().bitsLE(VT) ?
4576 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4577 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4578}
4579
4580SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4581 assert(Op.getValueType() == MVT::f16 &&((Op.getValueType() == MVT::f16 && "Do not know how to custom lower FP_ROUND for non-f16 type"
) ? static_cast<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-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4582, __PRETTY_FUNCTION__))
4582 "Do not know how to custom lower FP_ROUND for non-f16 type")((Op.getValueType() == MVT::f16 && "Do not know how to custom lower FP_ROUND for non-f16 type"
) ? static_cast<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-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4582, __PRETTY_FUNCTION__))
;
4583
4584 SDValue Src = Op.getOperand(0);
4585 EVT SrcVT = Src.getValueType();
4586 if (SrcVT != MVT::f64)
4587 return Op;
4588
4589 SDLoc DL(Op);
4590
4591 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4592 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4593 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4594}
4595
4596SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4597 SelectionDAG &DAG) const {
4598 EVT VT = Op.getValueType();
4599 const MachineFunction &MF = DAG.getMachineFunction();
4600 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4601 bool IsIEEEMode = Info->getMode().IEEE;
4602
4603 // FIXME: Assert during eslection that this is only selected for
4604 // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4605 // mode functions, but this happens to be OK since it's only done in cases
4606 // where there is known no sNaN.
4607 if (IsIEEEMode)
4608 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4609
4610 if (VT == MVT::v4f16)
4611 return splitBinaryVectorOp(Op, DAG);
4612 return Op;
4613}
4614
4615SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4616 SDLoc SL(Op);
4617 SDValue Chain = Op.getOperand(0);
4618
4619 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4620 !Subtarget->isTrapHandlerEnabled())
4621 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4622
4623 MachineFunction &MF = DAG.getMachineFunction();
4624 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4625 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4626 assert(UserSGPR != AMDGPU::NoRegister)((UserSGPR != AMDGPU::NoRegister) ? static_cast<void> (
0) : __assert_fail ("UserSGPR != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4626, __PRETTY_FUNCTION__))
;
4627 SDValue QueuePtr = CreateLiveInRegister(
4628 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4629 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4630 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4631 QueuePtr, SDValue());
4632 SDValue Ops[] = {
4633 ToReg,
4634 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4635 SGPR01,
4636 ToReg.getValue(1)
4637 };
4638 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4639}
4640
4641SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4642 SDLoc SL(Op);
4643 SDValue Chain = Op.getOperand(0);
4644 MachineFunction &MF = DAG.getMachineFunction();
4645
4646 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4647 !Subtarget->isTrapHandlerEnabled()) {
4648 DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4649 "debugtrap handler not supported",
4650 Op.getDebugLoc(),
4651 DS_Warning);
4652 LLVMContext &Ctx = MF.getFunction().getContext();
4653 Ctx.diagnose(NoTrap);
4654 return Chain;
4655 }
4656
4657 SDValue Ops[] = {
4658 Chain,
4659 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4660 };
4661 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4662}
4663
4664SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4665 SelectionDAG &DAG) const {
4666 // FIXME: Use inline constants (src_{shared, private}_base) instead.
4667 if (Subtarget->hasApertureRegs()) {
4668 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4669 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4670 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4671 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4672 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4673 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4674 unsigned Encoding =
4675 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4676 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4677 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4678
4679 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4680 SDValue ApertureReg = SDValue(
4681 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4682 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4683 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4684 }
4685
4686 MachineFunction &MF = DAG.getMachineFunction();
4687 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4688 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4689 assert(UserSGPR != AMDGPU::NoRegister)((UserSGPR != AMDGPU::NoRegister) ? static_cast<void> (
0) : __assert_fail ("UserSGPR != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4689, __PRETTY_FUNCTION__))
;
4690
4691 SDValue QueuePtr = CreateLiveInRegister(
4692 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4693
4694 // Offset into amd_queue_t for group_segment_aperture_base_hi /
4695 // private_segment_aperture_base_hi.
4696 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4697
4698 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4699
4700 // TODO: Use custom target PseudoSourceValue.
4701 // TODO: We should use the value from the IR intrinsic call, but it might not
4702 // be available and how do we get it?
4703 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4704 AMDGPUAS::CONSTANT_ADDRESS));
4705
4706 MachinePointerInfo PtrInfo(V, StructOffset);
4707 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4708 MinAlign(64, StructOffset),
4709 MachineMemOperand::MODereferenceable |
4710 MachineMemOperand::MOInvariant);
4711}
4712
4713SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4714 SelectionDAG &DAG) const {
4715 SDLoc SL(Op);
4716 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4717
4718 SDValue Src = ASC->getOperand(0);
4719 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4720
4721 const AMDGPUTargetMachine &TM =
4722 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4723
4724 // flat -> local/private
4725 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4726 unsigned DestAS = ASC->getDestAddressSpace();
4727
4728 if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4729 DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4730 unsigned NullVal = TM.getNullPointerValue(DestAS);
4731 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4732 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4733 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4734
4735 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4736 NonNull, Ptr, SegmentNullPtr);
4737 }
4738 }
4739
4740 // local/private -> flat
4741 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4742 unsigned SrcAS = ASC->getSrcAddressSpace();
4743
4744 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4745 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4746 unsigned NullVal = TM.getNullPointerValue(SrcAS);
4747 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4748
4749 SDValue NonNull
4750 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4751
4752 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4753 SDValue CvtPtr
4754 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4755
4756 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4757 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4758 FlatNullPtr);
4759 }
4760 }
4761
4762 // global <-> flat are no-ops and never emitted.
4763
4764 const MachineFunction &MF = DAG.getMachineFunction();
4765 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4766 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4767 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4768
4769 return DAG.getUNDEF(ASC->getValueType(0));
4770}
4771
4772// This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4773// the small vector and inserting them into the big vector. That is better than
4774// the default expansion of doing it via a stack slot. Even though the use of
4775// the stack slot would be optimized away afterwards, the stack slot itself
4776// remains.
4777SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4778 SelectionDAG &DAG) const {
4779 SDValue Vec = Op.getOperand(0);
4780 SDValue Ins = Op.getOperand(1);
4781 SDValue Idx = Op.getOperand(2);
4782 EVT VecVT = Vec.getValueType();
4783 EVT InsVT = Ins.getValueType();
4784 EVT EltVT = VecVT.getVectorElementType();
4785 unsigned InsNumElts = InsVT.getVectorNumElements();
4786 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4787 SDLoc SL(Op);
4788
4789 for (unsigned I = 0; I != InsNumElts; ++I) {
4790 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4791 DAG.getConstant(I, SL, MVT::i32));
4792 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4793 DAG.getConstant(IdxVal + I, SL, MVT::i32));
4794 }
4795 return Vec;
4796}
4797
4798SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4799 SelectionDAG &DAG) const {
4800 SDValue Vec = Op.getOperand(0);
4801 SDValue InsVal = Op.getOperand(1);
4802 SDValue Idx = Op.getOperand(2);
4803 EVT VecVT = Vec.getValueType();
4804 EVT EltVT = VecVT.getVectorElementType();
4805 unsigned VecSize = VecVT.getSizeInBits();
4806 unsigned EltSize = EltVT.getSizeInBits();
4807
4808
4809 assert(VecSize <= 64)((VecSize <= 64) ? static_cast<void> (0) : __assert_fail
("VecSize <= 64", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4809, __PRETTY_FUNCTION__))
;
4810
4811 unsigned NumElts = VecVT.getVectorNumElements();
4812 SDLoc SL(Op);
4813 auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4814
4815 if (NumElts == 4 && EltSize == 16 && KIdx) {
4816 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4817
4818 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4819 DAG.getConstant(0, SL, MVT::i32));
4820 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4821 DAG.getConstant(1, SL, MVT::i32));
4822
4823 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4824 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4825
4826 unsigned Idx = KIdx->getZExtValue();
4827 bool InsertLo = Idx < 2;
4828 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4829 InsertLo ? LoVec : HiVec,
4830 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4831 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4832
4833 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4834
4835 SDValue Concat = InsertLo ?
4836 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4837 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4838
4839 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4840 }
4841
4842 if (isa<ConstantSDNode>(Idx))
4843 return SDValue();
4844
4845 MVT IntVT = MVT::getIntegerVT(VecSize);
4846
4847 // Avoid stack access for dynamic indexing.
4848 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4849
4850 // Create a congruent vector with the target value in each element so that
4851 // the required element can be masked and ORed into the target vector.
4852 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4853 DAG.getSplatBuildVector(VecVT, SL, InsVal));
4854
4855 assert(isPowerOf2_32(EltSize))((isPowerOf2_32(EltSize)) ? static_cast<void> (0) : __assert_fail
("isPowerOf2_32(EltSize)", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4855, __PRETTY_FUNCTION__))
;
4856 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4857
4858 // Convert vector index to bit-index.
4859 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4860
4861 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4862 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4863 DAG.getConstant(0xffff, SL, IntVT),
4864 ScaledIdx);
4865
4866 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4867 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4868 DAG.getNOT(SL, BFM, IntVT), BCVec);
4869
4870 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4871 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4872}
4873
4874SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4875 SelectionDAG &DAG) const {
4876 SDLoc SL(Op);
4877
4878 EVT ResultVT = Op.getValueType();
4879 SDValue Vec = Op.getOperand(0);
4880 SDValue Idx = Op.getOperand(1);
4881 EVT VecVT = Vec.getValueType();
4882 unsigned VecSize = VecVT.getSizeInBits();
4883 EVT EltVT = VecVT.getVectorElementType();
4884 assert(VecSize <= 64)((VecSize <= 64) ? static_cast<void> (0) : __assert_fail
("VecSize <= 64", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4884, __PRETTY_FUNCTION__))
;
4885
4886 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4887
4888 // Make sure we do any optimizations that will make it easier to fold
4889 // source modifiers before obscuring it with bit operations.
4890
4891 // XXX - Why doesn't this get called when vector_shuffle is expanded?
4892 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4893 return Combined;
4894
4895 unsigned EltSize = EltVT.getSizeInBits();
4896 assert(isPowerOf2_32(EltSize))((isPowerOf2_32(EltSize)) ? static_cast<void> (0) : __assert_fail
("isPowerOf2_32(EltSize)", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4896, __PRETTY_FUNCTION__))
;
4897
4898 MVT IntVT = MVT::getIntegerVT(VecSize);
4899 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4900
4901 // Convert vector index to bit-index (* EltSize)
4902 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4903
4904 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4905 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4906
4907 if (ResultVT == MVT::f16) {
4908 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4909 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4910 }
4911
4912 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4913}
4914
4915static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
4916 assert(Elt % 2 == 0)((Elt % 2 == 0) ? static_cast<void> (0) : __assert_fail
("Elt % 2 == 0", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4916, __PRETTY_FUNCTION__))
;
4917 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
4918}
4919
4920SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4921 SelectionDAG &DAG) const {
4922 SDLoc SL(Op);
4923 EVT ResultVT = Op.getValueType();
4924 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
4925
4926 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
4927 EVT EltVT = PackVT.getVectorElementType();
4928 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
4929
4930 // vector_shuffle <0,1,6,7> lhs, rhs
4931 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
4932 //
4933 // vector_shuffle <6,7,2,3> lhs, rhs
4934 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
4935 //
4936 // vector_shuffle <6,7,0,1> lhs, rhs
4937 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
4938
4939 // Avoid scalarizing when both halves are reading from consecutive elements.
4940 SmallVector<SDValue, 4> Pieces;
4941 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
4942 if (elementPairIsContiguous(SVN->getMask(), I)) {
4943 const int Idx = SVN->getMaskElt(I);
4944 int VecIdx = Idx < SrcNumElts ? 0 : 1;
4945 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
4946 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
4947 PackVT, SVN->getOperand(VecIdx),
4948 DAG.getConstant(EltIdx, SL, MVT::i32));
4949 Pieces.push_back(SubVec);
4950 } else {
4951 const int Idx0 = SVN->getMaskElt(I);
4952 const int Idx1 = SVN->getMaskElt(I + 1);
4953 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
4954 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
4955 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
4956 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
4957
4958 SDValue Vec0 = SVN->getOperand(VecIdx0);
4959 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4960 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
4961
4962 SDValue Vec1 = SVN->getOperand(VecIdx1);
4963 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4964 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
4965 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
4966 }
4967 }
4968
4969 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
4970}
4971
4972SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4973 SelectionDAG &DAG) const {
4974 SDLoc SL(Op);
4975 EVT VT = Op.getValueType();
4976
4977 if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4978 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4979
4980 // Turn into pair of packed build_vectors.
4981 // TODO: Special case for constants that can be materialized with s_mov_b64.
4982 SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4983 { Op.getOperand(0), Op.getOperand(1) });
4984 SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4985 { Op.getOperand(2), Op.getOperand(3) });
4986
4987 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4988 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4989
4990 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4991 return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4992 }
4993
4994 assert(VT == MVT::v2f16 || VT == MVT::v2i16)((VT == MVT::v2f16 || VT == MVT::v2i16) ? static_cast<void
> (0) : __assert_fail ("VT == MVT::v2f16 || VT == MVT::v2i16"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4994, __PRETTY_FUNCTION__))
;
4995 assert(!Subtarget->hasVOP3PInsts() && "this should be legal")((!Subtarget->hasVOP3PInsts() && "this should be legal"
) ? static_cast<void> (0) : __assert_fail ("!Subtarget->hasVOP3PInsts() && \"this should be legal\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4995, __PRETTY_FUNCTION__))
;
4996
4997 SDValue Lo = Op.getOperand(0);
4998 SDValue Hi = Op.getOperand(1);
4999
5000 // Avoid adding defined bits with the zero_extend.
5001 if (Hi.isUndef()) {
5002 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5003 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5004 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5005 }
5006
5007 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5008 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5009
5010 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5011 DAG.getConstant(16, SL, MVT::i32));
5012 if (Lo.isUndef())
5013 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5014
5015 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5016 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5017
5018 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5019 return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5020}
5021
5022bool
5023SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5024 // We can fold offsets for anything that doesn't require a GOT relocation.
5025 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5026 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5027 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5028 !shouldEmitGOTReloc(GA->getGlobal());
5029}
5030
5031static SDValue
5032buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5033 const SDLoc &DL, unsigned Offset, EVT PtrVT,
5034 unsigned GAFlags = SIInstrInfo::MO_NONE) {
5035 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5036 // lowered to the following code sequence:
5037 //
5038 // For constant address space:
5039 // s_getpc_b64 s[0:1]
5040 // s_add_u32 s0, s0, $symbol
5041 // s_addc_u32 s1, s1, 0
5042 //
5043 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
5044 // a fixup or relocation is emitted to replace $symbol with a literal
5045 // constant, which is a pc-relative offset from the encoding of the $symbol
5046 // operand to the global variable.
5047 //
5048 // For global address space:
5049 // s_getpc_b64 s[0:1]
5050 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5051 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5052 //
5053 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
5054 // fixups or relocations are emitted to replace $symbol@*@lo and
5055 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5056 // which is a 64-bit pc-relative offset from the encoding of the $symbol
5057 // operand to the global variable.
5058 //
5059 // What we want here is an offset from the value returned by s_getpc
5060 // (which is the address of the s_add_u32 instruction) to the global
5061 // variable, but since the encoding of $symbol starts 4 bytes after the start
5062 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5063 // small. This requires us to add 4 to the global variable offset in order to
5064 // compute the correct address.
5065 SDValue PtrLo =
5066 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5067 SDValue PtrHi;
5068 if (GAFlags == SIInstrInfo::MO_NONE) {
5069 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5070 } else {
5071 PtrHi =
5072 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5073 }
5074 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5075}
5076
5077SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5078 SDValue Op,
5079 SelectionDAG &DAG) const {
5080 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5081 const GlobalValue *GV = GSD->getGlobal();
5082 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5083 (!GV->hasExternalLinkage() ||
5084 getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
5085 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) ||
5086 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5087 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5088 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5089
5090 SDLoc DL(GSD);
5091 EVT PtrVT = Op.getValueType();
5092
5093 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5094 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5095 SIInstrInfo::MO_ABS32_LO);
5096 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5097 }
5098
5099 if (shouldEmitFixup(GV))
5100 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5101 else if (shouldEmitPCReloc(GV))
5102 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5103 SIInstrInfo::MO_REL32);
5104
5105 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5106 SIInstrInfo::MO_GOTPCREL32);
5107
5108 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5109 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5110 const DataLayout &DataLayout = DAG.getDataLayout();
5111 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5112 MachinePointerInfo PtrInfo
5113 = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5114
5115 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5116 MachineMemOperand::MODereferenceable |
5117 MachineMemOperand::MOInvariant);
5118}
5119
5120SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5121 const SDLoc &DL, SDValue V) const {
5122 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5123 // the destination register.
5124 //
5125 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5126 // so we will end up with redundant moves to m0.
5127 //
5128 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5129
5130 // A Null SDValue creates a glue result.
5131 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5132 V, Chain);
5133 return SDValue(M0, 0);
5134}
5135
5136SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5137 SDValue Op,
5138 MVT VT,
5139 unsigned Offset) const {
5140 SDLoc SL(Op);
5141 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5142 DAG.getEntryNode(), Offset, 4, false);
5143 // The local size values will have the hi 16-bits as zero.
5144 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5145 DAG.getValueType(VT));
5146}
5147
5148static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5149 EVT VT) {
5150 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5151 "non-hsa intrinsic with hsa target",
5152 DL.getDebugLoc());
5153 DAG.getContext()->diagnose(BadIntrin);
5154 return DAG.getUNDEF(VT);
5155}
5156
5157static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5158 EVT VT) {
5159 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5160 "intrinsic not supported on subtarget",
5161 DL.getDebugLoc());
5162 DAG.getContext()->diagnose(BadIntrin);
5163 return DAG.getUNDEF(VT);
5164}
5165
5166static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5167 ArrayRef<SDValue> Elts) {
5168 assert(!Elts.empty())((!Elts.empty()) ? static_cast<void> (0) : __assert_fail
("!Elts.empty()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5168, __PRETTY_FUNCTION__))
;
5169 MVT Type;
5170 unsigned NumElts;
5171
5172 if (Elts.size() == 1) {
5173 Type = MVT::f32;
5174 NumElts = 1;
5175 } else if (Elts.size() == 2) {
5176 Type = MVT::v2f32;
5177 NumElts = 2;
5178 } else if (Elts.size() <= 4) {
5179 Type = MVT::v4f32;
5180 NumElts = 4;
5181 } else if (Elts.size() <= 8) {
5182 Type = MVT::v8f32;
5183 NumElts = 8;
5184 } else {
5185 assert(Elts.size() <= 16)((Elts.size() <= 16) ? static_cast<void> (0) : __assert_fail
("Elts.size() <= 16", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5185, __PRETTY_FUNCTION__))
;
5186 Type = MVT::v16f32;
5187 NumElts = 16;
5188 }
5189
5190 SmallVector<SDValue, 16> VecElts(NumElts);
5191 for (unsigned i = 0; i < Elts.size(); ++i) {
5192 SDValue Elt = Elts[i];
5193 if (Elt.getValueType() != MVT::f32)
5194 Elt = DAG.getBitcast(MVT::f32, Elt);
5195 VecElts[i] = Elt;
5196 }
5197 for (unsigned i = Elts.size(); i < NumElts; ++i)
5198 VecElts[i] = DAG.getUNDEF(MVT::f32);
5199
5200 if (NumElts == 1)
5201 return VecElts[0];
5202 return DAG.getBuildVector(Type, DL, VecElts);
5203}
5204
5205static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5206 SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5207 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5208
5209 uint64_t Value = CachePolicyConst->getZExtValue();
5210 SDLoc DL(CachePolicy);
5211 if (GLC) {
5212 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5213 Value &= ~(uint64_t)0x1;
5214 }
5215 if (SLC) {
5216 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5217 Value &= ~(uint64_t)0x2;
5218 }
5219 if (DLC) {
5220 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5221 Value &= ~(uint64_t)0x4;
5222 }
5223
5224 return Value == 0;
5225}
5226
5227// Re-construct the required return value for a image load intrinsic.
5228// This is more complicated due to the optional use TexFailCtrl which means the required
5229// return type is an aggregate
5230static SDValue constructRetValue(SelectionDAG &DAG,
5231 MachineSDNode *Result,
5232 ArrayRef<EVT> ResultTypes,
5233 bool IsTexFail, bool Unpacked, bool IsD16,
5234 int DMaskPop, int NumVDataDwords,
5235 const SDLoc &DL, LLVMContext &Context) {
5236 // Determine the required return type. This is the same regardless of IsTexFail flag
5237 EVT ReqRetVT = ResultTypes[0];
5238 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT;
5239 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5240 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT;
5241 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts)
5242 : AdjEltVT
5243 : ReqRetVT;
5244
5245 // Extract data part of the result
5246 // Bitcast the result to the same type as the required return type
5247 int NumElts;
5248 if (IsD16 && !Unpacked)
5249 NumElts = NumVDataDwords << 1;
5250 else
5251 NumElts = NumVDataDwords;
5252
5253 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts)
5254 : AdjEltVT;
5255
5256 // Special case for v6f16. Rather than add support for this, use v3i32 to
5257 // extract the data elements
5258 bool V6F16Special = false;
5259 if (NumElts == 6) {
5260 CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2);
5261 DMaskPop >>= 1;
5262 ReqRetNumElts >>= 1;
5263 V6F16Special = true;
5264 AdjVT = MVT::v2i32;
5265 }
5266
5267 SDValue N = SDValue(Result, 0);
5268 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N);
5269
5270 // Iterate over the result
5271 SmallVector<SDValue, 4> BVElts;
5272
5273 if (CastVT.isVector()) {
5274 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop);
5275 } else {
5276 BVElts.push_back(CastRes);
5277 }
5278 int ExtraElts = ReqRetNumElts - DMaskPop;
5279 while(ExtraElts--)
5280 BVElts.push_back(DAG.getUNDEF(AdjEltVT));
5281
5282 SDValue PreTFCRes;
5283 if (ReqRetNumElts > 1) {
5284 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts);
5285 if (IsD16 && Unpacked)
5286 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked);
5287 else
5288 PreTFCRes = NewVec;
5289 } else {
5290 PreTFCRes = BVElts[0];
5291 }
5292
5293 if (V6F16Special)
5294 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes);
5295
5296 if (!IsTexFail) {
5297 if (Result->getNumValues() > 1)
5298 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL);
5299 else
5300 return PreTFCRes;
5301 }
5302
5303 // Extract the TexFail result and insert into aggregate return
5304 SmallVector<SDValue, 1> TFCElt;
5305 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1);
5306 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]);
5307 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL);
5308}
5309
5310static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5311 SDValue *LWE, bool &IsTexFail) {
5312 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5313
5314 uint64_t Value = TexFailCtrlConst->getZExtValue();
5315 if (Value) {
5316 IsTexFail = true;
5317 }
5318
5319 SDLoc DL(TexFailCtrlConst);
5320 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5321 Value &= ~(uint64_t)0x1;
5322 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5323 Value &= ~(uint64_t)0x2;
5324
5325 return Value == 0;
5326}
5327
5328SDValue SITargetLowering::lowerImage(SDValue Op,
5329 const AMDGPU::ImageDimIntrinsicInfo *Intr,
5330 SelectionDAG &DAG) const {
5331 SDLoc DL(Op);
5332 MachineFunction &MF = DAG.getMachineFunction();
5333 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5334 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5335 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5336 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5337 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5338 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5339 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5340 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5341 unsigned IntrOpcode = Intr->BaseOpcode;
5342 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5343
5344 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5345 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5346 bool IsD16 = false;
5347 bool IsA16 = false;
5348 SDValue VData;
5349 int NumVDataDwords;
5350 bool AdjustRetType = false;
5351
5352 unsigned AddrIdx; // Index of first address argument
5353 unsigned DMask;
5354 unsigned DMaskLanes = 0;
5355
5356 if (BaseOpcode->Atomic) {
5357 VData = Op.getOperand(2);
5358
5359 bool Is64Bit = VData.getValueType() == MVT::i64;
5360 if (BaseOpcode->AtomicX2) {
5361 SDValue VData2 = Op.getOperand(3);
5362 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5363 {VData, VData2});
5364 if (Is64Bit)
5365 VData = DAG.getBitcast(MVT::v4i32, VData);
5366
5367 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5368 DMask = Is64Bit ? 0xf : 0x3;
5369 NumVDataDwords = Is64Bit ? 4 : 2;
5370 AddrIdx = 4;
5371 } else {
5372 DMask = Is64Bit ? 0x3 : 0x1;
5373 NumVDataDwords = Is64Bit ? 2 : 1;
5374 AddrIdx = 3;
5375 }
5376 } else {
5377 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5378 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5379 DMask = DMaskConst->getZExtValue();
5380 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5381
5382 if (BaseOpcode->Store) {
5383 VData = Op.getOperand(2);
5384
5385 MVT StoreVT = VData.getSimpleValueType();
5386 if (StoreVT.getScalarType() == MVT::f16) {
5387 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5388 return Op; // D16 is unsupported for this instruction
5389
5390 IsD16 = true;
5391 VData = handleD16VData(VData, DAG);
5392 }
5393
5394 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5395 } else {
5396 // Work out the num dwords based on the dmask popcount and underlying type
5397 // and whether packing is supported.
5398 MVT LoadVT = ResultTypes[0].getSimpleVT();
5399 if (LoadVT.getScalarType() == MVT::f16) {
5400 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5401 return Op; // D16 is unsupported for this instruction
5402
5403 IsD16 = true;
5404 }
5405
5406 // Confirm that the return type is large enough for the dmask specified
5407 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5408 (!LoadVT.isVector() && DMaskLanes > 1))
5409 return Op;
5410
5411 if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5412 NumVDataDwords = (DMaskLanes + 1) / 2;
5413 else
5414 NumVDataDwords = DMaskLanes;
5415
5416 AdjustRetType = true;
5417 }
5418
5419 AddrIdx = DMaskIdx + 1;
5420 }
5421
5422 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5423 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5424 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5425 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5426 NumCoords + NumLCM;
5427 unsigned NumMIVAddrs = NumVAddrs;
5428
5429 SmallVector<SDValue, 4> VAddrs;
5430
5431 // Optimize _L to _LZ when _L is zero
5432 if (LZMappingInfo) {
5433 if (auto ConstantLod =
5434 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5435 if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5436 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l
5437 NumMIVAddrs--; // remove 'lod'
5438 }
5439 }
5440 }
5441
5442 // Optimize _mip away, when 'lod' is zero
5443 if (MIPMappingInfo) {
5444 if (auto ConstantLod =
5445 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5446 if (ConstantLod->isNullValue()) {
5447 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip
5448 NumMIVAddrs--; // remove 'lod'
5449 }
5450 }
5451 }
5452
5453 // Check for 16 bit addresses and pack if true.
5454 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5455 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5456 const MVT VAddrScalarVT = VAddrVT.getScalarType();
5457 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) &&
5458 ST->hasFeature(AMDGPU::FeatureR128A16)) {
5459 IsA16 = true;
5460 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5461 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5462 SDValue AddrLo, AddrHi;
5463 // Push back extra arguments.
5464 if (i < DimIdx) {
5465 AddrLo = Op.getOperand(i);
5466 } else {
5467 AddrLo = Op.getOperand(i);
5468 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5469 // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5470 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5471 ((NumGradients / 2) % 2 == 1 &&
5472 (i == DimIdx + (NumGradients / 2) - 1 ||
5473 i == DimIdx + NumGradients - 1))) {
5474 AddrHi = DAG.getUNDEF(MVT::f16);
5475 } else {
5476 AddrHi = Op.getOperand(i + 1);
5477 i++;
5478 }
5479 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT,
5480 {AddrLo, AddrHi});
5481 AddrLo = DAG.getBitcast(MVT::i32, AddrLo);
5482 }
5483 VAddrs.push_back(AddrLo);
5484 }
5485 } else {
5486 for (unsigned i = 0; i < NumMIVAddrs; ++i)
5487 VAddrs.push_back(Op.getOperand(AddrIdx + i));
5488 }
5489
5490 // If the register allocator cannot place the address registers contiguously
5491 // without introducing moves, then using the non-sequential address encoding
5492 // is always preferable, since it saves VALU instructions and is usually a
5493 // wash in terms of code size or even better.
5494 //
5495 // However, we currently have no way of hinting to the register allocator that
5496 // MIMG addresses should be placed contiguously when it is possible to do so,
5497 // so force non-NSA for the common 2-address case as a heuristic.
5498 //
5499 // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5500 // allocation when possible.
5501 bool UseNSA =
5502 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5503 SDValue VAddr;
5504 if (!UseNSA)
5505 VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5506
5507 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5508 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5509 unsigned CtrlIdx; // Index of texfailctrl argument
5510 SDValue Unorm;
5511 if (!BaseOpcode->Sampler) {
5512 Unorm = True;
5513 CtrlIdx = AddrIdx + NumVAddrs + 1;
5514 } else {
5515 auto UnormConst =
5516 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5517
5518 Unorm = UnormConst->getZExtValue() ? True : False;
5519 CtrlIdx = AddrIdx + NumVAddrs + 3;
5520 }
5521
5522 SDValue TFE;
5523 SDValue LWE;
5524 SDValue TexFail = Op.getOperand(CtrlIdx);
5525 bool IsTexFail = false;
5526 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5527 return Op;
5528
5529 if (IsTexFail) {
5530 if (!DMaskLanes) {
5531 // Expecting to get an error flag since TFC is on - and dmask is 0
5532 // Force dmask to be at least 1 otherwise the instruction will fail
5533 DMask = 0x1;
5534 DMaskLanes = 1;
5535 NumVDataDwords = 1;
5536 }
5537 NumVDataDwords += 1;
5538 AdjustRetType = true;
5539 }
5540
5541 // Has something earlier tagged that the return type needs adjusting
5542 // This happens if the instruction is a load or has set TexFailCtrl flags
5543 if (AdjustRetType) {
5544 // NumVDataDwords reflects the true number of dwords required in the return type
5545 if (DMaskLanes == 0 && !BaseOpcode->Store) {
5546 // This is a no-op load. This can be eliminated
5547 SDValue Undef = DAG.getUNDEF(Op.getValueType());
5548 if (isa<MemSDNode>(Op))
5549 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5550 return Undef;
5551 }
5552
5553 EVT NewVT = NumVDataDwords > 1 ?
5554 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords)
5555 : MVT::f32;
5556
5557 ResultTypes[0] = NewVT;
5558 if (ResultTypes.size() == 3) {
5559 // Original result was aggregate type used for TexFailCtrl results
5560 // The actual instruction returns as a vector type which has now been
5561 // created. Remove the aggregate result.
5562 ResultTypes.erase(&ResultTypes[1]);
5563 }
5564 }
5565
5566 SDValue GLC;
5567 SDValue SLC;
5568 SDValue DLC;
5569 if (BaseOpcode->Atomic) {
5570 GLC = True; // TODO no-return optimization
5571 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5572 IsGFX10 ? &DLC : nullptr))
5573 return Op;
5574 } else {
5575 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5576 IsGFX10 ? &DLC : nullptr))
5577 return Op;
5578 }
5579
5580 SmallVector<SDValue, 26> Ops;
5581 if (BaseOpcode->Store || BaseOpcode->Atomic)
5582 Ops.push_back(VData); // vdata
5583 if (UseNSA) {
5584 for (const SDValue &Addr : VAddrs)
5585 Ops.push_back(Addr);
5586 } else {
5587 Ops.push_back(VAddr);
5588 }
5589 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5590 if (BaseOpcode->Sampler)
5591 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5592 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5593 if (IsGFX10)
5594 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5595 Ops.push_back(Unorm);
5596 if (IsGFX10)
5597 Ops.push_back(DLC);
5598 Ops.push_back(GLC);
5599 Ops.push_back(SLC);
5600 Ops.push_back(IsA16 && // a16 or r128
5601 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5602 Ops.push_back(TFE); // tfe
5603 Ops.push_back(LWE); // lwe
5604 if (!IsGFX10)
5605 Ops.push_back(DimInfo->DA ? True : False);
5606 if (BaseOpcode->HasD16)
5607 Ops.push_back(IsD16 ? True : False);
5608 if (isa<MemSDNode>(Op))
5609 Ops.push_back(Op.getOperand(0)); // chain
5610
5611 int NumVAddrDwords =
5612 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5613 int Opcode = -1;
5614
5615 if (IsGFX10) {
5616 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5617 UseNSA ? AMDGPU::MIMGEncGfx10NSA
5618 : AMDGPU::MIMGEncGfx10Default,
5619 NumVDataDwords, NumVAddrDwords);
5620 } else {
5621 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5622 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5623 NumVDataDwords, NumVAddrDwords);
5624 if (Opcode == -1)
5625 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5626 NumVDataDwords, NumVAddrDwords);
5627 }
5628 assert(Opcode != -1)((Opcode != -1) ? static_cast<void> (0) : __assert_fail
("Opcode != -1", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5628, __PRETTY_FUNCTION__))
;
5629
5630 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5631 if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5632 MachineMemOperand *MemRef = MemOp->getMemOperand();
5633 DAG.setNodeMemRefs(NewNode, {MemRef});
5634 }
5635
5636 if (BaseOpcode->AtomicX2) {
5637 SmallVector<SDValue, 1> Elt;
5638 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5639 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5640 } else if (!BaseOpcode->Store) {
5641 return constructRetValue(DAG, NewNode,
5642 OrigResultTypes, IsTexFail,
5643 Subtarget->hasUnpackedD16VMem(), IsD16,
5644 DMaskLanes, NumVDataDwords, DL,
5645 *DAG.getContext());
5646 }
5647
5648 return SDValue(NewNode, 0);
5649}
5650
5651SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5652 SDValue Offset, SDValue GLC, SDValue DLC,
5653 SelectionDAG &DAG) const {
5654 MachineFunction &MF = DAG.getMachineFunction();
5655 MachineMemOperand *MMO = MF.getMachineMemOperand(
5656 MachinePointerInfo(),
5657 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5658 MachineMemOperand::MOInvariant,
5659 VT.getStoreSize(), VT.getStoreSize());
5660
5661 if (!Offset->isDivergent()) {
5662 SDValue Ops[] = {
5663 Rsrc,
5664 Offset, // Offset
5665 GLC,
5666 DLC,
5667 };
5668 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5669 DAG.getVTList(VT), Ops, VT, MMO);
5670 }
5671
5672 // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5673 // assume that the buffer is unswizzled.
5674 SmallVector<SDValue, 4> Loads;
5675 unsigned NumLoads = 1;
5676 MVT LoadVT = VT.getSimpleVT();
5677 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5678 assert((LoadVT.getScalarType() == MVT::i32 ||(((LoadVT.getScalarType() == MVT::i32 || LoadVT.getScalarType
() == MVT::f32) && isPowerOf2_32(NumElts)) ? static_cast
<void> (0) : __assert_fail ("(LoadVT.getScalarType() == MVT::i32 || LoadVT.getScalarType() == MVT::f32) && isPowerOf2_32(NumElts)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5680, __PRETTY_FUNCTION__))
5679 LoadVT.getScalarType() == MVT::f32) &&(((LoadVT.getScalarType() == MVT::i32 || LoadVT.getScalarType
() == MVT::f32) && isPowerOf2_32(NumElts)) ? static_cast
<void> (0) : __assert_fail ("(LoadVT.getScalarType() == MVT::i32 || LoadVT.getScalarType() == MVT::f32) && isPowerOf2_32(NumElts)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5680, __PRETTY_FUNCTION__))
5680 isPowerOf2_32(NumElts))(((LoadVT.getScalarType() == MVT::i32 || LoadVT.getScalarType
() == MVT::f32) && isPowerOf2_32(NumElts)) ? static_cast
<void> (0) : __assert_fail ("(LoadVT.getScalarType() == MVT::i32 || LoadVT.getScalarType() == MVT::f32) && isPowerOf2_32(NumElts)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5680, __PRETTY_FUNCTION__))
;
5681
5682 if (NumElts == 8 || NumElts == 16) {
5683 NumLoads = NumElts == 16 ? 4 : 2;
5684 LoadVT = MVT::v4i32;
5685 }
5686
5687 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5688 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue();
5689 SDValue Ops[] = {
5690 DAG.getEntryNode(), // Chain
5691 Rsrc, // rsrc
5692 DAG.getConstant(0, DL, MVT::i32), // vindex
5693 {}, // voffset
5694 {}, // soffset
5695 {}, // offset
5696 DAG.getTargetConstant(CachePolicy, DL, MVT::i32), // cachepolicy
5697 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
5698 };
5699
5700 // Use the alignment to ensure that the required offsets will fit into the
5701 // immediate offsets.
5702 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5703
5704 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5705 for (unsigned i = 0; i < NumLoads; ++i) {
5706 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5707 Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList,
5708 Ops, LoadVT, MMO));
5709 }
5710
5711 if (VT == MVT::v8i32 || VT == MVT::v16i32)
5712 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5713
5714 return Loads[0];
5715}
5716
5717SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5718 SelectionDAG &DAG) const {
5719 MachineFunction &MF = DAG.getMachineFunction();
5720 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5721
5722 EVT VT = Op.getValueType();
5723 SDLoc DL(Op);
5724 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5725
5726 // TODO: Should this propagate fast-math-flags?
5727
5728 switch (IntrinsicID) {
5729 case Intrinsic::amdgcn_implicit_buffer_ptr: {
5730 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5731 return emitNonHSAIntrinsicError(DAG, DL, VT);
5732 return getPreloadedValue(DAG, *MFI, VT,
5733 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5734 }
5735 case Intrinsic::amdgcn_dispatch_ptr:
5736 case Intrinsic::amdgcn_queue_ptr: {
5737 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5738 DiagnosticInfoUnsupported BadIntrin(
5739 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5740 DL.getDebugLoc());
5741 DAG.getContext()->diagnose(BadIntrin);
5742 return DAG.getUNDEF(VT);
5743 }
5744
5745 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5746 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5747 return getPreloadedValue(DAG, *MFI, VT, RegID);
5748 }
5749 case Intrinsic::amdgcn_implicitarg_ptr: {
5750 if (MFI->isEntryFunction())
5751 return getImplicitArgPtr(DAG, DL);
5752 return getPreloadedValue(DAG, *MFI, VT,
5753 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5754 }
5755 case Intrinsic::amdgcn_kernarg_segment_ptr: {
5756 return getPreloadedValue(DAG, *MFI, VT,
5757 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5758 }
5759 case Intrinsic::amdgcn_dispatch_id: {
5760 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5761 }
5762 case Intrinsic::amdgcn_rcp:
5763 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5764 case Intrinsic::amdgcn_rsq:
5765 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5766 case Intrinsic::amdgcn_rsq_legacy:
5767 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5768 return emitRemovedIntrinsicError(DAG, DL, VT);
5769
5770 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5771 case Intrinsic::amdgcn_rcp_legacy:
5772 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5773 return emitRemovedIntrinsicError(DAG, DL, VT);
5774 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5775 case Intrinsic::amdgcn_rsq_clamp: {
5776 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5777 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5778
5779 Type *Type = VT.getTypeForEVT(*DAG.getContext());
5780 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5781 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5782
5783 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5784 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5785 DAG.getConstantFP(Max, DL, VT));
5786 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5787 DAG.getConstantFP(Min, DL, VT));
5788 }
5789 case Intrinsic::r600_read_ngroups_x:
5790 if (Subtarget->isAmdHsaOS())
5791 return emitNonHSAIntrinsicError(DAG, DL, VT);
5792
5793 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5794 SI::KernelInputOffsets::NGROUPS_X, 4, false);
5795 case Intrinsic::r600_read_ngroups_y:
5796 if (Subtarget->isAmdHsaOS())
5797 return emitNonHSAIntrinsicError(DAG, DL, VT);
5798
5799 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5800 SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5801 case Intrinsic::r600_read_ngroups_z:
5802 if (Subtarget->isAmdHsaOS())
5803 return emitNonHSAIntrinsicError(DAG, DL, VT);
5804
5805 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5806 SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5807 case Intrinsic::r600_read_global_size_x:
5808 if (Subtarget->isAmdHsaOS())
5809 return emitNonHSAIntrinsicError(DAG, DL, VT);
5810
5811 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5812 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5813 case Intrinsic::r600_read_global_size_y:
5814 if (Subtarget->isAmdHsaOS())
5815 return emitNonHSAIntrinsicError(DAG, DL, VT);
5816
5817 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5818 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5819 case Intrinsic::r600_read_global_size_z:
5820 if (Subtarget->isAmdHsaOS())
5821 return emitNonHSAIntrinsicError(DAG, DL, VT);
5822
5823 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5824 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5825 case Intrinsic::r600_read_local_size_x:
5826 if (Subtarget->isAmdHsaOS())
5827 return emitNonHSAIntrinsicError(DAG, DL, VT);
5828
5829 return lowerImplicitZextParam(DAG, Op, MVT::i16,
5830 SI::KernelInputOffsets::LOCAL_SIZE_X);
5831 case Intrinsic::r600_read_local_size_y:
5832 if (Subtarget->isAmdHsaOS())
5833 return emitNonHSAIntrinsicError(DAG, DL, VT);
5834
5835 return lowerImplicitZextParam(DAG, Op, MVT::i16,
5836 SI::KernelInputOffsets::LOCAL_SIZE_Y);
5837 case Intrinsic::r600_read_local_size_z:
5838 if (Subtarget->isAmdHsaOS())
5839 return emitNonHSAIntrinsicError(DAG, DL, VT);
5840
5841 return lowerImplicitZextParam(DAG, Op, MVT::i16,
5842 SI::KernelInputOffsets::LOCAL_SIZE_Z);
5843 case Intrinsic::amdgcn_workgroup_id_x:
5844 case Intrinsic::r600_read_tgid_x:
5845 return getPreloadedValue(DAG, *MFI, VT,
5846 AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5847 case Intrinsic::amdgcn_workgroup_id_y:
5848 case Intrinsic::r600_read_tgid_y:
5849 return getPreloadedValue(DAG, *MFI, VT,
5850 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5851 case Intrinsic::amdgcn_workgroup_id_z:
5852 case Intrinsic::r600_read_tgid_z:
5853 return getPreloadedValue(DAG, *MFI, VT,
5854 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5855 case Intrinsic::amdgcn_workitem_id_x:
5856 case Intrinsic::r600_read_tidig_x:
5857 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5858 SDLoc(DAG.getEntryNode()),
5859 MFI->getArgInfo().WorkItemIDX);
5860 case Intrinsic::amdgcn_workitem_id_y:
5861 case Intrinsic::r600_read_tidig_y:
5862 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5863 SDLoc(DAG.getEntryNode()),
5864 MFI->getArgInfo().WorkItemIDY);
5865 case Intrinsic::amdgcn_workitem_id_z:
5866 case Intrinsic::r600_read_tidig_z:
5867 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5868 SDLoc(DAG.getEntryNode()),
5869 MFI->getArgInfo().WorkItemIDZ);
5870 case Intrinsic::amdgcn_wavefrontsize:
5871 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
5872 SDLoc(Op), MVT::i32);
5873 case Intrinsic::amdgcn_s_buffer_load: {
5874 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5875 SDValue GLC;
5876 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5877 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5878 IsGFX10 ? &DLC : nullptr))
5879 return Op;
5880 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC,
5881 DAG);
5882 }
5883 case Intrinsic::amdgcn_fdiv_fast:
5884 return lowerFDIV_FAST(Op, DAG);
5885 case Intrinsic::amdgcn_interp_p1_f16: {
5886 SDValue ToM0 = DAG.getCopyToReg(DAG.getEntryNode(), DL, AMDGPU::M0,
5887 Op.getOperand(5), SDValue());
5888 if (getSubtarget()->getLDSBankCount() == 16) {
5889 // 16 bank LDS
5890
5891 // FIXME: This implicitly will insert a second CopyToReg to M0.
5892 SDValue S = DAG.getNode(
5893 ISD::INTRINSIC_WO_CHAIN, DL, MVT::f32,
5894 DAG.getTargetConstant(Intrinsic::amdgcn_interp_mov, DL, MVT::i32),
5895 DAG.getConstant(2, DL, MVT::i32), // P0
5896 Op.getOperand(2), // Attrchan
5897 Op.getOperand(3), // Attr
5898 Op.getOperand(5)); // m0
5899
5900 SDValue Ops[] = {
5901 Op.getOperand(1), // Src0
5902 Op.getOperand(2), // Attrchan
5903 Op.getOperand(3), // Attr
5904 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
5905 S, // Src2 - holds two f16 values selected by high
5906 DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers
5907 Op.getOperand(4), // high
5908 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp
5909 DAG.getTargetConstant(0, DL, MVT::i32) // $omod
5910 };
5911 return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops);
5912 } else {
5913 // 32 bank LDS
5914 SDValue Ops[] = {
5915 Op.getOperand(1), // Src0
5916 Op.getOperand(2), // Attrchan
5917 Op.getOperand(3), // Attr
5918 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
5919 Op.getOperand(4), // high
5920 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp
5921 DAG.getTargetConstant(0, DL, MVT::i32), // $omod
5922 ToM0.getValue(1)
5923 };
5924 return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops);
5925 }
5926 }
5927 case Intrinsic::amdgcn_interp_p2_f16: {
5928 SDValue ToM0 = DAG.getCopyToReg(DAG.getEntryNode(), DL, AMDGPU::M0,
5929 Op.getOperand(6), SDValue());
5930 SDValue Ops[] = {
5931 Op.getOperand(2), // Src0
5932 Op.getOperand(3), // Attrchan
5933 Op.getOperand(4), // Attr
5934 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
5935 Op.getOperand(1), // Src2
5936 DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers
5937 Op.getOperand(5), // high
5938 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp
5939 ToM0.getValue(1)
5940 };
5941 return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops);
5942 }
5943 case Intrinsic::amdgcn_sin:
5944 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5945
5946 case Intrinsic::amdgcn_cos:
5947 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5948
5949 case Intrinsic::amdgcn_mul_u24:
5950 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5951 case Intrinsic::amdgcn_mul_i24:
5952 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5953
5954 case Intrinsic::amdgcn_log_clamp: {
5955 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5956 return SDValue();
5957
5958 DiagnosticInfoUnsupported BadIntrin(
5959 MF.getFunction(), "intrinsic not supported on subtarget",
5960 DL.getDebugLoc());
5961 DAG.getContext()->diagnose(BadIntrin);
5962 return DAG.getUNDEF(VT);
5963 }
5964 case Intrinsic::amdgcn_ldexp:
5965 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5966 Op.getOperand(1), Op.getOperand(2));
5967
5968 case Intrinsic::amdgcn_fract:
5969 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5970
5971 case Intrinsic::amdgcn_class:
5972 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5973 Op.getOperand(1), Op.getOperand(2));
5974 case Intrinsic::amdgcn_div_fmas:
5975 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5976 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5977 Op.getOperand(4));
5978
5979 case Intrinsic::amdgcn_div_fixup:
5980 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5981 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5982
5983 case Intrinsic::amdgcn_trig_preop:
5984 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5985 Op.getOperand(1), Op.getOperand(2));
5986 case Intrinsic::amdgcn_div_scale: {
5987 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5988
5989 // Translate to the operands expected by the machine instruction. The
5990 // first parameter must be the same as the first instruction.
5991 SDValue Numerator = Op.getOperand(1);
5992 SDValue Denominator = Op.getOperand(2);
5993
5994 // Note this order is opposite of the machine instruction's operations,
5995 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
5996 // intrinsic has the numerator as the first operand to match a normal
5997 // division operation.
5998
5999 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6000
6001 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6002 Denominator, Numerator);
6003 }
6004 case Intrinsic::amdgcn_icmp: {
6005 // There is a Pat that handles this variant, so return it as-is.
6006 if (Op.getOperand(1).getValueType() == MVT::i1 &&
6007 Op.getConstantOperandVal(2) == 0 &&
6008 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6009 return Op;
6010 return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6011 }
6012 case Intrinsic::amdgcn_fcmp: {
6013 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6014 }
6015 case Intrinsic::amdgcn_fmed3:
6016 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6017 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6018 case Intrinsic::amdgcn_fdot2:
6019 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6020 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6021 Op.getOperand(4));
6022 case Intrinsic::amdgcn_fmul_legacy:
6023 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6024 Op.getOperand(1), Op.getOperand(2));
6025 case Intrinsic::amdgcn_sffbh:
6026 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6027 case Intrinsic::amdgcn_sbfe:
6028 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6029 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6030 case Intrinsic::amdgcn_ubfe:
6031 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6032 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6033 case Intrinsic::amdgcn_cvt_pkrtz:
6034 case Intrinsic::amdgcn_cvt_pknorm_i16:
6035 case Intrinsic::amdgcn_cvt_pknorm_u16:
6036 case Intrinsic::amdgcn_cvt_pk_i16:
6037 case Intrinsic::amdgcn_cvt_pk_u16: {
6038 // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6039 EVT VT = Op.getValueType();
6040 unsigned Opcode;
6041
6042 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6043 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6044 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6045 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6046 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6047 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6048 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6049 Opcode = AMDGPUISD::CVT_PK_I16_I32;
6050 else
6051 Opcode = AMDGPUISD::CVT_PK_U16_U32;
6052
6053 if (isTypeLegal(VT))
6054 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6055
6056 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6057 Op.getOperand(1), Op.getOperand(2));
6058 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6059 }
6060 case Intrinsic::amdgcn_fmad_ftz:
6061 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6062 Op.getOperand(2), Op.getOperand(3));
6063
6064 case Intrinsic::amdgcn_if_break:
6065 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6066 Op->getOperand(1), Op->getOperand(2)), 0);
6067
6068 case Intrinsic::amdgcn_groupstaticsize: {
6069 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6070 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6071 return Op;
6072
6073 const Module *M = MF.getFunction().getParent();
6074 const GlobalValue *GV =
6075 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6076 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6077 SIInstrInfo::MO_ABS32_LO);
6078 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6079 }
6080 case Intrinsic::amdgcn_is_shared:
6081 case Intrinsic::amdgcn_is_private: {
6082 SDLoc SL(Op);
6083 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6084 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6085 SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6086 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6087 Op.getOperand(1));
6088
6089 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6090 DAG.getConstant(1, SL, MVT::i32));
6091 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6092 }
6093 default:
6094 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6095 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6096 return lowerImage(Op, ImageDimIntr, DAG);
6097
6098 return Op;
6099 }
6100}
6101
6102// This function computes an appropriate offset to pass to
6103// MachineMemOperand::setOffset() based on the offset inputs to
6104// an intrinsic. If any of the offsets are non-contstant or
6105// if VIndex is non-zero then this function returns 0. Otherwise,
6106// it returns the sum of VOffset, SOffset, and Offset.
6107static unsigned getBufferOffsetForMMO(SDValue VOffset,
6108 SDValue SOffset,
6109 SDValue Offset,
6110 SDValue VIndex = SDValue()) {
6111
6112 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6113 !isa<ConstantSDNode>(Offset))
6114 return 0;
6115
6116 if (VIndex) {
6117 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6118 return 0;
6119 }
6120
6121 return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6122 cast<ConstantSDNode>(SOffset)->getSExtValue() +
6123 cast<ConstantSDNode>(Offset)->getSExtValue();
6124}
6125
6126SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6127 SelectionDAG &DAG) const {
6128 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6129 SDLoc DL(Op);
6130
6131 switch (IntrID) {
6132 case Intrinsic::amdgcn_ds_ordered_add:
6133 case Intrinsic::amdgcn_ds_ordered_swap: {
6134 MemSDNode *M = cast<MemSDNode>(Op);
6135 SDValue Chain = M->getOperand(0);
6136 SDValue M0 = M->getOperand(2);
6137 SDValue Value = M->getOperand(3);
6138 unsigned IndexOperand = M->getConstantOperandVal(7);
6139 unsigned WaveRelease = M->getConstantOperandVal(8);
6140 unsigned WaveDone = M->getConstantOperandVal(9);
6141 unsigned ShaderType;
6142 unsigned Instruction;
6143
6144 unsigned OrderedCountIndex = IndexOperand & 0x3f;
6145 IndexOperand &= ~0x3f;
6146 unsigned CountDw = 0;
6147
6148 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6149 CountDw = (IndexOperand >> 24) & 0xf;
6150 IndexOperand &= ~(0xf << 24);
6151
6152 if (CountDw < 1 || CountDw > 4) {
6153 report_fatal_error(
6154 "ds_ordered_count: dword count must be between 1 and 4");
6155 }
6156 }
6157
6158 if (IndexOperand)
6159 report_fatal_error("ds_ordered_count: bad index operand");
6160
6161 switch (IntrID) {
6162 case Intrinsic::amdgcn_ds_ordered_add:
6163 Instruction = 0;
6164 break;
6165 case Intrinsic::amdgcn_ds_ordered_swap:
6166 Instruction = 1;
6167 break;
6168 }
6169
6170 if (WaveDone && !WaveRelease)
6171 report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6172
6173 switch (DAG.getMachineFunction().getFunction().getCallingConv()) {
6174 case CallingConv::AMDGPU_CS:
6175 case CallingConv::AMDGPU_KERNEL:
6176 ShaderType = 0;
6177 break;
6178 case CallingConv::AMDGPU_PS:
6179 ShaderType = 1;
6180 break;
6181 case CallingConv::AMDGPU_VS:
6182 ShaderType = 2;
6183 break;
6184 case CallingConv::AMDGPU_GS:
6185 ShaderType = 3;
6186 break;
6187 default:
6188 report_fatal_error("ds_ordered_count unsupported for this calling conv");
6189 }
6190
6191 unsigned Offset0 = OrderedCountIndex << 2;
6192 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6193 (Instruction << 4);
6194
6195 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6196 Offset1 |= (CountDw - 1) << 6;
6197
6198 unsigned Offset = Offset0 | (Offset1 << 8);
6199
6200 SDValue Ops[] = {
6201 Chain,
6202 Value,
6203 DAG.getTargetConstant(Offset, DL, MVT::i16),
6204 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6205 };
6206 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6207 M->getVTList(), Ops, M->getMemoryVT(),
6208 M->getMemOperand());
6209 }
6210 case Intrinsic::amdgcn_ds_fadd: {
6211 MemSDNode *M = cast<MemSDNode>(Op);
6212 unsigned Opc;
6213 switch (IntrID) {
6214 case Intrinsic::amdgcn_ds_fadd:
6215 Opc = ISD::ATOMIC_LOAD_FADD;
6216 break;
6217 }
6218
6219 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6220 M->getOperand(0), M->getOperand(2), M->getOperand(3),
6221 M->getMemOperand());
6222 }
6223 case Intrinsic::amdgcn_atomic_inc:
6224 case Intrinsic::amdgcn_atomic_dec:
6225 case Intrinsic::amdgcn_ds_fmin:
6226 case Intrinsic::amdgcn_ds_fmax: {
6227 MemSDNode *M = cast<MemSDNode>(Op);
6228 unsigned Opc;
6229 switch (IntrID) {
6230 case Intrinsic::amdgcn_atomic_inc:
6231 Opc = AMDGPUISD::ATOMIC_INC;
6232 break;
6233 case Intrinsic::amdgcn_atomic_dec:
6234 Opc = AMDGPUISD::ATOMIC_DEC;
6235 break;
6236 case Intrinsic::amdgcn_ds_fmin:
6237 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6238 break;
6239 case Intrinsic::amdgcn_ds_fmax:
6240 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6241 break;
6242 default:
6243 llvm_unreachable("Unknown intrinsic!")::llvm::llvm_unreachable_internal("Unknown intrinsic!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6243)
;
6244 }
6245 SDValue Ops[] = {
6246 M->getOperand(0), // Chain
6247 M->getOperand(2), // Ptr
6248 M->getOperand(3) // Value
6249 };
6250
6251 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6252 M->getMemoryVT(), M->getMemOperand());
6253 }
6254 case Intrinsic::amdgcn_buffer_load:
6255 case Intrinsic::amdgcn_buffer_load_format: {
6256 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6257 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6258 unsigned IdxEn = 1;
6259 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6260 IdxEn = Idx->getZExtValue() != 0;
6261 SDValue Ops[] = {
6262 Op.getOperand(0), // Chain
6263 Op.getOperand(2), // rsrc
6264 Op.getOperand(3), // vindex
6265 SDValue(), // voffset -- will be set by setBufferOffsets
6266 SDValue(), // soffset -- will be set by setBufferOffsets
6267 SDValue(), // offset -- will be set by setBufferOffsets
6268 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6269 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6270 };
6271
6272 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6273 // We don't know the offset if vindex is non-zero, so clear it.