Bug Summary

File:lib/Target/AMDGPU/SIISelLowering.cpp
Warning:line 2296, 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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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~svn298304/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
2159unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
2160 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
2161 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
2162 case Intrinsic::amdgcn_if:
2163 return AMDGPUISD::IF;
2164 case Intrinsic::amdgcn_else:
2165 return AMDGPUISD::ELSE;
2166 case Intrinsic::amdgcn_loop:
2167 return AMDGPUISD::LOOP;
2168 case Intrinsic::amdgcn_end_cf:
2169 llvm_unreachable("should not occur")::llvm::llvm_unreachable_internal("should not occur", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2169)
;
2170 default:
2171 return 0;
2172 }
2173 }
2174
2175 // break, if_break, else_break are all only used as inputs to loop, not
2176 // directly as branch conditions.
2177 return 0;
2178}
2179
2180void SITargetLowering::createDebuggerPrologueStackObjects(
2181 MachineFunction &MF) const {
2182 // Create stack objects that are used for emitting debugger prologue.
2183 //
2184 // Debugger prologue writes work group IDs and work item IDs to scratch memory
2185 // at fixed location in the following format:
2186 // offset 0: work group ID x
2187 // offset 4: work group ID y
2188 // offset 8: work group ID z
2189 // offset 16: work item ID x
2190 // offset 20: work item ID y
2191 // offset 24: work item ID z
2192 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2193 int ObjectIdx = 0;
2194
2195 // For each dimension:
2196 for (unsigned i = 0; i < 3; ++i) {
2197 // Create fixed stack object for work group ID.
2198 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
2199 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
2200 // Create fixed stack object for work item ID.
2201 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
2202 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
2203 }
2204}
2205
2206bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
2207 const Triple &TT = getTargetMachine().getTargetTriple();
2208 return GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS &&
2209 AMDGPU::shouldEmitConstantsToTextSection(TT);
2210}
2211
2212bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
2213 return (GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
2214 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) &&
2215 !shouldEmitFixup(GV) &&
2216 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2217}
2218
2219bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
2220 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
2221}
2222
2223/// This transforms the control flow intrinsics to get the branch destination as
2224/// last parameter, also switches branch target with BR if the need arise
2225SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
2226 SelectionDAG &DAG) const {
2227 SDLoc DL(BRCOND);
2228
2229 SDNode *Intr = BRCOND.getOperand(1).getNode();
2230 SDValue Target = BRCOND.getOperand(2);
2231 SDNode *BR = nullptr;
2232 SDNode *SetCC = nullptr;
2233
2234 if (Intr->getOpcode() == ISD::SETCC) {
2235 // As long as we negate the condition everything is fine
2236 SetCC = Intr;
2237 Intr = SetCC->getOperand(0).getNode();
2238
2239 } else {
2240 // Get the target from BR if we don't negate the condition
2241 BR = findUser(BRCOND, ISD::BR);
2242 Target = BR->getOperand(1);
2243 }
2244
2245 // FIXME: This changes the types of the intrinsics instead of introducing new
2246 // nodes with the correct types.
2247 // e.g. llvm.amdgcn.loop
2248
2249 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
2250 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
2251
2252 unsigned CFNode = isCFIntrinsic(Intr);
2253 if (CFNode == 0) {
2254 // This is a uniform branch so we don't need to legalize.
2255 return BRCOND;
2256 }
2257
2258 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
2259 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
2260
2261 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~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2264, __PRETTY_FUNCTION__))
2262 (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~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2264, __PRETTY_FUNCTION__))
2263 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~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2264, __PRETTY_FUNCTION__))
2264 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~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2264, __PRETTY_FUNCTION__))
;
2265
2266 // operands of the new intrinsic call
2267 SmallVector<SDValue, 4> Ops;
2268 if (HaveChain)
2269 Ops.push_back(BRCOND.getOperand(0));
2270
2271 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
2272 Ops.push_back(Target);
2273
2274 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
2275
2276 // build the new intrinsic call
2277 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
2278
2279 if (!HaveChain) {
2280 SDValue Ops[] = {
2281 SDValue(Result, 0),
2282 BRCOND.getOperand(0)
2283 };
2284
2285 Result = DAG.getMergeValues(Ops, DL).getNode();
2286 }
2287
2288 if (BR) {
2289 // Give the branch instruction our target
2290 SDValue Ops[] = {
2291 BR->getOperand(0),
2292 BRCOND.getOperand(2)
2293 };
2294 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
2295 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
2296 BR = NewBR.getNode();
Value stored to 'BR' is never read
2297 }
2298
2299 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
2300
2301 // Copy the intrinsic results to registers
2302 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
2303 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
2304 if (!CopyToReg)
2305 continue;
2306
2307 Chain = DAG.getCopyToReg(
2308 Chain, DL,
2309 CopyToReg->getOperand(1),
2310 SDValue(Result, i - 1),
2311 SDValue());
2312
2313 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
2314 }
2315
2316 // Remove the old intrinsic from the chain
2317 DAG.ReplaceAllUsesOfValueWith(
2318 SDValue(Intr, Intr->getNumValues() - 1),
2319 Intr->getOperand(0));
2320
2321 return Chain;
2322}
2323
2324SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
2325 SDValue Op,
2326 const SDLoc &DL,
2327 EVT VT) const {
2328 return Op.getValueType().bitsLE(VT) ?
2329 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
2330 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
2331}
2332
2333SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2334 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~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2335, __PRETTY_FUNCTION__))
2335 "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~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2335, __PRETTY_FUNCTION__))
;
2336
2337 SDValue Src = Op.getOperand(0);
2338 EVT SrcVT = Src.getValueType();
2339 if (SrcVT != MVT::f64)
2340 return Op;
2341
2342 SDLoc DL(Op);
2343
2344 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
2345 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
2346 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);;
2347}
2348
2349SDValue SITargetLowering::getSegmentAperture(unsigned AS,
2350 SelectionDAG &DAG) const {
2351
2352 if (Subtarget->hasApertureRegs()) { // Read from Aperture Registers directly.
2353 unsigned RegNo = (AS == AMDGPUAS::LOCAL_ADDRESS) ? AMDGPU::SRC_SHARED_BASE :
2354 AMDGPU::SRC_PRIVATE_BASE;
2355 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, RegNo, MVT::i32);
2356 }
2357
2358 SDLoc SL;
2359 MachineFunction &MF = DAG.getMachineFunction();
2360 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2361 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2362 assert(UserSGPR != AMDGPU::NoRegister)((UserSGPR != AMDGPU::NoRegister) ? static_cast<void> (
0) : __assert_fail ("UserSGPR != AMDGPU::NoRegister", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2362, __PRETTY_FUNCTION__))
;
2363
2364 SDValue QueuePtr = CreateLiveInRegister(
2365 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2366
2367 // Offset into amd_queue_t for group_segment_aperture_base_hi /
2368 // private_segment_aperture_base_hi.
2369 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
2370
2371 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, QueuePtr,
2372 DAG.getConstant(StructOffset, SL, MVT::i64));
2373
2374 // TODO: Use custom target PseudoSourceValue.
2375 // TODO: We should use the value from the IR intrinsic call, but it might not
2376 // be available and how do we get it?
2377 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
2378 AMDGPUAS::CONSTANT_ADDRESS));
2379
2380 MachinePointerInfo PtrInfo(V, StructOffset);
2381 return DAG.getLoad(MVT::i32, SL, QueuePtr.getValue(1), Ptr, PtrInfo,
2382 MinAlign(64, StructOffset),
2383 MachineMemOperand::MODereferenceable |
2384 MachineMemOperand::MOInvariant);
2385}
2386
2387SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
2388 SelectionDAG &DAG) const {
2389 SDLoc SL(Op);
2390 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
2391
2392 SDValue Src = ASC->getOperand(0);
2393 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
2394
2395 const AMDGPUTargetMachine &TM =
2396 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
2397
2398 // flat -> local/private
2399 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
2400 unsigned DestAS = ASC->getDestAddressSpace();
2401 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
2402 unsigned NullVal = TM.getNullPointerValue(DestAS);
2403 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2404 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
2405 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
2406
2407 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
2408 NonNull, Ptr, SegmentNullPtr);
2409 }
2410 }
2411
2412 // local/private -> flat
2413 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
2414 unsigned SrcAS = ASC->getSrcAddressSpace();
2415 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
2416 unsigned NullVal = TM.getNullPointerValue(SrcAS);
2417 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2418
2419 SDValue NonNull
2420 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
2421
2422 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), DAG);
2423 SDValue CvtPtr
2424 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
2425
2426 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
2427 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
2428 FlatNullPtr);
2429 }
2430 }
2431
2432 // global <-> flat are no-ops and never emitted.
2433
2434 const MachineFunction &MF = DAG.getMachineFunction();
2435 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
2436 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
2437 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
2438
2439 return DAG.getUNDEF(ASC->getValueType(0));
2440}
2441
2442SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
2443 SelectionDAG &DAG) const {
2444 SDValue Idx = Op.getOperand(2);
2445 if (isa<ConstantSDNode>(Idx))
2446 return SDValue();
2447
2448 // Avoid stack access for dynamic indexing.
2449 SDLoc SL(Op);
2450 SDValue Vec = Op.getOperand(0);
2451 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
2452
2453 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
2454 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
2455
2456 // Convert vector index to bit-index.
2457 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
2458 DAG.getConstant(16, SL, MVT::i32));
2459
2460 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2461
2462 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
2463 DAG.getConstant(0xffff, SL, MVT::i32),
2464 ScaledIdx);
2465
2466 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
2467 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
2468 DAG.getNOT(SL, BFM, MVT::i32), BCVec);
2469
2470 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
2471 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
2472}
2473
2474SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
2475 SelectionDAG &DAG) const {
2476 SDLoc SL(Op);
2477
2478 EVT ResultVT = Op.getValueType();
2479 SDValue Vec = Op.getOperand(0);
2480 SDValue Idx = Op.getOperand(1);
2481
2482 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
2483 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2484
2485 if (CIdx->getZExtValue() == 1) {
2486 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
2487 DAG.getConstant(16, SL, MVT::i32));
2488 } else {
2489 assert(CIdx->getZExtValue() == 0)((CIdx->getZExtValue() == 0) ? static_cast<void> (0)
: __assert_fail ("CIdx->getZExtValue() == 0", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2489, __PRETTY_FUNCTION__))
;
2490 }
2491
2492 if (ResultVT.bitsLT(MVT::i32))
2493 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2494 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2495 }
2496
2497 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
2498
2499 // Convert vector index to bit-index.
2500 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
2501
2502 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2503 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
2504
2505 SDValue Result = Elt;
2506 if (ResultVT.bitsLT(MVT::i32))
2507 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2508
2509 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2510}
2511
2512bool
2513SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2514 // We can fold offsets for anything that doesn't require a GOT relocation.
2515 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
2516 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) &&
2517 !shouldEmitGOTReloc(GA->getGlobal());
2518}
2519
2520static SDValue
2521buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
2522 const SDLoc &DL, unsigned Offset, EVT PtrVT,
2523 unsigned GAFlags = SIInstrInfo::MO_NONE) {
2524 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
2525 // lowered to the following code sequence:
2526 //
2527 // For constant address space:
2528 // s_getpc_b64 s[0:1]
2529 // s_add_u32 s0, s0, $symbol
2530 // s_addc_u32 s1, s1, 0
2531 //
2532 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2533 // a fixup or relocation is emitted to replace $symbol with a literal
2534 // constant, which is a pc-relative offset from the encoding of the $symbol
2535 // operand to the global variable.
2536 //
2537 // For global address space:
2538 // s_getpc_b64 s[0:1]
2539 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
2540 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
2541 //
2542 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2543 // fixups or relocations are emitted to replace $symbol@*@lo and
2544 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
2545 // which is a 64-bit pc-relative offset from the encoding of the $symbol
2546 // operand to the global variable.
2547 //
2548 // What we want here is an offset from the value returned by s_getpc
2549 // (which is the address of the s_add_u32 instruction) to the global
2550 // variable, but since the encoding of $symbol starts 4 bytes after the start
2551 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
2552 // small. This requires us to add 4 to the global variable offset in order to
2553 // compute the correct address.
2554 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2555 GAFlags);
2556 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2557 GAFlags == SIInstrInfo::MO_NONE ?
2558 GAFlags : GAFlags + 1);
2559 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
2560}
2561
2562SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
2563 SDValue Op,
2564 SelectionDAG &DAG) const {
2565 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
2566
2567 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS &&
2568 GSD->getAddressSpace() != AMDGPUAS::GLOBAL_ADDRESS)
2569 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
2570
2571 SDLoc DL(GSD);
2572 const GlobalValue *GV = GSD->getGlobal();
2573 EVT PtrVT = Op.getValueType();
2574
2575 if (shouldEmitFixup(GV))
2576 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
2577 else if (shouldEmitPCReloc(GV))
2578 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
2579 SIInstrInfo::MO_REL32);
2580
2581 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
2582 SIInstrInfo::MO_GOTPCREL32);
2583
2584 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
2585 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
2586 const DataLayout &DataLayout = DAG.getDataLayout();
2587 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
2588 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
2589 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
2590
2591 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
2592 MachineMemOperand::MODereferenceable |
2593 MachineMemOperand::MOInvariant);
2594}
2595
2596SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
2597 const SDLoc &DL, SDValue V) const {
2598 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
2599 // the destination register.
2600 //
2601 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
2602 // so we will end up with redundant moves to m0.
2603 //
2604 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
2605
2606 // A Null SDValue creates a glue result.
2607 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
2608 V, Chain);
2609 return SDValue(M0, 0);
2610}
2611
2612SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
2613 SDValue Op,
2614 MVT VT,
2615 unsigned Offset) const {
2616 SDLoc SL(Op);
2617 SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL,
2618 DAG.getEntryNode(), Offset, false);
2619 // The local size values will have the hi 16-bits as zero.
2620 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
2621 DAG.getValueType(VT));
2622}
2623
2624static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2625 EVT VT) {
2626 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2627 "non-hsa intrinsic with hsa target",
2628 DL.getDebugLoc());
2629 DAG.getContext()->diagnose(BadIntrin);
2630 return DAG.getUNDEF(VT);
2631}
2632
2633static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2634 EVT VT) {
2635 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2636 "intrinsic not supported on subtarget",
2637 DL.getDebugLoc());
2638 DAG.getContext()->diagnose(BadIntrin);
2639 return DAG.getUNDEF(VT);
2640}
2641
2642SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2643 SelectionDAG &DAG) const {
2644 MachineFunction &MF = DAG.getMachineFunction();
2645 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
2646 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2647
2648 EVT VT = Op.getValueType();
2649 SDLoc DL(Op);
2650 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2651
2652 // TODO: Should this propagate fast-math-flags?
2653
2654 switch (IntrinsicID) {
2655 case Intrinsic::amdgcn_implicit_buffer_ptr: {
2656 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
2657 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2658 }
2659 case Intrinsic::amdgcn_dispatch_ptr:
2660 case Intrinsic::amdgcn_queue_ptr: {
2661 if (!Subtarget->isAmdCodeObjectV2(MF)) {
2662 DiagnosticInfoUnsupported BadIntrin(
2663 *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
2664 DL.getDebugLoc());
2665 DAG.getContext()->diagnose(BadIntrin);
2666 return DAG.getUNDEF(VT);
2667 }
2668
2669 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
2670 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
2671 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
2672 TRI->getPreloadedValue(MF, Reg), VT);
2673 }
2674 case Intrinsic::amdgcn_implicitarg_ptr: {
2675 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
2676 return LowerParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
2677 }
2678 case Intrinsic::amdgcn_kernarg_segment_ptr: {
2679 unsigned Reg
2680 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
2681 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2682 }
2683 case Intrinsic::amdgcn_dispatch_id: {
2684 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID);
2685 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2686 }
2687 case Intrinsic::amdgcn_rcp:
2688 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
2689 case Intrinsic::amdgcn_rsq:
2690 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2691 case Intrinsic::amdgcn_rsq_legacy:
2692 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2693 return emitRemovedIntrinsicError(DAG, DL, VT);
2694
2695 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
2696 case Intrinsic::amdgcn_rcp_legacy:
2697 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2698 return emitRemovedIntrinsicError(DAG, DL, VT);
2699 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
2700 case Intrinsic::amdgcn_rsq_clamp: {
2701 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2702 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
2703
2704 Type *Type = VT.getTypeForEVT(*DAG.getContext());
2705 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
2706 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
2707
2708 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2709 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
2710 DAG.getConstantFP(Max, DL, VT));
2711 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
2712 DAG.getConstantFP(Min, DL, VT));
2713 }
2714 case Intrinsic::r600_read_ngroups_x:
2715 if (Subtarget->isAmdHsaOS())
2716 return emitNonHSAIntrinsicError(DAG, DL, VT);
2717
2718 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2719 SI::KernelInputOffsets::NGROUPS_X, false);
2720 case Intrinsic::r600_read_ngroups_y:
2721 if (Subtarget->isAmdHsaOS())
2722 return emitNonHSAIntrinsicError(DAG, DL, VT);
2723
2724 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2725 SI::KernelInputOffsets::NGROUPS_Y, false);
2726 case Intrinsic::r600_read_ngroups_z:
2727 if (Subtarget->isAmdHsaOS())
2728 return emitNonHSAIntrinsicError(DAG, DL, VT);
2729
2730 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2731 SI::KernelInputOffsets::NGROUPS_Z, false);
2732 case Intrinsic::r600_read_global_size_x:
2733 if (Subtarget->isAmdHsaOS())
2734 return emitNonHSAIntrinsicError(DAG, DL, VT);
2735
2736 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2737 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
2738 case Intrinsic::r600_read_global_size_y:
2739 if (Subtarget->isAmdHsaOS())
2740 return emitNonHSAIntrinsicError(DAG, DL, VT);
2741
2742 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2743 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
2744 case Intrinsic::r600_read_global_size_z:
2745 if (Subtarget->isAmdHsaOS())
2746 return emitNonHSAIntrinsicError(DAG, DL, VT);
2747
2748 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2749 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
2750 case Intrinsic::r600_read_local_size_x:
2751 if (Subtarget->isAmdHsaOS())
2752 return emitNonHSAIntrinsicError(DAG, DL, VT);
2753
2754 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2755 SI::KernelInputOffsets::LOCAL_SIZE_X);
2756 case Intrinsic::r600_read_local_size_y:
2757 if (Subtarget->isAmdHsaOS())
2758 return emitNonHSAIntrinsicError(DAG, DL, VT);
2759
2760 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2761 SI::KernelInputOffsets::LOCAL_SIZE_Y);
2762 case Intrinsic::r600_read_local_size_z:
2763 if (Subtarget->isAmdHsaOS())
2764 return emitNonHSAIntrinsicError(DAG, DL, VT);
2765
2766 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2767 SI::KernelInputOffsets::LOCAL_SIZE_Z);
2768 case Intrinsic::amdgcn_workgroup_id_x:
2769 case Intrinsic::r600_read_tgid_x:
2770 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2771 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
2772 case Intrinsic::amdgcn_workgroup_id_y:
2773 case Intrinsic::r600_read_tgid_y:
2774 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2775 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
2776 case Intrinsic::amdgcn_workgroup_id_z:
2777 case Intrinsic::r600_read_tgid_z:
2778 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2779 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
2780 case Intrinsic::amdgcn_workitem_id_x:
2781 case Intrinsic::r600_read_tidig_x:
2782 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2783 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
2784 case Intrinsic::amdgcn_workitem_id_y:
2785 case Intrinsic::r600_read_tidig_y:
2786 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2787 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
2788 case Intrinsic::amdgcn_workitem_id_z:
2789 case Intrinsic::r600_read_tidig_z:
2790 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2791 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
2792 case AMDGPUIntrinsic::SI_load_const: {
2793 SDValue Ops[] = {
2794 Op.getOperand(1),
2795 Op.getOperand(2)
2796 };
2797
2798 MachineMemOperand *MMO = MF.getMachineMemOperand(
2799 MachinePointerInfo(),
2800 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
2801 MachineMemOperand::MOInvariant,
2802 VT.getStoreSize(), 4);
2803 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
2804 Op->getVTList(), Ops, VT, MMO);
2805 }
2806 case Intrinsic::amdgcn_fdiv_fast:
2807 return lowerFDIV_FAST(Op, DAG);
2808 case AMDGPUIntrinsic::SI_vs_load_input:
2809 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
2810 Op.getOperand(1),
2811 Op.getOperand(2),
2812 Op.getOperand(3));
2813 case Intrinsic::amdgcn_interp_mov: {
2814 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2815 SDValue Glue = M0.getValue(1);
2816 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
2817 Op.getOperand(2), Op.getOperand(3), Glue);
2818 }
2819 case Intrinsic::amdgcn_interp_p1: {
2820 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2821 SDValue Glue = M0.getValue(1);
2822 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
2823 Op.getOperand(2), Op.getOperand(3), Glue);
2824 }
2825 case Intrinsic::amdgcn_interp_p2: {
2826 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
2827 SDValue Glue = SDValue(M0.getNode(), 1);
2828 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
2829 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
2830 Glue);
2831 }
2832 case Intrinsic::amdgcn_sin:
2833 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
2834
2835 case Intrinsic::amdgcn_cos:
2836 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
2837
2838 case Intrinsic::amdgcn_log_clamp: {
2839 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2840 return SDValue();
2841
2842 DiagnosticInfoUnsupported BadIntrin(
2843 *MF.getFunction(), "intrinsic not supported on subtarget",
2844 DL.getDebugLoc());
2845 DAG.getContext()->diagnose(BadIntrin);
2846 return DAG.getUNDEF(VT);
2847 }
2848 case Intrinsic::amdgcn_ldexp:
2849 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
2850 Op.getOperand(1), Op.getOperand(2));
2851
2852 case Intrinsic::amdgcn_fract:
2853 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
2854
2855 case Intrinsic::amdgcn_class:
2856 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
2857 Op.getOperand(1), Op.getOperand(2));
2858 case Intrinsic::amdgcn_div_fmas:
2859 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
2860 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
2861 Op.getOperand(4));
2862
2863 case Intrinsic::amdgcn_div_fixup:
2864 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
2865 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2866
2867 case Intrinsic::amdgcn_trig_preop:
2868 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
2869 Op.getOperand(1), Op.getOperand(2));
2870 case Intrinsic::amdgcn_div_scale: {
2871 // 3rd parameter required to be a constant.
2872 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2873 if (!Param)
2874 return DAG.getUNDEF(VT);
2875
2876 // Translate to the operands expected by the machine instruction. The
2877 // first parameter must be the same as the first instruction.
2878 SDValue Numerator = Op.getOperand(1);
2879 SDValue Denominator = Op.getOperand(2);
2880
2881 // Note this order is opposite of the machine instruction's operations,
2882 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
2883 // intrinsic has the numerator as the first operand to match a normal
2884 // division operation.
2885
2886 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
2887
2888 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
2889 Denominator, Numerator);
2890 }
2891 case Intrinsic::amdgcn_icmp: {
2892 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2893 if (!CD)
2894 return DAG.getUNDEF(VT);
2895
2896 int CondCode = CD->getSExtValue();
2897 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
2898 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
2899 return DAG.getUNDEF(VT);
2900
2901 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
2902 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
2903 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2904 Op.getOperand(2), DAG.getCondCode(CCOpcode));
2905 }
2906 case Intrinsic::amdgcn_fcmp: {
2907 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2908 if (!CD)
2909 return DAG.getUNDEF(VT);
2910
2911 int CondCode = CD->getSExtValue();
2912 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
2913 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
2914 return DAG.getUNDEF(VT);
2915
2916 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
2917 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
2918 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2919 Op.getOperand(2), DAG.getCondCode(CCOpcode));
2920 }
2921 case Intrinsic::amdgcn_fmed3:
2922 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
2923 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2924 case Intrinsic::amdgcn_fmul_legacy:
2925 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
2926 Op.getOperand(1), Op.getOperand(2));
2927 case Intrinsic::amdgcn_sffbh:
2928 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
2929 case Intrinsic::amdgcn_sbfe:
2930 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
2931 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2932 case Intrinsic::amdgcn_ubfe:
2933 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
2934 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2935 case Intrinsic::amdgcn_cvt_pkrtz: {
2936 // FIXME: Stop adding cast if v2f16 legal.
2937 EVT VT = Op.getValueType();
2938 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32,
2939 Op.getOperand(1), Op.getOperand(2));
2940 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
2941 }
2942 default:
2943 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2944 }
2945}
2946
2947SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2948 SelectionDAG &DAG) const {
2949 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2950 SDLoc DL(Op);
2951 switch (IntrID) {
2952 case Intrinsic::amdgcn_atomic_inc:
2953 case Intrinsic::amdgcn_atomic_dec: {
2954 MemSDNode *M = cast<MemSDNode>(Op);
2955 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
2956 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
2957 SDValue Ops[] = {
2958 M->getOperand(0), // Chain
2959 M->getOperand(2), // Ptr
2960 M->getOperand(3) // Value
2961 };
2962
2963 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
2964 M->getMemoryVT(), M->getMemOperand());
2965 }
2966 case Intrinsic::amdgcn_buffer_load:
2967 case Intrinsic::amdgcn_buffer_load_format: {
2968 SDValue Ops[] = {
2969 Op.getOperand(0), // Chain
2970 Op.getOperand(2), // rsrc
2971 Op.getOperand(3), // vindex
2972 Op.getOperand(4), // offset
2973 Op.getOperand(5), // glc
2974 Op.getOperand(6) // slc
2975 };
2976 MachineFunction &MF = DAG.getMachineFunction();
2977 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2978
2979 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
2980 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
2981 EVT VT = Op.getValueType();
2982 EVT IntVT = VT.changeTypeToInteger();
2983
2984 MachineMemOperand *MMO = MF.getMachineMemOperand(
2985 MachinePointerInfo(MFI->getBufferPSV()),
2986 MachineMemOperand::MOLoad,
2987 VT.getStoreSize(), VT.getStoreSize());
2988
2989 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO);
2990 }
2991 default:
2992 return SDValue();
2993 }
2994}
2995
2996SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
2997 SelectionDAG &DAG) const {
2998 MachineFunction &MF = DAG.getMachineFunction();
2999 SDLoc DL(Op);
3000 SDValue Chain = Op.getOperand(0);
3001 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3002
3003 switch (IntrinsicID) {
3004 case Intrinsic::amdgcn_exp: {
3005 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3006 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3007 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
3008 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
3009
3010 const SDValue Ops[] = {
3011 Chain,
3012 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3013 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3014 Op.getOperand(4), // src0
3015 Op.getOperand(5), // src1
3016 Op.getOperand(6), // src2
3017 Op.getOperand(7), // src3
3018 DAG.getTargetConstant(0, DL, MVT::i1), // compr
3019 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3020 };
3021
3022 unsigned Opc = Done->isNullValue() ?
3023 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3024 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3025 }
3026 case Intrinsic::amdgcn_exp_compr: {
3027 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3028 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3029 SDValue Src0 = Op.getOperand(4);
3030 SDValue Src1 = Op.getOperand(5);
3031 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
3032 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
3033
3034 SDValue Undef = DAG.getUNDEF(MVT::f32);
3035 const SDValue Ops[] = {
3036 Chain,
3037 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3038 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3039 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
3040 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
3041 Undef, // src2
3042 Undef, // src3
3043 DAG.getTargetConstant(1, DL, MVT::i1), // compr
3044 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3045 };
3046
3047 unsigned Opc = Done->isNullValue() ?
3048 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3049 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3050 }
3051 case Intrinsic::amdgcn_s_sendmsg:
3052 case Intrinsic::amdgcn_s_sendmsghalt: {
3053 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
3054 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
3055 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
3056 SDValue Glue = Chain.getValue(1);
3057 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
3058 Op.getOperand(2), Glue);
3059 }
3060 case AMDGPUIntrinsic::SI_tbuffer_store: {
3061 SDValue Ops[] = {
3062 Chain,
3063 Op.getOperand(2),
3064 Op.getOperand(3),
3065 Op.getOperand(4),
3066 Op.getOperand(5),
3067 Op.getOperand(6),
3068 Op.getOperand(7),
3069 Op.getOperand(8),
3070 Op.getOperand(9),
3071 Op.getOperand(10),
3072 Op.getOperand(11),
3073 Op.getOperand(12),
3074 Op.getOperand(13),
3075 Op.getOperand(14)
3076 };
3077
3078 EVT VT = Op.getOperand(3).getValueType();
3079
3080 MachineMemOperand *MMO = MF.getMachineMemOperand(
3081 MachinePointerInfo(),
3082 MachineMemOperand::MOStore,
3083 VT.getStoreSize(), 4);
3084 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
3085 Op->getVTList(), Ops, VT, MMO);
3086 }
3087 case AMDGPUIntrinsic::AMDGPU_kill: {
3088 SDValue Src = Op.getOperand(2);
3089 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
3090 if (!K->isNegative())
3091 return Chain;
3092
3093 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
3094 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
3095 }
3096
3097 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
3098 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
3099 }
3100 case AMDGPUIntrinsic::SI_export: { // Legacy intrinsic.
3101 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(2));
3102 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(3));
3103 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(4));
3104 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(5));
3105 const ConstantSDNode *Compr = cast<ConstantSDNode>(Op.getOperand(6));
3106
3107 const SDValue Ops[] = {
3108 Chain,
3109 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8),
3110 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),
3111 Op.getOperand(7), // src0
3112 Op.getOperand(8), // src1
3113 Op.getOperand(9), // src2
3114 Op.getOperand(10), // src3
3115 DAG.getTargetConstant(Compr->getZExtValue(), DL, MVT::i1),
3116 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3117 };
3118
3119 unsigned Opc = Done->isNullValue() ?
3120 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3121 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3122 }
3123 default:
3124 return SDValue();
3125 }
3126}
3127
3128SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
3129 SDLoc DL(Op);
3130 LoadSDNode *Load = cast<LoadSDNode>(Op);
3131 ISD::LoadExtType ExtType = Load->getExtensionType();
3132 EVT MemVT = Load->getMemoryVT();
3133
3134 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
3135 // FIXME: Copied from PPC
3136 // First, load into 32 bits, then truncate to 1 bit.
3137
3138 SDValue Chain = Load->getChain();
3139 SDValue BasePtr = Load->getBasePtr();
3140 MachineMemOperand *MMO = Load->getMemOperand();
3141
3142 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
3143
3144 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
3145 BasePtr, RealMemVT, MMO);
3146
3147 SDValue Ops[] = {
3148 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
3149 NewLD.getValue(1)
3150 };
3151
3152 return DAG.getMergeValues(Ops, DL);
3153 }
3154
3155 if (!MemVT.isVector())
3156 return SDValue();
3157
3158 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~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3159, __PRETTY_FUNCTION__))
3159 "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~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3159, __PRETTY_FUNCTION__))
;
3160
3161 unsigned AS = Load->getAddressSpace();
3162 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
3163 AS, Load->getAlignment())) {
3164 SDValue Ops[2];
3165 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
3166 return DAG.getMergeValues(Ops, DL);
3167 }
3168
3169 MachineFunction &MF = DAG.getMachineFunction();
3170 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3171 // If there is a possibilty that flat instruction access scratch memory
3172 // then we need to use the same legalization rules we use for private.
3173 if (AS == AMDGPUAS::FLAT_ADDRESS)
3174 AS = MFI->hasFlatScratchInit() ?
3175 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
3176
3177 unsigned NumElements = MemVT.getVectorNumElements();
3178 switch (AS) {
3179 case AMDGPUAS::CONSTANT_ADDRESS:
3180 if (isMemOpUniform(Load))
3181 return SDValue();
3182 // Non-uniform loads will be selected to MUBUF instructions, so they
3183 // have the same legalization requirements as global and private
3184 // loads.
3185 //
3186 LLVM_FALLTHROUGH[[clang::fallthrough]];
3187 case AMDGPUAS::GLOBAL_ADDRESS:
3188 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
3189 isMemOpHasNoClobberedMemOperand(Load))
3190 return SDValue();
3191 // Non-uniform loads will be selected to MUBUF instructions, so they
3192 // have the same legalization requirements as global and private
3193 // loads.
3194 //
3195 LLVM_FALLTHROUGH[[clang::fallthrough]];
3196 case AMDGPUAS::FLAT_ADDRESS:
3197 if (NumElements > 4)
3198 return SplitVectorLoad(Op, DAG);
3199 // v4 loads are supported for private and global memory.
3200 return SDValue();
3201 case AMDGPUAS::PRIVATE_ADDRESS:
3202 // Depending on the setting of the private_element_size field in the
3203 // resource descriptor, we can only make private accesses up to a certain
3204 // size.
3205 switch (Subtarget->getMaxPrivateElementSize()) {
3206 case 4:
3207 return scalarizeVectorLoad(Load, DAG);
3208 case 8:
3209 if (NumElements > 2)
3210 return SplitVectorLoad(Op, DAG);
3211 return SDValue();
3212 case 16:
3213 // Same as global/flat
3214 if (NumElements > 4)
3215 return SplitVectorLoad(Op, DAG);
3216 return SDValue();
3217 default:
3218 llvm_unreachable("unsupported private_element_size")::llvm::llvm_unreachable_internal("unsupported private_element_size"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3218)
;
3219 }
3220 case AMDGPUAS::LOCAL_ADDRESS:
3221 if (NumElements > 2)
3222 return SplitVectorLoad(Op, DAG);
3223
3224 if (NumElements == 2)
3225 return SDValue();
3226
3227 // If properly aligned, if we split we might be able to use ds_read_b64.
3228 return SplitVectorLoad(Op, DAG);
3229 default:
3230 return SDValue();
3231 }
3232}
3233
3234SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3235 if (Op.getValueType() != MVT::i64)
3236 return SDValue();
3237
3238 SDLoc DL(Op);
3239 SDValue Cond = Op.getOperand(0);
3240
3241 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
3242 SDValue One = DAG.getConstant(1, DL, MVT::i32);
3243
3244 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
3245 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
3246
3247 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
3248 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
3249
3250 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
3251
3252 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
3253 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
3254
3255 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
3256
3257 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
3258 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
3259}
3260
3261// Catch division cases where we can use shortcuts with rcp and rsq
3262// instructions.
3263SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
3264 SelectionDAG &DAG) const {
3265 SDLoc SL(Op);
3266 SDValue LHS = Op.getOperand(0);
3267 SDValue RHS = Op.getOperand(1);
3268 EVT VT = Op.getValueType();
3269 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
3270
3271 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
3272 if (Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
3273 VT == MVT::f16) {
3274 if (CLHS->isExactlyValue(1.0)) {
3275 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
3276 // the CI documentation has a worst case error of 1 ulp.
3277 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
3278 // use it as long as we aren't trying to use denormals.
3279 //
3280 // v_rcp_f16 and v_rsq_f16 DO support denormals.
3281
3282 // 1.0 / sqrt(x) -> rsq(x)
3283
3284 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
3285 // error seems really high at 2^29 ULP.
3286 if (RHS.getOpcode() == ISD::FSQRT)
3287 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
3288
3289 // 1.0 / x -> rcp(x)
3290 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3291 }
3292
3293 // Same as for 1.0, but expand the sign out of the constant.
3294 if (CLHS->isExactlyValue(-1.0)) {
3295 // -1.0 / x -> rcp (fneg x)
3296 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3297 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
3298 }
3299 }
3300 }
3301
3302 const SDNodeFlags *Flags = Op->getFlags();
3303
3304 if (Unsafe || Flags->hasAllowReciprocal()) {
3305 // Turn into multiply by the reciprocal.
3306 // x / y -> x * (1.0 / y)
3307 SDNodeFlags Flags;
3308 Flags.setUnsafeAlgebra(true);
3309 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3310 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
3311 }
3312
3313 return SDValue();
3314}
3315
3316static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3317 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
3318 if (GlueChain->getNumValues() <= 1) {
3319 return DAG.getNode(Opcode, SL, VT, A, B);
3320 }
3321
3322 assert(GlueChain->getNumValues() == 3)((GlueChain->getNumValues() == 3) ? static_cast<void>
(0) : __assert_fail ("GlueChain->getNumValues() == 3", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3322, __PRETTY_FUNCTION__))
;
3323
3324 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3325 switch (Opcode) {
3326 default: llvm_unreachable("no chain equivalent for opcode")::llvm::llvm_unreachable_internal("no chain equivalent for opcode"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3326)
;
3327 case ISD::FMUL:
3328 Opcode = AMDGPUISD::FMUL_W_CHAIN;
3329 break;
3330 }
3331
3332 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
3333 GlueChain.getValue(2));
3334}
3335
3336static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3337 EVT VT, SDValue A, SDValue B, SDValue C,
3338 SDValue GlueChain) {
3339 if (GlueChain->getNumValues() <= 1) {
3340 return DAG.getNode(Opcode, SL, VT, A, B, C);
3341 }
3342
3343 assert(GlueChain->getNumValues() == 3)((GlueChain->getNumValues() == 3) ? static_cast<void>
(0) : __assert_fail ("GlueChain->getNumValues() == 3", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3343, __PRETTY_FUNCTION__))
;
3344
3345 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3346 switch (Opcode) {
3347 default: llvm_unreachable("no chain equivalent for opcode")::llvm::llvm_unreachable_internal("no chain equivalent for opcode"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3347)
;
3348 case ISD::FMA:
3349 Opcode = AMDGPUISD::FMA_W_CHAIN;
3350 break;
3351 }
3352
3353 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
3354 GlueChain.getValue(2));
3355}
3356
3357SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
3358 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3359 return FastLowered;
3360
3361 SDLoc SL(Op);
3362 SDValue Src0 = Op.getOperand(0);
3363 SDValue Src1 = Op.getOperand(1);
3364
3365 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3366 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3367
3368 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
3369 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
3370
3371 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
3372 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
3373
3374 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
3375}
3376
3377// Faster 2.5 ULP division that does not support denormals.
3378SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
3379 SDLoc SL(Op);
3380 SDValue LHS = Op.getOperand(1);
3381 SDValue RHS = Op.getOperand(2);
3382
3383 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
3384
3385 const APFloat K0Val(BitsToFloat(0x6f800000));
3386 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
3387
3388 const APFloat K1Val(BitsToFloat(0x2f800000));
3389 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
3390
3391 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3392
3393 EVT SetCCVT =
3394 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
3395
3396 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
3397
3398 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
3399
3400 // TODO: Should this propagate fast-math-flags?
3401 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
3402
3403 // rcp does not support denormals.
3404 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
3405
3406 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
3407
3408 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
3409}
3410
3411SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
3412 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3413 return FastLowered;
3414
3415 SDLoc SL(Op);
3416 SDValue LHS = Op.getOperand(0);
3417 SDValue RHS = Op.getOperand(1);
3418
3419 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3420
3421 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
3422
3423 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3424 RHS, RHS, LHS);
3425 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3426 LHS, RHS, LHS);
3427
3428 // Denominator is scaled to not be denormal, so using rcp is ok.
3429 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
3430 DenominatorScaled);
3431 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
3432 DenominatorScaled);
3433
3434 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
3435 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
3436 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
3437
3438 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
3439
3440 if (!Subtarget->hasFP32Denormals()) {
3441 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
3442 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE3,
3443 SL, MVT::i32);
3444 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
3445 DAG.getEntryNode(),
3446 EnableDenormValue, BitField);
3447 SDValue Ops[3] = {
3448 NegDivScale0,
3449 EnableDenorm.getValue(0),
3450 EnableDenorm.getValue(1)
3451 };
3452
3453 NegDivScale0 = DAG.getMergeValues(Ops, SL);
3454 }
3455
3456 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
3457 ApproxRcp, One, NegDivScale0);
3458
3459 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
3460 ApproxRcp, Fma0);
3461
3462 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
3463 Fma1, Fma1);
3464
3465 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
3466 NumeratorScaled, Mul);
3467
3468 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
3469
3470 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
3471 NumeratorScaled, Fma3);
3472
3473 if (!Subtarget->hasFP32Denormals()) {
3474 const SDValue DisableDenormValue =
3475 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT0, SL, MVT::i32);
3476 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
3477 Fma4.getValue(1),
3478 DisableDenormValue,
3479 BitField,
3480 Fma4.getValue(2));
3481
3482 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
3483 DisableDenorm, DAG.getRoot());
3484 DAG.setRoot(OutputChain);
3485 }
3486
3487 SDValue Scale = NumeratorScaled.getValue(1);
3488 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
3489 Fma4, Fma1, Fma3, Scale);
3490
3491 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
3492}
3493
3494SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
3495 if (DAG.getTarget().Options.UnsafeFPMath)
3496 return lowerFastUnsafeFDIV(Op, DAG);
3497
3498 SDLoc SL(Op);
3499 SDValue X = Op.getOperand(0);
3500 SDValue Y = Op.getOperand(1);
3501
3502 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
3503
3504 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
3505
3506 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
3507
3508 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
3509
3510 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
3511
3512 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
3513
3514 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
3515
3516 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
3517
3518 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
3519
3520 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
3521 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
3522
3523 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
3524 NegDivScale0, Mul, DivScale1);
3525
3526 SDValue Scale;
3527
3528 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
3529 // Workaround a hardware bug on SI where the condition output from div_scale
3530 // is not usable.
3531
3532 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
3533
3534 // Figure out if the scale to use for div_fmas.
3535 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
3536 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
3537 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
3538 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
3539
3540 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
3541 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
3542
3543 SDValue Scale0Hi
3544 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
3545 SDValue Scale1Hi
3546 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
3547
3548 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
3549 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
3550 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
3551 } else {
3552 Scale = DivScale1.getValue(1);
3553 }
3554
3555 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
3556 Fma4, Fma3, Mul, Scale);
3557
3558 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
3559}
3560
3561SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
3562 EVT VT = Op.getValueType();
3563
3564 if (VT == MVT::f32)
3565 return LowerFDIV32(Op, DAG);
3566
3567 if (VT == MVT::f64)
3568 return LowerFDIV64(Op, DAG);
3569
3570 if (VT == MVT::f16)
3571 return LowerFDIV16(Op, DAG);
3572
3573 llvm_unreachable("Unexpected type for fdiv")::llvm::llvm_unreachable_internal("Unexpected type for fdiv",
"/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3573)
;
3574}
3575
3576SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3577 SDLoc DL(Op);
3578 StoreSDNode *Store = cast<StoreSDNode>(Op);
3579 EVT VT = Store->getMemoryVT();
3580
3581 if (VT == MVT::i1) {
3582 return DAG.getTruncStore(Store->getChain(), DL,
3583 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
3584 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
3585 }
3586
3587 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~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3588, __PRETTY_FUNCTION__))
3588 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~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3588, __PRETTY_FUNCTION__))
;
3589
3590 unsigned AS = Store->getAddressSpace();
3591 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
3592 AS, Store->getAlignment())) {
3593 return expandUnalignedStore(Store, DAG);
3594 }
3595
3596 MachineFunction &MF = DAG.getMachineFunction();
3597 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3598 // If there is a possibilty that flat instruction access scratch memory
3599 // then we need to use the same legalization rules we use for private.
3600 if (AS == AMDGPUAS::FLAT_ADDRESS)
3601 AS = MFI->hasFlatScratchInit() ?
3602 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
3603
3604 unsigned NumElements = VT.getVectorNumElements();
3605 switch (AS) {
3606 case AMDGPUAS::GLOBAL_ADDRESS:
3607 case AMDGPUAS::FLAT_ADDRESS:
3608 if (NumElements > 4)
3609 return SplitVectorStore(Op, DAG);
3610 return SDValue();
3611 case AMDGPUAS::PRIVATE_ADDRESS: {
3612 switch (Subtarget->getMaxPrivateElementSize()) {
3613 case 4:
3614 return scalarizeVectorStore(Store, DAG);
3615 case 8:
3616 if (NumElements > 2)
3617 return SplitVectorStore(Op, DAG);
3618 return SDValue();
3619 case 16:
3620 if (NumElements > 4)
3621 return SplitVectorStore(Op, DAG);
3622 return SDValue();
3623 default:
3624 llvm_unreachable("unsupported private_element_size")::llvm::llvm_unreachable_internal("unsupported private_element_size"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3624)
;
3625 }
3626 }
3627 case AMDGPUAS::LOCAL_ADDRESS: {
3628 if (NumElements > 2)
3629 return SplitVectorStore(Op, DAG);
3630
3631 if (NumElements == 2)
3632 return Op;
3633
3634 // If properly aligned, if we split we might be able to use ds_write_b64.
3635 return SplitVectorStore(Op, DAG);
3636 }
3637 default:
3638 llvm_unreachable("unhandled address space")::llvm::llvm_unreachable_internal("unhandled address space", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3638)
;
3639 }
3640}
3641
3642SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
3643 SDLoc DL(Op);
3644 EVT VT = Op.getValueType();
3645 SDValue Arg = Op.getOperand(0);
3646 // TODO: Should this propagate fast-math-flags?
3647 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
3648 DAG.getNode(ISD::FMUL, DL, VT, Arg,
3649 DAG.getConstantFP(0.5/M_PI3.14159265358979323846, DL,
3650 VT)));
3651
3652 switch (Op.getOpcode()) {
3653 case ISD::FCOS:
3654 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
3655 case ISD::FSIN:
3656 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
3657 default:
3658 llvm_unreachable("Wrong trig opcode")::llvm::llvm_unreachable_internal("Wrong trig opcode", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3658)
;
3659 }
3660}
3661
3662SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
3663 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
3664 assert(AtomicNode->isCompareAndSwap())((AtomicNode->isCompareAndSwap()) ? static_cast<void>
(0) : __assert_fail ("AtomicNode->isCompareAndSwap()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3664, __PRETTY_FUNCTION__))
;
3665 unsigned AS = AtomicNode->getAddressSpace();
3666
3667 // No custom lowering required for local address space
3668 if (!isFlatGlobalAddrSpace(AS))
3669 return Op;
3670
3671 // Non-local address space requires custom lowering for atomic compare
3672 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
3673 SDLoc DL(Op);
3674 SDValue ChainIn = Op.getOperand(0);
3675 SDValue Addr = Op.getOperand(1);
3676 SDValue Old = Op.getOperand(2);
3677 SDValue New = Op.getOperand(3);
3678 EVT VT = Op.getValueType();
3679 MVT SimpleVT = VT.getSimpleVT();
3680 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
3681
3682 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
3683 SDValue Ops[] = { ChainIn, Addr, NewOld };
3684
3685 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
3686 Ops, VT, AtomicNode->getMemOperand());
3687}
3688
3689//===----------------------------------------------------------------------===//
3690// Custom DAG optimizations
3691//===----------------------------------------------------------------------===//
3692
3693SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
3694 DAGCombinerInfo &DCI) const {
3695 EVT VT = N->getValueType(0);
3696 EVT ScalarVT = VT.getScalarType();
3697 if (ScalarVT != MVT::f32)
3698 return SDValue();
3699
3700 SelectionDAG &DAG = DCI.DAG;
3701 SDLoc DL(N);
3702
3703 SDValue Src = N->getOperand(0);
3704 EVT SrcVT = Src.getValueType();
3705
3706 // TODO: We could try to match extracting the higher bytes, which would be
3707 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
3708 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
3709 // about in practice.
3710 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
3711 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
3712 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
3713 DCI.AddToWorklist(Cvt.getNode());
3714 return Cvt;
3715 }
3716 }
3717
3718 return SDValue();
3719}
3720
3721/// \brief Return true if the given offset Size in bytes can be folded into
3722/// the immediate offsets of a memory instruction for the given address space.
3723static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
3724 const SISubtarget &STI) {
3725 switch (AS) {
3726 case AMDGPUAS::GLOBAL_ADDRESS:
3727 // MUBUF instructions a 12-bit offset in bytes.
3728 return isUInt<12>(OffsetSize);
3729 case AMDGPUAS::CONSTANT_ADDRESS:
3730 // SMRD instructions have an 8-bit offset in dwords on SI and
3731 // a 20-bit offset in bytes on VI.
3732 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3733 return isUInt<20>(OffsetSize);
3734 else
3735 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
3736 case AMDGPUAS::LOCAL_ADDRESS:
3737 case AMDGPUAS::REGION_ADDRESS:
3738 // The single offset versions have a 16-bit offset in bytes.
3739 return isUInt<16>(OffsetSize);
3740 case AMDGPUAS::PRIVATE_ADDRESS:
3741 // Indirect register addressing does not use any offsets.
3742 default:
3743 return false;
3744 }
3745}
3746
3747// (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
3748
3749// This is a variant of
3750// (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
3751//
3752// The normal DAG combiner will do this, but only if the add has one use since
3753// that would increase the number of instructions.
3754//
3755// This prevents us from seeing a constant offset that can be folded into a
3756// memory instruction's addressing mode. If we know the resulting add offset of
3757// a pointer can be folded into an addressing offset, we can replace the pointer
3758// operand with the add of new constant offset. This eliminates one of the uses,
3759// and may allow the remaining use to also be simplified.
3760//
3761SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
3762 unsigned AddrSpace,
3763 DAGCombinerInfo &DCI) const {
3764 SDValue N0 = N->getOperand(0);
3765 SDValue N1 = N->getOperand(1);
3766
3767 if (N0.getOpcode() != ISD::ADD)
3768 return SDValue();
3769
3770 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
3771 if (!CN1)
3772 return SDValue();
3773
3774 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3775 if (!CAdd)
3776 return SDValue();
3777
3778 // If the resulting offset is too large, we can't fold it into the addressing
3779 // mode offset.
3780 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
3781 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
3782 return SDValue();
3783
3784 SelectionDAG &DAG = DCI.DAG;
3785 SDLoc SL(N);
3786 EVT VT = N->getValueType(0);
3787
3788 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
3789 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
3790
3791 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
3792}
3793
3794SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
3795 DAGCombinerInfo &DCI) const {
3796 SDValue Ptr = N->getBasePtr();
3797 SelectionDAG &DAG = DCI.DAG;
3798 SDLoc SL(N);
3799
3800 // TODO: We could also do this for multiplies.
3801 unsigned AS = N->getAddressSpace();
3802 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
3803 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
3804 if (NewPtr) {
3805 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
3806
3807 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
3808 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
3809 }
3810 }
3811
3812 return SDValue();
3813}
3814
3815static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
3816 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
3817 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
3818 (Opc == ISD::XOR && Val == 0);
3819}
3820
3821// Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
3822// will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
3823// integer combine opportunities since most 64-bit operations are decomposed
3824// this way. TODO: We won't want this for SALU especially if it is an inline
3825// immediate.
3826SDValue SITargetLowering::splitBinaryBitConstantOp(
3827 DAGCombinerInfo &DCI,
3828 const SDLoc &SL,
3829 unsigned Opc, SDValue LHS,
3830 const ConstantSDNode *CRHS) const {
3831 uint64_t Val = CRHS->getZExtValue();
3832 uint32_t ValLo = Lo_32(Val);
3833 uint32_t ValHi = Hi_32(Val);
3834 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3835
3836 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
3837 bitOpWithConstantIsReducible(Opc, ValHi)) ||
3838 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
3839 // If we need to materialize a 64-bit immediate, it will be split up later
3840 // anyway. Avoid creating the harder to understand 64-bit immediate
3841 // materialization.
3842 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
3843 }
3844
3845 return SDValue();
3846}
3847
3848SDValue SITargetLowering::performAndCombine(SDNode *N,
3849 DAGCombinerInfo &DCI) const {
3850 if (DCI.isBeforeLegalize())
3851 return SDValue();
3852
3853 SelectionDAG &DAG = DCI.DAG;
3854 EVT VT = N->getValueType(0);
3855 SDValue LHS = N->getOperand(0);
3856 SDValue RHS = N->getOperand(1);
3857
3858
3859 if (VT == MVT::i64) {
3860 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
3861 if (CRHS) {
3862 if (SDValue Split
3863 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
3864 return Split;
3865 }
3866 }
3867
3868 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
3869 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
3870 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
3871 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
3872 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
3873
3874 SDValue X = LHS.getOperand(0);
3875 SDValue Y = RHS.getOperand(0);
3876 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
3877 return SDValue();
3878
3879 if (LCC == ISD::SETO) {
3880 if (X != LHS.getOperand(1))
3881 return SDValue();
3882
3883 if (RCC == ISD::SETUNE) {
3884 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
3885 if (!C1 || !C1->isInfinity() || C1->isNegative())
3886 return SDValue();
3887
3888 const uint32_t Mask = SIInstrFlags::N_NORMAL |
3889 SIInstrFlags::N_SUBNORMAL |
3890 SIInstrFlags::N_ZERO |
3891 SIInstrFlags::P_ZERO |
3892 SIInstrFlags::P_SUBNORMAL |
3893 SIInstrFlags::P_NORMAL;
3894
3895 static_assert(((~(SIInstrFlags::S_NAN |
3896 SIInstrFlags::Q_NAN |
3897 SIInstrFlags::N_INFINITY |
3898 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
3899 "mask not equal");
3900
3901 SDLoc DL(N);
3902 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
3903 X, DAG.getConstant(Mask, DL, MVT::i32));
3904 }
3905 }
3906 }
3907
3908 return SDValue();
3909}
3910
3911SDValue SITargetLowering::performOrCombine(SDNode *N,
3912 DAGCombinerInfo &DCI) const {
3913 SelectionDAG &DAG = DCI.DAG;
3914 SDValue LHS = N->getOperand(0);
3915 SDValue RHS = N->getOperand(1);
3916
3917 EVT VT = N->getValueType(0);
3918 if (VT == MVT::i1) {
3919 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
3920 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
3921 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
3922 SDValue Src = LHS.getOperand(0);
3923 if (Src != RHS.getOperand(0))
3924 return SDValue();
3925
3926 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
3927 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
3928 if (!CLHS || !CRHS)
3929 return SDValue();
3930
3931 // Only 10 bits are used.
3932 static const uint32_t MaxMask = 0x3ff;
3933
3934 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
3935 SDLoc DL(N);
3936 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
3937 Src, DAG.getConstant(NewMask, DL, MVT::i32));
3938 }
3939
3940 return SDValue();
3941 }
3942
3943 if (VT != MVT::i64)
3944 return SDValue();
3945
3946 // TODO: This could be a generic combine with a predicate for extracting the
3947 // high half of an integer being free.
3948
3949 // (or i64:x, (zero_extend i32:y)) ->
3950 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
3951 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
3952 RHS.getOpcode() != ISD::ZERO_EXTEND)
3953 std::swap(LHS, RHS);
3954
3955 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
3956 SDValue ExtSrc = RHS.getOperand(0);
3957 EVT SrcVT = ExtSrc.getValueType();
3958 if (SrcVT == MVT::i32) {
3959 SDLoc SL(N);
3960 SDValue LowLHS, HiBits;
3961 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
3962 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
3963
3964 DCI.AddToWorklist(LowOr.getNode());
3965 DCI.AddToWorklist(HiBits.getNode());
3966
3967 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3968 LowOr, HiBits);
3969 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3970 }
3971 }
3972
3973 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3974 if (CRHS) {
3975 if (SDValue Split
3976 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
3977 return Split;
3978 }
3979
3980 return SDValue();
3981}
3982
3983SDValue SITargetLowering::performXorCombine(SDNode *N,
3984 DAGCombinerInfo &DCI) const {
3985 EVT VT = N->getValueType(0);
3986 if (VT != MVT::i64)
3987 return SDValue();
3988
3989 SDValue LHS = N->getOperand(0);
3990 SDValue RHS = N->getOperand(1);
3991
3992 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
3993 if (CRHS) {
3994 if (SDValue Split
3995 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
3996 return Split;
3997 }
3998
3999 return SDValue();
4000}
4001
4002SDValue SITargetLowering::performClassCombine(SDNode *N,
4003 DAGCombinerInfo &DCI) const {
4004 SelectionDAG &DAG = DCI.DAG;
4005 SDValue Mask = N->getOperand(1);
4006
4007 // fp_class x, 0 -> false
4008 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
4009 if (CMask->isNullValue())
4010 return DAG.getConstant(0, SDLoc(N), MVT::i1);
4011 }
4012
4013 if (N->getOperand(0).isUndef())
4014 return DAG.getUNDEF(MVT::i1);
4015
4016 return SDValue();
4017}
4018
4019// Constant fold canonicalize.
4020SDValue SITargetLowering::performFCanonicalizeCombine(
4021 SDNode *N,
4022 DAGCombinerInfo &DCI) const {
4023 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
4024 if (!CFP)
4025 return SDValue();
4026
4027 SelectionDAG &DAG = DCI.DAG;
4028 const APFloat &C = CFP->getValueAPF();
4029
4030 // Flush denormals to 0 if not enabled.
4031 if (C.isDenormal()) {
4032 EVT VT = N->getValueType(0);
4033 EVT SVT = VT.getScalarType();
4034 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
4035 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4036
4037 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
4038 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4039
4040 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
4041 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4042 }
4043
4044 if (C.isNaN()) {
4045 EVT VT = N->getValueType(0);
4046 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
4047 if (C.isSignaling()) {
4048 // Quiet a signaling NaN.
4049 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4050 }
4051
4052 // Make sure it is the canonical NaN bitpattern.
4053 //
4054 // TODO: Can we use -1 as the canonical NaN value since it's an inline
4055 // immediate?
4056 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
4057 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4058 }
4059
4060 return N->getOperand(0);
4061}
4062
4063static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
4064 switch (Opc) {
4065 case ISD::FMAXNUM:
4066 return AMDGPUISD::FMAX3;
4067 case ISD::SMAX:
4068 return AMDGPUISD::SMAX3;
4069 case ISD::UMAX:
4070 return AMDGPUISD::UMAX3;
4071 case ISD::FMINNUM:
4072 return AMDGPUISD::FMIN3;
4073 case ISD::SMIN:
4074 return AMDGPUISD::SMIN3;
4075 case ISD::UMIN:
4076 return AMDGPUISD::UMIN3;
4077 default:
4078 llvm_unreachable("Not a min/max opcode")::llvm::llvm_unreachable_internal("Not a min/max opcode", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4078)
;
4079 }
4080}
4081
4082SDValue SITargetLowering::performIntMed3ImmCombine(
4083 SelectionDAG &DAG, const SDLoc &SL,
4084 SDValue Op0, SDValue Op1, bool Signed) const {
4085 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
4086 if (!K1)
4087 return SDValue();
4088
4089 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
4090 if (!K0)
4091 return SDValue();
4092
4093 if (Signed) {
4094 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
4095 return SDValue();
4096 } else {
4097 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
4098 return SDValue();
4099 }
4100
4101 EVT VT = K0->getValueType(0);
4102 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
4103 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
4104 return DAG.getNode(Med3Opc, SL, VT,
4105 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
4106 }
4107
4108 // If there isn't a 16-bit med3 operation, convert to 32-bit.
4109 MVT NVT = MVT::i32;
4110 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4111
4112 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
4113 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
4114 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
4115
4116 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
4117 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
4118}
4119
4120static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
4121 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
4122 return true;
4123
4124 return DAG.isKnownNeverNaN(Op);
4125}
4126
4127SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
4128 const SDLoc &SL,
4129 SDValue Op0,
4130 SDValue Op1) const {
4131 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
4132 if (!K1)
4133 return SDValue();
4134
4135 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
4136 if (!K0)
4137 return SDValue();
4138
4139 // Ordered >= (although NaN inputs should have folded away by now).
4140 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
4141 if (Cmp == APFloat::cmpGreaterThan)
4142 return SDValue();
4143
4144 // TODO: Check IEEE bit enabled?
4145 EVT VT = K0->getValueType(0);
4146 if (Subtarget->enableDX10Clamp()) {
4147 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
4148 // hardware fmed3 behavior converting to a min.
4149 // FIXME: Should this be allowing -0.0?
4150 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
4151 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
4152 }
4153
4154 // med3 for f16 is only available on gfx9+.
4155 if (VT == MVT::f64 || (VT == MVT::f16 && !Subtarget->hasMed3_16()))
4156 return SDValue();
4157
4158 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
4159 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
4160 // give the other result, which is different from med3 with a NaN input.
4161 SDValue Var = Op0.getOperand(0);
4162 if (!isKnownNeverSNan(DAG, Var))
4163 return SDValue();
4164
4165 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
4166 Var, SDValue(K0, 0), SDValue(K1, 0));
4167}
4168
4169SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
4170 DAGCombinerInfo &DCI) const {
4171 SelectionDAG &DAG = DCI.DAG;
4172
4173 EVT VT = N->getValueType(0);
4174 unsigned Opc = N->getOpcode();
4175 SDValue Op0 = N->getOperand(0);
4176 SDValue Op1 = N->getOperand(1);
4177
4178 // Only do this if the inner op has one use since this will just increases
4179 // register pressure for no benefit.
4180
4181
4182 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
4183 VT != MVT::f64) {
4184 // max(max(a, b), c) -> max3(a, b, c)
4185 // min(min(a, b), c) -> min3(a, b, c)
4186 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
4187 SDLoc DL(N);
4188 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4189 DL,
4190 N->getValueType(0),
4191 Op0.getOperand(0),
4192 Op0.getOperand(1),
4193 Op1);
4194 }
4195
4196 // Try commuted.
4197 // max(a, max(b, c)) -> max3(a, b, c)
4198 // min(a, min(b, c)) -> min3(a, b, c)
4199 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
4200 SDLoc DL(N);
4201 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4202 DL,
4203 N->getValueType(0),
4204 Op0,
4205 Op1.getOperand(0),
4206 Op1.getOperand(1));
4207 }
4208 }
4209
4210 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
4211 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
4212 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
4213 return Med3;
4214 }
4215
4216 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4217 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
4218 return Med3;
4219 }
4220
4221 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
4222 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
4223 (Opc == AMDGPUISD::FMIN_LEGACY &&
4224 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
4225 (VT == MVT::f32 || VT == MVT::f64 ||
4226 (VT == MVT::f16 && Subtarget->has16BitInsts())) &&
4227 Op0.hasOneUse()) {
4228 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
4229 return Res;
4230 }
4231
4232 return SDValue();
4233}
4234
4235static bool isClampZeroToOne(SDValue A, SDValue B) {
4236 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
4237 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
4238 // FIXME: Should this be allowing -0.0?
4239 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
4240 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
4241 }
4242 }
4243
4244 return false;
4245}
4246
4247// FIXME: Should only worry about snans for version with chain.
4248SDValue SITargetLowering::performFMed3Combine(SDNode *N,
4249 DAGCombinerInfo &DCI) const {
4250 EVT VT = N->getValueType(0);
4251 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
4252 // NaNs. With a NaN input, the order of the operands may change the result.
4253
4254 SelectionDAG &DAG = DCI.DAG;
4255 SDLoc SL(N);
4256
4257 SDValue Src0 = N->getOperand(0);
4258 SDValue Src1 = N->getOperand(1);
4259 SDValue Src2 = N->getOperand(2);
4260
4261 if (isClampZeroToOne(Src0, Src1)) {
4262 // const_a, const_b, x -> clamp is safe in all cases including signaling
4263 // nans.
4264 // FIXME: Should this be allowing -0.0?
4265 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
4266 }
4267
4268 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
4269 // handling no dx10-clamp?
4270 if (Subtarget->enableDX10Clamp()) {
4271 // If NaNs is clamped to 0, we are free to reorder the inputs.
4272
4273 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4274 std::swap(Src0, Src1);
4275
4276 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
4277 std::swap(Src1, Src2);
4278
4279 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4280 std::swap(Src0, Src1);
4281
4282 if (isClampZeroToOne(Src1, Src2))
4283 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
4284 }
4285
4286 return SDValue();
4287}
4288
4289SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
4290 DAGCombinerInfo &DCI) const {
4291 SDValue Src0 = N->getOperand(0);
4292 SDValue Src1 = N->getOperand(1);
4293 if (Src0.isUndef() && Src1.isUndef())
4294 return DCI.DAG.getUNDEF(N->getValueType(0));
4295 return SDValue();
4296}
4297
4298unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
4299 const SDNode *N0,
4300 const SDNode *N1) const {
4301 EVT VT = N0->getValueType(0);
4302
4303 // Only do this if we are not trying to support denormals. v_mad_f32 does not
4304 // support denormals ever.
4305 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
4306 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
4307 return ISD::FMAD;
4308
4309 const TargetOptions &Options = DAG.getTarget().Options;
4310 if ((Options.AllowFPOpFusion == FPOpFusion::Fast ||
4311 Options.UnsafeFPMath ||
4312 (cast<BinaryWithFlagsSDNode>(N0)->Flags.hasUnsafeAlgebra() &&
4313 cast<BinaryWithFlagsSDNode>(N1)->Flags.hasUnsafeAlgebra())) &&
4314 isFMAFasterThanFMulAndFAdd(VT)) {
4315 return ISD::FMA;
4316 }
4317
4318 return 0;
4319}
4320
4321SDValue SITargetLowering::performFAddCombine(SDNode *N,
4322 DAGCombinerInfo &DCI) const {
4323 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4324 return SDValue();
4325
4326 SelectionDAG &DAG = DCI.DAG;
4327 EVT VT = N->getValueType(0);
4328
4329 SDLoc SL(N);
4330 SDValue LHS = N->getOperand(0);
4331 SDValue RHS = N->getOperand(1);
4332
4333 // These should really be instruction patterns, but writing patterns with
4334 // source modiifiers is a pain.
4335
4336 // fadd (fadd (a, a), b) -> mad 2.0, a, b
4337 if (LHS.getOpcode() == ISD::FADD) {
4338 SDValue A = LHS.getOperand(0);
4339 if (A == LHS.getOperand(1)) {
4340 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4341 if (FusedOp != 0) {
4342 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4343 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
4344 }
4345 }
4346 }
4347
4348 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
4349 if (RHS.getOpcode() == ISD::FADD) {
4350 SDValue A = RHS.getOperand(0);
4351 if (A == RHS.getOperand(1)) {
4352 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4353 if (FusedOp != 0) {
4354 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4355 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
4356 }
4357 }
4358 }
4359
4360 return SDValue();
4361}
4362
4363SDValue SITargetLowering::performFSubCombine(SDNode *N,
4364 DAGCombinerInfo &DCI) const {
4365 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4366 return SDValue();
4367
4368 SelectionDAG &DAG = DCI.DAG;
4369 SDLoc SL(N);
4370 EVT VT = N->getValueType(0);
4371 assert(!VT.isVector())((!VT.isVector()) ? static_cast<void> (0) : __assert_fail
("!VT.isVector()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4371, __PRETTY_FUNCTION__))
;
4372
4373 // Try to get the fneg to fold into the source modifier. This undoes generic
4374 // DAG combines and folds them into the mad.
4375 //
4376 // Only do this if we are not trying to support denormals. v_mad_f32 does
4377 // not support denormals ever.
4378 SDValue LHS = N->getOperand(0);
4379 SDValue RHS = N->getOperand(1);
4380 if (LHS.getOpcode() == ISD::FADD) {
4381 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
4382 SDValue A = LHS.getOperand(0);
4383 if (A == LHS.getOperand(1)) {
4384 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4385 if (FusedOp != 0){
4386 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4387 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
4388
4389 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
4390 }
4391 }
4392 }
4393
4394 if (RHS.getOpcode() == ISD::FADD) {
4395 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
4396
4397 SDValue A = RHS.getOperand(0);
4398 if (A == RHS.getOperand(1)) {
4399 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4400 if (FusedOp != 0){
4401 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
4402 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
4403 }
4404 }
4405 }
4406
4407 return SDValue();
4408}
4409
4410SDValue SITargetLowering::performSetCCCombine(SDNode *N,
4411 DAGCombinerInfo &DCI) const {
4412 SelectionDAG &DAG = DCI.DAG;
4413 SDLoc SL(N);
4414
4415 SDValue LHS = N->getOperand(0);
4416 SDValue RHS = N->getOperand(1);
4417 EVT VT = LHS.getValueType();
4418
4419 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
4420 VT != MVT::f16))
4421 return SDValue();
4422
4423 // Match isinf pattern
4424 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
4425 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
4426 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
4427 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
4428 if (!CRHS)
4429 return SDValue();
4430
4431 const APFloat &APF = CRHS->getValueAPF();
4432 if (APF.isInfinity() && !APF.isNegative()) {
4433 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
4434 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
4435 DAG.getConstant(Mask, SL, MVT::i32));
4436 }
4437 }
4438
4439 return SDValue();
4440}
4441
4442SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
4443 DAGCombinerInfo &DCI) const {
4444 SelectionDAG &DAG = DCI.DAG;
4445 SDLoc SL(N);
4446 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
4447
4448 SDValue Src = N->getOperand(0);
4449 SDValue Srl = N->getOperand(0);
4450 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
4451 Srl = Srl.getOperand(0);
4452
4453 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
4454 if (Srl.getOpcode() == ISD::SRL) {
4455 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
4456 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
4457 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
4458
4459 if (const ConstantSDNode *C =
4460 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
4461 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
4462 EVT(MVT::i32));
4463
4464 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
4465 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
4466 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
4467 MVT::f32, Srl);
4468 }
4469 }
4470 }
4471
4472 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
4473
4474 APInt KnownZero, KnownOne;
4475 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4476 !DCI.isBeforeLegalizeOps());
4477 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4478 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
4479 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
4480 DCI.CommitTargetLoweringOpt(TLO);
4481 }
4482
4483 return SDValue();
4484}
4485
4486SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
4487 DAGCombinerInfo &DCI) const {
4488 switch (N->getOpcode()) {
4489 default:
4490 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4491 case ISD::FADD:
4492 return performFAddCombine(N, DCI);
4493 case ISD::FSUB:
4494 return performFSubCombine(N, DCI);
4495 case ISD::SETCC:
4496 return performSetCCCombine(N, DCI);
4497 case ISD::FMAXNUM:
4498 case ISD::FMINNUM:
4499 case ISD::SMAX:
4500 case ISD::SMIN:
4501 case ISD::UMAX:
4502 case ISD::UMIN:
4503 case AMDGPUISD::FMIN_LEGACY:
4504 case AMDGPUISD::FMAX_LEGACY: {
4505 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
4506 getTargetMachine().getOptLevel() > CodeGenOpt::None)
4507 return performMinMaxCombine(N, DCI);
4508 break;
4509 }
4510 case ISD::LOAD:
4511 case ISD::STORE:
4512 case ISD::ATOMIC_LOAD:
4513 case ISD::ATOMIC_STORE:
4514 case ISD::ATOMIC_CMP_SWAP:
4515 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4516 case ISD::ATOMIC_SWAP:
4517 case ISD::ATOMIC_LOAD_ADD:
4518 case ISD::ATOMIC_LOAD_SUB:
4519 case ISD::ATOMIC_LOAD_AND:
4520 case ISD::ATOMIC_LOAD_OR:
4521 case ISD::ATOMIC_LOAD_XOR:
4522 case ISD::ATOMIC_LOAD_NAND:
4523 case ISD::ATOMIC_LOAD_MIN:
4524 case ISD::ATOMIC_LOAD_MAX:
4525 case ISD::ATOMIC_LOAD_UMIN:
4526 case ISD::ATOMIC_LOAD_UMAX:
4527 case AMDGPUISD::ATOMIC_INC:
4528 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics.
4529 if (DCI.isBeforeLegalize())
4530 break;
4531 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
4532 case ISD::AND:
4533 return performAndCombine(N, DCI);
4534 case ISD::OR:
4535 return performOrCombine(N, DCI);
4536 case ISD::XOR:
4537 return performXorCombine(N, DCI);
4538 case AMDGPUISD::FP_CLASS:
4539 return performClassCombine(N, DCI);
4540 case ISD::FCANONICALIZE:
4541 return performFCanonicalizeCombine(N, DCI);
4542 case AMDGPUISD::FRACT:
4543 case AMDGPUISD::RCP:
4544 case AMDGPUISD::RSQ:
4545 case AMDGPUISD::RCP_LEGACY:
4546 case AMDGPUISD::RSQ_LEGACY:
4547 case AMDGPUISD::RSQ_CLAMP:
4548 case AMDGPUISD::LDEXP: {
4549 SDValue Src = N->getOperand(0);
4550 if (Src.isUndef())
4551 return Src;
4552 break;
4553 }
4554 case ISD::SINT_TO_FP:
4555 case ISD::UINT_TO_FP:
4556 return performUCharToFloatCombine(N, DCI);
4557 case AMDGPUISD::CVT_F32_UBYTE0:
4558 case AMDGPUISD::CVT_F32_UBYTE1:
4559 case AMDGPUISD::CVT_F32_UBYTE2:
4560 case AMDGPUISD::CVT_F32_UBYTE3:
4561 return performCvtF32UByteNCombine(N, DCI);
4562 case AMDGPUISD::FMED3:
4563 return performFMed3Combine(N, DCI);
4564 case AMDGPUISD::CVT_PKRTZ_F16_F32:
4565 return performCvtPkRTZCombine(N, DCI);
4566 case ISD::SCALAR_TO_VECTOR: {
4567 SelectionDAG &DAG = DCI.DAG;
4568 EVT VT = N->getValueType(0);
4569
4570 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
4571 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
4572 SDLoc SL(N);
4573 SDValue Src = N->getOperand(0);
4574 EVT EltVT = Src.getValueType();
4575 if (EltVT == MVT::f16)
4576 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
4577
4578 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
4579 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
4580 }
4581
4582 break;
4583 }
4584 }
4585 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4586}
4587
4588/// \brief Helper function for adjustWritemask
4589static unsigned SubIdx2Lane(unsigned Idx) {
4590 switch (Idx) {
4591 default: return 0;
4592 case AMDGPU::sub0: return 0;
4593 case AMDGPU::sub1: return 1;
4594 case AMDGPU::sub2: return 2;
4595 case AMDGPU::sub3: return 3;
4596 }
4597}
4598
4599/// \brief Adjust the writemask of MIMG instructions
4600void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
4601 SelectionDAG &DAG) const {
4602 SDNode *Users[4] = { };
4603 unsigned Lane = 0;
4604 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
4605 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
4606 unsigned NewDmask = 0;
4607
4608 // Try to figure out the used register components
4609 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
4610 I != E; ++I) {
4611
4612 // Don't look at users of the chain.
4613 if (I.getUse().getResNo() != 0)
4614 continue;
4615
4616 // Abort if we can't understand the usage
4617 if (!I->isMachineOpcode() ||
4618 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
4619 return;
4620
4621 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
4622 // Note that subregs are packed, i.e. Lane==0 is the first bit set
4623 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
4624 // set, etc.
4625 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
4626
4627 // Set which texture component corresponds to the lane.
4628 unsigned Comp;
4629 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
4630 assert(Dmask)((Dmask) ? static_cast<void> (0) : __assert_fail ("Dmask"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4630, __PRETTY_FUNCTION__))
;
4631 Comp = countTrailingZeros(Dmask);
4632 Dmask &= ~(1 << Comp);
4633 }
4634
4635 // Abort if we have more than one user per component
4636 if (Users[Lane])
4637 return;
4638
4639 Users[Lane] = *I;
4640 NewDmask |= 1 << Comp;
4641 }
4642
4643 // Abort if there's no change
4644 if (NewDmask == OldDmask)
4645 return;
4646
4647 // Adjust the writemask in the node
4648 std::vector<SDValue> Ops;
4649 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
4650 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
4651 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
4652 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
4653
4654 // If we only got one lane, replace it with a copy
4655 // (if NewDmask has only one bit set...)
4656 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
4657 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
4658 MVT::i32);
4659 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4660 SDLoc(), Users[Lane]->getValueType(0),
4661 SDValue(Node, 0), RC);
4662 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
4663 return;
4664 }
4665
4666 // Update the users of the node with the new indices
4667 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
4668 SDNode *User = Users[i];
4669 if (!User)
4670 continue;
4671
4672 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
4673 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
4674
4675 switch (Idx) {
4676 default: break;
4677 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
4678 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
4679 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
4680 }
4681 }
4682}
4683
4684static bool isFrameIndexOp(SDValue Op) {
4685 if (Op.getOpcode() == ISD::AssertZext)
4686 Op = Op.getOperand(0);
4687
4688 return isa<FrameIndexSDNode>(Op);
4689}
4690
4691/// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
4692/// with frame index operands.
4693/// LLVM assumes that inputs are to these instructions are registers.
4694void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
4695 SelectionDAG &DAG) const {
4696
4697 SmallVector<SDValue, 8> Ops;
4698 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
4699 if (!isFrameIndexOp(Node->getOperand(i))) {
4700 Ops.push_back(Node->getOperand(i));
4701 continue;
4702 }
4703
4704 SDLoc DL(Node);
4705 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
4706 Node->getOperand(i).getValueType(),
4707 Node->getOperand(i)), 0));
4708 }
4709
4710 DAG.UpdateNodeOperands(Node, Ops);
4711}
4712
4713/// \brief Fold the instructions after selecting them.
4714SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
4715 SelectionDAG &DAG) const {
4716 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4717 unsigned Opcode = Node->getMachineOpcode();
4718
4719 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
4720 !TII->isGather4(Opcode))
4721 adjustWritemask(Node, DAG);
4722
4723 if (Opcode == AMDGPU::INSERT_SUBREG ||
4724 Opcode == AMDGPU::REG_SEQUENCE) {
4725 legalizeTargetIndependentNode(Node, DAG);
4726 return Node;
4727 }
4728 return Node;
4729}
4730
4731/// \brief Assign the register class depending on the number of
4732/// bits set in the writemask
4733void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
4734 SDNode *Node) const {
4735 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4736
4737 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4738
4739 if (TII->isVOP3(MI.getOpcode())) {
4740 // Make sure constant bus requirements are respected.
4741 TII->legalizeOperandsVOP3(MRI, MI);
4742 return;
4743 }
4744
4745 if (TII->isMIMG(MI)) {
4746 unsigned VReg = MI.getOperand(0).getReg();
4747 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
4748 // TODO: Need mapping tables to handle other cases (register classes).
4749 if (RC != &AMDGPU::VReg_128RegClass)
4750 return;
4751
4752 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4;
4753 unsigned Writemask = MI.getOperand(DmaskIdx).getImm();
4754 unsigned BitsSet = 0;
4755 for (unsigned i = 0; i < 4; ++i)
4756 BitsSet += Writemask & (1 << i) ? 1 : 0;
4757 switch (BitsSet) {
4758 default: return;
4759 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
4760 case 2: RC = &AMDGPU::VReg_64RegClass; break;
4761 case 3: RC = &AMDGPU::VReg_96RegClass; break;
4762 }
4763
4764 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet);
4765 MI.setDesc(TII->get(NewOpcode));
4766 MRI.setRegClass(VReg, RC);
4767 return;
4768 }
4769
4770 // Replace unused atomics with the no return version.
4771 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
4772 if (NoRetAtomicOp != -1) {
4773 if (!Node->hasAnyUseOfValue(0)) {
4774 MI.setDesc(TII->get(NoRetAtomicOp));
4775 MI.RemoveOperand(0);
4776 return;
4777 }
4778
4779 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
4780 // instruction, because the return type of these instructions is a vec2 of
4781 // the memory type, so it can be tied to the input operand.
4782 // This means these instructions always have a use, so we need to add a
4783 // special case to check if the atomic has only one extract_subreg use,
4784 // which itself has no uses.
4785 if ((Node->hasNUsesOfValue(1, 0) &&
4786 Node->use_begin()->isMachineOpcode() &&
4787 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
4788 !Node->use_begin()->hasAnyUseOfValue(0))) {
4789 unsigned Def = MI.getOperand(0).getReg();
4790
4791 // Change this into a noret atomic.
4792 MI.setDesc(TII->get(NoRetAtomicOp));
4793 MI.RemoveOperand(0);
4794
4795 // If we only remove the def operand from the atomic instruction, the
4796 // extract_subreg will be left with a use of a vreg without a def.
4797 // So we need to insert an implicit_def to avoid machine verifier
4798 // errors.
4799 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
4800 TII->get(AMDGPU::IMPLICIT_DEF), Def);
4801 }
4802 return;
4803 }
4804}
4805
4806static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
4807 uint64_t Val) {
4808 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
4809 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
4810}
4811
4812MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
4813 const SDLoc &DL,
4814 SDValue Ptr) const {
4815 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4816
4817 // Build the half of the subregister with the constants before building the
4818 // full 128-bit register. If we are building multiple resource descriptors,
4819 // this will allow CSEing of the 2-component register.
4820 const SDValue Ops0[] = {
4821 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
4822 buildSMovImm32(DAG, DL, 0),
4823 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
4824 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
4825 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
4826 };
4827
4828 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
4829 MVT::v2i32, Ops0), 0);
4830
4831 // Combine the constants and the pointer.
4832 const SDValue Ops1[] = {
4833 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
4834 Ptr,
4835 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
4836 SubRegHi,
4837 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
4838 };
4839
4840 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
4841}
4842
4843/// \brief Return a resource descriptor with the 'Add TID' bit enabled
4844/// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
4845/// of the resource descriptor) to create an offset, which is added to
4846/// the resource pointer.
4847MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
4848 SDValue Ptr, uint32_t RsrcDword1,
4849 uint64_t RsrcDword2And3) const {
4850 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
4851 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
4852 if (RsrcDword1) {
4853 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
4854 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
4855 0);
4856 }
4857
4858 SDValue DataLo = buildSMovImm32(DAG, DL,
4859 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)0xFFFFFFFFUL);
4860 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
4861
4862 const SDValue Ops[] = {
4863 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
4864 PtrLo,
4865 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
4866 PtrHi,
4867 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
4868 DataLo,
4869 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
4870 DataHi,
4871 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
4872 };
4873
4874 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
4875}
4876
4877SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
4878 const TargetRegisterClass *RC,
4879 unsigned Reg, EVT VT) const {
4880 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
4881
4882 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
4883 cast<RegisterSDNode>(VReg)->getReg(), VT);
4884}
4885
4886//===----------------------------------------------------------------------===//
4887// SI Inline Assembly Support
4888//===----------------------------------------------------------------------===//
4889
4890std::pair<unsigned, const TargetRegisterClass *>
4891SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4892 StringRef Constraint,
4893 MVT VT) const {
4894 if (!isTypeLegal(VT))
4895 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4896
4897 if (Constraint.size() == 1) {
4898 switch (Constraint[0]) {
4899 case 's':
4900 case 'r':
4901 switch (VT.getSizeInBits()) {
4902 default:
4903 return std::make_pair(0U, nullptr);
4904 case 32:
4905 case 16:
4906 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
4907 case 64:
4908 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
4909 case 128:
4910 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
4911 case 256:
4912 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
4913 case 512:
4914 return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
4915 }
4916
4917 case 'v':
4918 switch (VT.getSizeInBits()) {
4919 default:
4920 return std::make_pair(0U, nullptr);
4921 case 32:
4922 case 16:
4923 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
4924 case 64:
4925 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
4926 case 96:
4927 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
4928 case 128:
4929 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
4930 case 256:
4931 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
4932 case 512:
4933 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
4934 }
4935 }
4936 }
4937
4938 if (Constraint.size() > 1) {
4939 const TargetRegisterClass *RC = nullptr;
4940 if (Constraint[1] == 'v') {
4941 RC = &AMDGPU::VGPR_32RegClass;
4942 } else if (Constraint[1] == 's') {
4943 RC = &AMDGPU::SGPR_32RegClass;
4944 }
4945
4946 if (RC) {
4947 uint32_t Idx;
4948 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
4949 if (!Failed && Idx < RC->getNumRegs())
4950 return std::make_pair(RC->getRegister(Idx), RC);
4951 }
4952 }
4953 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4954}
4955
4956SITargetLowering::ConstraintType
4957SITargetLowering::getConstraintType(StringRef Constraint) const {
4958 if (Constraint.size() == 1) {
4959 switch (Constraint[0]) {
4960 default: break;
4961 case 's':
4962 case 'v':
4963 return C_RegisterClass;
4964 }
4965 }
4966 return TargetLowering::getConstraintType(Constraint);
4967}