Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/Target/AMDGPU/SIISelLowering.cpp
Warning:line 11774, column 52
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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