Bug Summary

File:lib/Target/AMDGPU/SIISelLowering.cpp
Warning:line 4129, column 5
Value stored to 'BR' is never read

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