Bug Summary

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