Bug Summary

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

Annotated Source Code

1//===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// \brief Custom DAG lowering for SI
12//
13//===----------------------------------------------------------------------===//
14
15#ifdef _MSC_VER
16// Provide M_PI.
17#define _USE_MATH_DEFINES
18#endif
19
20#include "AMDGPU.h"
21#include "AMDGPUIntrinsicInfo.h"
22#include "AMDGPUTargetMachine.h"
23#include "AMDGPUSubtarget.h"
24#include "SIDefines.h"
25#include "SIISelLowering.h"
26#include "SIInstrInfo.h"
27#include "SIMachineFunctionInfo.h"
28#include "SIRegisterInfo.h"
29#include "Utils/AMDGPUBaseInfo.h"
30#include "llvm/ADT/APFloat.h"
31#include "llvm/ADT/APInt.h"
32#include "llvm/ADT/ArrayRef.h"
33#include "llvm/ADT/BitVector.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/StringRef.h"
36#include "llvm/ADT/StringSwitch.h"
37#include "llvm/ADT/Twine.h"
38#include "llvm/CodeGen/Analysis.h"
39#include "llvm/CodeGen/CallingConvLower.h"
40#include "llvm/CodeGen/DAGCombine.h"
41#include "llvm/CodeGen/ISDOpcodes.h"
42#include "llvm/CodeGen/MachineBasicBlock.h"
43#include "llvm/CodeGen/MachineFrameInfo.h"
44#include "llvm/CodeGen/MachineFunction.h"
45#include "llvm/CodeGen/MachineInstr.h"
46#include "llvm/CodeGen/MachineInstrBuilder.h"
47#include "llvm/CodeGen/MachineMemOperand.h"
48#include "llvm/CodeGen/MachineOperand.h"
49#include "llvm/CodeGen/MachineRegisterInfo.h"
50#include "llvm/CodeGen/MachineValueType.h"
51#include "llvm/CodeGen/SelectionDAG.h"
52#include "llvm/CodeGen/SelectionDAGNodes.h"
53#include "llvm/CodeGen/ValueTypes.h"
54#include "llvm/IR/Constants.h"
55#include "llvm/IR/DataLayout.h"
56#include "llvm/IR/DebugLoc.h"
57#include "llvm/IR/DerivedTypes.h"
58#include "llvm/IR/DiagnosticInfo.h"
59#include "llvm/IR/Function.h"
60#include "llvm/IR/GlobalValue.h"
61#include "llvm/IR/InstrTypes.h"
62#include "llvm/IR/Instruction.h"
63#include "llvm/IR/Instructions.h"
64#include "llvm/IR/IntrinsicInst.h"
65#include "llvm/IR/Type.h"
66#include "llvm/Support/Casting.h"
67#include "llvm/Support/CodeGen.h"
68#include "llvm/Support/CommandLine.h"
69#include "llvm/Support/Compiler.h"
70#include "llvm/Support/ErrorHandling.h"
71#include "llvm/Support/MathExtras.h"
72#include "llvm/Target/TargetCallingConv.h"
73#include "llvm/Target/TargetOptions.h"
74#include "llvm/Target/TargetRegisterInfo.h"
75#include <cassert>
76#include <cmath>
77#include <cstdint>
78#include <iterator>
79#include <tuple>
80#include <utility>
81#include <vector>
82
83using namespace llvm;
84
85static cl::opt<bool> EnableVGPRIndexMode(
86 "amdgpu-vgpr-index-mode",
87 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
88 cl::init(false));
89
90static unsigned findFirstFreeSGPR(CCState &CCInfo) {
91 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
92 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
93 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
94 return AMDGPU::SGPR0 + Reg;
95 }
96 }
97 llvm_unreachable("Cannot allocate sgpr")::llvm::llvm_unreachable_internal("Cannot allocate sgpr", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 97)
;
98}
99
100SITargetLowering::SITargetLowering(const TargetMachine &TM,
101 const SISubtarget &STI)
102 : AMDGPUTargetLowering(TM, STI) {
103 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
104 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
105
106 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
107 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
108
109 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
110 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
111 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
112
113 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
114 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
115
116 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
117 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
118
119 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
120 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
121
122 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
123 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
124
125 if (Subtarget->has16BitInsts()) {
126 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
127 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
128 }
129
130 if (Subtarget->hasVOP3PInsts()) {
131 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
132 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
133 }
134
135 computeRegisterProperties(STI.getRegisterInfo());
136
137 // We need to custom lower vector stores from local memory
138 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
139 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
140 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
141 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
142 setOperationAction(ISD::LOAD, MVT::i1, Custom);
143
144 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
145 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
146 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
147 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
148 setOperationAction(ISD::STORE, MVT::i1, Custom);
149
150 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
151 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
152 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
153 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
154 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
155 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
156 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
157 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
158 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
159 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
160
161 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
162 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
163 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
164
165 setOperationAction(ISD::SELECT, MVT::i1, Promote);
166 setOperationAction(ISD::SELECT, MVT::i64, Custom);
167 setOperationAction(ISD::SELECT, MVT::f64, Promote);
168 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
169
170 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
171 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
172 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
173 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
174 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
175
176 setOperationAction(ISD::SETCC, MVT::i1, Promote);
177 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
178 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
179 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
180
181 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
182 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
183
184 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
185 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
186 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
187 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
188 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
189 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
190 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
191
192 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
193 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
194 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
195 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
196 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
197 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
198
199 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
200 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
201 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
202 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
203 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
204 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
205
206 setOperationAction(ISD::UADDO, MVT::i32, Legal);
207 setOperationAction(ISD::USUBO, MVT::i32, Legal);
208
209 // We only support LOAD/STORE and vector manipulation ops for vectors
210 // with > 4 elements.
211 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
212 MVT::v2i64, MVT::v2f64}) {
213 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
214 switch (Op) {
215 case ISD::LOAD:
216 case ISD::STORE:
217 case ISD::BUILD_VECTOR:
218 case ISD::BITCAST:
219 case ISD::EXTRACT_VECTOR_ELT:
220 case ISD::INSERT_VECTOR_ELT:
221 case ISD::INSERT_SUBVECTOR:
222 case ISD::EXTRACT_SUBVECTOR:
223 case ISD::SCALAR_TO_VECTOR:
224 break;
225 case ISD::CONCAT_VECTORS:
226 setOperationAction(Op, VT, Custom);
227 break;
228 default:
229 setOperationAction(Op, VT, Expand);
230 break;
231 }
232 }
233 }
234
235 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
236 // is expanded to avoid having two separate loops in case the index is a VGPR.
237
238 // Most operations are naturally 32-bit vector operations. We only support
239 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
240 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
241 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
242 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
243
244 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
245 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
246
247 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
248 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
249
250 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
251 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
252 }
253
254 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
255 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
256 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
257 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
258
259 // Avoid stack access for these.
260 // TODO: Generalize to more vector types.
261 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
262 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
263 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
264 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
265
266 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
267 // and output demarshalling
268 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
269 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
270
271 // We can't return success/failure, only the old value,
272 // let LLVM add the comparison
273 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
274 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
275
276 if (getSubtarget()->hasFlatAddressSpace()) {
277 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
278 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
279 }
280
281 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
282 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
283
284 // On SI this is s_memtime and s_memrealtime on VI.
285 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
286 setOperationAction(ISD::TRAP, MVT::Other, Legal);
287 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
288
289 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
290 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
291
292 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
293 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
294 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
295 setOperationAction(ISD::FRINT, MVT::f64, Legal);
296 }
297
298 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
299
300 setOperationAction(ISD::FSIN, MVT::f32, Custom);
301 setOperationAction(ISD::FCOS, MVT::f32, Custom);
302 setOperationAction(ISD::FDIV, MVT::f32, Custom);
303 setOperationAction(ISD::FDIV, MVT::f64, Custom);
304
305 if (Subtarget->has16BitInsts()) {
306 setOperationAction(ISD::Constant, MVT::i16, Legal);
307
308 setOperationAction(ISD::SMIN, MVT::i16, Legal);
309 setOperationAction(ISD::SMAX, MVT::i16, Legal);
310
311 setOperationAction(ISD::UMIN, MVT::i16, Legal);
312 setOperationAction(ISD::UMAX, MVT::i16, Legal);
313
314 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
315 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
316
317 setOperationAction(ISD::ROTR, MVT::i16, Promote);
318 setOperationAction(ISD::ROTL, MVT::i16, Promote);
319
320 setOperationAction(ISD::SDIV, MVT::i16, Promote);
321 setOperationAction(ISD::UDIV, MVT::i16, Promote);
322 setOperationAction(ISD::SREM, MVT::i16, Promote);
323 setOperationAction(ISD::UREM, MVT::i16, Promote);
324
325 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
326 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
327
328 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
329 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
330 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
331 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
332
333 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
334
335 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
336
337 setOperationAction(ISD::LOAD, MVT::i16, Custom);
338
339 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
340
341 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
342 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
343 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
344 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
345
346 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
347 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
348 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
349 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
350
351 // F16 - Constant Actions.
352 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
353
354 // F16 - Load/Store Actions.
355 setOperationAction(ISD::LOAD, MVT::f16, Promote);
356 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
357 setOperationAction(ISD::STORE, MVT::f16, Promote);
358 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
359
360 // F16 - VOP1 Actions.
361 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
362 setOperationAction(ISD::FCOS, MVT::f16, Promote);
363 setOperationAction(ISD::FSIN, MVT::f16, Promote);
364 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
365 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
366 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
367 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
368
369 // F16 - VOP2 Actions.
370 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
371 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
372 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
373 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
374 setOperationAction(ISD::FDIV, MVT::f16, Custom);
375
376 // F16 - VOP3 Actions.
377 setOperationAction(ISD::FMA, MVT::f16, Legal);
378 if (!Subtarget->hasFP16Denormals())
379 setOperationAction(ISD::FMAD, MVT::f16, Legal);
380 }
381
382 if (Subtarget->hasVOP3PInsts()) {
383 for (MVT VT : {MVT::v2i16, MVT::v2f16}) {
384 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
385 switch (Op) {
386 case ISD::LOAD:
387 case ISD::STORE:
388 case ISD::BUILD_VECTOR:
389 case ISD::BITCAST:
390 case ISD::EXTRACT_VECTOR_ELT:
391 case ISD::INSERT_VECTOR_ELT:
392 case ISD::INSERT_SUBVECTOR:
393 case ISD::EXTRACT_SUBVECTOR:
394 case ISD::SCALAR_TO_VECTOR:
395 break;
396 case ISD::CONCAT_VECTORS:
397 setOperationAction(Op, VT, Custom);
398 break;
399 default:
400 setOperationAction(Op, VT, Expand);
401 break;
402 }
403 }
404 }
405
406 // XXX - Do these do anything? Vector constants turn into build_vector.
407 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
408 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
409
410 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
411 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
412 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
413 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
414
415 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
416 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
417 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
418 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
419
420 setOperationAction(ISD::AND, MVT::v2i16, Promote);
421 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
422 setOperationAction(ISD::OR, MVT::v2i16, Promote);
423 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
424 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
425 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
426 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
427 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
428 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
429 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
430
431 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
432 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
433 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
434 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
435 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
436 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
437 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
438 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
439 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
440 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
441
442 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
443 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
444 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
445 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
446 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
447 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
448
449 // This isn't really legal, but this avoids the legalizer unrolling it (and
450 // allows matching fneg (fabs x) patterns)
451 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
452
453 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
454 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
455
456 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
457 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
458 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
459 }
460
461 setTargetDAGCombine(ISD::FADD);
462 setTargetDAGCombine(ISD::FSUB);
463 setTargetDAGCombine(ISD::FMINNUM);
464 setTargetDAGCombine(ISD::FMAXNUM);
465 setTargetDAGCombine(ISD::SMIN);
466 setTargetDAGCombine(ISD::SMAX);
467 setTargetDAGCombine(ISD::UMIN);
468 setTargetDAGCombine(ISD::UMAX);
469 setTargetDAGCombine(ISD::SETCC);
470 setTargetDAGCombine(ISD::AND);
471 setTargetDAGCombine(ISD::OR);
472 setTargetDAGCombine(ISD::XOR);
473 setTargetDAGCombine(ISD::SINT_TO_FP);
474 setTargetDAGCombine(ISD::UINT_TO_FP);
475 setTargetDAGCombine(ISD::FCANONICALIZE);
476 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
477
478 // All memory operations. Some folding on the pointer operand is done to help
479 // matching the constant offsets in the addressing modes.
480 setTargetDAGCombine(ISD::LOAD);
481 setTargetDAGCombine(ISD::STORE);
482 setTargetDAGCombine(ISD::ATOMIC_LOAD);
483 setTargetDAGCombine(ISD::ATOMIC_STORE);
484 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
485 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
486 setTargetDAGCombine(ISD::ATOMIC_SWAP);
487 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
488 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
489 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
490 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
491 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
492 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
493 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
494 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
495 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
496 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
497
498 setSchedulingPreference(Sched::RegPressure);
499}
500
501const SISubtarget *SITargetLowering::getSubtarget() const {
502 return static_cast<const SISubtarget *>(Subtarget);
503}
504
505//===----------------------------------------------------------------------===//
506// TargetLowering queries
507//===----------------------------------------------------------------------===//
508
509bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
510 EVT) const {
511 // SI has some legal vector types, but no legal vector operations. Say no
512 // shuffles are legal in order to prefer scalarizing some vector operations.
513 return false;
514}
515
516bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
517 const CallInst &CI,
518 unsigned IntrID) const {
519 switch (IntrID) {
520 case Intrinsic::amdgcn_atomic_inc:
521 case Intrinsic::amdgcn_atomic_dec:
522 Info.opc = ISD::INTRINSIC_W_CHAIN;
523 Info.memVT = MVT::getVT(CI.getType());
524 Info.ptrVal = CI.getOperand(0);
525 Info.align = 0;
526 Info.vol = false;
527 Info.readMem = true;
528 Info.writeMem = true;
529 return true;
530 default:
531 return false;
532 }
533}
534
535bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
536 SmallVectorImpl<Value*> &Ops,
537 Type *&AccessTy) const {
538 switch (II->getIntrinsicID()) {
539 case Intrinsic::amdgcn_atomic_inc:
540 case Intrinsic::amdgcn_atomic_dec: {
541 Value *Ptr = II->getArgOperand(0);
542 AccessTy = II->getType();
543 Ops.push_back(Ptr);
544 return true;
545 }
546 default:
547 return false;
548 }
549}
550
551bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
552 // Flat instructions do not have offsets, and only have the register
553 // address.
554 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
555}
556
557bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
558 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
559 // additionally can do r + r + i with addr64. 32-bit has more addressing
560 // mode options. Depending on the resource constant, it can also do
561 // (i64 r0) + (i32 r1) * (i14 i).
562 //
563 // Private arrays end up using a scratch buffer most of the time, so also
564 // assume those use MUBUF instructions. Scratch loads / stores are currently
565 // implemented as mubuf instructions with offen bit set, so slightly
566 // different than the normal addr64.
567 if (!isUInt<12>(AM.BaseOffs))
568 return false;
569
570 // FIXME: Since we can split immediate into soffset and immediate offset,
571 // would it make sense to allow any immediate?
572
573 switch (AM.Scale) {
574 case 0: // r + i or just i, depending on HasBaseReg.
575 return true;
576 case 1:
577 return true; // We have r + r or r + i.
578 case 2:
579 if (AM.HasBaseReg) {
580 // Reject 2 * r + r.
581 return false;
582 }
583
584 // Allow 2 * r as r + r
585 // Or 2 * r + i is allowed as r + r + i.
586 return true;
587 default: // Don't allow n * r
588 return false;
589 }
590}
591
592bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
593 const AddrMode &AM, Type *Ty,
594 unsigned AS) const {
595 // No global is ever allowed as a base.
596 if (AM.BaseGV)
597 return false;
598
599 switch (AS) {
600 case AMDGPUAS::GLOBAL_ADDRESS:
601 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
602 // Assume the we will use FLAT for all global memory accesses
603 // on VI.
604 // FIXME: This assumption is currently wrong. On VI we still use
605 // MUBUF instructions for the r + i addressing mode. As currently
606 // implemented, the MUBUF instructions only work on buffer < 4GB.
607 // It may be possible to support > 4GB buffers with MUBUF instructions,
608 // by setting the stride value in the resource descriptor which would
609 // increase the size limit to (stride * 4GB). However, this is risky,
610 // because it has never been validated.
611 return isLegalFlatAddressingMode(AM);
612 }
613
614 return isLegalMUBUFAddressingMode(AM);
615
616 case AMDGPUAS::CONSTANT_ADDRESS:
617 // If the offset isn't a multiple of 4, it probably isn't going to be
618 // correctly aligned.
619 // FIXME: Can we get the real alignment here?
620 if (AM.BaseOffs % 4 != 0)
621 return isLegalMUBUFAddressingMode(AM);
622
623 // There are no SMRD extloads, so if we have to do a small type access we
624 // will use a MUBUF load.
625 // FIXME?: We also need to do this if unaligned, but we don't know the
626 // alignment here.
627 if (DL.getTypeStoreSize(Ty) < 4)
628 return isLegalMUBUFAddressingMode(AM);
629
630 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
631 // SMRD instructions have an 8-bit, dword offset on SI.
632 if (!isUInt<8>(AM.BaseOffs / 4))
633 return false;
634 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
635 // On CI+, this can also be a 32-bit literal constant offset. If it fits
636 // in 8-bits, it can use a smaller encoding.
637 if (!isUInt<32>(AM.BaseOffs / 4))
638 return false;
639 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
640 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
641 if (!isUInt<20>(AM.BaseOffs))
642 return false;
643 } else
644 llvm_unreachable("unhandled generation")::llvm::llvm_unreachable_internal("unhandled generation", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 644)
;
645
646 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
647 return true;
648
649 if (AM.Scale == 1 && AM.HasBaseReg)
650 return true;
651
652 return false;
653
654 case AMDGPUAS::PRIVATE_ADDRESS:
655 return isLegalMUBUFAddressingMode(AM);
656
657 case AMDGPUAS::LOCAL_ADDRESS:
658 case AMDGPUAS::REGION_ADDRESS:
659 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
660 // field.
661 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
662 // an 8-bit dword offset but we don't know the alignment here.
663 if (!isUInt<16>(AM.BaseOffs))
664 return false;
665
666 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
667 return true;
668
669 if (AM.Scale == 1 && AM.HasBaseReg)
670 return true;
671
672 return false;
673
674 case AMDGPUAS::FLAT_ADDRESS:
675 case AMDGPUAS::UNKNOWN_ADDRESS_SPACE:
676 // For an unknown address space, this usually means that this is for some
677 // reason being used for pure arithmetic, and not based on some addressing
678 // computation. We don't have instructions that compute pointers with any
679 // addressing modes, so treat them as having no offset like flat
680 // instructions.
681 return isLegalFlatAddressingMode(AM);
682
683 default:
684 llvm_unreachable("unhandled address space")::llvm::llvm_unreachable_internal("unhandled address space", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 684)
;
685 }
686}
687
688bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
689 unsigned AddrSpace,
690 unsigned Align,
691 bool *IsFast) const {
692 if (IsFast)
693 *IsFast = false;
694
695 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
696 // which isn't a simple VT.
697 // Until MVT is extended to handle this, simply check for the size and
698 // rely on the condition below: allow accesses if the size is a multiple of 4.
699 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
700 VT.getStoreSize() > 16)) {
701 return false;
702 }
703
704 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
705 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
706 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
707 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
708 // with adjacent offsets.
709 bool AlignedBy4 = (Align % 4 == 0);
710 if (IsFast)
711 *IsFast = AlignedBy4;
712
713 return AlignedBy4;
714 }
715
716 // FIXME: We have to be conservative here and assume that flat operations
717 // will access scratch. If we had access to the IR function, then we
718 // could determine if any private memory was used in the function.
719 if (!Subtarget->hasUnalignedScratchAccess() &&
720 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
721 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
722 return false;
723 }
724
725 if (Subtarget->hasUnalignedBufferAccess()) {
726 // If we have an uniform constant load, it still requires using a slow
727 // buffer instruction if unaligned.
728 if (IsFast) {
729 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) ?
730 (Align % 4 == 0) : true;
731 }
732
733 return true;
734 }
735
736 // Smaller than dword value must be aligned.
737 if (VT.bitsLT(MVT::i32))
738 return false;
739
740 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
741 // byte-address are ignored, thus forcing Dword alignment.
742 // This applies to private, global, and constant memory.
743 if (IsFast)
744 *IsFast = true;
745
746 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
747}
748
749EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
750 unsigned SrcAlign, bool IsMemset,
751 bool ZeroMemset,
752 bool MemcpyStrSrc,
753 MachineFunction &MF) const {
754 // FIXME: Should account for address space here.
755
756 // The default fallback uses the private pointer size as a guess for a type to
757 // use. Make sure we switch these to 64-bit accesses.
758
759 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
760 return MVT::v4i32;
761
762 if (Size >= 8 && DstAlign >= 4)
763 return MVT::v2i32;
764
765 // Use the default.
766 return MVT::Other;
767}
768
769static bool isFlatGlobalAddrSpace(unsigned AS) {
770 return AS == AMDGPUAS::GLOBAL_ADDRESS ||
771 AS == AMDGPUAS::FLAT_ADDRESS ||
772 AS == AMDGPUAS::CONSTANT_ADDRESS;
773}
774
775bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
776 unsigned DestAS) const {
777 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
778}
779
780bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
781 const MemSDNode *MemNode = cast<MemSDNode>(N);
782 const Value *Ptr = MemNode->getMemOperand()->getValue();
783 const Instruction *I = dyn_cast<Instruction>(Ptr);
784 return I && I->getMetadata("amdgpu.noclobber");
785}
786
787bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
788 unsigned DestAS) const {
789 // Flat -> private/local is a simple truncate.
790 // Flat -> global is no-op
791 if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
792 return true;
793
794 return isNoopAddrSpaceCast(SrcAS, DestAS);
795}
796
797bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
798 const MemSDNode *MemNode = cast<MemSDNode>(N);
799
800 return AMDGPU::isUniformMMO(MemNode->getMemOperand());
801}
802
803TargetLoweringBase::LegalizeTypeAction
804SITargetLowering::getPreferredVectorAction(EVT VT) const {
805 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
806 return TypeSplitVector;
807
808 return TargetLoweringBase::getPreferredVectorAction(VT);
809}
810
811bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
812 Type *Ty) const {
813 // FIXME: Could be smarter if called for vector constants.
814 return true;
815}
816
817bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
818 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
819 switch (Op) {
820 case ISD::LOAD:
821 case ISD::STORE:
822
823 // These operations are done with 32-bit instructions anyway.
824 case ISD::AND:
825 case ISD::OR:
826 case ISD::XOR:
827 case ISD::SELECT:
828 // TODO: Extensions?
829 return true;
830 default:
831 return false;
832 }
833 }
834
835 // SimplifySetCC uses this function to determine whether or not it should
836 // create setcc with i1 operands. We don't have instructions for i1 setcc.
837 if (VT == MVT::i1 && Op == ISD::SETCC)
838 return false;
839
840 return TargetLowering::isTypeDesirableForOp(Op, VT);
841}
842
843SDValue SITargetLowering::LowerParameterPtr(SelectionDAG &DAG,
844 const SDLoc &SL, SDValue Chain,
845 unsigned Offset) const {
846 const DataLayout &DL = DAG.getDataLayout();
847 MachineFunction &MF = DAG.getMachineFunction();
848 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
849 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
850
851 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
852 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
853 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
854 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
855 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
856 DAG.getConstant(Offset, SL, PtrVT));
857}
858
859SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
860 const SDLoc &SL, SDValue Chain,
861 unsigned Offset, bool Signed,
862 const ISD::InputArg *Arg) const {
863 const DataLayout &DL = DAG.getDataLayout();
864 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
865 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
866 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
867
868 unsigned Align = DL.getABITypeAlignment(Ty);
869
870 SDValue Ptr = LowerParameterPtr(DAG, SL, Chain, Offset);
871 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
872 MachineMemOperand::MONonTemporal |
873 MachineMemOperand::MODereferenceable |
874 MachineMemOperand::MOInvariant);
875
876 SDValue Val = Load;
877 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
878 VT.bitsLT(MemVT)) {
879 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
880 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
881 }
882
883 if (MemVT.isFloatingPoint())
884 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
885 else if (Signed)
886 Val = DAG.getSExtOrTrunc(Val, SL, VT);
887 else
888 Val = DAG.getZExtOrTrunc(Val, SL, VT);
889
890 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
891}
892
893SDValue SITargetLowering::LowerFormalArguments(
894 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
895 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
896 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
897 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
898
899 MachineFunction &MF = DAG.getMachineFunction();
900 FunctionType *FType = MF.getFunction()->getFunctionType();
901 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
902 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
903
904 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
905 const Function *Fn = MF.getFunction();
906 DiagnosticInfoUnsupported NoGraphicsHSA(
907 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
908 DAG.getContext()->diagnose(NoGraphicsHSA);
909 return DAG.getEntryNode();
910 }
911
912 // Create stack objects that are used for emitting debugger prologue if
913 // "amdgpu-debugger-emit-prologue" attribute was specified.
914 if (ST.debuggerEmitPrologue())
915 createDebuggerPrologueStackObjects(MF);
916
917 SmallVector<ISD::InputArg, 16> Splits;
918 BitVector Skipped(Ins.size());
919
920 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
921 const ISD::InputArg &Arg = Ins[i];
922
923 // First check if it's a PS input addr
924 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
925 !Arg.Flags.isByVal() && PSInputNum <= 15) {
926
927 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
928 // We can safely skip PS inputs
929 Skipped.set(i);
930 ++PSInputNum;
931 continue;
932 }
933
934 Info->markPSInputAllocated(PSInputNum);
935 if (Arg.Used)
936 Info->PSInputEna |= 1 << PSInputNum;
937
938 ++PSInputNum;
939 }
940
941 if (AMDGPU::isShader(CallConv)) {
942 // Second split vertices into their elements
943 if (Arg.VT.isVector()) {
944 ISD::InputArg NewArg = Arg;
945 NewArg.Flags.setSplit();
946 NewArg.VT = Arg.VT.getVectorElementType();
947
948 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
949 // three or five element vertex only needs three or five registers,
950 // NOT four or eight.
951 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
952 unsigned NumElements = ParamType->getVectorNumElements();
953
954 for (unsigned j = 0; j != NumElements; ++j) {
955 Splits.push_back(NewArg);
956 NewArg.PartOffset += NewArg.VT.getStoreSize();
957 }
958 } else {
959 Splits.push_back(Arg);
960 }
961 }
962 }
963
964 SmallVector<CCValAssign, 16> ArgLocs;
965 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
966 *DAG.getContext());
967
968 // At least one interpolation mode must be enabled or else the GPU will hang.
969 //
970 // Check PSInputAddr instead of PSInputEna. The idea is that if the user set
971 // PSInputAddr, the user wants to enable some bits after the compilation
972 // based on run-time states. Since we can't know what the final PSInputEna
973 // will look like, so we shouldn't do anything here and the user should take
974 // responsibility for the correct programming.
975 //
976 // Otherwise, the following restrictions apply:
977 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
978 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
979 // enabled too.
980 if (CallConv == CallingConv::AMDGPU_PS &&
981 ((Info->getPSInputAddr() & 0x7F) == 0 ||
982 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11)))) {
983 CCInfo.AllocateReg(AMDGPU::VGPR0);
984 CCInfo.AllocateReg(AMDGPU::VGPR1);
985 Info->markPSInputAllocated(0);
986 Info->PSInputEna |= 1;
987 }
988
989 if (!AMDGPU::isShader(CallConv)) {
990 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX())((Info->hasWorkGroupIDX() && Info->hasWorkItemIDX
()) ? static_cast<void> (0) : __assert_fail ("Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 990, __PRETTY_FUNCTION__))
;
991 } else {
992 assert(!Info->hasDispatchPtr() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && !Info->hasFlatScratchInit() && !Info
->hasWorkGroupIDX() && !Info->hasWorkGroupIDY()
&& !Info->hasWorkGroupIDZ() && !Info->
hasWorkGroupInfo() && !Info->hasWorkItemIDX() &&
!Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ
()) ? static_cast<void> (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 997, __PRETTY_FUNCTION__))
993 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && !Info->hasFlatScratchInit() && !Info
->hasWorkGroupIDX() && !Info->hasWorkGroupIDY()
&& !Info->hasWorkGroupIDZ() && !Info->
hasWorkGroupInfo() && !Info->hasWorkItemIDX() &&
!Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ
()) ? static_cast<void> (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 997, __PRETTY_FUNCTION__))
994 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && !Info->hasFlatScratchInit() && !Info
->hasWorkGroupIDX() && !Info->hasWorkGroupIDY()
&& !Info->hasWorkGroupIDZ() && !Info->
hasWorkGroupInfo() && !Info->hasWorkItemIDX() &&
!Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ
()) ? static_cast<void> (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 997, __PRETTY_FUNCTION__))
995 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && !Info->hasFlatScratchInit() && !Info
->hasWorkGroupIDX() && !Info->hasWorkGroupIDY()
&& !Info->hasWorkGroupIDZ() && !Info->
hasWorkGroupInfo() && !Info->hasWorkItemIDX() &&
!Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ
()) ? static_cast<void> (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 997, __PRETTY_FUNCTION__))
996 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && !Info->hasFlatScratchInit() && !Info
->hasWorkGroupIDX() && !Info->hasWorkGroupIDY()
&& !Info->hasWorkGroupIDZ() && !Info->
hasWorkGroupInfo() && !Info->hasWorkItemIDX() &&
!Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ
()) ? static_cast<void> (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 997, __PRETTY_FUNCTION__))
997 !Info->hasWorkItemIDZ())((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && !Info->hasFlatScratchInit() && !Info
->hasWorkGroupIDX() && !Info->hasWorkGroupIDY()
&& !Info->hasWorkGroupIDZ() && !Info->
hasWorkGroupInfo() && !Info->hasWorkItemIDX() &&
!Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ
()) ? static_cast<void> (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 997, __PRETTY_FUNCTION__))
;
998 }
999
1000 if (Info->hasPrivateMemoryInputPtr()) {
1001 unsigned PrivateMemoryPtrReg = Info->addPrivateMemoryPtr(*TRI);
1002 MF.addLiveIn(PrivateMemoryPtrReg, &AMDGPU::SReg_64RegClass);
1003 CCInfo.AllocateReg(PrivateMemoryPtrReg);
1004 }
1005
1006 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1007 if (Info->hasPrivateSegmentBuffer()) {
1008 unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI);
1009 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass);
1010 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1011 }
1012
1013 if (Info->hasDispatchPtr()) {
1014 unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI);
1015 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1016 CCInfo.AllocateReg(DispatchPtrReg);
1017 }
1018
1019 if (Info->hasQueuePtr()) {
1020 unsigned QueuePtrReg = Info->addQueuePtr(*TRI);
1021 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1022 CCInfo.AllocateReg(QueuePtrReg);
1023 }
1024
1025 if (Info->hasKernargSegmentPtr()) {
1026 unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI);
1027 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1028 CCInfo.AllocateReg(InputPtrReg);
1029 }
1030
1031 if (Info->hasDispatchID()) {
1032 unsigned DispatchIDReg = Info->addDispatchID(*TRI);
1033 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1034 CCInfo.AllocateReg(DispatchIDReg);
1035 }
1036
1037 if (Info->hasFlatScratchInit()) {
1038 unsigned FlatScratchInitReg = Info->addFlatScratchInit(*TRI);
1039 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1040 CCInfo.AllocateReg(FlatScratchInitReg);
1041 }
1042
1043 if (!AMDGPU::isShader(CallConv))
1044 analyzeFormalArgumentsCompute(CCInfo, Ins);
1045 else
1046 AnalyzeFormalArguments(CCInfo, Splits);
1047
1048 SmallVector<SDValue, 16> Chains;
1049
1050 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1051 const ISD::InputArg &Arg = Ins[i];
1052 if (Skipped[i]) {
1053 InVals.push_back(DAG.getUNDEF(Arg.VT));
1054 continue;
1055 }
1056
1057 CCValAssign &VA = ArgLocs[ArgIdx++];
1058 MVT VT = VA.getLocVT();
1059
1060 if (VA.isMemLoc()) {
1061 VT = Ins[i].VT;
1062 EVT MemVT = VA.getLocVT();
1063 const unsigned Offset = Subtarget->getExplicitKernelArgOffset(MF) +
1064 VA.getLocMemOffset();
1065 // The first 36 bytes of the input buffer contains information about
1066 // thread group and global sizes.
1067 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain,
1068 Offset, Ins[i].Flags.isSExt(),
1069 &Ins[i]);
1070 Chains.push_back(Arg.getValue(1));
1071
1072 auto *ParamTy =
1073 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1074 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1075 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1076 // On SI local pointers are just offsets into LDS, so they are always
1077 // less than 16-bits. On CI and newer they could potentially be
1078 // real pointers, so we can't guarantee their size.
1079 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1080 DAG.getValueType(MVT::i16));
1081 }
1082
1083 InVals.push_back(Arg);
1084 Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1085 continue;
1086 }
1087 assert(VA.isRegLoc() && "Parameter must be in a register!")((VA.isRegLoc() && "Parameter must be in a register!"
) ? static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && \"Parameter must be in a register!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1087, __PRETTY_FUNCTION__))
;
1088
1089 unsigned Reg = VA.getLocReg();
1090
1091 if (VT == MVT::i64) {
1092 // For now assume it is a pointer
1093 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
1094 &AMDGPU::SGPR_64RegClass);
1095 Reg = MF.addLiveIn(Reg, &AMDGPU::SGPR_64RegClass);
1096 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1097 InVals.push_back(Copy);
1098 continue;
1099 }
1100
1101 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1102
1103 Reg = MF.addLiveIn(Reg, RC);
1104 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1105
1106 if (Arg.VT.isVector()) {
1107 // Build a vector from the registers
1108 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1109 unsigned NumElements = ParamType->getVectorNumElements();
1110
1111 SmallVector<SDValue, 4> Regs;
1112 Regs.push_back(Val);
1113 for (unsigned j = 1; j != NumElements; ++j) {
1114 Reg = ArgLocs[ArgIdx++].getLocReg();
1115 Reg = MF.addLiveIn(Reg, RC);
1116
1117 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1118 Regs.push_back(Copy);
1119 }
1120
1121 // Fill up the missing vector elements
1122 NumElements = Arg.VT.getVectorNumElements() - NumElements;
1123 Regs.append(NumElements, DAG.getUNDEF(VT));
1124
1125 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1126 continue;
1127 }
1128
1129 InVals.push_back(Val);
1130 }
1131
1132 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1133 // these from the dispatch pointer.
1134
1135 // Start adding system SGPRs.
1136 if (Info->hasWorkGroupIDX()) {
1137 unsigned Reg = Info->addWorkGroupIDX();
1138 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1139 CCInfo.AllocateReg(Reg);
1140 }
1141
1142 if (Info->hasWorkGroupIDY()) {
1143 unsigned Reg = Info->addWorkGroupIDY();
1144 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1145 CCInfo.AllocateReg(Reg);
1146 }
1147
1148 if (Info->hasWorkGroupIDZ()) {
1149 unsigned Reg = Info->addWorkGroupIDZ();
1150 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1151 CCInfo.AllocateReg(Reg);
1152 }
1153
1154 if (Info->hasWorkGroupInfo()) {
1155 unsigned Reg = Info->addWorkGroupInfo();
1156 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1157 CCInfo.AllocateReg(Reg);
1158 }
1159
1160 if (Info->hasPrivateSegmentWaveByteOffset()) {
1161 // Scratch wave offset passed in system SGPR.
1162 unsigned PrivateSegmentWaveByteOffsetReg;
1163
1164 if (AMDGPU::isShader(CallConv)) {
1165 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1166 Info->setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1167 } else
1168 PrivateSegmentWaveByteOffsetReg = Info->addPrivateSegmentWaveByteOffset();
1169
1170 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1171 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1172 }
1173
1174 // Now that we've figured out where the scratch register inputs are, see if
1175 // should reserve the arguments and use them directly.
1176 bool HasStackObjects = MF.getFrameInfo().hasStackObjects();
1177 // Record that we know we have non-spill stack objects so we don't need to
1178 // check all stack objects later.
1179 if (HasStackObjects)
1180 Info->setHasNonSpillStackObjects(true);
1181
1182 // Everything live out of a block is spilled with fast regalloc, so it's
1183 // almost certain that spilling will be required.
1184 if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
1185 HasStackObjects = true;
1186
1187 if (ST.isAmdCodeObjectV2(MF)) {
1188 if (HasStackObjects) {
1189 // If we have stack objects, we unquestionably need the private buffer
1190 // resource. For the Code Object V2 ABI, this will be the first 4 user
1191 // SGPR inputs. We can reserve those and use them directly.
1192
1193 unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue(
1194 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
1195 Info->setScratchRSrcReg(PrivateSegmentBufferReg);
1196
1197 unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue(
1198 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1199 Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1200 } else {
1201 unsigned ReservedBufferReg
1202 = TRI->reservedPrivateSegmentBufferReg(MF);
1203 unsigned ReservedOffsetReg
1204 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
1205
1206 // We tentatively reserve the last registers (skipping the last two
1207 // which may contain VCC). After register allocation, we'll replace
1208 // these with the ones immediately after those which were really
1209 // allocated. In the prologue copies will be inserted from the argument
1210 // to these reserved registers.
1211 Info->setScratchRSrcReg(ReservedBufferReg);
1212 Info->setScratchWaveOffsetReg(ReservedOffsetReg);
1213 }
1214 } else {
1215 unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF);
1216
1217 // Without HSA, relocations are used for the scratch pointer and the
1218 // buffer resource setup is always inserted in the prologue. Scratch wave
1219 // offset is still in an input SGPR.
1220 Info->setScratchRSrcReg(ReservedBufferReg);
1221
1222 if (HasStackObjects) {
1223 unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue(
1224 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1225 Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1226 } else {
1227 unsigned ReservedOffsetReg
1228 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
1229 Info->setScratchWaveOffsetReg(ReservedOffsetReg);
1230 }
1231 }
1232
1233 if (Info->hasWorkItemIDX()) {
1234 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
1235 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1236 CCInfo.AllocateReg(Reg);
1237 }
1238
1239 if (Info->hasWorkItemIDY()) {
1240 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
1241 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1242 CCInfo.AllocateReg(Reg);
1243 }
1244
1245 if (Info->hasWorkItemIDZ()) {
1246 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
1247 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1248 CCInfo.AllocateReg(Reg);
1249 }
1250
1251 if (Chains.empty())
1252 return Chain;
1253
1254 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1255}
1256
1257SDValue
1258SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1259 bool isVarArg,
1260 const SmallVectorImpl<ISD::OutputArg> &Outs,
1261 const SmallVectorImpl<SDValue> &OutVals,
1262 const SDLoc &DL, SelectionDAG &DAG) const {
1263 MachineFunction &MF = DAG.getMachineFunction();
1264 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1265
1266 if (!AMDGPU::isShader(CallConv))
1267 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1268 OutVals, DL, DAG);
1269
1270 Info->setIfReturnsVoid(Outs.size() == 0);
1271
1272 SmallVector<ISD::OutputArg, 48> Splits;
1273 SmallVector<SDValue, 48> SplitVals;
1274
1275 // Split vectors into their elements.
1276 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1277 const ISD::OutputArg &Out = Outs[i];
1278
1279 if (Out.VT.isVector()) {
1280 MVT VT = Out.VT.getVectorElementType();
1281 ISD::OutputArg NewOut = Out;
1282 NewOut.Flags.setSplit();
1283 NewOut.VT = VT;
1284
1285 // We want the original number of vector elements here, e.g.
1286 // three or five, not four or eight.
1287 unsigned NumElements = Out.ArgVT.getVectorNumElements();
1288
1289 for (unsigned j = 0; j != NumElements; ++j) {
1290 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1291 DAG.getConstant(j, DL, MVT::i32));
1292 SplitVals.push_back(Elem);
1293 Splits.push_back(NewOut);
1294 NewOut.PartOffset += NewOut.VT.getStoreSize();
1295 }
1296 } else {
1297 SplitVals.push_back(OutVals[i]);
1298 Splits.push_back(Out);
1299 }
1300 }
1301
1302 // CCValAssign - represent the assignment of the return value to a location.
1303 SmallVector<CCValAssign, 48> RVLocs;
1304
1305 // CCState - Info about the registers and stack slots.
1306 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1307 *DAG.getContext());
1308
1309 // Analyze outgoing return values.
1310 AnalyzeReturn(CCInfo, Splits);
1311
1312 SDValue Flag;
1313 SmallVector<SDValue, 48> RetOps;
1314 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1315
1316 // Copy the result values into the output registers.
1317 for (unsigned i = 0, realRVLocIdx = 0;
1318 i != RVLocs.size();
1319 ++i, ++realRVLocIdx) {
1320 CCValAssign &VA = RVLocs[i];
1321 assert(VA.isRegLoc() && "Can only return in registers!")((VA.isRegLoc() && "Can only return in registers!") ?
static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1321, __PRETTY_FUNCTION__))
;
1322
1323 SDValue Arg = SplitVals[realRVLocIdx];
1324
1325 // Copied from other backends.
1326 switch (VA.getLocInfo()) {
1327 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1327)
;
1328 case CCValAssign::Full:
1329 break;
1330 case CCValAssign::BCvt:
1331 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1332 break;
1333 }
1334
1335 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1336 Flag = Chain.getValue(1);
1337 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1338 }
1339
1340 // Update chain and glue.
1341 RetOps[0] = Chain;
1342 if (Flag.getNode())
1343 RetOps.push_back(Flag);
1344
1345 unsigned Opc = Info->returnsVoid() ? AMDGPUISD::ENDPGM : AMDGPUISD::RETURN;
1346 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1347}
1348
1349unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
1350 SelectionDAG &DAG) const {
1351 unsigned Reg = StringSwitch<unsigned>(RegName)
1352 .Case("m0", AMDGPU::M0)
1353 .Case("exec", AMDGPU::EXEC)
1354 .Case("exec_lo", AMDGPU::EXEC_LO)
1355 .Case("exec_hi", AMDGPU::EXEC_HI)
1356 .Case("flat_scratch", AMDGPU::FLAT_SCR)
1357 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1358 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1359 .Default(AMDGPU::NoRegister);
1360
1361 if (Reg == AMDGPU::NoRegister) {
1362 report_fatal_error(Twine("invalid register name \""
1363 + StringRef(RegName) + "\"."));
1364
1365 }
1366
1367 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1368 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
1369 report_fatal_error(Twine("invalid register \""
1370 + StringRef(RegName) + "\" for subtarget."));
1371 }
1372
1373 switch (Reg) {
1374 case AMDGPU::M0:
1375 case AMDGPU::EXEC_LO:
1376 case AMDGPU::EXEC_HI:
1377 case AMDGPU::FLAT_SCR_LO:
1378 case AMDGPU::FLAT_SCR_HI:
1379 if (VT.getSizeInBits() == 32)
1380 return Reg;
1381 break;
1382 case AMDGPU::EXEC:
1383 case AMDGPU::FLAT_SCR:
1384 if (VT.getSizeInBits() == 64)
1385 return Reg;
1386 break;
1387 default:
1388 llvm_unreachable("missing register type checking")::llvm::llvm_unreachable_internal("missing register type checking"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1388)
;
1389 }
1390
1391 report_fatal_error(Twine("invalid type for register \""
1392 + StringRef(RegName) + "\"."));
1393}
1394
1395// If kill is not the last instruction, split the block so kill is always a
1396// proper terminator.
1397MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
1398 MachineBasicBlock *BB) const {
1399 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1400
1401 MachineBasicBlock::iterator SplitPoint(&MI);
1402 ++SplitPoint;
1403
1404 if (SplitPoint == BB->end()) {
1405 // Don't bother with a new block.
1406 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1407 return BB;
1408 }
1409
1410 MachineFunction *MF = BB->getParent();
1411 MachineBasicBlock *SplitBB
1412 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
1413
1414 MF->insert(++MachineFunction::iterator(BB), SplitBB);
1415 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
1416
1417 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
1418 BB->addSuccessor(SplitBB);
1419
1420 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1421 return SplitBB;
1422}
1423
1424// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
1425// wavefront. If the value is uniform and just happens to be in a VGPR, this
1426// will only do one iteration. In the worst case, this will loop 64 times.
1427//
1428// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
1429static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
1430 const SIInstrInfo *TII,
1431 MachineRegisterInfo &MRI,
1432 MachineBasicBlock &OrigBB,
1433 MachineBasicBlock &LoopBB,
1434 const DebugLoc &DL,
1435 const MachineOperand &IdxReg,
1436 unsigned InitReg,
1437 unsigned ResultReg,
1438 unsigned PhiReg,
1439 unsigned InitSaveExecReg,
1440 int Offset,
1441 bool UseGPRIdxMode) {
1442 MachineBasicBlock::iterator I = LoopBB.begin();
1443
1444 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1445 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1446 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1447 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1448
1449 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
1450 .addReg(InitReg)
1451 .addMBB(&OrigBB)
1452 .addReg(ResultReg)
1453 .addMBB(&LoopBB);
1454
1455 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
1456 .addReg(InitSaveExecReg)
1457 .addMBB(&OrigBB)
1458 .addReg(NewExec)
1459 .addMBB(&LoopBB);
1460
1461 // Read the next variant <- also loop target.
1462 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
1463 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
1464
1465 // Compare the just read M0 value to all possible Idx values.
1466 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
1467 .addReg(CurrentIdxReg)
1468 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
1469
1470 if (UseGPRIdxMode) {
1471 unsigned IdxReg;
1472 if (Offset == 0) {
1473 IdxReg = CurrentIdxReg;
1474 } else {
1475 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1476 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
1477 .addReg(CurrentIdxReg, RegState::Kill)
1478 .addImm(Offset);
1479 }
1480
1481 MachineInstr *SetIdx =
1482 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
1483 .addReg(IdxReg, RegState::Kill);
1484 SetIdx->getOperand(2).setIsUndef();
1485 } else {
1486 // Move index from VCC into M0
1487 if (Offset == 0) {
1488 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1489 .addReg(CurrentIdxReg, RegState::Kill);
1490 } else {
1491 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1492 .addReg(CurrentIdxReg, RegState::Kill)
1493 .addImm(Offset);
1494 }
1495 }
1496
1497 // Update EXEC, save the original EXEC value to VCC.
1498 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
1499 .addReg(CondReg, RegState::Kill);
1500
1501 MRI.setSimpleHint(NewExec, CondReg);
1502
1503 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
1504 MachineInstr *InsertPt =
1505 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
1506 .addReg(AMDGPU::EXEC)
1507 .addReg(NewExec);
1508
1509 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
1510 // s_cbranch_scc0?
1511
1512 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
1513 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
1514 .addMBB(&LoopBB);
1515
1516 return InsertPt->getIterator();
1517}
1518
1519// This has slightly sub-optimal regalloc when the source vector is killed by
1520// the read. The register allocator does not understand that the kill is
1521// per-workitem, so is kept alive for the whole loop so we end up not re-using a
1522// subregister from it, using 1 more VGPR than necessary. This was saved when
1523// this was expanded after register allocation.
1524static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
1525 MachineBasicBlock &MBB,
1526 MachineInstr &MI,
1527 unsigned InitResultReg,
1528 unsigned PhiReg,
1529 int Offset,
1530 bool UseGPRIdxMode) {
1531 MachineFunction *MF = MBB.getParent();
1532 MachineRegisterInfo &MRI = MF->getRegInfo();
1533 const DebugLoc &DL = MI.getDebugLoc();
1534 MachineBasicBlock::iterator I(&MI);
1535
1536 unsigned DstReg = MI.getOperand(0).getReg();
1537 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1538 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1539
1540 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
1541
1542 // Save the EXEC mask
1543 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
1544 .addReg(AMDGPU::EXEC);
1545
1546 // To insert the loop we need to split the block. Move everything after this
1547 // point to a new block, and insert a new empty block between the two.
1548 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
1549 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
1550 MachineFunction::iterator MBBI(MBB);
1551 ++MBBI;
1552
1553 MF->insert(MBBI, LoopBB);
1554 MF->insert(MBBI, RemainderBB);
1555
1556 LoopBB->addSuccessor(LoopBB);
1557 LoopBB->addSuccessor(RemainderBB);
1558
1559 // Move the rest of the block into a new block.
1560 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
1561 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
1562
1563 MBB.addSuccessor(LoopBB);
1564
1565 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1566
1567 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
1568 InitResultReg, DstReg, PhiReg, TmpExec,
1569 Offset, UseGPRIdxMode);
1570
1571 MachineBasicBlock::iterator First = RemainderBB->begin();
1572 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
1573 .addReg(SaveExec);
1574
1575 return InsPt;
1576}
1577
1578// Returns subreg index, offset
1579static std::pair<unsigned, int>
1580computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
1581 const TargetRegisterClass *SuperRC,
1582 unsigned VecReg,
1583 int Offset) {
1584 int NumElts = SuperRC->getSize() / 4;
1585
1586 // Skip out of bounds offsets, or else we would end up using an undefined
1587 // register.
1588 if (Offset >= NumElts || Offset < 0)
1589 return std::make_pair(AMDGPU::sub0, Offset);
1590
1591 return std::make_pair(AMDGPU::sub0 + Offset, 0);
1592}
1593
1594// Return true if the index is an SGPR and was set.
1595static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
1596 MachineRegisterInfo &MRI,
1597 MachineInstr &MI,
1598 int Offset,
1599 bool UseGPRIdxMode,
1600 bool IsIndirectSrc) {
1601 MachineBasicBlock *MBB = MI.getParent();
1602 const DebugLoc &DL = MI.getDebugLoc();
1603 MachineBasicBlock::iterator I(&MI);
1604
1605 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1606 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
1607
1608 assert(Idx->getReg() != AMDGPU::NoRegister)((Idx->getReg() != AMDGPU::NoRegister) ? static_cast<void
> (0) : __assert_fail ("Idx->getReg() != AMDGPU::NoRegister"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1608, __PRETTY_FUNCTION__))
;
1609
1610 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
1611 return false;
1612
1613 if (UseGPRIdxMode) {
1614 unsigned IdxMode = IsIndirectSrc ?
1615 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
1616 if (Offset == 0) {
1617 MachineInstr *SetOn =
1618 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1619 .add(*Idx)
1620 .addImm(IdxMode);
1621
1622 SetOn->getOperand(3).setIsUndef();
1623 } else {
1624 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1625 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
1626 .add(*Idx)
1627 .addImm(Offset);
1628 MachineInstr *SetOn =
1629 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1630 .addReg(Tmp, RegState::Kill)
1631 .addImm(IdxMode);
1632
1633 SetOn->getOperand(3).setIsUndef();
1634 }
1635
1636 return true;
1637 }
1638
1639 if (Offset == 0) {
1640 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1641 .add(*Idx);
1642 } else {
1643 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1644 .add(*Idx)
1645 .addImm(Offset);
1646 }
1647
1648 return true;
1649}
1650
1651// Control flow needs to be inserted if indexing with a VGPR.
1652static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
1653 MachineBasicBlock &MBB,
1654 const SISubtarget &ST) {
1655 const SIInstrInfo *TII = ST.getInstrInfo();
1656 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1657 MachineFunction *MF = MBB.getParent();
1658 MachineRegisterInfo &MRI = MF->getRegInfo();
1659
1660 unsigned Dst = MI.getOperand(0).getReg();
1661 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
1662 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1663
1664 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
1665
1666 unsigned SubReg;
1667 std::tie(SubReg, Offset)
1668 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
1669
1670 bool UseGPRIdxMode = ST.hasVGPRIndexMode() && EnableVGPRIndexMode;
1671
1672 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
1673 MachineBasicBlock::iterator I(&MI);
1674 const DebugLoc &DL = MI.getDebugLoc();
1675
1676 if (UseGPRIdxMode) {
1677 // TODO: Look at the uses to avoid the copy. This may require rescheduling
1678 // to avoid interfering with other uses, so probably requires a new
1679 // optimization pass.
1680 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1681 .addReg(SrcReg, RegState::Undef, SubReg)
1682 .addReg(SrcReg, RegState::Implicit)
1683 .addReg(AMDGPU::M0, RegState::Implicit);
1684 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1685 } else {
1686 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1687 .addReg(SrcReg, RegState::Undef, SubReg)
1688 .addReg(SrcReg, RegState::Implicit);
1689 }
1690
1691 MI.eraseFromParent();
1692
1693 return &MBB;
1694 }
1695
1696 const DebugLoc &DL = MI.getDebugLoc();
1697 MachineBasicBlock::iterator I(&MI);
1698
1699 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1700 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1701
1702 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
1703
1704 if (UseGPRIdxMode) {
1705 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1706 .addImm(0) // Reset inside loop.
1707 .addImm(VGPRIndexMode::SRC0_ENABLE);
1708 SetOn->getOperand(3).setIsUndef();
1709
1710 // Disable again after the loop.
1711 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1712 }
1713
1714 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
1715 MachineBasicBlock *LoopBB = InsPt->getParent();
1716
1717 if (UseGPRIdxMode) {
1718 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1719 .addReg(SrcReg, RegState::Undef, SubReg)
1720 .addReg(SrcReg, RegState::Implicit)
1721 .addReg(AMDGPU::M0, RegState::Implicit);
1722 } else {
1723 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1724 .addReg(SrcReg, RegState::Undef, SubReg)
1725 .addReg(SrcReg, RegState::Implicit);
1726 }
1727
1728 MI.eraseFromParent();
1729
1730 return LoopBB;
1731}
1732
1733static unsigned getMOVRELDPseudo(const TargetRegisterClass *VecRC) {
1734 switch (VecRC->getSize()) {
1735 case 4:
1736 return AMDGPU::V_MOVRELD_B32_V1;
1737 case 8:
1738 return AMDGPU::V_MOVRELD_B32_V2;
1739 case 16:
1740 return AMDGPU::V_MOVRELD_B32_V4;
1741 case 32:
1742 return AMDGPU::V_MOVRELD_B32_V8;
1743 case 64:
1744 return AMDGPU::V_MOVRELD_B32_V16;
1745 default:
1746 llvm_unreachable("unsupported size for MOVRELD pseudos")::llvm::llvm_unreachable_internal("unsupported size for MOVRELD pseudos"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1746)
;
1747 }
1748}
1749
1750static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
1751 MachineBasicBlock &MBB,
1752 const SISubtarget &ST) {
1753 const SIInstrInfo *TII = ST.getInstrInfo();
1754 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1755 MachineFunction *MF = MBB.getParent();
1756 MachineRegisterInfo &MRI = MF->getRegInfo();
1757
1758 unsigned Dst = MI.getOperand(0).getReg();
1759 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
1760 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1761 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
1762 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1763 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
1764
1765 // This can be an immediate, but will be folded later.
1766 assert(Val->getReg())((Val->getReg()) ? static_cast<void> (0) : __assert_fail
("Val->getReg()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1766, __PRETTY_FUNCTION__))
;
1767
1768 unsigned SubReg;
1769 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
1770 SrcVec->getReg(),
1771 Offset);
1772 bool UseGPRIdxMode = ST.hasVGPRIndexMode() && EnableVGPRIndexMode;
1773
1774 if (Idx->getReg() == AMDGPU::NoRegister) {
1775 MachineBasicBlock::iterator I(&MI);
1776 const DebugLoc &DL = MI.getDebugLoc();
1777
1778 assert(Offset == 0)((Offset == 0) ? static_cast<void> (0) : __assert_fail (
"Offset == 0", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1778, __PRETTY_FUNCTION__))
;
1779
1780 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
1781 .add(*SrcVec)
1782 .add(*Val)
1783 .addImm(SubReg);
1784
1785 MI.eraseFromParent();
1786 return &MBB;
1787 }
1788
1789 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
1790 MachineBasicBlock::iterator I(&MI);
1791 const DebugLoc &DL = MI.getDebugLoc();
1792
1793 if (UseGPRIdxMode) {
1794 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1795 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
1796 .add(*Val)
1797 .addReg(Dst, RegState::ImplicitDefine)
1798 .addReg(SrcVec->getReg(), RegState::Implicit)
1799 .addReg(AMDGPU::M0, RegState::Implicit);
1800
1801 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1802 } else {
1803 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1804
1805 BuildMI(MBB, I, DL, MovRelDesc)
1806 .addReg(Dst, RegState::Define)
1807 .addReg(SrcVec->getReg())
1808 .add(*Val)
1809 .addImm(SubReg - AMDGPU::sub0);
1810 }
1811
1812 MI.eraseFromParent();
1813 return &MBB;
1814 }
1815
1816 if (Val->isReg())
1817 MRI.clearKillFlags(Val->getReg());
1818
1819 const DebugLoc &DL = MI.getDebugLoc();
1820
1821 if (UseGPRIdxMode) {
1822 MachineBasicBlock::iterator I(&MI);
1823
1824 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1825 .addImm(0) // Reset inside loop.
1826 .addImm(VGPRIndexMode::DST_ENABLE);
1827 SetOn->getOperand(3).setIsUndef();
1828
1829 // Disable again after the loop.
1830 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1831 }
1832
1833 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
1834
1835 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
1836 Offset, UseGPRIdxMode);
1837 MachineBasicBlock *LoopBB = InsPt->getParent();
1838
1839 if (UseGPRIdxMode) {
1840 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1841 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
1842 .add(*Val) // src0
1843 .addReg(Dst, RegState::ImplicitDefine)
1844 .addReg(PhiReg, RegState::Implicit)
1845 .addReg(AMDGPU::M0, RegState::Implicit);
1846 } else {
1847 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1848
1849 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
1850 .addReg(Dst, RegState::Define)
1851 .addReg(PhiReg)
1852 .add(*Val)
1853 .addImm(SubReg - AMDGPU::sub0);
1854 }
1855
1856 MI.eraseFromParent();
1857
1858 return LoopBB;
1859}
1860
1861MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
1862 MachineInstr &MI, MachineBasicBlock *BB) const {
1863
1864 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1865 MachineFunction *MF = BB->getParent();
1866 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1867
1868 if (TII->isMIMG(MI)) {
1869 if (!MI.memoperands_empty())
1870 return BB;
1871 // Add a memoperand for mimg instructions so that they aren't assumed to
1872 // be ordered memory instuctions.
1873
1874 MachinePointerInfo PtrInfo(MFI->getImagePSV());
1875 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable;
1876 if (MI.mayStore())
1877 Flags |= MachineMemOperand::MOStore;
1878
1879 if (MI.mayLoad())
1880 Flags |= MachineMemOperand::MOLoad;
1881
1882 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0);
1883 MI.addMemOperand(*MF, MMO);
1884 return BB;
1885 }
1886
1887 switch (MI.getOpcode()) {
1888 case AMDGPU::S_TRAP_PSEUDO: {
1889 const DebugLoc &DL = MI.getDebugLoc();
1890 const int TrapType = MI.getOperand(0).getImm();
1891
1892 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
1893 Subtarget->isTrapHandlerEnabled()) {
1894
1895 MachineFunction *MF = BB->getParent();
1896 SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1897 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
1898 assert(UserSGPR != AMDGPU::NoRegister)((UserSGPR != AMDGPU::NoRegister) ? static_cast<void> (
0) : __assert_fail ("UserSGPR != AMDGPU::NoRegister", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1898, __PRETTY_FUNCTION__))
;
1899
1900 if (!BB->isLiveIn(UserSGPR))
1901 BB->addLiveIn(UserSGPR);
1902
1903 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), AMDGPU::SGPR0_SGPR1)
1904 .addReg(UserSGPR);
1905 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_TRAP))
1906 .addImm(TrapType)
1907 .addReg(AMDGPU::SGPR0_SGPR1, RegState::Implicit);
1908 } else {
1909 switch (TrapType) {
1910 case SISubtarget::TrapIDLLVMTrap:
1911 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_ENDPGM));
1912 break;
1913 case SISubtarget::TrapIDLLVMDebugTrap: {
1914 DiagnosticInfoUnsupported NoTrap(*MF->getFunction(),
1915 "debugtrap handler not supported",
1916 DL,
1917 DS_Warning);
1918 LLVMContext &C = MF->getFunction()->getContext();
1919 C.diagnose(NoTrap);
1920 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_NOP))
1921 .addImm(0);
1922 break;
1923 }
1924 default:
1925 llvm_unreachable("unsupported trap handler type!")::llvm::llvm_unreachable_internal("unsupported trap handler type!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1925)
;
1926 }
1927 }
1928
1929 MI.eraseFromParent();
1930 return BB;
1931 }
1932 case AMDGPU::SI_INIT_M0:
1933 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
1934 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1935 .add(MI.getOperand(0));
1936 MI.eraseFromParent();
1937 return BB;
1938
1939 case AMDGPU::GET_GROUPSTATICSIZE: {
1940 DebugLoc DL = MI.getDebugLoc();
1941 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
1942 .add(MI.getOperand(0))
1943 .addImm(MFI->getLDSSize());
1944 MI.eraseFromParent();
1945 return BB;
1946 }
1947 case AMDGPU::SI_INDIRECT_SRC_V1:
1948 case AMDGPU::SI_INDIRECT_SRC_V2:
1949 case AMDGPU::SI_INDIRECT_SRC_V4:
1950 case AMDGPU::SI_INDIRECT_SRC_V8:
1951 case AMDGPU::SI_INDIRECT_SRC_V16:
1952 return emitIndirectSrc(MI, *BB, *getSubtarget());
1953 case AMDGPU::SI_INDIRECT_DST_V1:
1954 case AMDGPU::SI_INDIRECT_DST_V2:
1955 case AMDGPU::SI_INDIRECT_DST_V4:
1956 case AMDGPU::SI_INDIRECT_DST_V8:
1957 case AMDGPU::SI_INDIRECT_DST_V16:
1958 return emitIndirectDst(MI, *BB, *getSubtarget());
1959 case AMDGPU::SI_KILL:
1960 return splitKillBlock(MI, BB);
1961 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
1962 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
1963
1964 unsigned Dst = MI.getOperand(0).getReg();
1965 unsigned Src0 = MI.getOperand(1).getReg();
1966 unsigned Src1 = MI.getOperand(2).getReg();
1967 const DebugLoc &DL = MI.getDebugLoc();
1968 unsigned SrcCond = MI.getOperand(3).getReg();
1969
1970 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1971 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1972
1973 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
1974 .addReg(Src0, 0, AMDGPU::sub0)
1975 .addReg(Src1, 0, AMDGPU::sub0)
1976 .addReg(SrcCond);
1977 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
1978 .addReg(Src0, 0, AMDGPU::sub1)
1979 .addReg(Src1, 0, AMDGPU::sub1)
1980 .addReg(SrcCond);
1981
1982 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
1983 .addReg(DstLo)
1984 .addImm(AMDGPU::sub0)
1985 .addReg(DstHi)
1986 .addImm(AMDGPU::sub1);
1987 MI.eraseFromParent();
1988 return BB;
1989 }
1990 case AMDGPU::SI_BR_UNDEF: {
1991 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1992 const DebugLoc &DL = MI.getDebugLoc();
1993 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
1994 .add(MI.getOperand(0));
1995 Br->getOperand(1).setIsUndef(true); // read undef SCC
1996 MI.eraseFromParent();
1997 return BB;
1998 }
1999 default:
2000 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
2001 }
2002}
2003
2004bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
2005 // This currently forces unfolding various combinations of fsub into fma with
2006 // free fneg'd operands. As long as we have fast FMA (controlled by
2007 // isFMAFasterThanFMulAndFAdd), we should perform these.
2008
2009 // When fma is quarter rate, for f64 where add / sub are at best half rate,
2010 // most of these combines appear to be cycle neutral but save on instruction
2011 // count / code size.
2012 return true;
2013}
2014
2015EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
2016 EVT VT) const {
2017 if (!VT.isVector()) {
2018 return MVT::i1;
2019 }
2020 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
2021}
2022
2023MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
2024 // TODO: Should i16 be used always if legal? For now it would force VALU
2025 // shifts.
2026 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
2027}
2028
2029// Answering this is somewhat tricky and depends on the specific device which
2030// have different rates for fma or all f64 operations.
2031//
2032// v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
2033// regardless of which device (although the number of cycles differs between
2034// devices), so it is always profitable for f64.
2035//
2036// v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
2037// only on full rate devices. Normally, we should prefer selecting v_mad_f32
2038// which we can always do even without fused FP ops since it returns the same
2039// result as the separate operations and since it is always full
2040// rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
2041// however does not support denormals, so we do report fma as faster if we have
2042// a fast fma device and require denormals.
2043//
2044bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
2045 VT = VT.getScalarType();
2046
2047 switch (VT.getSimpleVT().SimpleTy) {
2048 case MVT::f32:
2049 // This is as fast on some subtargets. However, we always have full rate f32
2050 // mad available which returns the same result as the separate operations
2051 // which we should prefer over fma. We can't use this if we want to support
2052 // denormals, so only report this in these cases.
2053 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
2054 case MVT::f64:
2055 return true;
2056 case MVT::f16:
2057 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
2058 default:
2059 break;
2060 }
2061
2062 return false;
2063}
2064
2065//===----------------------------------------------------------------------===//
2066// Custom DAG Lowering Operations
2067//===----------------------------------------------------------------------===//
2068
2069SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2070 switch (Op.getOpcode()) {
2071 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2072 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2073 case ISD::LOAD: {
2074 SDValue Result = LowerLOAD(Op, DAG);
2075 assert((!Result.getNode() ||(((!Result.getNode() || Result.getNode()->getNumValues() ==
2) && "Load should return a value and a chain") ? static_cast
<void> (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2077, __PRETTY_FUNCTION__))
2076 Result.getNode()->getNumValues() == 2) &&(((!Result.getNode() || Result.getNode()->getNumValues() ==
2) && "Load should return a value and a chain") ? static_cast
<void> (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2077, __PRETTY_FUNCTION__))
2077 "Load should return a value and a chain")(((!Result.getNode() || Result.getNode()->getNumValues() ==
2) && "Load should return a value and a chain") ? static_cast
<void> (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2077, __PRETTY_FUNCTION__))
;
2078 return Result;
2079 }
2080
2081 case ISD::FSIN:
2082 case ISD::FCOS:
2083 return LowerTrig(Op, DAG);
2084 case ISD::SELECT: return LowerSELECT(Op, DAG);
2085 case ISD::FDIV: return LowerFDIV(Op, DAG);
2086 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
2087 case ISD::STORE: return LowerSTORE(Op, DAG);
2088 case ISD::GlobalAddress: {
2089 MachineFunction &MF = DAG.getMachineFunction();
2090 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2091 return LowerGlobalAddress(MFI, Op, DAG);
2092 }
2093 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2094 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2095 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
2096 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
2097 case ISD::INSERT_VECTOR_ELT:
2098 return lowerINSERT_VECTOR_ELT(Op, DAG);
2099 case ISD::EXTRACT_VECTOR_ELT:
2100 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2101 case ISD::FP_ROUND:
2102 return lowerFP_ROUND(Op, DAG);
2103 }
2104 return SDValue();
2105}
2106
2107void SITargetLowering::ReplaceNodeResults(SDNode *N,
2108 SmallVectorImpl<SDValue> &Results,
2109 SelectionDAG &DAG) const {
2110 switch (N->getOpcode()) {
2111 case ISD::INSERT_VECTOR_ELT: {
2112 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
2113 Results.push_back(Res);
2114 return;
2115 }
2116 case ISD::EXTRACT_VECTOR_ELT: {
2117 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
2118 Results.push_back(Res);
2119 return;
2120 }
2121 case ISD::INTRINSIC_WO_CHAIN: {
2122 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2123 switch (IID) {
2124 case Intrinsic::amdgcn_cvt_pkrtz: {
2125 SDValue Src0 = N->getOperand(1);
2126 SDValue Src1 = N->getOperand(2);
2127 SDLoc SL(N);
2128 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
2129 Src0, Src1);
2130
2131 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
2132 return;
2133 }
2134 default:
2135 break;
2136 }
2137 }
2138 default:
2139 break;
2140 }
2141}
2142
2143/// \brief Helper function for LowerBRCOND
2144static SDNode *findUser(SDValue Value, unsigned Opcode) {
2145
2146 SDNode *Parent = Value.getNode();
2147 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
2148 I != E; ++I) {
2149
2150 if (I.getUse().get() != Value)
2151 continue;
2152
2153 if (I->getOpcode() == Opcode)
2154 return *I;
2155 }
2156 return nullptr;
2157}
2158
2159bool SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
2160 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
2161 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
2162 case AMDGPUIntrinsic::amdgcn_if:
2163 case AMDGPUIntrinsic::amdgcn_else:
2164 case AMDGPUIntrinsic::amdgcn_end_cf:
2165 case AMDGPUIntrinsic::amdgcn_loop:
2166 return true;
2167 default:
2168 return false;
2169 }
2170 }
2171
2172 if (Intr->getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
2173 switch (cast<ConstantSDNode>(Intr->getOperand(0))->getZExtValue()) {
2174 case AMDGPUIntrinsic::amdgcn_break:
2175 case AMDGPUIntrinsic::amdgcn_if_break:
2176 case AMDGPUIntrinsic::amdgcn_else_break:
2177 return true;
2178 default:
2179 return false;
2180 }
2181 }
2182
2183 return false;
2184}
2185
2186void SITargetLowering::createDebuggerPrologueStackObjects(
2187 MachineFunction &MF) const {
2188 // Create stack objects that are used for emitting debugger prologue.
2189 //
2190 // Debugger prologue writes work group IDs and work item IDs to scratch memory
2191 // at fixed location in the following format:
2192 // offset 0: work group ID x
2193 // offset 4: work group ID y
2194 // offset 8: work group ID z
2195 // offset 16: work item ID x
2196 // offset 20: work item ID y
2197 // offset 24: work item ID z
2198 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2199 int ObjectIdx = 0;
2200
2201 // For each dimension:
2202 for (unsigned i = 0; i < 3; ++i) {
2203 // Create fixed stack object for work group ID.
2204 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
2205 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
2206 // Create fixed stack object for work item ID.
2207 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
2208 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
2209 }
2210}
2211
2212bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
2213 const Triple &TT = getTargetMachine().getTargetTriple();
2214 return GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS &&
2215 AMDGPU::shouldEmitConstantsToTextSection(TT);
2216}
2217
2218bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
2219 return (GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
2220 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) &&
2221 !shouldEmitFixup(GV) &&
2222 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2223}
2224
2225bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
2226 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
2227}
2228
2229/// This transforms the control flow intrinsics to get the branch destination as
2230/// last parameter, also switches branch target with BR if the need arise
2231SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
2232 SelectionDAG &DAG) const {
2233 SDLoc DL(BRCOND);
2234
2235 SDNode *Intr = BRCOND.getOperand(1).getNode();
2236 SDValue Target = BRCOND.getOperand(2);
2237 SDNode *BR = nullptr;
2238 SDNode *SetCC = nullptr;
2239
2240 if (Intr->getOpcode() == ISD::SETCC) {
2241 // As long as we negate the condition everything is fine
2242 SetCC = Intr;
2243 Intr = SetCC->getOperand(0).getNode();
2244
2245 } else {
2246 // Get the target from BR if we don't negate the condition
2247 BR = findUser(BRCOND, ISD::BR);
2248 Target = BR->getOperand(1);
2249 }
2250
2251 // FIXME: This changes the types of the intrinsics instead of introducing new
2252 // nodes with the correct types.
2253 // e.g. llvm.amdgcn.loop
2254
2255 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
2256 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
2257
2258 if (!isCFIntrinsic(Intr)) {
2259 // This is a uniform branch so we don't need to legalize.
2260 return BRCOND;
2261 }
2262
2263 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
2264 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
2265
2266 assert(!SetCC ||((!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode()
)->get() == ISD::SETNE)) ? static_cast<void> (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2269, __PRETTY_FUNCTION__))
2267 (SetCC->getConstantOperandVal(1) == 1 &&((!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode()
)->get() == ISD::SETNE)) ? static_cast<void> (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2269, __PRETTY_FUNCTION__))
2268 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==((!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode()
)->get() == ISD::SETNE)) ? static_cast<void> (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2269, __PRETTY_FUNCTION__))
2269 ISD::SETNE))((!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode()
)->get() == ISD::SETNE)) ? static_cast<void> (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2269, __PRETTY_FUNCTION__))
;
2270
2271 // operands of the new intrinsic call
2272 SmallVector<SDValue, 4> Ops;
2273 if (HaveChain)
2274 Ops.push_back(BRCOND.getOperand(0));
2275
2276 Ops.append(Intr->op_begin() + (HaveChain ? 1 : 0), Intr->op_end());
2277 Ops.push_back(Target);
2278
2279 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
2280
2281 // build the new intrinsic call
2282 SDNode *Result = DAG.getNode(
2283 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
2284 DAG.getVTList(Res), Ops).getNode();
2285
2286 if (!HaveChain) {
2287 SDValue Ops[] = {
2288 SDValue(Result, 0),
2289 BRCOND.getOperand(0)
2290 };
2291
2292 Result = DAG.getMergeValues(Ops, DL).getNode();
2293 }
2294
2295 if (BR) {
2296 // Give the branch instruction our target
2297 SDValue Ops[] = {
2298 BR->getOperand(0),
2299 BRCOND.getOperand(2)
2300 };
2301 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
2302 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
2303 BR = NewBR.getNode();
Value stored to 'BR' is never read
2304 }
2305
2306 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
2307
2308 // Copy the intrinsic results to registers
2309 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
2310 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
2311 if (!CopyToReg)
2312 continue;
2313
2314 Chain = DAG.getCopyToReg(
2315 Chain, DL,
2316 CopyToReg->getOperand(1),
2317 SDValue(Result, i - 1),
2318 SDValue());
2319
2320 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
2321 }
2322
2323 // Remove the old intrinsic from the chain
2324 DAG.ReplaceAllUsesOfValueWith(
2325 SDValue(Intr, Intr->getNumValues() - 1),
2326 Intr->getOperand(0));
2327
2328 return Chain;
2329}
2330
2331SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
2332 SDValue Op,
2333 const SDLoc &DL,
2334 EVT VT) const {
2335 return Op.getValueType().bitsLE(VT) ?
2336 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
2337 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
2338}
2339
2340SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2341 assert(Op.getValueType() == MVT::f16 &&((Op.getValueType() == MVT::f16 && "Do not know how to custom lower FP_ROUND for non-f16 type"
) ? static_cast<void> (0) : __assert_fail ("Op.getValueType() == MVT::f16 && \"Do not know how to custom lower FP_ROUND for non-f16 type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2342, __PRETTY_FUNCTION__))
2342 "Do not know how to custom lower FP_ROUND for non-f16 type")((Op.getValueType() == MVT::f16 && "Do not know how to custom lower FP_ROUND for non-f16 type"
) ? static_cast<void> (0) : __assert_fail ("Op.getValueType() == MVT::f16 && \"Do not know how to custom lower FP_ROUND for non-f16 type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2342, __PRETTY_FUNCTION__))
;
2343
2344 SDValue Src = Op.getOperand(0);
2345 EVT SrcVT = Src.getValueType();
2346 if (SrcVT != MVT::f64)
2347 return Op;
2348
2349 SDLoc DL(Op);
2350
2351 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
2352 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
2353 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);;
2354}
2355
2356SDValue SITargetLowering::getSegmentAperture(unsigned AS,
2357 SelectionDAG &DAG) const {
2358
2359 if (Subtarget->hasApertureRegs()) { // Read from Aperture Registers directly.
2360 unsigned RegNo = (AS == AMDGPUAS::LOCAL_ADDRESS) ? AMDGPU::SRC_SHARED_BASE :
2361 AMDGPU::SRC_PRIVATE_BASE;
2362 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, RegNo, MVT::i32);
2363 }
2364
2365 SDLoc SL;
2366 MachineFunction &MF = DAG.getMachineFunction();
2367 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2368 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2369 assert(UserSGPR != AMDGPU::NoRegister)((UserSGPR != AMDGPU::NoRegister) ? static_cast<void> (
0) : __assert_fail ("UserSGPR != AMDGPU::NoRegister", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2369, __PRETTY_FUNCTION__))
;
2370
2371 SDValue QueuePtr = CreateLiveInRegister(
2372 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2373
2374 // Offset into amd_queue_t for group_segment_aperture_base_hi /
2375 // private_segment_aperture_base_hi.
2376 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
2377
2378 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, QueuePtr,
2379 DAG.getConstant(StructOffset, SL, MVT::i64));
2380
2381 // TODO: Use custom target PseudoSourceValue.
2382 // TODO: We should use the value from the IR intrinsic call, but it might not
2383 // be available and how do we get it?
2384 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
2385 AMDGPUAS::CONSTANT_ADDRESS));
2386
2387 MachinePointerInfo PtrInfo(V, StructOffset);
2388 return DAG.getLoad(MVT::i32, SL, QueuePtr.getValue(1), Ptr, PtrInfo,
2389 MinAlign(64, StructOffset),
2390 MachineMemOperand::MODereferenceable |
2391 MachineMemOperand::MOInvariant);
2392}
2393
2394SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
2395 SelectionDAG &DAG) const {
2396 SDLoc SL(Op);
2397 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
2398
2399 SDValue Src = ASC->getOperand(0);
2400 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
2401
2402 const AMDGPUTargetMachine &TM =
2403 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
2404
2405 // flat -> local/private
2406 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
2407 unsigned DestAS = ASC->getDestAddressSpace();
2408 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
2409 unsigned NullVal = TM.getNullPointerValue(DestAS);
2410 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2411 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
2412 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
2413
2414 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
2415 NonNull, Ptr, SegmentNullPtr);
2416 }
2417 }
2418
2419 // local/private -> flat
2420 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
2421 unsigned SrcAS = ASC->getSrcAddressSpace();
2422 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
2423 unsigned NullVal = TM.getNullPointerValue(SrcAS);
2424 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2425
2426 SDValue NonNull
2427 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
2428
2429 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), DAG);
2430 SDValue CvtPtr
2431 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
2432
2433 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
2434 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
2435 FlatNullPtr);
2436 }
2437 }
2438
2439 // global <-> flat are no-ops and never emitted.
2440
2441 const MachineFunction &MF = DAG.getMachineFunction();
2442 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
2443 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
2444 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
2445
2446 return DAG.getUNDEF(ASC->getValueType(0));
2447}
2448
2449SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
2450 SelectionDAG &DAG) const {
2451 SDValue Idx = Op.getOperand(2);
2452 if (isa<ConstantSDNode>(Idx))
2453 return SDValue();
2454
2455 // Avoid stack access for dynamic indexing.
2456 SDLoc SL(Op);
2457 SDValue Vec = Op.getOperand(0);
2458 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
2459
2460 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
2461 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
2462
2463 // Convert vector index to bit-index.
2464 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
2465 DAG.getConstant(16, SL, MVT::i32));
2466
2467 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2468
2469 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
2470 DAG.getConstant(0xffff, SL, MVT::i32),
2471 ScaledIdx);
2472
2473 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
2474 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
2475 DAG.getNOT(SL, BFM, MVT::i32), BCVec);
2476
2477 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
2478 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
2479}
2480
2481SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
2482 SelectionDAG &DAG) const {
2483 SDLoc SL(Op);
2484
2485 EVT ResultVT = Op.getValueType();
2486 SDValue Vec = Op.getOperand(0);
2487 SDValue Idx = Op.getOperand(1);
2488
2489 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
2490 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2491
2492 if (CIdx->getZExtValue() == 1) {
2493 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
2494 DAG.getConstant(16, SL, MVT::i32));
2495 } else {
2496 assert(CIdx->getZExtValue() == 0)((CIdx->getZExtValue() == 0) ? static_cast<void> (0)
: __assert_fail ("CIdx->getZExtValue() == 0", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2496, __PRETTY_FUNCTION__))
;
2497 }
2498
2499 if (ResultVT.bitsLT(MVT::i32))
2500 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2501 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2502 }
2503
2504 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
2505
2506 // Convert vector index to bit-index.
2507 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
2508
2509 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2510 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
2511
2512 SDValue Result = Elt;
2513 if (ResultVT.bitsLT(MVT::i32))
2514 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2515
2516 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2517}
2518
2519bool
2520SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2521 // We can fold offsets for anything that doesn't require a GOT relocation.
2522 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
2523 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) &&
2524 !shouldEmitGOTReloc(GA->getGlobal());
2525}
2526
2527static SDValue
2528buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
2529 const SDLoc &DL, unsigned Offset, EVT PtrVT,
2530 unsigned GAFlags = SIInstrInfo::MO_NONE) {
2531 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
2532 // lowered to the following code sequence:
2533 //
2534 // For constant address space:
2535 // s_getpc_b64 s[0:1]
2536 // s_add_u32 s0, s0, $symbol
2537 // s_addc_u32 s1, s1, 0
2538 //
2539 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2540 // a fixup or relocation is emitted to replace $symbol with a literal
2541 // constant, which is a pc-relative offset from the encoding of the $symbol
2542 // operand to the global variable.
2543 //
2544 // For global address space:
2545 // s_getpc_b64 s[0:1]
2546 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
2547 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
2548 //
2549 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2550 // fixups or relocations are emitted to replace $symbol@*@lo and
2551 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
2552 // which is a 64-bit pc-relative offset from the encoding of the $symbol
2553 // operand to the global variable.
2554 //
2555 // What we want here is an offset from the value returned by s_getpc
2556 // (which is the address of the s_add_u32 instruction) to the global
2557 // variable, but since the encoding of $symbol starts 4 bytes after the start
2558 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
2559 // small. This requires us to add 4 to the global variable offset in order to
2560 // compute the correct address.
2561 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2562 GAFlags);
2563 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2564 GAFlags == SIInstrInfo::MO_NONE ?
2565 GAFlags : GAFlags + 1);
2566 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
2567}
2568
2569SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
2570 SDValue Op,
2571 SelectionDAG &DAG) const {
2572 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
2573
2574 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS &&
2575 GSD->getAddressSpace() != AMDGPUAS::GLOBAL_ADDRESS)
2576 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
2577
2578 SDLoc DL(GSD);
2579 const GlobalValue *GV = GSD->getGlobal();
2580 EVT PtrVT = Op.getValueType();
2581
2582 if (shouldEmitFixup(GV))
2583 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
2584 else if (shouldEmitPCReloc(GV))
2585 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
2586 SIInstrInfo::MO_REL32);
2587
2588 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
2589 SIInstrInfo::MO_GOTPCREL32);
2590
2591 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
2592 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
2593 const DataLayout &DataLayout = DAG.getDataLayout();
2594 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
2595 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
2596 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
2597
2598 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
2599 MachineMemOperand::MODereferenceable |
2600 MachineMemOperand::MOInvariant);
2601}
2602
2603SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
2604 const SDLoc &DL, SDValue V) const {
2605 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
2606 // the destination register.
2607 //
2608 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
2609 // so we will end up with redundant moves to m0.
2610 //
2611 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
2612
2613 // A Null SDValue creates a glue result.
2614 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
2615 V, Chain);
2616 return SDValue(M0, 0);
2617}
2618
2619SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
2620 SDValue Op,
2621 MVT VT,
2622 unsigned Offset) const {
2623 SDLoc SL(Op);
2624 SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL,
2625 DAG.getEntryNode(), Offset, false);
2626 // The local size values will have the hi 16-bits as zero.
2627 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
2628 DAG.getValueType(VT));
2629}
2630
2631static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2632 EVT VT) {
2633 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2634 "non-hsa intrinsic with hsa target",
2635 DL.getDebugLoc());
2636 DAG.getContext()->diagnose(BadIntrin);
2637 return DAG.getUNDEF(VT);
2638}
2639
2640static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2641 EVT VT) {
2642 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2643 "intrinsic not supported on subtarget",
2644 DL.getDebugLoc());
2645 DAG.getContext()->diagnose(BadIntrin);
2646 return DAG.getUNDEF(VT);
2647}
2648
2649SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2650 SelectionDAG &DAG) const {
2651 MachineFunction &MF = DAG.getMachineFunction();
2652 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
2653 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2654
2655 EVT VT = Op.getValueType();
2656 SDLoc DL(Op);
2657 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2658
2659 // TODO: Should this propagate fast-math-flags?
2660
2661 switch (IntrinsicID) {
2662 case Intrinsic::amdgcn_implicit_buffer_ptr: {
2663 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
2664 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2665 }
2666 case Intrinsic::amdgcn_dispatch_ptr:
2667 case Intrinsic::amdgcn_queue_ptr: {
2668 if (!Subtarget->isAmdCodeObjectV2(MF)) {
2669 DiagnosticInfoUnsupported BadIntrin(
2670 *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
2671 DL.getDebugLoc());
2672 DAG.getContext()->diagnose(BadIntrin);
2673 return DAG.getUNDEF(VT);
2674 }
2675
2676 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
2677 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
2678 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
2679 TRI->getPreloadedValue(MF, Reg), VT);
2680 }
2681 case Intrinsic::amdgcn_implicitarg_ptr: {
2682 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
2683 return LowerParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
2684 }
2685 case Intrinsic::amdgcn_kernarg_segment_ptr: {
2686 unsigned Reg
2687 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
2688 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2689 }
2690 case Intrinsic::amdgcn_dispatch_id: {
2691 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID);
2692 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2693 }
2694 case Intrinsic::amdgcn_rcp:
2695 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
2696 case Intrinsic::amdgcn_rsq:
2697 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2698 case Intrinsic::amdgcn_rsq_legacy:
2699 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2700 return emitRemovedIntrinsicError(DAG, DL, VT);
2701
2702 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
2703 case Intrinsic::amdgcn_rcp_legacy:
2704 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2705 return emitRemovedIntrinsicError(DAG, DL, VT);
2706 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
2707 case Intrinsic::amdgcn_rsq_clamp: {
2708 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2709 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
2710
2711 Type *Type = VT.getTypeForEVT(*DAG.getContext());
2712 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
2713 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
2714
2715 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2716 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
2717 DAG.getConstantFP(Max, DL, VT));
2718 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
2719 DAG.getConstantFP(Min, DL, VT));
2720 }
2721 case Intrinsic::r600_read_ngroups_x:
2722 if (Subtarget->isAmdHsaOS())
2723 return emitNonHSAIntrinsicError(DAG, DL, VT);
2724
2725 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2726 SI::KernelInputOffsets::NGROUPS_X, false);
2727 case Intrinsic::r600_read_ngroups_y:
2728 if (Subtarget->isAmdHsaOS())
2729 return emitNonHSAIntrinsicError(DAG, DL, VT);
2730
2731 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2732 SI::KernelInputOffsets::NGROUPS_Y, false);
2733 case Intrinsic::r600_read_ngroups_z:
2734 if (Subtarget->isAmdHsaOS())
2735 return emitNonHSAIntrinsicError(DAG, DL, VT);
2736
2737 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2738 SI::KernelInputOffsets::NGROUPS_Z, false);
2739 case Intrinsic::r600_read_global_size_x:
2740 if (Subtarget->isAmdHsaOS())
2741 return emitNonHSAIntrinsicError(DAG, DL, VT);
2742
2743 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2744 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
2745 case Intrinsic::r600_read_global_size_y:
2746 if (Subtarget->isAmdHsaOS())
2747 return emitNonHSAIntrinsicError(DAG, DL, VT);
2748
2749 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2750 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
2751 case Intrinsic::r600_read_global_size_z:
2752 if (Subtarget->isAmdHsaOS())
2753 return emitNonHSAIntrinsicError(DAG, DL, VT);
2754
2755 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2756 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
2757 case Intrinsic::r600_read_local_size_x:
2758 if (Subtarget->isAmdHsaOS())
2759 return emitNonHSAIntrinsicError(DAG, DL, VT);
2760
2761 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2762 SI::KernelInputOffsets::LOCAL_SIZE_X);
2763 case Intrinsic::r600_read_local_size_y:
2764 if (Subtarget->isAmdHsaOS())
2765 return emitNonHSAIntrinsicError(DAG, DL, VT);
2766
2767 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2768 SI::KernelInputOffsets::LOCAL_SIZE_Y);
2769 case Intrinsic::r600_read_local_size_z:
2770 if (Subtarget->isAmdHsaOS())
2771 return emitNonHSAIntrinsicError(DAG, DL, VT);
2772
2773 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2774 SI::KernelInputOffsets::LOCAL_SIZE_Z);
2775 case Intrinsic::amdgcn_workgroup_id_x:
2776 case Intrinsic::r600_read_tgid_x:
2777 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2778 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
2779 case Intrinsic::amdgcn_workgroup_id_y:
2780 case Intrinsic::r600_read_tgid_y:
2781 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2782 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
2783 case Intrinsic::amdgcn_workgroup_id_z:
2784 case Intrinsic::r600_read_tgid_z:
2785 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2786 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
2787 case Intrinsic::amdgcn_workitem_id_x:
2788 case Intrinsic::r600_read_tidig_x:
2789 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2790 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
2791 case Intrinsic::amdgcn_workitem_id_y:
2792 case Intrinsic::r600_read_tidig_y:
2793 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2794 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
2795 case Intrinsic::amdgcn_workitem_id_z:
2796 case Intrinsic::r600_read_tidig_z:
2797 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2798 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
2799 case AMDGPUIntrinsic::SI_load_const: {
2800 SDValue Ops[] = {
2801 Op.getOperand(1),
2802 Op.getOperand(2)
2803 };
2804
2805 MachineMemOperand *MMO = MF.getMachineMemOperand(
2806 MachinePointerInfo(),
2807 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
2808 MachineMemOperand::MOInvariant,
2809 VT.getStoreSize(), 4);
2810 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
2811 Op->getVTList(), Ops, VT, MMO);
2812 }
2813 case AMDGPUIntrinsic::amdgcn_fdiv_fast:
2814 return lowerFDIV_FAST(Op, DAG);
2815 case AMDGPUIntrinsic::SI_vs_load_input:
2816 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
2817 Op.getOperand(1),
2818 Op.getOperand(2),
2819 Op.getOperand(3));
2820 case Intrinsic::amdgcn_interp_mov: {
2821 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2822 SDValue Glue = M0.getValue(1);
2823 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
2824 Op.getOperand(2), Op.getOperand(3), Glue);
2825 }
2826 case Intrinsic::amdgcn_interp_p1: {
2827 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2828 SDValue Glue = M0.getValue(1);
2829 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
2830 Op.getOperand(2), Op.getOperand(3), Glue);
2831 }
2832 case Intrinsic::amdgcn_interp_p2: {
2833 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
2834 SDValue Glue = SDValue(M0.getNode(), 1);
2835 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
2836 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
2837 Glue);
2838 }
2839 case Intrinsic::amdgcn_sin:
2840 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
2841
2842 case Intrinsic::amdgcn_cos:
2843 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
2844
2845 case Intrinsic::amdgcn_log_clamp: {
2846 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2847 return SDValue();
2848
2849 DiagnosticInfoUnsupported BadIntrin(
2850 *MF.getFunction(), "intrinsic not supported on subtarget",
2851 DL.getDebugLoc());
2852 DAG.getContext()->diagnose(BadIntrin);
2853 return DAG.getUNDEF(VT);
2854 }
2855 case Intrinsic::amdgcn_ldexp:
2856 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
2857 Op.getOperand(1), Op.getOperand(2));
2858
2859 case Intrinsic::amdgcn_fract:
2860 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
2861
2862 case Intrinsic::amdgcn_class:
2863 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
2864 Op.getOperand(1), Op.getOperand(2));
2865 case Intrinsic::amdgcn_div_fmas:
2866 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
2867 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
2868 Op.getOperand(4));
2869
2870 case Intrinsic::amdgcn_div_fixup:
2871 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
2872 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2873
2874 case Intrinsic::amdgcn_trig_preop:
2875 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
2876 Op.getOperand(1), Op.getOperand(2));
2877 case Intrinsic::amdgcn_div_scale: {
2878 // 3rd parameter required to be a constant.
2879 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2880 if (!Param)
2881 return DAG.getUNDEF(VT);
2882
2883 // Translate to the operands expected by the machine instruction. The
2884 // first parameter must be the same as the first instruction.
2885 SDValue Numerator = Op.getOperand(1);
2886 SDValue Denominator = Op.getOperand(2);
2887
2888 // Note this order is opposite of the machine instruction's operations,
2889 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
2890 // intrinsic has the numerator as the first operand to match a normal
2891 // division operation.
2892
2893 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
2894
2895 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
2896 Denominator, Numerator);
2897 }
2898 case Intrinsic::amdgcn_icmp: {
2899 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2900 if (!CD)
2901 return DAG.getUNDEF(VT);
2902
2903 int CondCode = CD->getSExtValue();
2904 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
2905 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
2906 return DAG.getUNDEF(VT);
2907
2908 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
2909 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
2910 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2911 Op.getOperand(2), DAG.getCondCode(CCOpcode));
2912 }
2913 case Intrinsic::amdgcn_fcmp: {
2914 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2915 if (!CD)
2916 return DAG.getUNDEF(VT);
2917
2918 int CondCode = CD->getSExtValue();
2919 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
2920 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
2921 return DAG.getUNDEF(VT);
2922
2923 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
2924 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
2925 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2926 Op.getOperand(2), DAG.getCondCode(CCOpcode));
2927 }
2928 case Intrinsic::amdgcn_fmed3:
2929 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
2930 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2931 case Intrinsic::amdgcn_fmul_legacy:
2932 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
2933 Op.getOperand(1), Op.getOperand(2));
2934 case Intrinsic::amdgcn_sffbh:
2935 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
2936 case Intrinsic::amdgcn_sbfe:
2937 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
2938 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2939 case Intrinsic::amdgcn_ubfe:
2940 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
2941 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2942 case Intrinsic::amdgcn_cvt_pkrtz: {
2943 // FIXME: Stop adding cast if v2f16 legal.
2944 EVT VT = Op.getValueType();
2945 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32,
2946 Op.getOperand(1), Op.getOperand(2));
2947 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
2948 }
2949 default:
2950 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2951 }
2952}
2953
2954SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2955 SelectionDAG &DAG) const {
2956 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2957 SDLoc DL(Op);
2958 switch (IntrID) {
2959 case Intrinsic::amdgcn_atomic_inc:
2960 case Intrinsic::amdgcn_atomic_dec: {
2961 MemSDNode *M = cast<MemSDNode>(Op);
2962 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
2963 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
2964 SDValue Ops[] = {
2965 M->getOperand(0), // Chain
2966 M->getOperand(2), // Ptr
2967 M->getOperand(3) // Value
2968 };
2969
2970 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
2971 M->getMemoryVT(), M->getMemOperand());
2972 }
2973 case Intrinsic::amdgcn_buffer_load:
2974 case Intrinsic::amdgcn_buffer_load_format: {
2975 SDValue Ops[] = {
2976 Op.getOperand(0), // Chain
2977 Op.getOperand(2), // rsrc
2978 Op.getOperand(3), // vindex
2979 Op.getOperand(4), // offset
2980 Op.getOperand(5), // glc
2981 Op.getOperand(6) // slc
2982 };
2983 MachineFunction &MF = DAG.getMachineFunction();
2984 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2985
2986 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
2987 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
2988 EVT VT = Op.getValueType();
2989 EVT IntVT = VT.changeTypeToInteger();
2990
2991 MachineMemOperand *MMO = MF.getMachineMemOperand(
2992 MachinePointerInfo(MFI->getBufferPSV()),
2993 MachineMemOperand::MOLoad,
2994 VT.getStoreSize(), VT.getStoreSize());
2995
2996 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO);
2997 }
2998 default:
2999 return SDValue();
3000 }
3001}
3002
3003SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
3004 SelectionDAG &DAG) const {
3005 MachineFunction &MF = DAG.getMachineFunction();
3006 SDLoc DL(Op);
3007 SDValue Chain = Op.getOperand(0);
3008 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3009
3010 switch (IntrinsicID) {
3011 case Intrinsic::amdgcn_exp: {
3012 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3013 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3014 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
3015 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
3016
3017 const SDValue Ops[] = {
3018 Chain,
3019 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3020 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3021 Op.getOperand(4), // src0
3022 Op.getOperand(5), // src1
3023 Op.getOperand(6), // src2
3024 Op.getOperand(7), // src3
3025 DAG.getTargetConstant(0, DL, MVT::i1), // compr
3026 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3027 };
3028
3029 unsigned Opc = Done->isNullValue() ?
3030 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3031 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3032 }
3033 case Intrinsic::amdgcn_exp_compr: {
3034 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3035 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3036 SDValue Src0 = Op.getOperand(4);
3037 SDValue Src1 = Op.getOperand(5);
3038 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
3039 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
3040
3041 SDValue Undef = DAG.getUNDEF(MVT::f32);
3042 const SDValue Ops[] = {
3043 Chain,
3044 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3045 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3046 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
3047 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
3048 Undef, // src2
3049 Undef, // src3
3050 DAG.getTargetConstant(1, DL, MVT::i1), // compr
3051 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3052 };
3053
3054 unsigned Opc = Done->isNullValue() ?
3055 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3056 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3057 }
3058 case Intrinsic::amdgcn_s_sendmsg:
3059 case Intrinsic::amdgcn_s_sendmsghalt: {
3060 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
3061 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
3062 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
3063 SDValue Glue = Chain.getValue(1);
3064 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
3065 Op.getOperand(2), Glue);
3066 }
3067 case AMDGPUIntrinsic::SI_tbuffer_store: {
3068 SDValue Ops[] = {
3069 Chain,
3070 Op.getOperand(2),
3071 Op.getOperand(3),
3072 Op.getOperand(4),
3073 Op.getOperand(5),
3074 Op.getOperand(6),
3075 Op.getOperand(7),
3076 Op.getOperand(8),
3077 Op.getOperand(9),
3078 Op.getOperand(10),
3079 Op.getOperand(11),
3080 Op.getOperand(12),
3081 Op.getOperand(13),
3082 Op.getOperand(14)
3083 };
3084
3085 EVT VT = Op.getOperand(3).getValueType();
3086
3087 MachineMemOperand *MMO = MF.getMachineMemOperand(
3088 MachinePointerInfo(),
3089 MachineMemOperand::MOStore,
3090 VT.getStoreSize(), 4);
3091 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
3092 Op->getVTList(), Ops, VT, MMO);
3093 }
3094 case AMDGPUIntrinsic::AMDGPU_kill: {
3095 SDValue Src = Op.getOperand(2);
3096 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
3097 if (!K->isNegative())
3098 return Chain;
3099
3100 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
3101 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
3102 }
3103
3104 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
3105 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
3106 }
3107 case AMDGPUIntrinsic::SI_export: { // Legacy intrinsic.
3108 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(2));
3109 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(3));
3110 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(4));
3111 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(5));
3112 const ConstantSDNode *Compr = cast<ConstantSDNode>(Op.getOperand(6));
3113
3114 const SDValue Ops[] = {
3115 Chain,
3116 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8),
3117 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),
3118 Op.getOperand(7), // src0
3119 Op.getOperand(8), // src1
3120 Op.getOperand(9), // src2
3121 Op.getOperand(10), // src3
3122 DAG.getTargetConstant(Compr->getZExtValue(), DL, MVT::i1),
3123 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3124 };
3125
3126 unsigned Opc = Done->isNullValue() ?
3127 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3128 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3129 }
3130 default:
3131 return SDValue();
3132 }
3133}
3134
3135SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
3136 SDLoc DL(Op);
3137 LoadSDNode *Load = cast<LoadSDNode>(Op);
3138 ISD::LoadExtType ExtType = Load->getExtensionType();
3139 EVT MemVT = Load->getMemoryVT();
3140
3141 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
3142 // FIXME: Copied from PPC
3143 // First, load into 32 bits, then truncate to 1 bit.
3144
3145 SDValue Chain = Load->getChain();
3146 SDValue BasePtr = Load->getBasePtr();
3147 MachineMemOperand *MMO = Load->getMemOperand();
3148
3149 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
3150
3151 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
3152 BasePtr, RealMemVT, MMO);
3153
3154 SDValue Ops[] = {
3155 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
3156 NewLD.getValue(1)
3157 };
3158
3159 return DAG.getMergeValues(Ops, DL);
3160 }
3161
3162 if (!MemVT.isVector())
3163 return SDValue();
3164
3165 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&((Op.getValueType().getVectorElementType() == MVT::i32 &&
"Custom lowering for non-i32 vectors hasn't been implemented."
) ? static_cast<void> (0) : __assert_fail ("Op.getValueType().getVectorElementType() == MVT::i32 && \"Custom lowering for non-i32 vectors hasn't been implemented.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3166, __PRETTY_FUNCTION__))
3166 "Custom lowering for non-i32 vectors hasn't been implemented.")((Op.getValueType().getVectorElementType() == MVT::i32 &&
"Custom lowering for non-i32 vectors hasn't been implemented."
) ? static_cast<void> (0) : __assert_fail ("Op.getValueType().getVectorElementType() == MVT::i32 && \"Custom lowering for non-i32 vectors hasn't been implemented.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3166, __PRETTY_FUNCTION__))
;
3167
3168 unsigned AS = Load->getAddressSpace();
3169 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
3170 AS, Load->getAlignment())) {
3171 SDValue Ops[2];
3172 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
3173 return DAG.getMergeValues(Ops, DL);
3174 }
3175
3176 MachineFunction &MF = DAG.getMachineFunction();
3177 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3178 // If there is a possibilty that flat instruction access scratch memory
3179 // then we need to use the same legalization rules we use for private.
3180 if (AS == AMDGPUAS::FLAT_ADDRESS)
3181 AS = MFI->hasFlatScratchInit() ?
3182 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
3183
3184 unsigned NumElements = MemVT.getVectorNumElements();
3185 switch (AS) {
3186 case AMDGPUAS::CONSTANT_ADDRESS:
3187 if (isMemOpUniform(Load))
3188 return SDValue();
3189 // Non-uniform loads will be selected to MUBUF instructions, so they
3190 // have the same legalization requirements as global and private
3191 // loads.
3192 //
3193 LLVM_FALLTHROUGH[[clang::fallthrough]];
3194 case AMDGPUAS::GLOBAL_ADDRESS:
3195 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
3196 isMemOpHasNoClobberedMemOperand(Load))
3197 return SDValue();
3198 // Non-uniform loads will be selected to MUBUF instructions, so they
3199 // have the same legalization requirements as global and private
3200 // loads.
3201 //
3202 LLVM_FALLTHROUGH[[clang::fallthrough]];
3203 case AMDGPUAS::FLAT_ADDRESS:
3204 if (NumElements > 4)
3205 return SplitVectorLoad(Op, DAG);
3206 // v4 loads are supported for private and global memory.
3207 return SDValue();
3208 case AMDGPUAS::PRIVATE_ADDRESS:
3209 // Depending on the setting of the private_element_size field in the
3210 // resource descriptor, we can only make private accesses up to a certain
3211 // size.
3212 switch (Subtarget->getMaxPrivateElementSize()) {
3213 case 4:
3214 return scalarizeVectorLoad(Load, DAG);
3215 case 8:
3216 if (NumElements > 2)
3217 return SplitVectorLoad(Op, DAG);
3218 return SDValue();
3219 case 16:
3220 // Same as global/flat
3221 if (NumElements > 4)
3222 return SplitVectorLoad(Op, DAG);
3223 return SDValue();
3224 default:
3225 llvm_unreachable("unsupported private_element_size")::llvm::llvm_unreachable_internal("unsupported private_element_size"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3225)
;
3226 }
3227 case AMDGPUAS::LOCAL_ADDRESS:
3228 if (NumElements > 2)
3229 return SplitVectorLoad(Op, DAG);
3230
3231 if (NumElements == 2)
3232 return SDValue();
3233
3234 // If properly aligned, if we split we might be able to use ds_read_b64.
3235 return SplitVectorLoad(Op, DAG);
3236 default:
3237 return SDValue();
3238 }
3239}
3240
3241SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3242 if (Op.getValueType() != MVT::i64)
3243 return SDValue();
3244
3245 SDLoc DL(Op);
3246 SDValue Cond = Op.getOperand(0);
3247
3248 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
3249 SDValue One = DAG.getConstant(1, DL, MVT::i32);
3250
3251 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
3252 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
3253
3254 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
3255 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
3256
3257 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
3258
3259 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
3260 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
3261
3262 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
3263
3264 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
3265 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
3266}
3267
3268// Catch division cases where we can use shortcuts with rcp and rsq
3269// instructions.
3270SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
3271 SelectionDAG &DAG) const {
3272 SDLoc SL(Op);
3273 SDValue LHS = Op.getOperand(0);
3274 SDValue RHS = Op.getOperand(1);
3275 EVT VT = Op.getValueType();
3276 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
3277
3278 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
3279 if (Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
3280 VT == MVT::f16) {
3281 if (CLHS->isExactlyValue(1.0)) {
3282 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
3283 // the CI documentation has a worst case error of 1 ulp.
3284 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
3285 // use it as long as we aren't trying to use denormals.
3286 //
3287 // v_rcp_f16 and v_rsq_f16 DO support denormals.
3288
3289 // 1.0 / sqrt(x) -> rsq(x)
3290
3291 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
3292 // error seems really high at 2^29 ULP.
3293 if (RHS.getOpcode() == ISD::FSQRT)
3294 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
3295
3296 // 1.0 / x -> rcp(x)
3297 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3298 }
3299
3300 // Same as for 1.0, but expand the sign out of the constant.
3301 if (CLHS->isExactlyValue(-1.0)) {
3302 // -1.0 / x -> rcp (fneg x)
3303 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3304 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
3305 }
3306 }
3307 }
3308
3309 const SDNodeFlags *Flags = Op->getFlags();
3310
3311 if (Unsafe || Flags->hasAllowReciprocal()) {
3312 // Turn into multiply by the reciprocal.
3313 // x / y -> x * (1.0 / y)
3314 SDNodeFlags Flags;
3315 Flags.setUnsafeAlgebra(true);
3316 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3317 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
3318 }
3319
3320 return SDValue();
3321}
3322
3323static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3324 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
3325 if (GlueChain->getNumValues() <= 1) {
3326 return DAG.getNode(Opcode, SL, VT, A, B);
3327 }
3328
3329 assert(GlueChain->getNumValues() == 3)((GlueChain->getNumValues() == 3) ? static_cast<void>
(0) : __assert_fail ("GlueChain->getNumValues() == 3", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3329, __PRETTY_FUNCTION__))
;
3330
3331 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3332 switch (Opcode) {
3333 default: llvm_unreachable("no chain equivalent for opcode")::llvm::llvm_unreachable_internal("no chain equivalent for opcode"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3333)
;
3334 case ISD::FMUL:
3335 Opcode = AMDGPUISD::FMUL_W_CHAIN;
3336 break;
3337 }
3338
3339 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
3340 GlueChain.getValue(2));
3341}
3342
3343static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3344 EVT VT, SDValue A, SDValue B, SDValue C,
3345 SDValue GlueChain) {
3346 if (GlueChain->getNumValues() <= 1) {
3347 return DAG.getNode(Opcode, SL, VT, A, B, C);
3348 }
3349
3350 assert(GlueChain->getNumValues() == 3)((GlueChain->getNumValues() == 3) ? static_cast<void>
(0) : __assert_fail ("GlueChain->getNumValues() == 3", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3350, __PRETTY_FUNCTION__))
;
3351
3352 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3353 switch (Opcode) {
3354 default: llvm_unreachable("no chain equivalent for opcode")::llvm::llvm_unreachable_internal("no chain equivalent for opcode"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3354)
;
3355 case ISD::FMA:
3356 Opcode = AMDGPUISD::FMA_W_CHAIN;
3357 break;
3358 }
3359
3360 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
3361 GlueChain.getValue(2));
3362}
3363
3364SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
3365 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3366 return FastLowered;
3367
3368 SDLoc SL(Op);
3369 SDValue Src0 = Op.getOperand(0);
3370 SDValue Src1 = Op.getOperand(1);
3371
3372 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3373 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3374
3375 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
3376 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
3377
3378 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
3379 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
3380
3381 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
3382}
3383
3384// Faster 2.5 ULP division that does not support denormals.
3385SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
3386 SDLoc SL(Op);
3387 SDValue LHS = Op.getOperand(1);
3388 SDValue RHS = Op.getOperand(2);
3389
3390 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
3391
3392 const APFloat K0Val(BitsToFloat(0x6f800000));
3393 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
3394
3395 const APFloat K1Val(BitsToFloat(0x2f800000));
3396 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
3397
3398 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3399
3400 EVT SetCCVT =
3401 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
3402
3403 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
3404
3405 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
3406
3407 // TODO: Should this propagate fast-math-flags?
3408 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
3409
3410 // rcp does not support denormals.
3411 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
3412
3413 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
3414
3415 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
3416}
3417
3418SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
3419 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3420 return FastLowered;
3421
3422 SDLoc SL(Op);
3423 SDValue LHS = Op.getOperand(0);
3424 SDValue RHS = Op.getOperand(1);
3425
3426 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3427
3428 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
3429
3430 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3431 RHS, RHS, LHS);
3432 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3433 LHS, RHS, LHS);
3434
3435 // Denominator is scaled to not be denormal, so using rcp is ok.
3436 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
3437 DenominatorScaled);
3438 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
3439 DenominatorScaled);
3440
3441 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
3442 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
3443 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
3444
3445 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
3446
3447 if (!Subtarget->hasFP32Denormals()) {
3448 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
3449 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE3,
3450 SL, MVT::i32);
3451 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
3452 DAG.getEntryNode(),
3453 EnableDenormValue, BitField);
3454 SDValue Ops[3] = {
3455 NegDivScale0,
3456 EnableDenorm.getValue(0),
3457 EnableDenorm.getValue(1)
3458 };
3459
3460 NegDivScale0 = DAG.getMergeValues(Ops, SL);
3461 }
3462
3463 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
3464 ApproxRcp, One, NegDivScale0);
3465
3466 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
3467 ApproxRcp, Fma0);
3468
3469 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
3470 Fma1, Fma1);
3471
3472 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
3473 NumeratorScaled, Mul);
3474
3475 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
3476
3477 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
3478 NumeratorScaled, Fma3);
3479
3480 if (!Subtarget->hasFP32Denormals()) {
3481 const SDValue DisableDenormValue =
3482 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT0, SL, MVT::i32);
3483 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
3484 Fma4.getValue(1),
3485 DisableDenormValue,
3486 BitField,
3487 Fma4.getValue(2));
3488
3489 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
3490 DisableDenorm, DAG.getRoot());
3491 DAG.setRoot(OutputChain);
3492 }
3493
3494 SDValue Scale = NumeratorScaled.getValue(1);
3495 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
3496 Fma4, Fma1, Fma3, Scale);
3497
3498 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
3499}
3500
3501SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
3502 if (DAG.getTarget().Options.UnsafeFPMath)
3503 return lowerFastUnsafeFDIV(Op, DAG);
3504
3505 SDLoc SL(Op);
3506 SDValue X = Op.getOperand(0);
3507 SDValue Y = Op.getOperand(1);
3508
3509 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
3510
3511 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
3512
3513 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
3514
3515 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
3516
3517 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
3518
3519 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
3520
3521 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
3522
3523 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
3524
3525 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
3526
3527 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
3528 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
3529
3530 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
3531 NegDivScale0, Mul, DivScale1);
3532
3533 SDValue Scale;
3534
3535 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
3536 // Workaround a hardware bug on SI where the condition output from div_scale
3537 // is not usable.
3538
3539 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
3540
3541 // Figure out if the scale to use for div_fmas.
3542 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
3543 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
3544 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
3545 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
3546
3547 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
3548 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
3549
3550 SDValue Scale0Hi
3551 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
3552 SDValue Scale1Hi
3553 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
3554
3555 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
3556 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
3557 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
3558 } else {
3559 Scale = DivScale1.getValue(1);
3560 }
3561
3562 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
3563 Fma4, Fma3, Mul, Scale);
3564
3565 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
3566}
3567
3568SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
3569 EVT VT = Op.getValueType();
3570
3571 if (VT == MVT::f32)
3572 return LowerFDIV32(Op, DAG);
3573
3574 if (VT == MVT::f64)
3575 return LowerFDIV64(Op, DAG);
3576
3577 if (VT == MVT::f16)
3578 return LowerFDIV16(Op, DAG);
3579
3580 llvm_unreachable("Unexpected type for fdiv")::llvm::llvm_unreachable_internal("Unexpected type for fdiv",
"/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3580)
;
3581}
3582
3583SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3584 SDLoc DL(Op);
3585 StoreSDNode *Store = cast<StoreSDNode>(Op);
3586 EVT VT = Store->getMemoryVT();
3587
3588 if (VT == MVT::i1) {
3589 return DAG.getTruncStore(Store->getChain(), DL,
3590 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
3591 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
3592 }
3593
3594 assert(VT.isVector() &&((VT.isVector() && Store->getValue().getValueType(
).getScalarType() == MVT::i32) ? static_cast<void> (0) :
__assert_fail ("VT.isVector() && Store->getValue().getValueType().getScalarType() == MVT::i32"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3595, __PRETTY_FUNCTION__))
3595 Store->getValue().getValueType().getScalarType() == MVT::i32)((VT.isVector() && Store->getValue().getValueType(
).getScalarType() == MVT::i32) ? static_cast<void> (0) :
__assert_fail ("VT.isVector() && Store->getValue().getValueType().getScalarType() == MVT::i32"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3595, __PRETTY_FUNCTION__))
;
3596
3597 unsigned AS = Store->getAddressSpace();
3598 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
3599 AS, Store->getAlignment())) {
3600 return expandUnalignedStore(Store, DAG);
3601 }
3602
3603 MachineFunction &MF = DAG.getMachineFunction();
3604 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3605 // If there is a possibilty that flat instruction access scratch memory
3606 // then we need to use the same legalization rules we use for private.
3607 if (AS == AMDGPUAS::FLAT_ADDRESS)
3608 AS = MFI->hasFlatScratchInit() ?
3609 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
3610
3611 unsigned NumElements = VT.getVectorNumElements();
3612 switch (AS) {
3613 case AMDGPUAS::GLOBAL_ADDRESS:
3614 case AMDGPUAS::FLAT_ADDRESS:
3615 if (NumElements > 4)
3616 return SplitVectorStore(Op, DAG);
3617 return SDValue();
3618 case AMDGPUAS::PRIVATE_ADDRESS: {
3619 switch (Subtarget->getMaxPrivateElementSize()) {
3620 case 4:
3621 return scalarizeVectorStore(Store, DAG);
3622 case 8:
3623 if (NumElements > 2)
3624 return SplitVectorStore(Op, DAG);
3625 return SDValue();
3626 case 16:
3627 if (NumElements > 4)
3628 return SplitVectorStore(Op, DAG);
3629 return SDValue();
3630 default:
3631 llvm_unreachable("unsupported private_element_size")::llvm::llvm_unreachable_internal("unsupported private_element_size"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3631)
;
3632 }
3633 }
3634 case AMDGPUAS::LOCAL_ADDRESS: {
3635 if (NumElements > 2)
3636 return SplitVectorStore(Op, DAG);
3637
3638 if (NumElements == 2)
3639 return Op;
3640
3641 // If properly aligned, if we split we might be able to use ds_write_b64.
3642 return SplitVectorStore(Op, DAG);
3643 }
3644 default:
3645 llvm_unreachable("unhandled address space")::llvm::llvm_unreachable_internal("unhandled address space", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3645)
;
3646 }
3647}
3648
3649SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
3650 SDLoc DL(Op);
3651 EVT VT = Op.getValueType();
3652 SDValue Arg = Op.getOperand(0);
3653 // TODO: Should this propagate fast-math-flags?
3654 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
3655 DAG.getNode(ISD::FMUL, DL, VT, Arg,
3656 DAG.getConstantFP(0.5/M_PI3.14159265358979323846, DL,
3657 VT)));
3658
3659 switch (Op.getOpcode()) {
3660 case ISD::FCOS:
3661 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
3662 case ISD::FSIN:
3663 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
3664 default:
3665 llvm_unreachable("Wrong trig opcode")::llvm::llvm_unreachable_internal("Wrong trig opcode", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3665)
;
3666 }
3667}
3668
3669SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
3670 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
3671 assert(AtomicNode->isCompareAndSwap())((AtomicNode->isCompareAndSwap()) ? static_cast<void>
(0) : __assert_fail ("AtomicNode->isCompareAndSwap()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3671, __PRETTY_FUNCTION__))
;
3672 unsigned AS = AtomicNode->getAddressSpace();
3673
3674 // No custom lowering required for local address space
3675 if (!isFlatGlobalAddrSpace(AS))
3676 return Op;
3677
3678 // Non-local address space requires custom lowering for atomic compare
3679 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
3680 SDLoc DL(Op);
3681 SDValue ChainIn = Op.getOperand(0);
3682 SDValue Addr = Op.getOperand(1);
3683 SDValue Old = Op.getOperand(2);
3684 SDValue New = Op.getOperand(3);
3685 EVT VT = Op.getValueType();
3686 MVT SimpleVT = VT.getSimpleVT();
3687 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
3688
3689 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
3690 SDValue Ops[] = { ChainIn, Addr, NewOld };
3691
3692 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
3693 Ops, VT, AtomicNode->getMemOperand());
3694}
3695
3696//===----------------------------------------------------------------------===//
3697// Custom DAG optimizations
3698//===----------------------------------------------------------------------===//
3699
3700SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
3701 DAGCombinerInfo &DCI) const {
3702 EVT VT = N->getValueType(0);
3703 EVT ScalarVT = VT.getScalarType();
3704 if (ScalarVT != MVT::f32)
3705 return SDValue();
3706
3707 SelectionDAG &DAG = DCI.DAG;
3708 SDLoc DL(N);
3709
3710 SDValue Src = N->getOperand(0);
3711 EVT SrcVT = Src.getValueType();
3712
3713 // TODO: We could try to match extracting the higher bytes, which would be
3714 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
3715 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
3716 // about in practice.
3717 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
3718 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
3719 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
3720 DCI.AddToWorklist(Cvt.getNode());
3721 return Cvt;
3722 }
3723 }
3724
3725 return SDValue();
3726}
3727
3728/// \brief Return true if the given offset Size in bytes can be folded into
3729/// the immediate offsets of a memory instruction for the given address space.
3730static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
3731 const SISubtarget &STI) {
3732 switch (AS) {
3733 case AMDGPUAS::GLOBAL_ADDRESS:
3734 // MUBUF instructions a 12-bit offset in bytes.
3735 return isUInt<12>(OffsetSize);
3736 case AMDGPUAS::CONSTANT_ADDRESS:
3737 // SMRD instructions have an 8-bit offset in dwords on SI and
3738 // a 20-bit offset in bytes on VI.
3739 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3740 return isUInt<20>(OffsetSize);
3741 else
3742 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
3743 case AMDGPUAS::LOCAL_ADDRESS:
3744 case AMDGPUAS::REGION_ADDRESS:
3745 // The single offset versions have a 16-bit offset in bytes.
3746 return isUInt<16>(OffsetSize);
3747 case AMDGPUAS::PRIVATE_ADDRESS:
3748 // Indirect register addressing does not use any offsets.
3749 default:
3750 return false;
3751 }
3752}
3753
3754// (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
3755
3756// This is a variant of
3757// (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
3758//
3759// The normal DAG combiner will do this, but only if the add has one use since
3760// that would increase the number of instructions.
3761//
3762// This prevents us from seeing a constant offset that can be folded into a
3763// memory instruction's addressing mode. If we know the resulting add offset of
3764// a pointer can be folded into an addressing offset, we can replace the pointer
3765// operand with the add of new constant offset. This eliminates one of the uses,
3766// and may allow the remaining use to also be simplified.
3767//
3768SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
3769 unsigned AddrSpace,
3770 DAGCombinerInfo &DCI) const {
3771 SDValue N0 = N->getOperand(0);
3772 SDValue N1 = N->getOperand(1);
3773
3774 if (N0.getOpcode() != ISD::ADD)
3775 return SDValue();
3776
3777 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
3778 if (!CN1)
3779 return SDValue();
3780
3781 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3782 if (!CAdd)
3783 return SDValue();
3784
3785 // If the resulting offset is too large, we can't fold it into the addressing
3786 // mode offset.
3787 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
3788 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
3789 return SDValue();
3790
3791 SelectionDAG &DAG = DCI.DAG;
3792 SDLoc SL(N);
3793 EVT VT = N->getValueType(0);
3794
3795 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
3796 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
3797
3798 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
3799}
3800
3801SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
3802 DAGCombinerInfo &DCI) const {
3803 SDValue Ptr = N->getBasePtr();
3804 SelectionDAG &DAG = DCI.DAG;
3805 SDLoc SL(N);
3806
3807 // TODO: We could also do this for multiplies.
3808 unsigned AS = N->getAddressSpace();
3809 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
3810 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
3811 if (NewPtr) {
3812 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
3813
3814 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
3815 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
3816 }
3817 }
3818
3819 return SDValue();
3820}
3821
3822static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
3823 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
3824 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
3825 (Opc == ISD::XOR && Val == 0);
3826}
3827
3828// Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
3829// will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
3830// integer combine opportunities since most 64-bit operations are decomposed
3831// this way. TODO: We won't want this for SALU especially if it is an inline
3832// immediate.
3833SDValue SITargetLowering::splitBinaryBitConstantOp(
3834 DAGCombinerInfo &DCI,
3835 const SDLoc &SL,
3836 unsigned Opc, SDValue LHS,
3837 const ConstantSDNode *CRHS) const {
3838 uint64_t Val = CRHS->getZExtValue();
3839 uint32_t ValLo = Lo_32(Val);
3840 uint32_t ValHi = Hi_32(Val);
3841 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3842
3843 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
3844 bitOpWithConstantIsReducible(Opc, ValHi)) ||
3845 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
3846 // If we need to materialize a 64-bit immediate, it will be split up later
3847 // anyway. Avoid creating the harder to understand 64-bit immediate
3848 // materialization.
3849 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
3850 }
3851
3852 return SDValue();
3853}
3854
3855SDValue SITargetLowering::performAndCombine(SDNode *N,
3856 DAGCombinerInfo &DCI) const {
3857 if (DCI.isBeforeLegalize())
3858 return SDValue();
3859
3860 SelectionDAG &DAG = DCI.DAG;
3861 EVT VT = N->getValueType(0);
3862 SDValue LHS = N->getOperand(0);
3863 SDValue RHS = N->getOperand(1);
3864
3865
3866 if (VT == MVT::i64) {
3867 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
3868 if (CRHS) {
3869 if (SDValue Split
3870 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
3871 return Split;
3872 }
3873 }
3874
3875 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
3876 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
3877 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
3878 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
3879 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
3880
3881 SDValue X = LHS.getOperand(0);
3882 SDValue Y = RHS.getOperand(0);
3883 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
3884 return SDValue();
3885
3886 if (LCC == ISD::SETO) {
3887 if (X != LHS.getOperand(1))
3888 return SDValue();
3889
3890 if (RCC == ISD::SETUNE) {
3891 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
3892 if (!C1 || !C1->isInfinity() || C1->isNegative())
3893 return SDValue();
3894
3895 const uint32_t Mask = SIInstrFlags::N_NORMAL |
3896 SIInstrFlags::N_SUBNORMAL |
3897 SIInstrFlags::N_ZERO |
3898 SIInstrFlags::P_ZERO |
3899 SIInstrFlags::P_SUBNORMAL |
3900 SIInstrFlags::P_NORMAL;
3901
3902 static_assert(((~(SIInstrFlags::S_NAN |
3903 SIInstrFlags::Q_NAN |
3904 SIInstrFlags::N_INFINITY |
3905 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
3906 "mask not equal");
3907
3908 SDLoc DL(N);
3909 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
3910 X, DAG.getConstant(Mask, DL, MVT::i32));
3911 }
3912 }
3913 }
3914
3915 return SDValue();
3916}
3917
3918SDValue SITargetLowering::performOrCombine(SDNode *N,
3919 DAGCombinerInfo &DCI) const {
3920 SelectionDAG &DAG = DCI.DAG;
3921 SDValue LHS = N->getOperand(0);
3922 SDValue RHS = N->getOperand(1);
3923
3924 EVT VT = N->getValueType(0);
3925 if (VT == MVT::i1) {
3926 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
3927 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
3928 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
3929 SDValue Src = LHS.getOperand(0);
3930 if (Src != RHS.getOperand(0))
3931 return SDValue();
3932
3933 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
3934 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
3935 if (!CLHS || !CRHS)
3936 return SDValue();
3937
3938 // Only 10 bits are used.
3939 static const uint32_t MaxMask = 0x3ff;
3940
3941 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
3942 SDLoc DL(N);
3943 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
3944 Src, DAG.getConstant(NewMask, DL, MVT::i32));
3945 }
3946
3947 return SDValue();
3948 }
3949
3950 if (VT != MVT::i64)
3951 return SDValue();
3952
3953 // TODO: This could be a generic combine with a predicate for extracting the
3954 // high half of an integer being free.
3955
3956 // (or i64:x, (zero_extend i32:y)) ->
3957 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
3958 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
3959 RHS.getOpcode() != ISD::ZERO_EXTEND)
3960 std::swap(LHS, RHS);
3961
3962 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
3963 SDValue ExtSrc = RHS.getOperand(0);
3964 EVT SrcVT = ExtSrc.getValueType();
3965 if (SrcVT == MVT::i32) {
3966 SDLoc SL(N);
3967 SDValue LowLHS, HiBits;
3968 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
3969 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
3970
3971 DCI.AddToWorklist(LowOr.getNode());
3972 DCI.AddToWorklist(HiBits.getNode());
3973
3974 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3975 LowOr, HiBits);
3976 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3977 }
3978 }
3979
3980 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3981 if (CRHS) {
3982 if (SDValue Split
3983 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
3984 return Split;
3985 }
3986
3987 return SDValue();
3988}
3989
3990SDValue SITargetLowering::performXorCombine(SDNode *N,
3991 DAGCombinerInfo &DCI) const {
3992 EVT VT = N->getValueType(0);
3993 if (VT != MVT::i64)
3994 return SDValue();
3995
3996 SDValue LHS = N->getOperand(0);
3997 SDValue RHS = N->getOperand(1);
3998
3999 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4000 if (CRHS) {
4001 if (SDValue Split
4002 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
4003 return Split;
4004 }
4005
4006 return SDValue();
4007}
4008
4009SDValue SITargetLowering::performClassCombine(SDNode *N,
4010 DAGCombinerInfo &DCI) const {
4011 SelectionDAG &DAG = DCI.DAG;
4012 SDValue Mask = N->getOperand(1);
4013
4014 // fp_class x, 0 -> false
4015 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
4016 if (CMask->isNullValue())
4017 return DAG.getConstant(0, SDLoc(N), MVT::i1);
4018 }
4019
4020 if (N->getOperand(0).isUndef())
4021 return DAG.getUNDEF(MVT::i1);
4022
4023 return SDValue();
4024}
4025
4026// Constant fold canonicalize.
4027SDValue SITargetLowering::performFCanonicalizeCombine(
4028 SDNode *N,
4029 DAGCombinerInfo &DCI) const {
4030 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
4031 if (!CFP)
4032 return SDValue();
4033
4034 SelectionDAG &DAG = DCI.DAG;
4035 const APFloat &C = CFP->getValueAPF();
4036
4037 // Flush denormals to 0 if not enabled.
4038 if (C.isDenormal()) {
4039 EVT VT = N->getValueType(0);
4040 EVT SVT = VT.getScalarType();
4041 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
4042 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4043
4044 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
4045 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4046
4047 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
4048 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4049 }
4050
4051 if (C.isNaN()) {
4052 EVT VT = N->getValueType(0);
4053 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
4054 if (C.isSignaling()) {
4055 // Quiet a signaling NaN.
4056 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4057 }
4058
4059 // Make sure it is the canonical NaN bitpattern.
4060 //
4061 // TODO: Can we use -1 as the canonical NaN value since it's an inline
4062 // immediate?
4063 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
4064 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4065 }
4066
4067 return N->getOperand(0);
4068}
4069
4070static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
4071 switch (Opc) {
4072 case ISD::FMAXNUM:
4073 return AMDGPUISD::FMAX3;
4074 case ISD::SMAX:
4075 return AMDGPUISD::SMAX3;
4076 case ISD::UMAX:
4077 return AMDGPUISD::UMAX3;
4078 case ISD::FMINNUM:
4079 return AMDGPUISD::FMIN3;
4080 case ISD::SMIN:
4081 return AMDGPUISD::SMIN3;
4082 case ISD::UMIN:
4083 return AMDGPUISD::UMIN3;
4084 default:
4085 llvm_unreachable("Not a min/max opcode")::llvm::llvm_unreachable_internal("Not a min/max opcode", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4085)
;
4086 }
4087}
4088
4089SDValue SITargetLowering::performIntMed3ImmCombine(
4090 SelectionDAG &DAG, const SDLoc &SL,
4091 SDValue Op0, SDValue Op1, bool Signed) const {
4092 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
4093 if (!K1)
4094 return SDValue();
4095
4096 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
4097 if (!K0)
4098 return SDValue();
4099
4100 if (Signed) {
4101 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
4102 return SDValue();
4103 } else {
4104 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
4105 return SDValue();
4106 }
4107
4108 EVT VT = K0->getValueType(0);
4109 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
4110 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
4111 return DAG.getNode(Med3Opc, SL, VT,
4112 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
4113 }
4114
4115 // If there isn't a 16-bit med3 operation, convert to 32-bit.
4116 MVT NVT = MVT::i32;
4117 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4118
4119 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
4120 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
4121 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
4122
4123 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
4124 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
4125}
4126
4127static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
4128 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
4129 return true;
4130
4131 return DAG.isKnownNeverNaN(Op);
4132}
4133
4134SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
4135 const SDLoc &SL,
4136 SDValue Op0,
4137 SDValue Op1) const {
4138 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
4139 if (!K1)
4140 return SDValue();
4141
4142 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
4143 if (!K0)
4144 return SDValue();
4145
4146 // Ordered >= (although NaN inputs should have folded away by now).
4147 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
4148 if (Cmp == APFloat::cmpGreaterThan)
4149 return SDValue();
4150
4151 // TODO: Check IEEE bit enabled?
4152 EVT VT = K0->getValueType(0);
4153 if (Subtarget->enableDX10Clamp()) {
4154 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
4155 // hardware fmed3 behavior converting to a min.
4156 // FIXME: Should this be allowing -0.0?
4157 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
4158 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
4159 }
4160
4161 // med3 for f16 is only available on gfx9+.
4162 if (VT == MVT::f64 || (VT == MVT::f16 && !Subtarget->hasMed3_16()))
4163 return SDValue();
4164
4165 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
4166 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
4167 // give the other result, which is different from med3 with a NaN input.
4168 SDValue Var = Op0.getOperand(0);
4169 if (!isKnownNeverSNan(DAG, Var))
4170 return SDValue();
4171
4172 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
4173 Var, SDValue(K0, 0), SDValue(K1, 0));
4174}
4175
4176SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
4177 DAGCombinerInfo &DCI) const {
4178 SelectionDAG &DAG = DCI.DAG;
4179
4180 EVT VT = N->getValueType(0);
4181 unsigned Opc = N->getOpcode();
4182 SDValue Op0 = N->getOperand(0);
4183 SDValue Op1 = N->getOperand(1);
4184
4185 // Only do this if the inner op has one use since this will just increases
4186 // register pressure for no benefit.
4187
4188
4189 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
4190 VT != MVT::f64) {
4191 // max(max(a, b), c) -> max3(a, b, c)
4192 // min(min(a, b), c) -> min3(a, b, c)
4193 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
4194 SDLoc DL(N);
4195 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4196 DL,
4197 N->getValueType(0),
4198 Op0.getOperand(0),
4199 Op0.getOperand(1),
4200 Op1);
4201 }
4202
4203 // Try commuted.
4204 // max(a, max(b, c)) -> max3(a, b, c)
4205 // min(a, min(b, c)) -> min3(a, b, c)
4206 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
4207 SDLoc DL(N);
4208 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4209 DL,
4210 N->getValueType(0),
4211 Op0,
4212 Op1.getOperand(0),
4213 Op1.getOperand(1));
4214 }
4215 }
4216
4217 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
4218 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
4219 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
4220 return Med3;
4221 }
4222
4223 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4224 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
4225 return Med3;
4226 }
4227
4228 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
4229 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
4230 (Opc == AMDGPUISD::FMIN_LEGACY &&
4231 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
4232 (VT == MVT::f32 || VT == MVT::f64 ||
4233 (VT == MVT::f16 && Subtarget->has16BitInsts())) &&
4234 Op0.hasOneUse()) {
4235 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
4236 return Res;
4237 }
4238
4239 return SDValue();
4240}
4241
4242static bool isClampZeroToOne(SDValue A, SDValue B) {
4243 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
4244 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
4245 // FIXME: Should this be allowing -0.0?
4246 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
4247 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
4248 }
4249 }
4250
4251 return false;
4252}
4253
4254// FIXME: Should only worry about snans for version with chain.
4255SDValue SITargetLowering::performFMed3Combine(SDNode *N,
4256 DAGCombinerInfo &DCI) const {
4257 EVT VT = N->getValueType(0);
4258 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
4259 // NaNs. With a NaN input, the order of the operands may change the result.
4260
4261 SelectionDAG &DAG = DCI.DAG;
4262 SDLoc SL(N);
4263
4264 SDValue Src0 = N->getOperand(0);
4265 SDValue Src1 = N->getOperand(1);
4266 SDValue Src2 = N->getOperand(2);
4267
4268 if (isClampZeroToOne(Src0, Src1)) {
4269 // const_a, const_b, x -> clamp is safe in all cases including signaling
4270 // nans.
4271 // FIXME: Should this be allowing -0.0?
4272 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
4273 }
4274
4275 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
4276 // handling no dx10-clamp?
4277 if (Subtarget->enableDX10Clamp()) {
4278 // If NaNs is clamped to 0, we are free to reorder the inputs.
4279
4280 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4281 std::swap(Src0, Src1);
4282
4283 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
4284 std::swap(Src1, Src2);
4285
4286 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4287 std::swap(Src0, Src1);
4288
4289 if (isClampZeroToOne(Src1, Src2))
4290 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
4291 }
4292
4293 return SDValue();
4294}
4295
4296SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
4297 DAGCombinerInfo &DCI) const {
4298 SDValue Src0 = N->getOperand(0);
4299 SDValue Src1 = N->getOperand(1);
4300 if (Src0.isUndef() && Src1.isUndef())
4301 return DCI.DAG.getUNDEF(N->getValueType(0));
4302 return SDValue();
4303}
4304
4305unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
4306 const SDNode *N0,
4307 const SDNode *N1) const {
4308 EVT VT = N0->getValueType(0);
4309
4310 // Only do this if we are not trying to support denormals. v_mad_f32 does not
4311 // support denormals ever.
4312 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
4313 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
4314 return ISD::FMAD;
4315
4316 const TargetOptions &Options = DAG.getTarget().Options;
4317 if ((Options.AllowFPOpFusion == FPOpFusion::Fast ||
4318 Options.UnsafeFPMath ||
4319 (cast<BinaryWithFlagsSDNode>(N0)->Flags.hasUnsafeAlgebra() &&
4320 cast<BinaryWithFlagsSDNode>(N1)->Flags.hasUnsafeAlgebra())) &&
4321 isFMAFasterThanFMulAndFAdd(VT)) {
4322 return ISD::FMA;
4323 }
4324
4325 return 0;
4326}
4327
4328SDValue SITargetLowering::performFAddCombine(SDNode *N,
4329 DAGCombinerInfo &DCI) const {
4330 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4331 return SDValue();
4332
4333 SelectionDAG &DAG = DCI.DAG;
4334 EVT VT = N->getValueType(0);
4335
4336 SDLoc SL(N);
4337 SDValue LHS = N->getOperand(0);
4338 SDValue RHS = N->getOperand(1);
4339
4340 // These should really be instruction patterns, but writing patterns with
4341 // source modiifiers is a pain.
4342
4343 // fadd (fadd (a, a), b) -> mad 2.0, a, b
4344 if (LHS.getOpcode() == ISD::FADD) {
4345 SDValue A = LHS.getOperand(0);
4346 if (A == LHS.getOperand(1)) {
4347 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4348 if (FusedOp != 0) {
4349 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4350 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
4351 }
4352 }
4353 }
4354
4355 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
4356 if (RHS.getOpcode() == ISD::FADD) {
4357 SDValue A = RHS.getOperand(0);
4358 if (A == RHS.getOperand(1)) {
4359 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4360 if (FusedOp != 0) {
4361 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4362 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
4363 }
4364 }
4365 }
4366
4367 return SDValue();
4368}
4369
4370SDValue SITargetLowering::performFSubCombine(SDNode *N,
4371 DAGCombinerInfo &DCI) const {
4372 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4373 return SDValue();
4374
4375 SelectionDAG &DAG = DCI.DAG;
4376 SDLoc SL(N);
4377 EVT VT = N->getValueType(0);
4378 assert(!VT.isVector())((!VT.isVector()) ? static_cast<void> (0) : __assert_fail
("!VT.isVector()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4378, __PRETTY_FUNCTION__))
;
4379
4380 // Try to get the fneg to fold into the source modifier. This undoes generic
4381 // DAG combines and folds them into the mad.
4382 //
4383 // Only do this if we are not trying to support denormals. v_mad_f32 does
4384 // not support denormals ever.
4385 SDValue LHS = N->getOperand(0);
4386 SDValue RHS = N->getOperand(1);
4387 if (LHS.getOpcode() == ISD::FADD) {
4388 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
4389 SDValue A = LHS.getOperand(0);
4390 if (A == LHS.getOperand(1)) {
4391 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4392 if (FusedOp != 0){
4393 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4394 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
4395
4396 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
4397 }
4398 }
4399 }
4400
4401 if (RHS.getOpcode() == ISD::FADD) {
4402 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
4403
4404 SDValue A = RHS.getOperand(0);
4405 if (A == RHS.getOperand(1)) {
4406 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4407 if (FusedOp != 0){
4408 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
4409 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
4410 }
4411 }
4412 }
4413
4414 return SDValue();
4415}
4416
4417SDValue SITargetLowering::performSetCCCombine(SDNode *N,
4418 DAGCombinerInfo &DCI) const {
4419 SelectionDAG &DAG = DCI.DAG;
4420 SDLoc SL(N);
4421
4422 SDValue LHS = N->getOperand(0);
4423 SDValue RHS = N->getOperand(1);
4424 EVT VT = LHS.getValueType();
4425
4426 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
4427 VT != MVT::f16))
4428 return SDValue();
4429
4430 // Match isinf pattern
4431 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
4432 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
4433 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
4434 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
4435 if (!CRHS)
4436 return SDValue();
4437
4438 const APFloat &APF = CRHS->getValueAPF();
4439 if (APF.isInfinity() && !APF.isNegative()) {
4440 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
4441 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
4442 DAG.getConstant(Mask, SL, MVT::i32));
4443 }
4444 }
4445
4446 return SDValue();
4447}
4448
4449SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
4450 DAGCombinerInfo &DCI) const {
4451 SelectionDAG &DAG = DCI.DAG;
4452 SDLoc SL(N);
4453 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
4454
4455 SDValue Src = N->getOperand(0);
4456 SDValue Srl = N->getOperand(0);
4457 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
4458 Srl = Srl.getOperand(0);
4459
4460 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
4461 if (Srl.getOpcode() == ISD::SRL) {
4462 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
4463 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
4464 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
4465
4466 if (const ConstantSDNode *C =
4467 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
4468 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
4469 EVT(MVT::i32));
4470
4471 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
4472 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
4473 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
4474 MVT::f32, Srl);
4475 }
4476 }
4477 }
4478
4479 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
4480
4481 APInt KnownZero, KnownOne;
4482 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4483 !DCI.isBeforeLegalizeOps());
4484 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4485 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
4486 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
4487 DCI.CommitTargetLoweringOpt(TLO);
4488 }
4489
4490 return SDValue();
4491}
4492
4493SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
4494 DAGCombinerInfo &DCI) const {
4495 switch (N->getOpcode()) {
4496 default:
4497 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4498 case ISD::FADD:
4499 return performFAddCombine(N, DCI);
4500 case ISD::FSUB:
4501 return performFSubCombine(N, DCI);
4502 case ISD::SETCC:
4503 return performSetCCCombine(N, DCI);
4504 case ISD::FMAXNUM:
4505 case ISD::FMINNUM:
4506 case ISD::SMAX:
4507 case ISD::SMIN:
4508 case ISD::UMAX:
4509 case ISD::UMIN:
4510 case AMDGPUISD::FMIN_LEGACY:
4511 case AMDGPUISD::FMAX_LEGACY: {
4512 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
4513 getTargetMachine().getOptLevel() > CodeGenOpt::None)
4514 return performMinMaxCombine(N, DCI);
4515 break;
4516 }
4517 case ISD::LOAD:
4518 case ISD::STORE:
4519 case ISD::ATOMIC_LOAD:
4520 case ISD::ATOMIC_STORE:
4521 case ISD::ATOMIC_CMP_SWAP:
4522 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4523 case ISD::ATOMIC_SWAP:
4524 case ISD::ATOMIC_LOAD_ADD:
4525 case ISD::ATOMIC_LOAD_SUB:
4526 case ISD::ATOMIC_LOAD_AND:
4527 case ISD::ATOMIC_LOAD_OR:
4528 case ISD::ATOMIC_LOAD_XOR:
4529 case ISD::ATOMIC_LOAD_NAND:
4530 case ISD::ATOMIC_LOAD_MIN:
4531 case ISD::ATOMIC_LOAD_MAX:
4532 case ISD::ATOMIC_LOAD_UMIN:
4533 case ISD::ATOMIC_LOAD_UMAX:
4534 case AMDGPUISD::ATOMIC_INC:
4535 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics.
4536 if (DCI.isBeforeLegalize())
4537 break;
4538 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
4539 case ISD::AND:
4540 return performAndCombine(N, DCI);
4541 case ISD::OR:
4542 return performOrCombine(N, DCI);
4543 case ISD::XOR:
4544 return performXorCombine(N, DCI);
4545 case AMDGPUISD::FP_CLASS:
4546 return performClassCombine(N, DCI);
4547 case ISD::FCANONICALIZE:
4548 return performFCanonicalizeCombine(N, DCI);
4549 case AMDGPUISD::FRACT:
4550 case AMDGPUISD::RCP:
4551 case AMDGPUISD::RSQ:
4552 case AMDGPUISD::RCP_LEGACY:
4553 case AMDGPUISD::RSQ_LEGACY:
4554 case AMDGPUISD::RSQ_CLAMP:
4555 case AMDGPUISD::LDEXP: {
4556 SDValue Src = N->getOperand(0);
4557 if (Src.isUndef())
4558 return Src;
4559 break;
4560 }
4561 case ISD::SINT_TO_FP:
4562 case ISD::UINT_TO_FP:
4563 return performUCharToFloatCombine(N, DCI);
4564 case AMDGPUISD::CVT_F32_UBYTE0:
4565 case AMDGPUISD::CVT_F32_UBYTE1:
4566 case AMDGPUISD::CVT_F32_UBYTE2:
4567 case AMDGPUISD::CVT_F32_UBYTE3:
4568 return performCvtF32UByteNCombine(N, DCI);
4569 case AMDGPUISD::FMED3:
4570 return performFMed3Combine(N, DCI);
4571 case AMDGPUISD::CVT_PKRTZ_F16_F32:
4572 return performCvtPkRTZCombine(N, DCI);
4573 case ISD::SCALAR_TO_VECTOR: {
4574 SelectionDAG &DAG = DCI.DAG;
4575 EVT VT = N->getValueType(0);
4576
4577 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
4578 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
4579 SDLoc SL(N);
4580 SDValue Src = N->getOperand(0);
4581 EVT EltVT = Src.getValueType();
4582 if (EltVT == MVT::f16)
4583 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
4584
4585 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
4586 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
4587 }
4588
4589 break;
4590 }
4591 }
4592 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4593}
4594
4595/// \brief Helper function for adjustWritemask
4596static unsigned SubIdx2Lane(unsigned Idx) {
4597 switch (Idx) {
4598 default: return 0;
4599 case AMDGPU::sub0: return 0;
4600 case AMDGPU::sub1: return 1;
4601 case AMDGPU::sub2: return 2;
4602 case AMDGPU::sub3: return 3;
4603 }
4604}
4605
4606/// \brief Adjust the writemask of MIMG instructions
4607void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
4608 SelectionDAG &DAG) const {
4609 SDNode *Users[4] = { };
4610 unsigned Lane = 0;
4611 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
4612 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
4613 unsigned NewDmask = 0;
4614
4615 // Try to figure out the used register components
4616 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
4617 I != E; ++I) {
4618
4619 // Don't look at users of the chain.
4620 if (I.getUse().getResNo() != 0)
4621 continue;
4622
4623 // Abort if we can't understand the usage
4624 if (!I->isMachineOpcode() ||
4625 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
4626 return;
4627
4628 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
4629 // Note that subregs are packed, i.e. Lane==0 is the first bit set
4630 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
4631 // set, etc.
4632 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
4633
4634 // Set which texture component corresponds to the lane.
4635 unsigned Comp;
4636 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
4637 assert(Dmask)((Dmask) ? static_cast<void> (0) : __assert_fail ("Dmask"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298059/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4637, __PRETTY_FUNCTION__))
;
4638 Comp = countTrailingZeros(Dmask);
4639 Dmask &= ~(1 << Comp);
4640 }
4641
4642 // Abort if we have more than one user per component
4643 if (Users[Lane])
4644 return;
4645
4646 Users[Lane] = *I;
4647 NewDmask |= 1 << Comp;
4648 }
4649
4650 // Abort if there's no change
4651 if (NewDmask == OldDmask)
4652 return;
4653
4654 // Adjust the writemask in the node
4655 std::vector<SDValue> Ops;
4656 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
4657 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
4658 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
4659 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
4660
4661 // If we only got one lane, replace it with a copy
4662 // (if NewDmask has only one bit set...)
4663 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
4664 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
4665 MVT::i32);
4666 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4667 SDLoc(), Users[Lane]->getValueType(0),
4668 SDValue(Node, 0), RC);
4669 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
4670 return;
4671 }
4672
4673 // Update the users of the node with the new indices
4674 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
4675 SDNode *User = Users[i];
4676 if (!User)
4677 continue;
4678
4679 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
4680 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
4681
4682 switch (Idx) {
4683 default: break;
4684 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
4685 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
4686 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
4687 }
4688 }
4689}
4690
4691static bool isFrameIndexOp(SDValue Op) {
4692 if (Op.getOpcode() == ISD::AssertZext)
4693 Op = Op.getOperand(0);
4694
4695 return isa<FrameIndexSDNode>(Op);
4696}
4697
4698/// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
4699/// with frame index operands.
4700/// LLVM assumes that inputs are to these instructions are registers.
4701void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
4702 SelectionDAG &DAG) const {
4703
4704 SmallVector<SDValue, 8> Ops;
4705 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
4706 if (!isFrameIndexOp(Node->getOperand(i))) {
4707 Ops.push_back(Node->getOperand(i));
4708 continue;
4709 }
4710
4711 SDLoc DL(Node);
4712 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
4713 Node->getOperand(i).getValueType(),
4714 Node->getOperand(i)), 0));
4715 }
4716
4717 DAG.UpdateNodeOperands(Node, Ops);
4718}
4719
4720/// \brief Fold the instructions after selecting them.
4721SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
4722 SelectionDAG &DAG) const {
4723 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4724 unsigned Opcode = Node->getMachineOpcode();
4725
4726 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
4727 !TII->isGather4(Opcode))
4728 adjustWritemask(Node, DAG);
4729
4730 if (Opcode == AMDGPU::INSERT_SUBREG ||
4731 Opcode == AMDGPU::REG_SEQUENCE) {
4732 legalizeTargetIndependentNode(Node, DAG);
4733 return Node;
4734 }
4735 return Node;
4736}
4737
4738/// \brief Assign the register class depending on the number of
4739/// bits set in the writemask
4740void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
4741 SDNode *Node) const {
4742 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4743
4744 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4745
4746 if (TII->isVOP3(MI.getOpcode())) {
4747 // Make sure constant bus requirements are respected.
4748 TII->legalizeOperandsVOP3(MRI, MI);
4749 return;
4750 }
4751
4752 if (TII->isMIMG(MI)) {
4753 unsigned VReg = MI.getOperand(0).getReg();
4754 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
4755 // TODO: Need mapping tables to handle other cases (register classes).
4756 if (RC != &AMDGPU::VReg_128RegClass)
4757 return;
4758
4759 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4;
4760 unsigned Writemask = MI.getOperand(DmaskIdx).getImm();
4761 unsigned BitsSet = 0;
4762 for (unsigned i = 0; i < 4; ++i)
4763 BitsSet += Writemask & (1 << i) ? 1 : 0;
4764 switch (BitsSet) {
4765 default: return;
4766 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
4767 case 2: RC = &AMDGPU::VReg_64RegClass; break;
4768 case 3: RC = &AMDGPU::VReg_96RegClass; break;
4769 }
4770
4771 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet);
4772 MI.setDesc(TII->get(NewOpcode));
4773 MRI.setRegClass(VReg, RC);
4774 return;
4775 }
4776
4777 // Replace unused atomics with the no return version.
4778 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
4779 if (NoRetAtomicOp != -1) {
4780 if (!Node->hasAnyUseOfValue(0)) {
4781 MI.setDesc(TII->get(NoRetAtomicOp));
4782 MI.RemoveOperand(0);
4783 return;
4784 }
4785
4786 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
4787 // instruction, because the return type of these instructions is a vec2 of
4788 // the memory type, so it can be tied to the input operand.
4789 // This means these instructions always have a use, so we need to add a
4790 // special case to check if the atomic has only one extract_subreg use,
4791 // which itself has no uses.
4792 if ((Node->hasNUsesOfValue(1, 0) &&
4793 Node->use_begin()->isMachineOpcode() &&
4794 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
4795 !Node->use_begin()->hasAnyUseOfValue(0))) {
4796 unsigned Def = MI.getOperand(0).getReg();
4797
4798 // Change this into a noret atomic.
4799 MI.setDesc(TII->get(NoRetAtomicOp));
4800 MI.RemoveOperand(0);
4801
4802 // If we only remove the def operand from the atomic instruction, the
4803 // extract_subreg will be left with a use of a vreg without a def.
4804 // So we need to insert an implicit_def to avoid machine verifier
4805 // errors.
4806 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
4807 TII->get(AMDGPU::IMPLICIT_DEF), Def);
4808 }
4809 return;
4810 }
4811}
4812
4813static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
4814 uint64_t Val) {
4815 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
4816 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
4817}
4818
4819MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
4820 const SDLoc &DL,
4821 SDValue Ptr) const {
4822 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4823
4824 // Build the half of the subregister with the constants before building the
4825 // full 128-bit register. If we are building multiple resource descriptors,
4826 // this will allow CSEing of the 2-component register.
4827 const SDValue Ops0[] = {
4828 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
4829 buildSMovImm32(DAG, DL, 0),
4830 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
4831 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
4832 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
4833 };
4834
4835 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
4836 MVT::v2i32, Ops0), 0);
4837
4838 // Combine the constants and the pointer.
4839 const SDValue Ops1[] = {
4840 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
4841 Ptr,
4842 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
4843 SubRegHi,
4844 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
4845 };
4846
4847 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
4848}
4849
4850/// \brief Return a resource descriptor with the 'Add TID' bit enabled
4851/// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
4852/// of the resource descriptor) to create an offset, which is added to
4853/// the resource pointer.
4854MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
4855 SDValue Ptr, uint32_t RsrcDword1,
4856 uint64_t RsrcDword2And3) const {
4857 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
4858 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
4859 if (RsrcDword1) {
4860 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
4861 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
4862 0);
4863 }
4864
4865 SDValue DataLo = buildSMovImm32(DAG, DL,
4866 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)0xFFFFFFFFUL);
4867 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
4868
4869 const SDValue Ops[] = {
4870 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
4871 PtrLo,
4872 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
4873 PtrHi,
4874 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
4875 DataLo,
4876 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
4877 DataHi,
4878 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
4879 };
4880
4881 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
4882}
4883
4884SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
4885 const TargetRegisterClass *RC,
4886 unsigned Reg, EVT VT) const {
4887 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
4888
4889 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
4890 cast<RegisterSDNode>(VReg)->getReg(), VT);
4891}
4892
4893//===----------------------------------------------------------------------===//
4894// SI Inline Assembly Support
4895//===----------------------------------------------------------------------===//
4896
4897std::pair<unsigned, const TargetRegisterClass *>
4898SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4899 StringRef Constraint,
4900 MVT VT) const {
4901 if (!isTypeLegal(VT))
4902 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4903
4904 if (Constraint.size() == 1) {
4905 switch (Constraint[0]) {
4906 case 's':
4907 case 'r':
4908 switch (VT.getSizeInBits()) {
4909 default:
4910 return std::make_pair(0U, nullptr);
4911 case 32:
4912 case 16:
4913 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
4914 case 64:
4915 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
4916 case 128:
4917 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
4918 case 256:
4919 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
4920 case 512:
4921 return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
4922 }
4923
4924 case 'v':
4925 switch (VT.getSizeInBits()) {
4926 default:
4927 return std::make_pair(0U, nullptr);
4928 case 32:
4929 case 16:
4930 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
4931 case 64:
4932 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
4933 case 96:
4934 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
4935 case 128:
4936 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
4937 case 256:
4938 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
4939 case 512:
4940 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
4941 }
4942 }
4943 }
4944
4945 if (Constraint.size() > 1) {
4946 const TargetRegisterClass *RC = nullptr;
4947 if (Constraint[1] == 'v') {
4948 RC = &AMDGPU::VGPR_32RegClass;
4949 } else if (Constraint[1] == 's') {
4950 RC = &AMDGPU::SGPR_32RegClass;
4951 }
4952
4953 if (RC) {
4954 uint32_t Idx;
4955 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
4956 if (!Failed && Idx < RC->getNumRegs())
4957 return std::make_pair(RC->getRegister(Idx), RC);
4958 }
4959 }
4960 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4961}
4962
4963SITargetLowering::ConstraintType
4964SITargetLowering::getConstraintType(StringRef Constraint) const {
4965 if (Constraint.size() == 1) {
4966 switch (Constraint[0]) {
4967 default: break;
4968 case 's':
4969 case 'v':
4970 return C_RegisterClass;
4971 }
4972 }
4973 return TargetLowering::getConstraintType(Constraint);
4974}