Bug Summary

File:lib/Target/AMDGPU/SIISelLowering.cpp
Warning:line 6665, column 52
Called C++ object pointer is null

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 "SIISelLowering.h"
21#include "AMDGPU.h"
22#include "AMDGPUIntrinsicInfo.h"
23#include "AMDGPUSubtarget.h"
24#include "AMDGPUTargetMachine.h"
25#include "SIDefines.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/Statistic.h"
36#include "llvm/ADT/StringRef.h"
37#include "llvm/ADT/StringSwitch.h"
38#include "llvm/ADT/Twine.h"
39#include "llvm/CodeGen/Analysis.h"
40#include "llvm/CodeGen/CallingConvLower.h"
41#include "llvm/CodeGen/DAGCombine.h"
42#include "llvm/CodeGen/ISDOpcodes.h"
43#include "llvm/CodeGen/MachineBasicBlock.h"
44#include "llvm/CodeGen/MachineFrameInfo.h"
45#include "llvm/CodeGen/MachineFunction.h"
46#include "llvm/CodeGen/MachineInstr.h"
47#include "llvm/CodeGen/MachineInstrBuilder.h"
48#include "llvm/CodeGen/MachineMemOperand.h"
49#include "llvm/CodeGen/MachineModuleInfo.h"
50#include "llvm/CodeGen/MachineOperand.h"
51#include "llvm/CodeGen/MachineRegisterInfo.h"
52#include "llvm/CodeGen/MachineValueType.h"
53#include "llvm/CodeGen/SelectionDAG.h"
54#include "llvm/CodeGen/SelectionDAGNodes.h"
55#include "llvm/CodeGen/TargetCallingConv.h"
56#include "llvm/CodeGen/TargetRegisterInfo.h"
57#include "llvm/CodeGen/ValueTypes.h"
58#include "llvm/IR/Constants.h"
59#include "llvm/IR/DataLayout.h"
60#include "llvm/IR/DebugLoc.h"
61#include "llvm/IR/DerivedTypes.h"
62#include "llvm/IR/DiagnosticInfo.h"
63#include "llvm/IR/Function.h"
64#include "llvm/IR/GlobalValue.h"
65#include "llvm/IR/InstrTypes.h"
66#include "llvm/IR/Instruction.h"
67#include "llvm/IR/Instructions.h"
68#include "llvm/IR/IntrinsicInst.h"
69#include "llvm/IR/Type.h"
70#include "llvm/Support/Casting.h"
71#include "llvm/Support/CodeGen.h"
72#include "llvm/Support/CommandLine.h"
73#include "llvm/Support/Compiler.h"
74#include "llvm/Support/ErrorHandling.h"
75#include "llvm/Support/KnownBits.h"
76#include "llvm/Support/MathExtras.h"
77#include "llvm/Target/TargetOptions.h"
78#include <cassert>
79#include <cmath>
80#include <cstdint>
81#include <iterator>
82#include <tuple>
83#include <utility>
84#include <vector>
85
86using namespace llvm;
87
88#define DEBUG_TYPE"si-lower" "si-lower"
89
90STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"si-lower", "NumTailCalls"
, "Number of tail calls", {0}, false}
;
91
92static cl::opt<bool> EnableVGPRIndexMode(
93 "amdgpu-vgpr-index-mode",
94 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
95 cl::init(false));
96
97static cl::opt<unsigned> AssumeFrameIndexHighZeroBits(
98 "amdgpu-frame-index-zero-bits",
99 cl::desc("High bits of frame index assumed to be zero"),
100 cl::init(5),
101 cl::ReallyHidden);
102
103static unsigned findFirstFreeSGPR(CCState &CCInfo) {
104 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
105 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
106 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
107 return AMDGPU::SGPR0 + Reg;
108 }
109 }
110 llvm_unreachable("Cannot allocate sgpr")::llvm::llvm_unreachable_internal("Cannot allocate sgpr", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 110)
;
111}
112
113SITargetLowering::SITargetLowering(const TargetMachine &TM,
114 const SISubtarget &STI)
115 : AMDGPUTargetLowering(TM, STI) {
116 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
117 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
118
119 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
120 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
121
122 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
123 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
124 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
125
126 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
127 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
128
129 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
130 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
131
132 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
133 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
134
135 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
136 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
137
138 if (Subtarget->has16BitInsts()) {
139 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
140 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
141 }
142
143 if (Subtarget->hasVOP3PInsts()) {
144 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
145 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
146 }
147
148 computeRegisterProperties(STI.getRegisterInfo());
149
150 // We need to custom lower vector stores from local memory
151 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
152 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
153 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
154 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
155 setOperationAction(ISD::LOAD, MVT::i1, Custom);
156
157 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
158 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
159 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
160 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
161 setOperationAction(ISD::STORE, MVT::i1, Custom);
162
163 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
164 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
165 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
166 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
167 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
168 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
169 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
170 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
171 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
172 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
173
174 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
175 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
176 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
177
178 setOperationAction(ISD::SELECT, MVT::i1, Promote);
179 setOperationAction(ISD::SELECT, MVT::i64, Custom);
180 setOperationAction(ISD::SELECT, MVT::f64, Promote);
181 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
182
183 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
184 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
185 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
186 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
187 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
188
189 setOperationAction(ISD::SETCC, MVT::i1, Promote);
190 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
191 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
192 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
193
194 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
195 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
196
197 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
198 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
199 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
200 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
201 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
204
205 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
206 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
207 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
208 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
209
210 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
211
212 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
213 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
214 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
215
216 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
217 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
218 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
219 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
220 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
221 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
222
223 setOperationAction(ISD::UADDO, MVT::i32, Legal);
224 setOperationAction(ISD::USUBO, MVT::i32, Legal);
225
226 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
227 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
228
229#if 0
230 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
231 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
232#endif
233
234 //setOperationAction(ISD::ADDC, MVT::i64, Expand);
235 //setOperationAction(ISD::SUBC, MVT::i64, Expand);
236
237 // We only support LOAD/STORE and vector manipulation ops for vectors
238 // with > 4 elements.
239 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
240 MVT::v2i64, MVT::v2f64}) {
241 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
242 switch (Op) {
243 case ISD::LOAD:
244 case ISD::STORE:
245 case ISD::BUILD_VECTOR:
246 case ISD::BITCAST:
247 case ISD::EXTRACT_VECTOR_ELT:
248 case ISD::INSERT_VECTOR_ELT:
249 case ISD::INSERT_SUBVECTOR:
250 case ISD::EXTRACT_SUBVECTOR:
251 case ISD::SCALAR_TO_VECTOR:
252 break;
253 case ISD::CONCAT_VECTORS:
254 setOperationAction(Op, VT, Custom);
255 break;
256 default:
257 setOperationAction(Op, VT, Expand);
258 break;
259 }
260 }
261 }
262
263 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
264 // is expanded to avoid having two separate loops in case the index is a VGPR.
265
266 // Most operations are naturally 32-bit vector operations. We only support
267 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
268 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
269 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
270 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
271
272 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
273 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
274
275 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
276 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
277
278 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
279 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
280 }
281
282 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
283 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
284 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
285 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
286
287 // Avoid stack access for these.
288 // TODO: Generalize to more vector types.
289 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
290 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
291 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
292 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
293
294 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
295 // and output demarshalling
296 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
297 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
298
299 // We can't return success/failure, only the old value,
300 // let LLVM add the comparison
301 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
302 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
303
304 if (getSubtarget()->hasFlatAddressSpace()) {
305 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
306 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
307 }
308
309 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
310 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
311
312 // On SI this is s_memtime and s_memrealtime on VI.
313 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
314 setOperationAction(ISD::TRAP, MVT::Other, Custom);
315 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
316
317 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
318 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
319
320 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
321 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
322 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
323 setOperationAction(ISD::FRINT, MVT::f64, Legal);
324 }
325
326 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
327
328 setOperationAction(ISD::FSIN, MVT::f32, Custom);
329 setOperationAction(ISD::FCOS, MVT::f32, Custom);
330 setOperationAction(ISD::FDIV, MVT::f32, Custom);
331 setOperationAction(ISD::FDIV, MVT::f64, Custom);
332
333 if (Subtarget->has16BitInsts()) {
334 setOperationAction(ISD::Constant, MVT::i16, Legal);
335
336 setOperationAction(ISD::SMIN, MVT::i16, Legal);
337 setOperationAction(ISD::SMAX, MVT::i16, Legal);
338
339 setOperationAction(ISD::UMIN, MVT::i16, Legal);
340 setOperationAction(ISD::UMAX, MVT::i16, Legal);
341
342 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
343 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
344
345 setOperationAction(ISD::ROTR, MVT::i16, Promote);
346 setOperationAction(ISD::ROTL, MVT::i16, Promote);
347
348 setOperationAction(ISD::SDIV, MVT::i16, Promote);
349 setOperationAction(ISD::UDIV, MVT::i16, Promote);
350 setOperationAction(ISD::SREM, MVT::i16, Promote);
351 setOperationAction(ISD::UREM, MVT::i16, Promote);
352
353 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
354 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
355
356 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
357 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
358 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
360
361 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
362
363 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
364
365 setOperationAction(ISD::LOAD, MVT::i16, Custom);
366
367 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
368
369 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
370 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
371 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
372 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
373
374 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
375 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
376 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
377 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
378
379 // F16 - Constant Actions.
380 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
381
382 // F16 - Load/Store Actions.
383 setOperationAction(ISD::LOAD, MVT::f16, Promote);
384 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
385 setOperationAction(ISD::STORE, MVT::f16, Promote);
386 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
387
388 // F16 - VOP1 Actions.
389 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
390 setOperationAction(ISD::FCOS, MVT::f16, Promote);
391 setOperationAction(ISD::FSIN, MVT::f16, Promote);
392 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
393 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
394 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
395 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
396 setOperationAction(ISD::FROUND, MVT::f16, Custom);
397
398 // F16 - VOP2 Actions.
399 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
400 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
401 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
402 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
403 setOperationAction(ISD::FDIV, MVT::f16, Custom);
404
405 // F16 - VOP3 Actions.
406 setOperationAction(ISD::FMA, MVT::f16, Legal);
407 if (!Subtarget->hasFP16Denormals())
408 setOperationAction(ISD::FMAD, MVT::f16, Legal);
409 }
410
411 if (Subtarget->hasVOP3PInsts()) {
412 for (MVT VT : {MVT::v2i16, MVT::v2f16}) {
413 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
414 switch (Op) {
415 case ISD::LOAD:
416 case ISD::STORE:
417 case ISD::BUILD_VECTOR:
418 case ISD::BITCAST:
419 case ISD::EXTRACT_VECTOR_ELT:
420 case ISD::INSERT_VECTOR_ELT:
421 case ISD::INSERT_SUBVECTOR:
422 case ISD::EXTRACT_SUBVECTOR:
423 case ISD::SCALAR_TO_VECTOR:
424 break;
425 case ISD::CONCAT_VECTORS:
426 setOperationAction(Op, VT, Custom);
427 break;
428 default:
429 setOperationAction(Op, VT, Expand);
430 break;
431 }
432 }
433 }
434
435 // XXX - Do these do anything? Vector constants turn into build_vector.
436 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
437 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
438
439 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
440 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
441 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
442 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
443
444 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
445 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
446 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
447 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
448
449 setOperationAction(ISD::AND, MVT::v2i16, Promote);
450 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
451 setOperationAction(ISD::OR, MVT::v2i16, Promote);
452 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
453 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
454 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
455 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
456 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
457 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
458 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
459
460 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
461 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
462 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
463 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
464 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
465 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
466 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
467 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
468 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
469 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
470
471 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
472 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
473 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
474 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
475 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
476 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
477
478 // This isn't really legal, but this avoids the legalizer unrolling it (and
479 // allows matching fneg (fabs x) patterns)
480 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
481
482 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
483 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
484
485 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
486 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
487 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
488 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
489 } else {
490 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
491 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
492 }
493
494 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
495 setOperationAction(ISD::SELECT, VT, Custom);
496 }
497
498 setTargetDAGCombine(ISD::ADD);
499 setTargetDAGCombine(ISD::ADDCARRY);
500 setTargetDAGCombine(ISD::SUB);
501 setTargetDAGCombine(ISD::SUBCARRY);
502 setTargetDAGCombine(ISD::FADD);
503 setTargetDAGCombine(ISD::FSUB);
504 setTargetDAGCombine(ISD::FMINNUM);
505 setTargetDAGCombine(ISD::FMAXNUM);
506 setTargetDAGCombine(ISD::SMIN);
507 setTargetDAGCombine(ISD::SMAX);
508 setTargetDAGCombine(ISD::UMIN);
509 setTargetDAGCombine(ISD::UMAX);
510 setTargetDAGCombine(ISD::SETCC);
511 setTargetDAGCombine(ISD::AND);
512 setTargetDAGCombine(ISD::OR);
513 setTargetDAGCombine(ISD::XOR);
514 setTargetDAGCombine(ISD::SINT_TO_FP);
515 setTargetDAGCombine(ISD::UINT_TO_FP);
516 setTargetDAGCombine(ISD::FCANONICALIZE);
517 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
518 setTargetDAGCombine(ISD::ZERO_EXTEND);
519 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
520 setTargetDAGCombine(ISD::BUILD_VECTOR);
521
522 // All memory operations. Some folding on the pointer operand is done to help
523 // matching the constant offsets in the addressing modes.
524 setTargetDAGCombine(ISD::LOAD);
525 setTargetDAGCombine(ISD::STORE);
526 setTargetDAGCombine(ISD::ATOMIC_LOAD);
527 setTargetDAGCombine(ISD::ATOMIC_STORE);
528 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
529 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
530 setTargetDAGCombine(ISD::ATOMIC_SWAP);
531 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
532 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
533 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
534 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
535 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
536 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
537 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
538 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
539 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
540 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
541
542 setSchedulingPreference(Sched::RegPressure);
543}
544
545const SISubtarget *SITargetLowering::getSubtarget() const {
546 return static_cast<const SISubtarget *>(Subtarget);
547}
548
549//===----------------------------------------------------------------------===//
550// TargetLowering queries
551//===----------------------------------------------------------------------===//
552
553bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
554 // SI has some legal vector types, but no legal vector operations. Say no
555 // shuffles are legal in order to prefer scalarizing some vector operations.
556 return false;
557}
558
559bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
560 const CallInst &CI,
561 unsigned IntrID) const {
562 switch (IntrID) {
563 case Intrinsic::amdgcn_atomic_inc:
564 case Intrinsic::amdgcn_atomic_dec: {
565 Info.opc = ISD::INTRINSIC_W_CHAIN;
566 Info.memVT = MVT::getVT(CI.getType());
567 Info.ptrVal = CI.getOperand(0);
568 Info.align = 0;
569
570 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
571 Info.vol = !Vol || !Vol->isZero();
572 Info.readMem = true;
573 Info.writeMem = true;
574 return true;
575 }
576 default:
577 return false;
578 }
579}
580
581bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
582 SmallVectorImpl<Value*> &Ops,
583 Type *&AccessTy) const {
584 switch (II->getIntrinsicID()) {
585 case Intrinsic::amdgcn_atomic_inc:
586 case Intrinsic::amdgcn_atomic_dec: {
587 Value *Ptr = II->getArgOperand(0);
588 AccessTy = II->getType();
589 Ops.push_back(Ptr);
590 return true;
591 }
592 default:
593 return false;
594 }
595}
596
597bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
598 if (!Subtarget->hasFlatInstOffsets()) {
599 // Flat instructions do not have offsets, and only have the register
600 // address.
601 return AM.BaseOffs == 0 && AM.Scale == 0;
602 }
603
604 // GFX9 added a 13-bit signed offset. When using regular flat instructions,
605 // the sign bit is ignored and is treated as a 12-bit unsigned offset.
606
607 // Just r + i
608 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
609}
610
611bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
612 if (Subtarget->hasFlatGlobalInsts())
613 return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
614
615 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
616 // Assume the we will use FLAT for all global memory accesses
617 // on VI.
618 // FIXME: This assumption is currently wrong. On VI we still use
619 // MUBUF instructions for the r + i addressing mode. As currently
620 // implemented, the MUBUF instructions only work on buffer < 4GB.
621 // It may be possible to support > 4GB buffers with MUBUF instructions,
622 // by setting the stride value in the resource descriptor which would
623 // increase the size limit to (stride * 4GB). However, this is risky,
624 // because it has never been validated.
625 return isLegalFlatAddressingMode(AM);
626 }
627
628 return isLegalMUBUFAddressingMode(AM);
629}
630
631bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
632 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
633 // additionally can do r + r + i with addr64. 32-bit has more addressing
634 // mode options. Depending on the resource constant, it can also do
635 // (i64 r0) + (i32 r1) * (i14 i).
636 //
637 // Private arrays end up using a scratch buffer most of the time, so also
638 // assume those use MUBUF instructions. Scratch loads / stores are currently
639 // implemented as mubuf instructions with offen bit set, so slightly
640 // different than the normal addr64.
641 if (!isUInt<12>(AM.BaseOffs))
642 return false;
643
644 // FIXME: Since we can split immediate into soffset and immediate offset,
645 // would it make sense to allow any immediate?
646
647 switch (AM.Scale) {
648 case 0: // r + i or just i, depending on HasBaseReg.
649 return true;
650 case 1:
651 return true; // We have r + r or r + i.
652 case 2:
653 if (AM.HasBaseReg) {
654 // Reject 2 * r + r.
655 return false;
656 }
657
658 // Allow 2 * r as r + r
659 // Or 2 * r + i is allowed as r + r + i.
660 return true;
661 default: // Don't allow n * r
662 return false;
663 }
664}
665
666bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
667 const AddrMode &AM, Type *Ty,
668 unsigned AS, Instruction *I) const {
669 // No global is ever allowed as a base.
670 if (AM.BaseGV)
671 return false;
672
673 if (AS == AMDGPUASI.GLOBAL_ADDRESS)
674 return isLegalGlobalAddressingMode(AM);
675
676 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
677 // If the offset isn't a multiple of 4, it probably isn't going to be
678 // correctly aligned.
679 // FIXME: Can we get the real alignment here?
680 if (AM.BaseOffs % 4 != 0)
681 return isLegalMUBUFAddressingMode(AM);
682
683 // There are no SMRD extloads, so if we have to do a small type access we
684 // will use a MUBUF load.
685 // FIXME?: We also need to do this if unaligned, but we don't know the
686 // alignment here.
687 if (DL.getTypeStoreSize(Ty) < 4)
688 return isLegalGlobalAddressingMode(AM);
689
690 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
691 // SMRD instructions have an 8-bit, dword offset on SI.
692 if (!isUInt<8>(AM.BaseOffs / 4))
693 return false;
694 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
695 // On CI+, this can also be a 32-bit literal constant offset. If it fits
696 // in 8-bits, it can use a smaller encoding.
697 if (!isUInt<32>(AM.BaseOffs / 4))
698 return false;
699 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
700 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
701 if (!isUInt<20>(AM.BaseOffs))
702 return false;
703 } else
704 llvm_unreachable("unhandled generation")::llvm::llvm_unreachable_internal("unhandled generation", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 704)
;
705
706 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
707 return true;
708
709 if (AM.Scale == 1 && AM.HasBaseReg)
710 return true;
711
712 return false;
713
714 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
715 return isLegalMUBUFAddressingMode(AM);
716 } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
717 AS == AMDGPUASI.REGION_ADDRESS) {
718 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
719 // field.
720 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
721 // an 8-bit dword offset but we don't know the alignment here.
722 if (!isUInt<16>(AM.BaseOffs))
723 return false;
724
725 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
726 return true;
727
728 if (AM.Scale == 1 && AM.HasBaseReg)
729 return true;
730
731 return false;
732 } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
733 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
734 // For an unknown address space, this usually means that this is for some
735 // reason being used for pure arithmetic, and not based on some addressing
736 // computation. We don't have instructions that compute pointers with any
737 // addressing modes, so treat them as having no offset like flat
738 // instructions.
739 return isLegalFlatAddressingMode(AM);
740 } else {
741 llvm_unreachable("unhandled address space")::llvm::llvm_unreachable_internal("unhandled address space", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 741)
;
742 }
743}
744
745bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
746 const SelectionDAG &DAG) const {
747 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) {
748 return (MemVT.getSizeInBits() <= 4 * 32);
749 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
750 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
751 return (MemVT.getSizeInBits() <= MaxPrivateBits);
752 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
753 return (MemVT.getSizeInBits() <= 2 * 32);
754 }
755 return true;
756}
757
758bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
759 unsigned AddrSpace,
760 unsigned Align,
761 bool *IsFast) const {
762 if (IsFast)
763 *IsFast = false;
764
765 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
766 // which isn't a simple VT.
767 // Until MVT is extended to handle this, simply check for the size and
768 // rely on the condition below: allow accesses if the size is a multiple of 4.
769 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
770 VT.getStoreSize() > 16)) {
771 return false;
772 }
773
774 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
775 AddrSpace == AMDGPUASI.REGION_ADDRESS) {
776 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
777 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
778 // with adjacent offsets.
779 bool AlignedBy4 = (Align % 4 == 0);
780 if (IsFast)
781 *IsFast = AlignedBy4;
782
783 return AlignedBy4;
784 }
785
786 // FIXME: We have to be conservative here and assume that flat operations
787 // will access scratch. If we had access to the IR function, then we
788 // could determine if any private memory was used in the function.
789 if (!Subtarget->hasUnalignedScratchAccess() &&
790 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
791 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
792 return false;
793 }
794
795 if (Subtarget->hasUnalignedBufferAccess()) {
796 // If we have an uniform constant load, it still requires using a slow
797 // buffer instruction if unaligned.
798 if (IsFast) {
799 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ?
800 (Align % 4 == 0) : true;
801 }
802
803 return true;
804 }
805
806 // Smaller than dword value must be aligned.
807 if (VT.bitsLT(MVT::i32))
808 return false;
809
810 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
811 // byte-address are ignored, thus forcing Dword alignment.
812 // This applies to private, global, and constant memory.
813 if (IsFast)
814 *IsFast = true;
815
816 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
817}
818
819EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
820 unsigned SrcAlign, bool IsMemset,
821 bool ZeroMemset,
822 bool MemcpyStrSrc,
823 MachineFunction &MF) const {
824 // FIXME: Should account for address space here.
825
826 // The default fallback uses the private pointer size as a guess for a type to
827 // use. Make sure we switch these to 64-bit accesses.
828
829 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
830 return MVT::v4i32;
831
832 if (Size >= 8 && DstAlign >= 4)
833 return MVT::v2i32;
834
835 // Use the default.
836 return MVT::Other;
837}
838
839static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
840 return AS == AMDGPUASI.GLOBAL_ADDRESS ||
841 AS == AMDGPUASI.FLAT_ADDRESS ||
842 AS == AMDGPUASI.CONSTANT_ADDRESS;
843}
844
845bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
846 unsigned DestAS) const {
847 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
848 isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
849}
850
851bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
852 const MemSDNode *MemNode = cast<MemSDNode>(N);
853 const Value *Ptr = MemNode->getMemOperand()->getValue();
854 const Instruction *I = dyn_cast<Instruction>(Ptr);
855 return I && I->getMetadata("amdgpu.noclobber");
856}
857
858bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
859 unsigned DestAS) const {
860 // Flat -> private/local is a simple truncate.
861 // Flat -> global is no-op
862 if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
863 return true;
864
865 return isNoopAddrSpaceCast(SrcAS, DestAS);
866}
867
868bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
869 const MemSDNode *MemNode = cast<MemSDNode>(N);
870
871 return AMDGPU::isUniformMMO(MemNode->getMemOperand());
872}
873
874TargetLoweringBase::LegalizeTypeAction
875SITargetLowering::getPreferredVectorAction(EVT VT) const {
876 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
877 return TypeSplitVector;
878
879 return TargetLoweringBase::getPreferredVectorAction(VT);
880}
881
882bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
883 Type *Ty) const {
884 // FIXME: Could be smarter if called for vector constants.
885 return true;
886}
887
888bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
889 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
890 switch (Op) {
891 case ISD::LOAD:
892 case ISD::STORE:
893
894 // These operations are done with 32-bit instructions anyway.
895 case ISD::AND:
896 case ISD::OR:
897 case ISD::XOR:
898 case ISD::SELECT:
899 // TODO: Extensions?
900 return true;
901 default:
902 return false;
903 }
904 }
905
906 // SimplifySetCC uses this function to determine whether or not it should
907 // create setcc with i1 operands. We don't have instructions for i1 setcc.
908 if (VT == MVT::i1 && Op == ISD::SETCC)
909 return false;
910
911 return TargetLowering::isTypeDesirableForOp(Op, VT);
912}
913
914SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
915 const SDLoc &SL,
916 SDValue Chain,
917 uint64_t Offset) const {
918 const DataLayout &DL = DAG.getDataLayout();
919 MachineFunction &MF = DAG.getMachineFunction();
920 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
921
922 const ArgDescriptor *InputPtrReg;
923 const TargetRegisterClass *RC;
924
925 std::tie(InputPtrReg, RC)
926 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
927
928 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
929 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
930 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
931 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
932
933 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
934 DAG.getConstant(Offset, SL, PtrVT));
935}
936
937SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
938 const SDLoc &SL) const {
939 auto MFI = DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
940 uint64_t Offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
941 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
942}
943
944SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
945 const SDLoc &SL, SDValue Val,
946 bool Signed,
947 const ISD::InputArg *Arg) const {
948 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
949 VT.bitsLT(MemVT)) {
950 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
951 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
952 }
953
954 if (MemVT.isFloatingPoint())
955 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
956 else if (Signed)
957 Val = DAG.getSExtOrTrunc(Val, SL, VT);
958 else
959 Val = DAG.getZExtOrTrunc(Val, SL, VT);
960
961 return Val;
962}
963
964SDValue SITargetLowering::lowerKernargMemParameter(
965 SelectionDAG &DAG, EVT VT, EVT MemVT,
966 const SDLoc &SL, SDValue Chain,
967 uint64_t Offset, bool Signed,
968 const ISD::InputArg *Arg) const {
969 const DataLayout &DL = DAG.getDataLayout();
970 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
971 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
972 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
973
974 unsigned Align = DL.getABITypeAlignment(Ty);
975
976 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
977 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
978 MachineMemOperand::MONonTemporal |
979 MachineMemOperand::MODereferenceable |
980 MachineMemOperand::MOInvariant);
981
982 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
983 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
984}
985
986SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
987 const SDLoc &SL, SDValue Chain,
988 const ISD::InputArg &Arg) const {
989 MachineFunction &MF = DAG.getMachineFunction();
990 MachineFrameInfo &MFI = MF.getFrameInfo();
991
992 if (Arg.Flags.isByVal()) {
993 unsigned Size = Arg.Flags.getByValSize();
994 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
995 return DAG.getFrameIndex(FrameIdx, MVT::i32);
996 }
997
998 unsigned ArgOffset = VA.getLocMemOffset();
999 unsigned ArgSize = VA.getValVT().getStoreSize();
1000
1001 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1002
1003 // Create load nodes to retrieve arguments from the stack.
1004 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1005 SDValue ArgValue;
1006
1007 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1008 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1009 MVT MemVT = VA.getValVT();
1010
1011 switch (VA.getLocInfo()) {
1012 default:
1013 break;
1014 case CCValAssign::BCvt:
1015 MemVT = VA.getLocVT();
1016 break;
1017 case CCValAssign::SExt:
1018 ExtType = ISD::SEXTLOAD;
1019 break;
1020 case CCValAssign::ZExt:
1021 ExtType = ISD::ZEXTLOAD;
1022 break;
1023 case CCValAssign::AExt:
1024 ExtType = ISD::EXTLOAD;
1025 break;
1026 }
1027
1028 ArgValue = DAG.getExtLoad(
1029 ExtType, SL, VA.getLocVT(), Chain, FIN,
1030 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1031 MemVT);
1032 return ArgValue;
1033}
1034
1035SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1036 const SIMachineFunctionInfo &MFI,
1037 EVT VT,
1038 AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1039 const ArgDescriptor *Reg;
1040 const TargetRegisterClass *RC;
1041
1042 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1043 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1044}
1045
1046static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1047 CallingConv::ID CallConv,
1048 ArrayRef<ISD::InputArg> Ins,
1049 BitVector &Skipped,
1050 FunctionType *FType,
1051 SIMachineFunctionInfo *Info) {
1052 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1053 const ISD::InputArg &Arg = Ins[I];
1054
1055 // First check if it's a PS input addr.
1056 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
1057 !Arg.Flags.isByVal() && PSInputNum <= 15) {
1058
1059 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
1060 // We can safely skip PS inputs.
1061 Skipped.set(I);
1062 ++PSInputNum;
1063 continue;
1064 }
1065
1066 Info->markPSInputAllocated(PSInputNum);
1067 if (Arg.Used)
1068 Info->markPSInputEnabled(PSInputNum);
1069
1070 ++PSInputNum;
1071 }
1072
1073 // Second split vertices into their elements.
1074 if (Arg.VT.isVector()) {
1075 ISD::InputArg NewArg = Arg;
1076 NewArg.Flags.setSplit();
1077 NewArg.VT = Arg.VT.getVectorElementType();
1078
1079 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
1080 // three or five element vertex only needs three or five registers,
1081 // NOT four or eight.
1082 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1083 unsigned NumElements = ParamType->getVectorNumElements();
1084
1085 for (unsigned J = 0; J != NumElements; ++J) {
1086 Splits.push_back(NewArg);
1087 NewArg.PartOffset += NewArg.VT.getStoreSize();
1088 }
1089 } else {
1090 Splits.push_back(Arg);
1091 }
1092 }
1093}
1094
1095// Allocate special inputs passed in VGPRs.
1096static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1097 MachineFunction &MF,
1098 const SIRegisterInfo &TRI,
1099 SIMachineFunctionInfo &Info) {
1100 if (Info.hasWorkItemIDX()) {
1101 unsigned Reg = AMDGPU::VGPR0;
1102 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1103
1104 CCInfo.AllocateReg(Reg);
1105 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1106 }
1107
1108 if (Info.hasWorkItemIDY()) {
1109 unsigned Reg = AMDGPU::VGPR1;
1110 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1111
1112 CCInfo.AllocateReg(Reg);
1113 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1114 }
1115
1116 if (Info.hasWorkItemIDZ()) {
1117 unsigned Reg = AMDGPU::VGPR2;
1118 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1119
1120 CCInfo.AllocateReg(Reg);
1121 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1122 }
1123}
1124
1125// Try to allocate a VGPR at the end of the argument list, or if no argument
1126// VGPRs are left allocating a stack slot.
1127static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1128 ArrayRef<MCPhysReg> ArgVGPRs
1129 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1130 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1131 if (RegIdx == ArgVGPRs.size()) {
1132 // Spill to stack required.
1133 int64_t Offset = CCInfo.AllocateStack(4, 4);
1134
1135 return ArgDescriptor::createStack(Offset);
1136 }
1137
1138 unsigned Reg = ArgVGPRs[RegIdx];
1139 Reg = CCInfo.AllocateReg(Reg);
1140 assert(Reg != AMDGPU::NoRegister)(static_cast <bool> (Reg != AMDGPU::NoRegister) ? void (
0) : __assert_fail ("Reg != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1140, __extension__ __PRETTY_FUNCTION__))
;
1141
1142 MachineFunction &MF = CCInfo.getMachineFunction();
1143 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1144 return ArgDescriptor::createRegister(Reg);
1145}
1146
1147static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1148 const TargetRegisterClass *RC,
1149 unsigned NumArgRegs) {
1150 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1151 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1152 if (RegIdx == ArgSGPRs.size())
1153 report_fatal_error("ran out of SGPRs for arguments");
1154
1155 unsigned Reg = ArgSGPRs[RegIdx];
1156 Reg = CCInfo.AllocateReg(Reg);
1157 assert(Reg != AMDGPU::NoRegister)(static_cast <bool> (Reg != AMDGPU::NoRegister) ? void (
0) : __assert_fail ("Reg != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1157, __extension__ __PRETTY_FUNCTION__))
;
1158
1159 MachineFunction &MF = CCInfo.getMachineFunction();
1160 MF.addLiveIn(Reg, RC);
1161 return ArgDescriptor::createRegister(Reg);
1162}
1163
1164static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1165 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1166}
1167
1168static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1169 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1170}
1171
1172static void allocateSpecialInputVGPRs(CCState &CCInfo,
1173 MachineFunction &MF,
1174 const SIRegisterInfo &TRI,
1175 SIMachineFunctionInfo &Info) {
1176 if (Info.hasWorkItemIDX())
1177 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1178
1179 if (Info.hasWorkItemIDY())
1180 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1181
1182 if (Info.hasWorkItemIDZ())
1183 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1184}
1185
1186static void allocateSpecialInputSGPRs(CCState &CCInfo,
1187 MachineFunction &MF,
1188 const SIRegisterInfo &TRI,
1189 SIMachineFunctionInfo &Info) {
1190 auto &ArgInfo = Info.getArgInfo();
1191
1192 // TODO: Unify handling with private memory pointers.
1193
1194 if (Info.hasDispatchPtr())
1195 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1196
1197 if (Info.hasQueuePtr())
1198 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1199
1200 if (Info.hasKernargSegmentPtr())
1201 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1202
1203 if (Info.hasDispatchID())
1204 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1205
1206 // flat_scratch_init is not applicable for non-kernel functions.
1207
1208 if (Info.hasWorkGroupIDX())
1209 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1210
1211 if (Info.hasWorkGroupIDY())
1212 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1213
1214 if (Info.hasWorkGroupIDZ())
1215 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1216
1217 if (Info.hasImplicitArgPtr())
1218 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1219}
1220
1221// Allocate special inputs passed in user SGPRs.
1222static void allocateHSAUserSGPRs(CCState &CCInfo,
1223 MachineFunction &MF,
1224 const SIRegisterInfo &TRI,
1225 SIMachineFunctionInfo &Info) {
1226 if (Info.hasImplicitBufferPtr()) {
1227 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1228 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1229 CCInfo.AllocateReg(ImplicitBufferPtrReg);
1230 }
1231
1232 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1233 if (Info.hasPrivateSegmentBuffer()) {
1234 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1235 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1236 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1237 }
1238
1239 if (Info.hasDispatchPtr()) {
1240 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1241 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1242 CCInfo.AllocateReg(DispatchPtrReg);
1243 }
1244
1245 if (Info.hasQueuePtr()) {
1246 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1247 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1248 CCInfo.AllocateReg(QueuePtrReg);
1249 }
1250
1251 if (Info.hasKernargSegmentPtr()) {
1252 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1253 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1254 CCInfo.AllocateReg(InputPtrReg);
1255 }
1256
1257 if (Info.hasDispatchID()) {
1258 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1259 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1260 CCInfo.AllocateReg(DispatchIDReg);
1261 }
1262
1263 if (Info.hasFlatScratchInit()) {
1264 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1265 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1266 CCInfo.AllocateReg(FlatScratchInitReg);
1267 }
1268
1269 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1270 // these from the dispatch pointer.
1271}
1272
1273// Allocate special input registers that are initialized per-wave.
1274static void allocateSystemSGPRs(CCState &CCInfo,
1275 MachineFunction &MF,
1276 SIMachineFunctionInfo &Info,
1277 CallingConv::ID CallConv,
1278 bool IsShader) {
1279 if (Info.hasWorkGroupIDX()) {
1280 unsigned Reg = Info.addWorkGroupIDX();
1281 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1282 CCInfo.AllocateReg(Reg);
1283 }
1284
1285 if (Info.hasWorkGroupIDY()) {
1286 unsigned Reg = Info.addWorkGroupIDY();
1287 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1288 CCInfo.AllocateReg(Reg);
1289 }
1290
1291 if (Info.hasWorkGroupIDZ()) {
1292 unsigned Reg = Info.addWorkGroupIDZ();
1293 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1294 CCInfo.AllocateReg(Reg);
1295 }
1296
1297 if (Info.hasWorkGroupInfo()) {
1298 unsigned Reg = Info.addWorkGroupInfo();
1299 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1300 CCInfo.AllocateReg(Reg);
1301 }
1302
1303 if (Info.hasPrivateSegmentWaveByteOffset()) {
1304 // Scratch wave offset passed in system SGPR.
1305 unsigned PrivateSegmentWaveByteOffsetReg;
1306
1307 if (IsShader) {
1308 PrivateSegmentWaveByteOffsetReg =
1309 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1310
1311 // This is true if the scratch wave byte offset doesn't have a fixed
1312 // location.
1313 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1314 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1315 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1316 }
1317 } else
1318 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1319
1320 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1321 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1322 }
1323}
1324
1325static void reservePrivateMemoryRegs(const TargetMachine &TM,
1326 MachineFunction &MF,
1327 const SIRegisterInfo &TRI,
1328 SIMachineFunctionInfo &Info) {
1329 // Now that we've figured out where the scratch register inputs are, see if
1330 // should reserve the arguments and use them directly.
1331 MachineFrameInfo &MFI = MF.getFrameInfo();
1332 bool HasStackObjects = MFI.hasStackObjects();
1333
1334 // Record that we know we have non-spill stack objects so we don't need to
1335 // check all stack objects later.
1336 if (HasStackObjects)
1337 Info.setHasNonSpillStackObjects(true);
1338
1339 // Everything live out of a block is spilled with fast regalloc, so it's
1340 // almost certain that spilling will be required.
1341 if (TM.getOptLevel() == CodeGenOpt::None)
1342 HasStackObjects = true;
1343
1344 // For now assume stack access is needed in any callee functions, so we need
1345 // the scratch registers to pass in.
1346 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1347
1348 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1349 if (ST.isAmdCodeObjectV2(MF)) {
1350 if (RequiresStackAccess) {
1351 // If we have stack objects, we unquestionably need the private buffer
1352 // resource. For the Code Object V2 ABI, this will be the first 4 user
1353 // SGPR inputs. We can reserve those and use them directly.
1354
1355 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg(
1356 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1357 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1358
1359 if (MFI.hasCalls()) {
1360 // If we have calls, we need to keep the frame register in a register
1361 // that won't be clobbered by a call, so ensure it is copied somewhere.
1362
1363 // This is not a problem for the scratch wave offset, because the same
1364 // registers are reserved in all functions.
1365
1366 // FIXME: Nothing is really ensuring this is a call preserved register,
1367 // it's just selected from the end so it happens to be.
1368 unsigned ReservedOffsetReg
1369 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1370 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1371 } else {
1372 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg(
1373 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1374 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1375 }
1376 } else {
1377 unsigned ReservedBufferReg
1378 = TRI.reservedPrivateSegmentBufferReg(MF);
1379 unsigned ReservedOffsetReg
1380 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1381
1382 // We tentatively reserve the last registers (skipping the last two
1383 // which may contain VCC). After register allocation, we'll replace
1384 // these with the ones immediately after those which were really
1385 // allocated. In the prologue copies will be inserted from the argument
1386 // to these reserved registers.
1387 Info.setScratchRSrcReg(ReservedBufferReg);
1388 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1389 }
1390 } else {
1391 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1392
1393 // Without HSA, relocations are used for the scratch pointer and the
1394 // buffer resource setup is always inserted in the prologue. Scratch wave
1395 // offset is still in an input SGPR.
1396 Info.setScratchRSrcReg(ReservedBufferReg);
1397
1398 if (HasStackObjects && !MFI.hasCalls()) {
1399 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg(
1400 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1401 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1402 } else {
1403 unsigned ReservedOffsetReg
1404 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1405 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1406 }
1407 }
1408}
1409
1410bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1411 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1412 return !Info->isEntryFunction();
1413}
1414
1415void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1416
1417}
1418
1419void SITargetLowering::insertCopiesSplitCSR(
1420 MachineBasicBlock *Entry,
1421 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1422 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1423
1424 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1425 if (!IStart)
1426 return;
1427
1428 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1429 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1430 MachineBasicBlock::iterator MBBI = Entry->begin();
1431 for (const MCPhysReg *I = IStart; *I; ++I) {
1432 const TargetRegisterClass *RC = nullptr;
1433 if (AMDGPU::SReg_64RegClass.contains(*I))
1434 RC = &AMDGPU::SGPR_64RegClass;
1435 else if (AMDGPU::SReg_32RegClass.contains(*I))
1436 RC = &AMDGPU::SGPR_32RegClass;
1437 else
1438 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1438)
;
1439
1440 unsigned NewVR = MRI->createVirtualRegister(RC);
1441 // Create copy from CSR to a virtual register.
1442 Entry->addLiveIn(*I);
1443 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1444 .addReg(*I);
1445
1446 // Insert the copy-back instructions right before the terminator.
1447 for (auto *Exit : Exits)
1448 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1449 TII->get(TargetOpcode::COPY), *I)
1450 .addReg(NewVR);
1451 }
1452}
1453
1454SDValue SITargetLowering::LowerFormalArguments(
1455 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1456 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1457 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1458 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1459
1460 MachineFunction &MF = DAG.getMachineFunction();
1461 FunctionType *FType = MF.getFunction()->getFunctionType();
1462 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1463 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1464
1465 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1466 const Function *Fn = MF.getFunction();
1467 DiagnosticInfoUnsupported NoGraphicsHSA(
1468 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1469 DAG.getContext()->diagnose(NoGraphicsHSA);
1470 return DAG.getEntryNode();
1471 }
1472
1473 // Create stack objects that are used for emitting debugger prologue if
1474 // "amdgpu-debugger-emit-prologue" attribute was specified.
1475 if (ST.debuggerEmitPrologue())
1476 createDebuggerPrologueStackObjects(MF);
1477
1478 SmallVector<ISD::InputArg, 16> Splits;
1479 SmallVector<CCValAssign, 16> ArgLocs;
1480 BitVector Skipped(Ins.size());
1481 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1482 *DAG.getContext());
1483
1484 bool IsShader = AMDGPU::isShader(CallConv);
1485 bool IsKernel = AMDGPU::isKernel(CallConv);
1486 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1487
1488 if (!IsEntryFunc) {
1489 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over
1490 // this when allocating argument fixed offsets.
1491 CCInfo.AllocateStack(4, 4);
1492 }
1493
1494 if (IsShader) {
1495 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1496
1497 // At least one interpolation mode must be enabled or else the GPU will
1498 // hang.
1499 //
1500 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1501 // set PSInputAddr, the user wants to enable some bits after the compilation
1502 // based on run-time states. Since we can't know what the final PSInputEna
1503 // will look like, so we shouldn't do anything here and the user should take
1504 // responsibility for the correct programming.
1505 //
1506 // Otherwise, the following restrictions apply:
1507 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1508 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1509 // enabled too.
1510 if (CallConv == CallingConv::AMDGPU_PS) {
1511 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1512 ((Info->getPSInputAddr() & 0xF) == 0 &&
1513 Info->isPSInputAllocated(11))) {
1514 CCInfo.AllocateReg(AMDGPU::VGPR0);
1515 CCInfo.AllocateReg(AMDGPU::VGPR1);
1516 Info->markPSInputAllocated(0);
1517 Info->markPSInputEnabled(0);
1518 }
1519 if (Subtarget->isAmdPalOS()) {
1520 // For isAmdPalOS, the user does not enable some bits after compilation
1521 // based on run-time states; the register values being generated here are
1522 // the final ones set in hardware. Therefore we need to apply the
1523 // workaround to PSInputAddr and PSInputEnable together. (The case where
1524 // a bit is set in PSInputAddr but not PSInputEnable is where the
1525 // frontend set up an input arg for a particular interpolation mode, but
1526 // nothing uses that input arg. Really we should have an earlier pass
1527 // that removes such an arg.)
1528 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1529 if ((PsInputBits & 0x7F) == 0 ||
1530 ((PsInputBits & 0xF) == 0 &&
1531 (PsInputBits >> 11 & 1)))
1532 Info->markPSInputEnabled(
1533 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
1534 }
1535 }
1536
1537 assert(!Info->hasDispatchPtr() &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit
() && !Info->hasWorkGroupIDX() && !Info->
hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() &&
!Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX
() && !Info->hasWorkItemIDY() && !Info->
hasWorkItemIDZ()) ? void (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1542, __extension__ __PRETTY_FUNCTION__))
1538 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit
() && !Info->hasWorkGroupIDX() && !Info->
hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() &&
!Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX
() && !Info->hasWorkItemIDY() && !Info->
hasWorkItemIDZ()) ? void (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1542, __extension__ __PRETTY_FUNCTION__))
1539 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit
() && !Info->hasWorkGroupIDX() && !Info->
hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() &&
!Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX
() && !Info->hasWorkItemIDY() && !Info->
hasWorkItemIDZ()) ? void (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1542, __extension__ __PRETTY_FUNCTION__))
1540 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit
() && !Info->hasWorkGroupIDX() && !Info->
hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() &&
!Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX
() && !Info->hasWorkItemIDY() && !Info->
hasWorkItemIDZ()) ? void (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1542, __extension__ __PRETTY_FUNCTION__))
1541 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit
() && !Info->hasWorkGroupIDX() && !Info->
hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() &&
!Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX
() && !Info->hasWorkItemIDY() && !Info->
hasWorkItemIDZ()) ? void (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1542, __extension__ __PRETTY_FUNCTION__))
1542 !Info->hasWorkItemIDZ())(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit
() && !Info->hasWorkGroupIDX() && !Info->
hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() &&
!Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX
() && !Info->hasWorkItemIDY() && !Info->
hasWorkItemIDZ()) ? void (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1542, __extension__ __PRETTY_FUNCTION__))
;
1543 } else if (IsKernel) {
1544 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX())(static_cast <bool> (Info->hasWorkGroupIDX() &&
Info->hasWorkItemIDX()) ? void (0) : __assert_fail ("Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1544, __extension__ __PRETTY_FUNCTION__))
;
1545 } else {
1546 Splits.append(Ins.begin(), Ins.end());
1547 }
1548
1549 if (IsEntryFunc) {
1550 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
1551 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1552 }
1553
1554 if (IsKernel) {
1555 analyzeFormalArgumentsCompute(CCInfo, Ins);
1556 } else {
1557 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1558 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1559 }
1560
1561 SmallVector<SDValue, 16> Chains;
1562
1563 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1564 const ISD::InputArg &Arg = Ins[i];
1565 if (Skipped[i]) {
1566 InVals.push_back(DAG.getUNDEF(Arg.VT));
1567 continue;
1568 }
1569
1570 CCValAssign &VA = ArgLocs[ArgIdx++];
1571 MVT VT = VA.getLocVT();
1572
1573 if (IsEntryFunc && VA.isMemLoc()) {
1574 VT = Ins[i].VT;
1575 EVT MemVT = VA.getLocVT();
1576
1577 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) +
1578 VA.getLocMemOffset();
1579 Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1580
1581 // The first 36 bytes of the input buffer contains information about
1582 // thread group and global sizes.
1583 SDValue Arg = lowerKernargMemParameter(
1584 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]);
1585 Chains.push_back(Arg.getValue(1));
1586
1587 auto *ParamTy =
1588 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1589 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1590 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1591 // On SI local pointers are just offsets into LDS, so they are always
1592 // less than 16-bits. On CI and newer they could potentially be
1593 // real pointers, so we can't guarantee their size.
1594 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1595 DAG.getValueType(MVT::i16));
1596 }
1597
1598 InVals.push_back(Arg);
1599 continue;
1600 } else if (!IsEntryFunc && VA.isMemLoc()) {
1601 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1602 InVals.push_back(Val);
1603 if (!Arg.Flags.isByVal())
1604 Chains.push_back(Val.getValue(1));
1605 continue;
1606 }
1607
1608 assert(VA.isRegLoc() && "Parameter must be in a register!")(static_cast <bool> (VA.isRegLoc() && "Parameter must be in a register!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Parameter must be in a register!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1608, __extension__ __PRETTY_FUNCTION__))
;
1609
1610 unsigned Reg = VA.getLocReg();
1611 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1612 EVT ValVT = VA.getValVT();
1613
1614 Reg = MF.addLiveIn(Reg, RC);
1615 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1616
1617 if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) {
1618 // The return object should be reasonably addressable.
1619
1620 // FIXME: This helps when the return is a real sret. If it is a
1621 // automatically inserted sret (i.e. CanLowerReturn returns false), an
1622 // extra copy is inserted in SelectionDAGBuilder which obscures this.
1623 unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits;
1624 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1625 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
1626 }
1627
1628 // If this is an 8 or 16-bit value, it is really passed promoted
1629 // to 32 bits. Insert an assert[sz]ext to capture this, then
1630 // truncate to the right size.
1631 switch (VA.getLocInfo()) {
1632 case CCValAssign::Full:
1633 break;
1634 case CCValAssign::BCvt:
1635 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
1636 break;
1637 case CCValAssign::SExt:
1638 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
1639 DAG.getValueType(ValVT));
1640 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1641 break;
1642 case CCValAssign::ZExt:
1643 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1644 DAG.getValueType(ValVT));
1645 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1646 break;
1647 case CCValAssign::AExt:
1648 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1649 break;
1650 default:
1651 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1651)
;
1652 }
1653
1654 if (IsShader && Arg.VT.isVector()) {
1655 // Build a vector from the registers
1656 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1657 unsigned NumElements = ParamType->getVectorNumElements();
1658
1659 SmallVector<SDValue, 4> Regs;
1660 Regs.push_back(Val);
1661 for (unsigned j = 1; j != NumElements; ++j) {
1662 Reg = ArgLocs[ArgIdx++].getLocReg();
1663 Reg = MF.addLiveIn(Reg, RC);
1664
1665 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1666 Regs.push_back(Copy);
1667 }
1668
1669 // Fill up the missing vector elements
1670 NumElements = Arg.VT.getVectorNumElements() - NumElements;
1671 Regs.append(NumElements, DAG.getUNDEF(VT));
1672
1673 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1674 continue;
1675 }
1676
1677 InVals.push_back(Val);
1678 }
1679
1680 if (!IsEntryFunc) {
1681 // Special inputs come after user arguments.
1682 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1683 }
1684
1685 // Start adding system SGPRs.
1686 if (IsEntryFunc) {
1687 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
1688 } else {
1689 CCInfo.AllocateReg(Info->getScratchRSrcReg());
1690 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
1691 CCInfo.AllocateReg(Info->getFrameOffsetReg());
1692 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
1693 }
1694
1695 auto &ArgUsageInfo =
1696 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
1697 ArgUsageInfo.setFuncArgInfo(*MF.getFunction(), Info->getArgInfo());
1698
1699 unsigned StackArgSize = CCInfo.getNextStackOffset();
1700 Info->setBytesInStackArgArea(StackArgSize);
1701
1702 return Chains.empty() ? Chain :
1703 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1704}
1705
1706// TODO: If return values can't fit in registers, we should return as many as
1707// possible in registers before passing on stack.
1708bool SITargetLowering::CanLowerReturn(
1709 CallingConv::ID CallConv,
1710 MachineFunction &MF, bool IsVarArg,
1711 const SmallVectorImpl<ISD::OutputArg> &Outs,
1712 LLVMContext &Context) const {
1713 // Replacing returns with sret/stack usage doesn't make sense for shaders.
1714 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
1715 // for shaders. Vector types should be explicitly handled by CC.
1716 if (AMDGPU::isEntryFunctionCC(CallConv))
1717 return true;
1718
1719 SmallVector<CCValAssign, 16> RVLocs;
1720 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1721 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
1722}
1723
1724SDValue
1725SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1726 bool isVarArg,
1727 const SmallVectorImpl<ISD::OutputArg> &Outs,
1728 const SmallVectorImpl<SDValue> &OutVals,
1729 const SDLoc &DL, SelectionDAG &DAG) const {
1730 MachineFunction &MF = DAG.getMachineFunction();
1731 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1732
1733 if (AMDGPU::isKernel(CallConv)) {
1734 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1735 OutVals, DL, DAG);
1736 }
1737
1738 bool IsShader = AMDGPU::isShader(CallConv);
1739
1740 Info->setIfReturnsVoid(Outs.size() == 0);
1741 bool IsWaveEnd = Info->returnsVoid() && IsShader;
1742
1743 SmallVector<ISD::OutputArg, 48> Splits;
1744 SmallVector<SDValue, 48> SplitVals;
1745
1746 // Split vectors into their elements.
1747 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1748 const ISD::OutputArg &Out = Outs[i];
1749
1750 if (IsShader && Out.VT.isVector()) {
1751 MVT VT = Out.VT.getVectorElementType();
1752 ISD::OutputArg NewOut = Out;
1753 NewOut.Flags.setSplit();
1754 NewOut.VT = VT;
1755
1756 // We want the original number of vector elements here, e.g.
1757 // three or five, not four or eight.
1758 unsigned NumElements = Out.ArgVT.getVectorNumElements();
1759
1760 for (unsigned j = 0; j != NumElements; ++j) {
1761 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1762 DAG.getConstant(j, DL, MVT::i32));
1763 SplitVals.push_back(Elem);
1764 Splits.push_back(NewOut);
1765 NewOut.PartOffset += NewOut.VT.getStoreSize();
1766 }
1767 } else {
1768 SplitVals.push_back(OutVals[i]);
1769 Splits.push_back(Out);
1770 }
1771 }
1772
1773 // CCValAssign - represent the assignment of the return value to a location.
1774 SmallVector<CCValAssign, 48> RVLocs;
1775
1776 // CCState - Info about the registers and stack slots.
1777 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1778 *DAG.getContext());
1779
1780 // Analyze outgoing return values.
1781 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg));
1782
1783 SDValue Flag;
1784 SmallVector<SDValue, 48> RetOps;
1785 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1786
1787 // Add return address for callable functions.
1788 if (!Info->isEntryFunction()) {
1789 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1790 SDValue ReturnAddrReg = CreateLiveInRegister(
1791 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
1792
1793 // FIXME: Should be able to use a vreg here, but need a way to prevent it
1794 // from being allcoated to a CSR.
1795
1796 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
1797 MVT::i64);
1798
1799 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
1800 Flag = Chain.getValue(1);
1801
1802 RetOps.push_back(PhysReturnAddrReg);
1803 }
1804
1805 // Copy the result values into the output registers.
1806 for (unsigned i = 0, realRVLocIdx = 0;
1807 i != RVLocs.size();
1808 ++i, ++realRVLocIdx) {
1809 CCValAssign &VA = RVLocs[i];
1810 assert(VA.isRegLoc() && "Can only return in registers!")(static_cast <bool> (VA.isRegLoc() && "Can only return in registers!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1810, __extension__ __PRETTY_FUNCTION__))
;
1811 // TODO: Partially return in registers if return values don't fit.
1812
1813 SDValue Arg = SplitVals[realRVLocIdx];
1814
1815 // Copied from other backends.
1816 switch (VA.getLocInfo()) {
1817 case CCValAssign::Full:
1818 break;
1819 case CCValAssign::BCvt:
1820 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1821 break;
1822 case CCValAssign::SExt:
1823 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
1824 break;
1825 case CCValAssign::ZExt:
1826 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
1827 break;
1828 case CCValAssign::AExt:
1829 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
1830 break;
1831 default:
1832 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1832)
;
1833 }
1834
1835 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1836 Flag = Chain.getValue(1);
1837 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1838 }
1839
1840 // FIXME: Does sret work properly?
1841 if (!Info->isEntryFunction()) {
1842 const SIRegisterInfo *TRI
1843 = static_cast<const SISubtarget *>(Subtarget)->getRegisterInfo();
1844 const MCPhysReg *I =
1845 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
1846 if (I) {
1847 for (; *I; ++I) {
1848 if (AMDGPU::SReg_64RegClass.contains(*I))
1849 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
1850 else if (AMDGPU::SReg_32RegClass.contains(*I))
1851 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
1852 else
1853 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1853)
;
1854 }
1855 }
1856 }
1857
1858 // Update chain and glue.
1859 RetOps[0] = Chain;
1860 if (Flag.getNode())
1861 RetOps.push_back(Flag);
1862
1863 unsigned Opc = AMDGPUISD::ENDPGM;
1864 if (!IsWaveEnd)
1865 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
1866 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1867}
1868
1869SDValue SITargetLowering::LowerCallResult(
1870 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
1871 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1872 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
1873 SDValue ThisVal) const {
1874 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
1875
1876 // Assign locations to each value returned by this call.
1877 SmallVector<CCValAssign, 16> RVLocs;
1878 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
1879 *DAG.getContext());
1880 CCInfo.AnalyzeCallResult(Ins, RetCC);
1881
1882 // Copy all of the result registers out of their specified physreg.
1883 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1884 CCValAssign VA = RVLocs[i];
1885 SDValue Val;
1886
1887 if (VA.isRegLoc()) {
1888 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
1889 Chain = Val.getValue(1);
1890 InFlag = Val.getValue(2);
1891 } else if (VA.isMemLoc()) {
1892 report_fatal_error("TODO: return values in memory");
1893 } else
1894 llvm_unreachable("unknown argument location type")::llvm::llvm_unreachable_internal("unknown argument location type"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1894)
;
1895
1896 switch (VA.getLocInfo()) {
1897 case CCValAssign::Full:
1898 break;
1899 case CCValAssign::BCvt:
1900 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1901 break;
1902 case CCValAssign::ZExt:
1903 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
1904 DAG.getValueType(VA.getValVT()));
1905 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
1906 break;
1907 case CCValAssign::SExt:
1908 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
1909 DAG.getValueType(VA.getValVT()));
1910 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
1911 break;
1912 case CCValAssign::AExt:
1913 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
1914 break;
1915 default:
1916 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1916)
;
1917 }
1918
1919 InVals.push_back(Val);
1920 }
1921
1922 return Chain;
1923}
1924
1925// Add code to pass special inputs required depending on used features separate
1926// from the explicit user arguments present in the IR.
1927void SITargetLowering::passSpecialInputs(
1928 CallLoweringInfo &CLI,
1929 const SIMachineFunctionInfo &Info,
1930 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
1931 SmallVectorImpl<SDValue> &MemOpChains,
1932 SDValue Chain,
1933 SDValue StackPtr) const {
1934 // If we don't have a call site, this was a call inserted by
1935 // legalization. These can never use special inputs.
1936 if (!CLI.CS)
1937 return;
1938
1939 const Function *CalleeFunc = CLI.CS.getCalledFunction();
1940 assert(CalleeFunc)(static_cast <bool> (CalleeFunc) ? void (0) : __assert_fail
("CalleeFunc", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1940, __extension__ __PRETTY_FUNCTION__))
;
1941
1942 SelectionDAG &DAG = CLI.DAG;
1943 const SDLoc &DL = CLI.DL;
1944
1945 const SISubtarget *ST = getSubtarget();
1946 const SIRegisterInfo *TRI = ST->getRegisterInfo();
1947
1948 auto &ArgUsageInfo =
1949 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
1950 const AMDGPUFunctionArgInfo &CalleeArgInfo
1951 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
1952
1953 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
1954
1955 // TODO: Unify with private memory register handling. This is complicated by
1956 // the fact that at least in kernels, the input argument is not necessarily
1957 // in the same location as the input.
1958 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
1959 AMDGPUFunctionArgInfo::DISPATCH_PTR,
1960 AMDGPUFunctionArgInfo::QUEUE_PTR,
1961 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
1962 AMDGPUFunctionArgInfo::DISPATCH_ID,
1963 AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
1964 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
1965 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
1966 AMDGPUFunctionArgInfo::WORKITEM_ID_X,
1967 AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
1968 AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
1969 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
1970 };
1971
1972 for (auto InputID : InputRegs) {
1973 const ArgDescriptor *OutgoingArg;
1974 const TargetRegisterClass *ArgRC;
1975
1976 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
1977 if (!OutgoingArg)
1978 continue;
1979
1980 const ArgDescriptor *IncomingArg;
1981 const TargetRegisterClass *IncomingArgRC;
1982 std::tie(IncomingArg, IncomingArgRC)
1983 = CallerArgInfo.getPreloadedValue(InputID);
1984 assert(IncomingArgRC == ArgRC)(static_cast <bool> (IncomingArgRC == ArgRC) ? void (0)
: __assert_fail ("IncomingArgRC == ArgRC", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1984, __extension__ __PRETTY_FUNCTION__))
;
1985
1986 // All special arguments are ints for now.
1987 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
1988 SDValue InputReg;
1989
1990 if (IncomingArg) {
1991 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
1992 } else {
1993 // The implicit arg ptr is special because it doesn't have a corresponding
1994 // input for kernels, and is computed from the kernarg segment pointer.
1995 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR)(static_cast <bool> (InputID == AMDGPUFunctionArgInfo::
IMPLICIT_ARG_PTR) ? void (0) : __assert_fail ("InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1995, __extension__ __PRETTY_FUNCTION__))
;
1996 InputReg = getImplicitArgPtr(DAG, DL);
1997 }
1998
1999 if (OutgoingArg->isRegister()) {
2000 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2001 } else {
2002 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr,
2003 InputReg,
2004 OutgoingArg->getStackOffset());
2005 MemOpChains.push_back(ArgStore);
2006 }
2007 }
2008}
2009
2010static bool canGuaranteeTCO(CallingConv::ID CC) {
2011 return CC == CallingConv::Fast;
2012}
2013
2014/// Return true if we might ever do TCO for calls with this calling convention.
2015static bool mayTailCallThisCC(CallingConv::ID CC) {
2016 switch (CC) {
2017 case CallingConv::C:
2018 return true;
2019 default:
2020 return canGuaranteeTCO(CC);
2021 }
2022}
2023
2024bool SITargetLowering::isEligibleForTailCallOptimization(
2025 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2026 const SmallVectorImpl<ISD::OutputArg> &Outs,
2027 const SmallVectorImpl<SDValue> &OutVals,
2028 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2029 if (!mayTailCallThisCC(CalleeCC))
2030 return false;
2031
2032 MachineFunction &MF = DAG.getMachineFunction();
2033 const Function *CallerF = MF.getFunction();
2034 CallingConv::ID CallerCC = CallerF->getCallingConv();
2035 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2036 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2037
2038 // Kernels aren't callable, and don't have a live in return address so it
2039 // doesn't make sense to do a tail call with entry functions.
2040 if (!CallerPreserved)
2041 return false;
2042
2043 bool CCMatch = CallerCC == CalleeCC;
2044
2045 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2046 if (canGuaranteeTCO(CalleeCC) && CCMatch)
2047 return true;
2048 return false;
2049 }
2050
2051 // TODO: Can we handle var args?
2052 if (IsVarArg)
2053 return false;
2054
2055 for (const Argument &Arg : CallerF->args()) {
2056 if (Arg.hasByValAttr())
2057 return false;
2058 }
2059
2060 LLVMContext &Ctx = *DAG.getContext();
2061
2062 // Check that the call results are passed in the same way.
2063 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2064 CCAssignFnForCall(CalleeCC, IsVarArg),
2065 CCAssignFnForCall(CallerCC, IsVarArg)))
2066 return false;
2067
2068 // The callee has to preserve all registers the caller needs to preserve.
2069 if (!CCMatch) {
2070 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2071 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2072 return false;
2073 }
2074
2075 // Nothing more to check if the callee is taking no arguments.
2076 if (Outs.empty())
2077 return true;
2078
2079 SmallVector<CCValAssign, 16> ArgLocs;
2080 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2081
2082 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2083
2084 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2085 // If the stack arguments for this call do not fit into our own save area then
2086 // the call cannot be made tail.
2087 // TODO: Is this really necessary?
2088 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2089 return false;
2090
2091 const MachineRegisterInfo &MRI = MF.getRegInfo();
2092 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2093}
2094
2095bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2096 if (!CI->isTailCall())
2097 return false;
2098
2099 const Function *ParentFn = CI->getParent()->getParent();
2100 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2101 return false;
2102
2103 auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2104 return (Attr.getValueAsString() != "true");
2105}
2106
2107// The wave scratch offset register is used as the global base pointer.
2108SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2109 SmallVectorImpl<SDValue> &InVals) const {
2110 SelectionDAG &DAG = CLI.DAG;
2111 const SDLoc &DL = CLI.DL;
2112 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2113 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2114 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2115 SDValue Chain = CLI.Chain;
2116 SDValue Callee = CLI.Callee;
2117 bool &IsTailCall = CLI.IsTailCall;
2118 CallingConv::ID CallConv = CLI.CallConv;
2119 bool IsVarArg = CLI.IsVarArg;
2120 bool IsSibCall = false;
2121 bool IsThisReturn = false;
2122 MachineFunction &MF = DAG.getMachineFunction();
2123
2124 if (IsVarArg) {
2125 return lowerUnhandledCall(CLI, InVals,
2126 "unsupported call to variadic function ");
2127 }
2128
2129 if (!CLI.CS.getCalledFunction()) {
2130 return lowerUnhandledCall(CLI, InVals,
2131 "unsupported indirect call to function ");
2132 }
2133
2134 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2135 return lowerUnhandledCall(CLI, InVals,
2136 "unsupported required tail call to function ");
2137 }
2138
2139 // The first 4 bytes are reserved for the callee's emergency stack slot.
2140 const unsigned CalleeUsableStackOffset = 4;
2141
2142 if (IsTailCall) {
2143 IsTailCall = isEligibleForTailCallOptimization(
2144 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2145 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2146 report_fatal_error("failed to perform tail call elimination on a call "
2147 "site marked musttail");
2148 }
2149
2150 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2151
2152 // A sibling call is one where we're under the usual C ABI and not planning
2153 // to change that but can still do a tail call:
2154 if (!TailCallOpt && IsTailCall)
2155 IsSibCall = true;
2156
2157 if (IsTailCall)
2158 ++NumTailCalls;
2159 }
2160
2161 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) {
2162 // FIXME: Remove this hack for function pointer types after removing
2163 // support of old address space mapping. In the new address space
2164 // mapping the pointer in default address space is 64 bit, therefore
2165 // does not need this hack.
2166 if (Callee.getValueType() == MVT::i32) {
2167 const GlobalValue *GV = GA->getGlobal();
2168 Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false,
2169 GA->getTargetFlags());
2170 }
2171 }
2172 assert(Callee.getValueType() == MVT::i64)(static_cast <bool> (Callee.getValueType() == MVT::i64)
? void (0) : __assert_fail ("Callee.getValueType() == MVT::i64"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2172, __extension__ __PRETTY_FUNCTION__))
;
2173
2174 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2175
2176 // Analyze operands of the call, assigning locations to each operand.
2177 SmallVector<CCValAssign, 16> ArgLocs;
2178 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2179 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2180 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2181
2182 // Get a count of how many bytes are to be pushed on the stack.
2183 unsigned NumBytes = CCInfo.getNextStackOffset();
2184
2185 if (IsSibCall) {
2186 // Since we're not changing the ABI to make this a tail call, the memory
2187 // operands are already available in the caller's incoming argument space.
2188 NumBytes = 0;
2189 }
2190
2191 // FPDiff is the byte offset of the call's argument area from the callee's.
2192 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2193 // by this amount for a tail call. In a sibling call it must be 0 because the
2194 // caller will deallocate the entire stack and the callee still expects its
2195 // arguments to begin at SP+0. Completely unused for non-tail calls.
2196 int32_t FPDiff = 0;
2197 MachineFrameInfo &MFI = MF.getFrameInfo();
2198 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2199
2200 SDValue CallerSavedFP;
2201
2202 // Adjust the stack pointer for the new arguments...
2203 // These operations are automatically eliminated by the prolog/epilog pass
2204 if (!IsSibCall) {
2205 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2206
2207 unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2208
2209 // In the HSA case, this should be an identity copy.
2210 SDValue ScratchRSrcReg
2211 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2212 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2213
2214 // TODO: Don't hardcode these registers and get from the callee function.
2215 SDValue ScratchWaveOffsetReg
2216 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2217 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2218
2219 if (!Info->isEntryFunction()) {
2220 // Avoid clobbering this function's FP value. In the current convention
2221 // callee will overwrite this, so do save/restore around the call site.
2222 CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2223 Info->getFrameOffsetReg(), MVT::i32);
2224 }
2225 }
2226
2227 // Stack pointer relative accesses are done by changing the offset SGPR. This
2228 // is just the VGPR offset component.
2229 SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32);
2230
2231 SmallVector<SDValue, 8> MemOpChains;
2232 MVT PtrVT = MVT::i32;
2233
2234 // Walk the register/memloc assignments, inserting copies/loads.
2235 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2236 ++i, ++realArgIdx) {
2237 CCValAssign &VA = ArgLocs[i];
2238 SDValue Arg = OutVals[realArgIdx];
2239
2240 // Promote the value if needed.
2241 switch (VA.getLocInfo()) {
2242 case CCValAssign::Full:
2243 break;
2244 case CCValAssign::BCvt:
2245 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2246 break;
2247 case CCValAssign::ZExt:
2248 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2249 break;
2250 case CCValAssign::SExt:
2251 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2252 break;
2253 case CCValAssign::AExt:
2254 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2255 break;
2256 case CCValAssign::FPExt:
2257 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2258 break;
2259 default:
2260 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2260)
;
2261 }
2262
2263 if (VA.isRegLoc()) {
2264 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2265 } else {
2266 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2266, __extension__ __PRETTY_FUNCTION__))
;
2267
2268 SDValue DstAddr;
2269 MachinePointerInfo DstInfo;
2270
2271 unsigned LocMemOffset = VA.getLocMemOffset();
2272 int32_t Offset = LocMemOffset;
2273
2274 SDValue PtrOff = DAG.getObjectPtrOffset(DL, StackPtr, Offset);
2275
2276 if (IsTailCall) {
2277 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2278 unsigned OpSize = Flags.isByVal() ?
2279 Flags.getByValSize() : VA.getValVT().getStoreSize();
2280
2281 Offset = Offset + FPDiff;
2282 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2283
2284 DstAddr = DAG.getObjectPtrOffset(DL, DAG.getFrameIndex(FI, PtrVT),
2285 StackPtr);
2286 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2287
2288 // Make sure any stack arguments overlapping with where we're storing
2289 // are loaded before this eventual operation. Otherwise they'll be
2290 // clobbered.
2291
2292 // FIXME: Why is this really necessary? This seems to just result in a
2293 // lot of code to copy the stack and write them back to the same
2294 // locations, which are supposed to be immutable?
2295 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2296 } else {
2297 DstAddr = PtrOff;
2298 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2299 }
2300
2301 if (Outs[i].Flags.isByVal()) {
2302 SDValue SizeNode =
2303 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2304 SDValue Cpy = DAG.getMemcpy(
2305 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2306 /*isVol = */ false, /*AlwaysInline = */ true,
2307 /*isTailCall = */ false, DstInfo,
2308 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2309 *DAG.getContext(), AMDGPUASI.PRIVATE_ADDRESS))));
2310
2311 MemOpChains.push_back(Cpy);
2312 } else {
2313 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
2314 MemOpChains.push_back(Store);
2315 }
2316 }
2317 }
2318
2319 // Copy special input registers after user input arguments.
2320 passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr);
2321
2322 if (!MemOpChains.empty())
2323 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2324
2325 // Build a sequence of copy-to-reg nodes chained together with token chain
2326 // and flag operands which copy the outgoing args into the appropriate regs.
2327 SDValue InFlag;
2328 for (auto &RegToPass : RegsToPass) {
2329 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2330 RegToPass.second, InFlag);
2331 InFlag = Chain.getValue(1);
2332 }
2333
2334
2335 SDValue PhysReturnAddrReg;
2336 if (IsTailCall) {
2337 // Since the return is being combined with the call, we need to pass on the
2338 // return address.
2339
2340 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2341 SDValue ReturnAddrReg = CreateLiveInRegister(
2342 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2343
2344 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2345 MVT::i64);
2346 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2347 InFlag = Chain.getValue(1);
2348 }
2349
2350 // We don't usually want to end the call-sequence here because we would tidy
2351 // the frame up *after* the call, however in the ABI-changing tail-call case
2352 // we've carefully laid out the parameters so that when sp is reset they'll be
2353 // in the correct location.
2354 if (IsTailCall && !IsSibCall) {
2355 Chain = DAG.getCALLSEQ_END(Chain,
2356 DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2357 DAG.getTargetConstant(0, DL, MVT::i32),
2358 InFlag, DL);
2359 InFlag = Chain.getValue(1);
2360 }
2361
2362 std::vector<SDValue> Ops;
2363 Ops.push_back(Chain);
2364 Ops.push_back(Callee);
2365
2366 if (IsTailCall) {
2367 // Each tail call may have to adjust the stack by a different amount, so
2368 // this information must travel along with the operation for eventual
2369 // consumption by emitEpilogue.
2370 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2371
2372 Ops.push_back(PhysReturnAddrReg);
2373 }
2374
2375 // Add argument registers to the end of the list so that they are known live
2376 // into the call.
2377 for (auto &RegToPass : RegsToPass) {
2378 Ops.push_back(DAG.getRegister(RegToPass.first,
2379 RegToPass.second.getValueType()));
2380 }
2381
2382 // Add a register mask operand representing the call-preserved registers.
2383
2384 const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo();
2385 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2386 assert(Mask && "Missing call preserved mask for calling convention")(static_cast <bool> (Mask && "Missing call preserved mask for calling convention"
) ? void (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2386, __extension__ __PRETTY_FUNCTION__))
;
2387 Ops.push_back(DAG.getRegisterMask(Mask));
2388
2389 if (InFlag.getNode())
2390 Ops.push_back(InFlag);
2391
2392 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2393
2394 // If we're doing a tall call, use a TC_RETURN here rather than an
2395 // actual call instruction.
2396 if (IsTailCall) {
2397 MFI.setHasTailCall();
2398 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2399 }
2400
2401 // Returns a chain and a flag for retval copy to use.
2402 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2403 Chain = Call.getValue(0);
2404 InFlag = Call.getValue(1);
2405
2406 if (CallerSavedFP) {
2407 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2408 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2409 InFlag = Chain.getValue(1);
2410 }
2411
2412 uint64_t CalleePopBytes = NumBytes;
2413 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2414 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2415 InFlag, DL);
2416 if (!Ins.empty())
2417 InFlag = Chain.getValue(1);
2418
2419 // Handle result values, copying them out of physregs into vregs that we
2420 // return.
2421 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2422 InVals, IsThisReturn,
2423 IsThisReturn ? OutVals[0] : SDValue());
2424}
2425
2426unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2427 SelectionDAG &DAG) const {
2428 unsigned Reg = StringSwitch<unsigned>(RegName)
2429 .Case("m0", AMDGPU::M0)
2430 .Case("exec", AMDGPU::EXEC)
2431 .Case("exec_lo", AMDGPU::EXEC_LO)
2432 .Case("exec_hi", AMDGPU::EXEC_HI)
2433 .Case("flat_scratch", AMDGPU::FLAT_SCR)
2434 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2435 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2436 .Default(AMDGPU::NoRegister);
2437
2438 if (Reg == AMDGPU::NoRegister) {
2439 report_fatal_error(Twine("invalid register name \""
2440 + StringRef(RegName) + "\"."));
2441
2442 }
2443
2444 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
2445 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2446 report_fatal_error(Twine("invalid register \""
2447 + StringRef(RegName) + "\" for subtarget."));
2448 }
2449
2450 switch (Reg) {
2451 case AMDGPU::M0:
2452 case AMDGPU::EXEC_LO:
2453 case AMDGPU::EXEC_HI:
2454 case AMDGPU::FLAT_SCR_LO:
2455 case AMDGPU::FLAT_SCR_HI:
2456 if (VT.getSizeInBits() == 32)
2457 return Reg;
2458 break;
2459 case AMDGPU::EXEC:
2460 case AMDGPU::FLAT_SCR:
2461 if (VT.getSizeInBits() == 64)
2462 return Reg;
2463 break;
2464 default:
2465 llvm_unreachable("missing register type checking")::llvm::llvm_unreachable_internal("missing register type checking"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2465)
;
2466 }
2467
2468 report_fatal_error(Twine("invalid type for register \""
2469 + StringRef(RegName) + "\"."));
2470}
2471
2472// If kill is not the last instruction, split the block so kill is always a
2473// proper terminator.
2474MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2475 MachineBasicBlock *BB) const {
2476 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2477
2478 MachineBasicBlock::iterator SplitPoint(&MI);
2479 ++SplitPoint;
2480
2481 if (SplitPoint == BB->end()) {
2482 // Don't bother with a new block.
2483 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2484 return BB;
2485 }
2486
2487 MachineFunction *MF = BB->getParent();
2488 MachineBasicBlock *SplitBB
2489 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2490
2491 MF->insert(++MachineFunction::iterator(BB), SplitBB);
2492 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2493
2494 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2495 BB->addSuccessor(SplitBB);
2496
2497 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2498 return SplitBB;
2499}
2500
2501// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2502// wavefront. If the value is uniform and just happens to be in a VGPR, this
2503// will only do one iteration. In the worst case, this will loop 64 times.
2504//
2505// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2506static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
2507 const SIInstrInfo *TII,
2508 MachineRegisterInfo &MRI,
2509 MachineBasicBlock &OrigBB,
2510 MachineBasicBlock &LoopBB,
2511 const DebugLoc &DL,
2512 const MachineOperand &IdxReg,
2513 unsigned InitReg,
2514 unsigned ResultReg,
2515 unsigned PhiReg,
2516 unsigned InitSaveExecReg,
2517 int Offset,
2518 bool UseGPRIdxMode) {
2519 MachineBasicBlock::iterator I = LoopBB.begin();
2520
2521 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2522 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2523 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2524 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2525
2526 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2527 .addReg(InitReg)
2528 .addMBB(&OrigBB)
2529 .addReg(ResultReg)
2530 .addMBB(&LoopBB);
2531
2532 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2533 .addReg(InitSaveExecReg)
2534 .addMBB(&OrigBB)
2535 .addReg(NewExec)
2536 .addMBB(&LoopBB);
2537
2538 // Read the next variant <- also loop target.
2539 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2540 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2541
2542 // Compare the just read M0 value to all possible Idx values.
2543 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2544 .addReg(CurrentIdxReg)
2545 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2546
2547 if (UseGPRIdxMode) {
2548 unsigned IdxReg;
2549 if (Offset == 0) {
2550 IdxReg = CurrentIdxReg;
2551 } else {
2552 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2553 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2554 .addReg(CurrentIdxReg, RegState::Kill)
2555 .addImm(Offset);
2556 }
2557
2558 MachineInstr *SetIdx =
2559 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
2560 .addReg(IdxReg, RegState::Kill);
2561 SetIdx->getOperand(2).setIsUndef();
2562 } else {
2563 // Move index from VCC into M0
2564 if (Offset == 0) {
2565 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2566 .addReg(CurrentIdxReg, RegState::Kill);
2567 } else {
2568 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2569 .addReg(CurrentIdxReg, RegState::Kill)
2570 .addImm(Offset);
2571 }
2572 }
2573
2574 // Update EXEC, save the original EXEC value to VCC.
2575 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
2576 .addReg(CondReg, RegState::Kill);
2577
2578 MRI.setSimpleHint(NewExec, CondReg);
2579
2580 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
2581 MachineInstr *InsertPt =
2582 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
2583 .addReg(AMDGPU::EXEC)
2584 .addReg(NewExec);
2585
2586 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
2587 // s_cbranch_scc0?
2588
2589 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
2590 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
2591 .addMBB(&LoopBB);
2592
2593 return InsertPt->getIterator();
2594}
2595
2596// This has slightly sub-optimal regalloc when the source vector is killed by
2597// the read. The register allocator does not understand that the kill is
2598// per-workitem, so is kept alive for the whole loop so we end up not re-using a
2599// subregister from it, using 1 more VGPR than necessary. This was saved when
2600// this was expanded after register allocation.
2601static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
2602 MachineBasicBlock &MBB,
2603 MachineInstr &MI,
2604 unsigned InitResultReg,
2605 unsigned PhiReg,
2606 int Offset,
2607 bool UseGPRIdxMode) {
2608 MachineFunction *MF = MBB.getParent();
2609 MachineRegisterInfo &MRI = MF->getRegInfo();
2610 const DebugLoc &DL = MI.getDebugLoc();
2611 MachineBasicBlock::iterator I(&MI);
2612
2613 unsigned DstReg = MI.getOperand(0).getReg();
2614 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2615 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2616
2617 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
2618
2619 // Save the EXEC mask
2620 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
2621 .addReg(AMDGPU::EXEC);
2622
2623 // To insert the loop we need to split the block. Move everything after this
2624 // point to a new block, and insert a new empty block between the two.
2625 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
2626 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2627 MachineFunction::iterator MBBI(MBB);
2628 ++MBBI;
2629
2630 MF->insert(MBBI, LoopBB);
2631 MF->insert(MBBI, RemainderBB);
2632
2633 LoopBB->addSuccessor(LoopBB);
2634 LoopBB->addSuccessor(RemainderBB);
2635
2636 // Move the rest of the block into a new block.
2637 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
2638 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
2639
2640 MBB.addSuccessor(LoopBB);
2641
2642 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2643
2644 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
2645 InitResultReg, DstReg, PhiReg, TmpExec,
2646 Offset, UseGPRIdxMode);
2647
2648 MachineBasicBlock::iterator First = RemainderBB->begin();
2649 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
2650 .addReg(SaveExec);
2651
2652 return InsPt;
2653}
2654
2655// Returns subreg index, offset
2656static std::pair<unsigned, int>
2657computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
2658 const TargetRegisterClass *SuperRC,
2659 unsigned VecReg,
2660 int Offset) {
2661 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
2662
2663 // Skip out of bounds offsets, or else we would end up using an undefined
2664 // register.
2665 if (Offset >= NumElts || Offset < 0)
2666 return std::make_pair(AMDGPU::sub0, Offset);
2667
2668 return std::make_pair(AMDGPU::sub0 + Offset, 0);
2669}
2670
2671// Return true if the index is an SGPR and was set.
2672static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
2673 MachineRegisterInfo &MRI,
2674 MachineInstr &MI,
2675 int Offset,
2676 bool UseGPRIdxMode,
2677 bool IsIndirectSrc) {
2678 MachineBasicBlock *MBB = MI.getParent();
2679 const DebugLoc &DL = MI.getDebugLoc();
2680 MachineBasicBlock::iterator I(&MI);
2681
2682 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2683 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
2684
2685 assert(Idx->getReg() != AMDGPU::NoRegister)(static_cast <bool> (Idx->getReg() != AMDGPU::NoRegister
) ? void (0) : __assert_fail ("Idx->getReg() != AMDGPU::NoRegister"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2685, __extension__ __PRETTY_FUNCTION__))
;
2686
2687 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
2688 return false;
2689
2690 if (UseGPRIdxMode) {
2691 unsigned IdxMode = IsIndirectSrc ?
2692 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2693 if (Offset == 0) {
2694 MachineInstr *SetOn =
2695 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2696 .add(*Idx)
2697 .addImm(IdxMode);
2698
2699 SetOn->getOperand(3).setIsUndef();
2700 } else {
2701 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2702 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
2703 .add(*Idx)
2704 .addImm(Offset);
2705 MachineInstr *SetOn =
2706 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2707 .addReg(Tmp, RegState::Kill)
2708 .addImm(IdxMode);
2709
2710 SetOn->getOperand(3).setIsUndef();
2711 }
2712
2713 return true;
2714 }
2715
2716 if (Offset == 0) {
2717 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2718 .add(*Idx);
2719 } else {
2720 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2721 .add(*Idx)
2722 .addImm(Offset);
2723 }
2724
2725 return true;
2726}
2727
2728// Control flow needs to be inserted if indexing with a VGPR.
2729static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
2730 MachineBasicBlock &MBB,
2731 const SISubtarget &ST) {
2732 const SIInstrInfo *TII = ST.getInstrInfo();
2733 const SIRegisterInfo &TRI = TII->getRegisterInfo();
2734 MachineFunction *MF = MBB.getParent();
2735 MachineRegisterInfo &MRI = MF->getRegInfo();
2736
2737 unsigned Dst = MI.getOperand(0).getReg();
2738 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
2739 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
2740
2741 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
2742
2743 unsigned SubReg;
2744 std::tie(SubReg, Offset)
2745 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
2746
2747 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
2748
2749 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
2750 MachineBasicBlock::iterator I(&MI);
2751 const DebugLoc &DL = MI.getDebugLoc();
2752
2753 if (UseGPRIdxMode) {
2754 // TODO: Look at the uses to avoid the copy. This may require rescheduling
2755 // to avoid interfering with other uses, so probably requires a new
2756 // optimization pass.
2757 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
2758 .addReg(SrcReg, RegState::Undef, SubReg)
2759 .addReg(SrcReg, RegState::Implicit)
2760 .addReg(AMDGPU::M0, RegState::Implicit);
2761 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2762 } else {
2763 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
2764 .addReg(SrcReg, RegState::Undef, SubReg)
2765 .addReg(SrcReg, RegState::Implicit);
2766 }
2767
2768 MI.eraseFromParent();
2769
2770 return &MBB;
2771 }
2772
2773 const DebugLoc &DL = MI.getDebugLoc();
2774 MachineBasicBlock::iterator I(&MI);
2775
2776 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2777 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2778
2779 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
2780
2781 if (UseGPRIdxMode) {
2782 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2783 .addImm(0) // Reset inside loop.
2784 .addImm(VGPRIndexMode::SRC0_ENABLE);
2785 SetOn->getOperand(3).setIsUndef();
2786
2787 // Disable again after the loop.
2788 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2789 }
2790
2791 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
2792 MachineBasicBlock *LoopBB = InsPt->getParent();
2793
2794 if (UseGPRIdxMode) {
2795 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
2796 .addReg(SrcReg, RegState::Undef, SubReg)
2797 .addReg(SrcReg, RegState::Implicit)
2798 .addReg(AMDGPU::M0, RegState::Implicit);
2799 } else {
2800 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
2801 .addReg(SrcReg, RegState::Undef, SubReg)
2802 .addReg(SrcReg, RegState::Implicit);
2803 }
2804
2805 MI.eraseFromParent();
2806
2807 return LoopBB;
2808}
2809
2810static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
2811 const TargetRegisterClass *VecRC) {
2812 switch (TRI.getRegSizeInBits(*VecRC)) {
2813 case 32: // 4 bytes
2814 return AMDGPU::V_MOVRELD_B32_V1;
2815 case 64: // 8 bytes
2816 return AMDGPU::V_MOVRELD_B32_V2;
2817 case 128: // 16 bytes
2818 return AMDGPU::V_MOVRELD_B32_V4;
2819 case 256: // 32 bytes
2820 return AMDGPU::V_MOVRELD_B32_V8;
2821 case 512: // 64 bytes
2822 return AMDGPU::V_MOVRELD_B32_V16;
2823 default:
2824 llvm_unreachable("unsupported size for MOVRELD pseudos")::llvm::llvm_unreachable_internal("unsupported size for MOVRELD pseudos"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2824)
;
2825 }
2826}
2827
2828static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
2829 MachineBasicBlock &MBB,
2830 const SISubtarget &ST) {
2831 const SIInstrInfo *TII = ST.getInstrInfo();
2832 const SIRegisterInfo &TRI = TII->getRegisterInfo();
2833 MachineFunction *MF = MBB.getParent();
2834 MachineRegisterInfo &MRI = MF->getRegInfo();
2835
2836 unsigned Dst = MI.getOperand(0).getReg();
2837 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
2838 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2839 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
2840 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
2841 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
2842
2843 // This can be an immediate, but will be folded later.
2844 assert(Val->getReg())(static_cast <bool> (Val->getReg()) ? void (0) : __assert_fail
("Val->getReg()", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2844, __extension__ __PRETTY_FUNCTION__))
;
2845
2846 unsigned SubReg;
2847 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
2848 SrcVec->getReg(),
2849 Offset);
2850 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
2851
2852 if (Idx->getReg() == AMDGPU::NoRegister) {
2853 MachineBasicBlock::iterator I(&MI);
2854 const DebugLoc &DL = MI.getDebugLoc();
2855
2856 assert(Offset == 0)(static_cast <bool> (Offset == 0) ? void (0) : __assert_fail
("Offset == 0", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2856, __extension__ __PRETTY_FUNCTION__))
;
2857
2858 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
2859 .add(*SrcVec)
2860 .add(*Val)
2861 .addImm(SubReg);
2862
2863 MI.eraseFromParent();
2864 return &MBB;
2865 }
2866
2867 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
2868 MachineBasicBlock::iterator I(&MI);
2869 const DebugLoc &DL = MI.getDebugLoc();
2870
2871 if (UseGPRIdxMode) {
2872 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
2873 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
2874 .add(*Val)
2875 .addReg(Dst, RegState::ImplicitDefine)
2876 .addReg(SrcVec->getReg(), RegState::Implicit)
2877 .addReg(AMDGPU::M0, RegState::Implicit);
2878
2879 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2880 } else {
2881 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
2882
2883 BuildMI(MBB, I, DL, MovRelDesc)
2884 .addReg(Dst, RegState::Define)
2885 .addReg(SrcVec->getReg())
2886 .add(*Val)
2887 .addImm(SubReg - AMDGPU::sub0);
2888 }
2889
2890 MI.eraseFromParent();
2891 return &MBB;
2892 }
2893
2894 if (Val->isReg())
2895 MRI.clearKillFlags(Val->getReg());
2896
2897 const DebugLoc &DL = MI.getDebugLoc();
2898
2899 if (UseGPRIdxMode) {
2900 MachineBasicBlock::iterator I(&MI);
2901
2902 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2903 .addImm(0) // Reset inside loop.
2904 .addImm(VGPRIndexMode::DST_ENABLE);
2905 SetOn->getOperand(3).setIsUndef();
2906
2907 // Disable again after the loop.
2908 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2909 }
2910
2911 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
2912
2913 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
2914 Offset, UseGPRIdxMode);
2915 MachineBasicBlock *LoopBB = InsPt->getParent();
2916
2917 if (UseGPRIdxMode) {
2918 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
2919 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
2920 .add(*Val) // src0
2921 .addReg(Dst, RegState::ImplicitDefine)
2922 .addReg(PhiReg, RegState::Implicit)
2923 .addReg(AMDGPU::M0, RegState::Implicit);
2924 } else {
2925 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
2926
2927 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
2928 .addReg(Dst, RegState::Define)
2929 .addReg(PhiReg)
2930 .add(*Val)
2931 .addImm(SubReg - AMDGPU::sub0);
2932 }
2933
2934 MI.eraseFromParent();
2935
2936 return LoopBB;
2937}
2938
2939MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
2940 MachineInstr &MI, MachineBasicBlock *BB) const {
2941
2942 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2943 MachineFunction *MF = BB->getParent();
2944 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
2945
2946 if (TII->isMIMG(MI)) {
2947 if (!MI.memoperands_empty())
2948 return BB;
2949 // Add a memoperand for mimg instructions so that they aren't assumed to
2950 // be ordered memory instuctions.
2951
2952 MachinePointerInfo PtrInfo(MFI->getImagePSV());
2953 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable;
2954 if (MI.mayStore())
2955 Flags |= MachineMemOperand::MOStore;
2956
2957 if (MI.mayLoad())
2958 Flags |= MachineMemOperand::MOLoad;
2959
2960 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0);
2961 MI.addMemOperand(*MF, MMO);
2962 return BB;
2963 }
2964
2965 switch (MI.getOpcode()) {
2966 case AMDGPU::S_ADD_U64_PSEUDO:
2967 case AMDGPU::S_SUB_U64_PSEUDO: {
2968 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
2969 const DebugLoc &DL = MI.getDebugLoc();
2970
2971 MachineOperand &Dest = MI.getOperand(0);
2972 MachineOperand &Src0 = MI.getOperand(1);
2973 MachineOperand &Src1 = MI.getOperand(2);
2974
2975 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2976 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2977
2978 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
2979 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
2980 &AMDGPU::SReg_32_XM0RegClass);
2981 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
2982 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
2983 &AMDGPU::SReg_32_XM0RegClass);
2984
2985 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
2986 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
2987 &AMDGPU::SReg_32_XM0RegClass);
2988 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
2989 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
2990 &AMDGPU::SReg_32_XM0RegClass);
2991
2992 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
2993
2994 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
2995 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
2996 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
2997 .add(Src0Sub0)
2998 .add(Src1Sub0);
2999 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3000 .add(Src0Sub1)
3001 .add(Src1Sub1);
3002 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3003 .addReg(DestSub0)
3004 .addImm(AMDGPU::sub0)
3005 .addReg(DestSub1)
3006 .addImm(AMDGPU::sub1);
3007 MI.eraseFromParent();
3008 return BB;
3009 }
3010 case AMDGPU::SI_INIT_M0: {
3011 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3012 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3013 .add(MI.getOperand(0));
3014 MI.eraseFromParent();
3015 return BB;
3016 }
3017 case AMDGPU::SI_INIT_EXEC:
3018 // This should be before all vector instructions.
3019 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3020 AMDGPU::EXEC)
3021 .addImm(MI.getOperand(0).getImm());
3022 MI.eraseFromParent();
3023 return BB;
3024
3025 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3026 // Extract the thread count from an SGPR input and set EXEC accordingly.
3027 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3028 //
3029 // S_BFE_U32 count, input, {shift, 7}
3030 // S_BFM_B64 exec, count, 0
3031 // S_CMP_EQ_U32 count, 64
3032 // S_CMOV_B64 exec, -1
3033 MachineInstr *FirstMI = &*BB->begin();
3034 MachineRegisterInfo &MRI = MF->getRegInfo();
3035 unsigned InputReg = MI.getOperand(0).getReg();
3036 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3037 bool Found = false;
3038
3039 // Move the COPY of the input reg to the beginning, so that we can use it.
3040 for (auto I = BB->begin(); I != &MI; I++) {
3041 if (I->getOpcode() != TargetOpcode::COPY ||
3042 I->getOperand(0).getReg() != InputReg)
3043 continue;
3044
3045 if (I == FirstMI) {
3046 FirstMI = &*++BB->begin();
3047 } else {
3048 I->removeFromParent();
3049 BB->insert(FirstMI, &*I);
3050 }
3051 Found = true;
3052 break;
3053 }
3054 assert(Found)(static_cast <bool> (Found) ? void (0) : __assert_fail (
"Found", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3054, __extension__ __PRETTY_FUNCTION__))
;
3055 (void)Found;
3056
3057 // This should be before all vector instructions.
3058 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3059 .addReg(InputReg)
3060 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
3061 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
3062 AMDGPU::EXEC)
3063 .addReg(CountReg)
3064 .addImm(0);
3065 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3066 .addReg(CountReg, RegState::Kill)
3067 .addImm(64);
3068 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
3069 AMDGPU::EXEC)
3070 .addImm(-1);
3071 MI.eraseFromParent();
3072 return BB;
3073 }
3074
3075 case AMDGPU::GET_GROUPSTATICSIZE: {
3076 DebugLoc DL = MI.getDebugLoc();
3077 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3078 .add(MI.getOperand(0))
3079 .addImm(MFI->getLDSSize());
3080 MI.eraseFromParent();
3081 return BB;
3082 }
3083 case AMDGPU::SI_INDIRECT_SRC_V1:
3084 case AMDGPU::SI_INDIRECT_SRC_V2:
3085 case AMDGPU::SI_INDIRECT_SRC_V4:
3086 case AMDGPU::SI_INDIRECT_SRC_V8:
3087 case AMDGPU::SI_INDIRECT_SRC_V16:
3088 return emitIndirectSrc(MI, *BB, *getSubtarget());
3089 case AMDGPU::SI_INDIRECT_DST_V1:
3090 case AMDGPU::SI_INDIRECT_DST_V2:
3091 case AMDGPU::SI_INDIRECT_DST_V4:
3092 case AMDGPU::SI_INDIRECT_DST_V8:
3093 case AMDGPU::SI_INDIRECT_DST_V16:
3094 return emitIndirectDst(MI, *BB, *getSubtarget());
3095 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3096 case AMDGPU::SI_KILL_I1_PSEUDO:
3097 return splitKillBlock(MI, BB);
3098 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3099 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3100
3101 unsigned Dst = MI.getOperand(0).getReg();
3102 unsigned Src0 = MI.getOperand(1).getReg();
3103 unsigned Src1 = MI.getOperand(2).getReg();
3104 const DebugLoc &DL = MI.getDebugLoc();
3105 unsigned SrcCond = MI.getOperand(3).getReg();
3106
3107 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3108 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3109 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3110
3111 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3112 .addReg(SrcCond);
3113 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3114 .addReg(Src0, 0, AMDGPU::sub0)
3115 .addReg(Src1, 0, AMDGPU::sub0)
3116 .addReg(SrcCondCopy);
3117 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3118 .addReg(Src0, 0, AMDGPU::sub1)
3119 .addReg(Src1, 0, AMDGPU::sub1)
3120 .addReg(SrcCondCopy);
3121
3122 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3123 .addReg(DstLo)
3124 .addImm(AMDGPU::sub0)
3125 .addReg(DstHi)
3126 .addImm(AMDGPU::sub1);
3127 MI.eraseFromParent();
3128 return BB;
3129 }
3130 case AMDGPU::SI_BR_UNDEF: {
3131 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3132 const DebugLoc &DL = MI.getDebugLoc();
3133 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3134 .add(MI.getOperand(0));
3135 Br->getOperand(1).setIsUndef(true); // read undef SCC
3136 MI.eraseFromParent();
3137 return BB;
3138 }
3139 case AMDGPU::ADJCALLSTACKUP:
3140 case AMDGPU::ADJCALLSTACKDOWN: {
3141 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3142 MachineInstrBuilder MIB(*MF, &MI);
3143 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3144 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
3145 return BB;
3146 }
3147 case AMDGPU::SI_CALL_ISEL:
3148 case AMDGPU::SI_TCRETURN_ISEL: {
3149 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3150 const DebugLoc &DL = MI.getDebugLoc();
3151 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3152
3153 MachineRegisterInfo &MRI = MF->getRegInfo();
3154 unsigned GlobalAddrReg = MI.getOperand(0).getReg();
3155 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg);
3156 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET)(static_cast <bool> (PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET
) ? void (0) : __assert_fail ("PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3156, __extension__ __PRETTY_FUNCTION__))
;
3157
3158 const GlobalValue *G = PCRel->getOperand(1).getGlobal();
3159
3160 MachineInstrBuilder MIB;
3161 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
3162 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg)
3163 .add(MI.getOperand(0))
3164 .addGlobalAddress(G);
3165 } else {
3166 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN))
3167 .add(MI.getOperand(0))
3168 .addGlobalAddress(G);
3169
3170 // There is an additional imm operand for tcreturn, but it should be in the
3171 // right place already.
3172 }
3173
3174 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3175 MIB.add(MI.getOperand(I));
3176
3177 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
3178 MI.eraseFromParent();
3179 return BB;
3180 }
3181 default:
3182 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3183 }
3184}
3185
3186bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3187 return isTypeLegal(VT.getScalarType());
3188}
3189
3190bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3191 // This currently forces unfolding various combinations of fsub into fma with
3192 // free fneg'd operands. As long as we have fast FMA (controlled by
3193 // isFMAFasterThanFMulAndFAdd), we should perform these.
3194
3195 // When fma is quarter rate, for f64 where add / sub are at best half rate,
3196 // most of these combines appear to be cycle neutral but save on instruction
3197 // count / code size.
3198 return true;
3199}
3200
3201EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3202 EVT VT) const {
3203 if (!VT.isVector()) {
3204 return MVT::i1;
3205 }
3206 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3207}
3208
3209MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3210 // TODO: Should i16 be used always if legal? For now it would force VALU
3211 // shifts.
3212 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3213}
3214
3215// Answering this is somewhat tricky and depends on the specific device which
3216// have different rates for fma or all f64 operations.
3217//
3218// v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3219// regardless of which device (although the number of cycles differs between
3220// devices), so it is always profitable for f64.
3221//
3222// v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3223// only on full rate devices. Normally, we should prefer selecting v_mad_f32
3224// which we can always do even without fused FP ops since it returns the same
3225// result as the separate operations and since it is always full
3226// rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3227// however does not support denormals, so we do report fma as faster if we have
3228// a fast fma device and require denormals.
3229//
3230bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3231 VT = VT.getScalarType();
3232
3233 switch (VT.getSimpleVT().SimpleTy) {
3234 case MVT::f32:
3235 // This is as fast on some subtargets. However, we always have full rate f32
3236 // mad available which returns the same result as the separate operations
3237 // which we should prefer over fma. We can't use this if we want to support
3238 // denormals, so only report this in these cases.
3239 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
3240 case MVT::f64:
3241 return true;
3242 case MVT::f16:
3243 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3244 default:
3245 break;
3246 }
3247
3248 return false;
3249}
3250
3251//===----------------------------------------------------------------------===//
3252// Custom DAG Lowering Operations
3253//===----------------------------------------------------------------------===//
3254
3255SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3256 switch (Op.getOpcode()) {
3257 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3258 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3259 case ISD::LOAD: {
3260 SDValue Result = LowerLOAD(Op, DAG);
3261 assert((!Result.getNode() ||(static_cast <bool> ((!Result.getNode() || Result.getNode
()->getNumValues() == 2) && "Load should return a value and a chain"
) ? void (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3263, __extension__ __PRETTY_FUNCTION__))
3262 Result.getNode()->getNumValues() == 2) &&(static_cast <bool> ((!Result.getNode() || Result.getNode
()->getNumValues() == 2) && "Load should return a value and a chain"
) ? void (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3263, __extension__ __PRETTY_FUNCTION__))
3263 "Load should return a value and a chain")(static_cast <bool> ((!Result.getNode() || Result.getNode
()->getNumValues() == 2) && "Load should return a value and a chain"
) ? void (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3263, __extension__ __PRETTY_FUNCTION__))
;
3264 return Result;
3265 }
3266
3267 case ISD::FSIN:
3268 case ISD::FCOS:
3269 return LowerTrig(Op, DAG);
3270 case ISD::SELECT: return LowerSELECT(Op, DAG);
3271 case ISD::FDIV: return LowerFDIV(Op, DAG);
3272 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3273 case ISD::STORE: return LowerSTORE(Op, DAG);
3274 case ISD::GlobalAddress: {
3275 MachineFunction &MF = DAG.getMachineFunction();
3276 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3277 return LowerGlobalAddress(MFI, Op, DAG);
3278 }
3279 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3280 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3281 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3282 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3283 case ISD::INSERT_VECTOR_ELT:
3284 return lowerINSERT_VECTOR_ELT(Op, DAG);
3285 case ISD::EXTRACT_VECTOR_ELT:
3286 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3287 case ISD::FP_ROUND:
3288 return lowerFP_ROUND(Op, DAG);
3289 case ISD::TRAP:
3290 case ISD::DEBUGTRAP:
3291 return lowerTRAP(Op, DAG);
3292 }
3293 return SDValue();
3294}
3295
3296void SITargetLowering::ReplaceNodeResults(SDNode *N,
3297 SmallVectorImpl<SDValue> &Results,
3298 SelectionDAG &DAG) const {
3299 switch (N->getOpcode()) {
3300 case ISD::INSERT_VECTOR_ELT: {
3301 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3302 Results.push_back(Res);
3303 return;
3304 }
3305 case ISD::EXTRACT_VECTOR_ELT: {
3306 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3307 Results.push_back(Res);
3308 return;
3309 }
3310 case ISD::INTRINSIC_WO_CHAIN: {
3311 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3312 if (IID == Intrinsic::amdgcn_cvt_pkrtz) {
3313 SDValue Src0 = N->getOperand(1);
3314 SDValue Src1 = N->getOperand(2);
3315 SDLoc SL(N);
3316 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
3317 Src0, Src1);
3318 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3319 return;
3320 }
3321 break;
3322 }
3323 case ISD::SELECT: {
3324 SDLoc SL(N);
3325 EVT VT = N->getValueType(0);
3326 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
3327 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
3328 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
3329
3330 EVT SelectVT = NewVT;
3331 if (NewVT.bitsLT(MVT::i32)) {
3332 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
3333 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
3334 SelectVT = MVT::i32;
3335 }
3336
3337 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
3338 N->getOperand(0), LHS, RHS);
3339
3340 if (NewVT != SelectVT)
3341 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
3342 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
3343 return;
3344 }
3345 default:
3346 break;
3347 }
3348}
3349
3350/// \brief Helper function for LowerBRCOND
3351static SDNode *findUser(SDValue Value, unsigned Opcode) {
3352
3353 SDNode *Parent = Value.getNode();
3354 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
3355 I != E; ++I) {
3356
3357 if (I.getUse().get() != Value)
3358 continue;
3359
3360 if (I->getOpcode() == Opcode)
3361 return *I;
3362 }
3363 return nullptr;
3364}
3365
3366unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
3367 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
3368 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
3369 case Intrinsic::amdgcn_if:
3370 return AMDGPUISD::IF;
3371 case Intrinsic::amdgcn_else:
3372 return AMDGPUISD::ELSE;
3373 case Intrinsic::amdgcn_loop:
3374 return AMDGPUISD::LOOP;
3375 case Intrinsic::amdgcn_end_cf:
3376 llvm_unreachable("should not occur")::llvm::llvm_unreachable_internal("should not occur", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3376)
;
3377 default:
3378 return 0;
3379 }
3380 }
3381
3382 // break, if_break, else_break are all only used as inputs to loop, not
3383 // directly as branch conditions.
3384 return 0;
3385}
3386
3387void SITargetLowering::createDebuggerPrologueStackObjects(
3388 MachineFunction &MF) const {
3389 // Create stack objects that are used for emitting debugger prologue.
3390 //
3391 // Debugger prologue writes work group IDs and work item IDs to scratch memory
3392 // at fixed location in the following format:
3393 // offset 0: work group ID x
3394 // offset 4: work group ID y
3395 // offset 8: work group ID z
3396 // offset 16: work item ID x
3397 // offset 20: work item ID y
3398 // offset 24: work item ID z
3399 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3400 int ObjectIdx = 0;
3401
3402 // For each dimension:
3403 for (unsigned i = 0; i < 3; ++i) {
3404 // Create fixed stack object for work group ID.
3405 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
3406 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
3407 // Create fixed stack object for work item ID.
3408 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
3409 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
3410 }
3411}
3412
3413bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
3414 const Triple &TT = getTargetMachine().getTargetTriple();
3415 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS &&
3416 AMDGPU::shouldEmitConstantsToTextSection(TT);
3417}
3418
3419bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
3420 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
3421 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
3422 !shouldEmitFixup(GV) &&
3423 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3424}
3425
3426bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
3427 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
3428}
3429
3430/// This transforms the control flow intrinsics to get the branch destination as
3431/// last parameter, also switches branch target with BR if the need arise
3432SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
3433 SelectionDAG &DAG) const {
3434 SDLoc DL(BRCOND);
3435
3436 SDNode *Intr = BRCOND.getOperand(1).getNode();
3437 SDValue Target = BRCOND.getOperand(2);
3438 SDNode *BR = nullptr;
3439 SDNode *SetCC = nullptr;
3440
3441 if (Intr->getOpcode() == ISD::SETCC) {
3442 // As long as we negate the condition everything is fine
3443 SetCC = Intr;
3444 Intr = SetCC->getOperand(0).getNode();
3445
3446 } else {
3447 // Get the target from BR if we don't negate the condition
3448 BR = findUser(BRCOND, ISD::BR);
3449 Target = BR->getOperand(1);
3450 }
3451
3452 // FIXME: This changes the types of the intrinsics instead of introducing new
3453 // nodes with the correct types.
3454 // e.g. llvm.amdgcn.loop
3455
3456 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
3457 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
3458
3459 unsigned CFNode = isCFIntrinsic(Intr);
3460 if (CFNode == 0) {
3461 // This is a uniform branch so we don't need to legalize.
3462 return BRCOND;
3463 }
3464
3465 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
3466 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
3467
3468 assert(!SetCC ||(static_cast <bool> (!SetCC || (SetCC->getConstantOperandVal
(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand
(2).getNode())->get() == ISD::SETNE)) ? void (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3471, __extension__ __PRETTY_FUNCTION__))
3469 (SetCC->getConstantOperandVal(1) == 1 &&(static_cast <bool> (!SetCC || (SetCC->getConstantOperandVal
(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand
(2).getNode())->get() == ISD::SETNE)) ? void (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3471, __extension__ __PRETTY_FUNCTION__))
3470 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==(static_cast <bool> (!SetCC || (SetCC->getConstantOperandVal
(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand
(2).getNode())->get() == ISD::SETNE)) ? void (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3471, __extension__ __PRETTY_FUNCTION__))
3471 ISD::SETNE))(static_cast <bool> (!SetCC || (SetCC->getConstantOperandVal
(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand
(2).getNode())->get() == ISD::SETNE)) ? void (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3471, __extension__ __PRETTY_FUNCTION__))
;
3472
3473 // operands of the new intrinsic call
3474 SmallVector<SDValue, 4> Ops;
3475 if (HaveChain)
3476 Ops.push_back(BRCOND.getOperand(0));
3477
3478 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
3479 Ops.push_back(Target);
3480
3481 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
3482
3483 // build the new intrinsic call
3484 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
3485
3486 if (!HaveChain) {
3487 SDValue Ops[] = {
3488 SDValue(Result, 0),
3489 BRCOND.getOperand(0)
3490 };
3491
3492 Result = DAG.getMergeValues(Ops, DL).getNode();
3493 }
3494
3495 if (BR) {
3496 // Give the branch instruction our target
3497 SDValue Ops[] = {
3498 BR->getOperand(0),
3499 BRCOND.getOperand(2)
3500 };
3501 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
3502 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
3503 BR = NewBR.getNode();
3504 }
3505
3506 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
3507
3508 // Copy the intrinsic results to registers
3509 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
3510 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
3511 if (!CopyToReg)
3512 continue;
3513
3514 Chain = DAG.getCopyToReg(
3515 Chain, DL,
3516 CopyToReg->getOperand(1),
3517 SDValue(Result, i - 1),
3518 SDValue());
3519
3520 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
3521 }
3522
3523 // Remove the old intrinsic from the chain
3524 DAG.ReplaceAllUsesOfValueWith(
3525 SDValue(Intr, Intr->getNumValues() - 1),
3526 Intr->getOperand(0));
3527
3528 return Chain;
3529}
3530
3531SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
3532 SDValue Op,
3533 const SDLoc &DL,
3534 EVT VT) const {
3535 return Op.getValueType().bitsLE(VT) ?
3536 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
3537 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
3538}
3539
3540SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
3541 assert(Op.getValueType() == MVT::f16 &&(static_cast <bool> (Op.getValueType() == MVT::f16 &&
"Do not know how to custom lower FP_ROUND for non-f16 type")
? void (0) : __assert_fail ("Op.getValueType() == MVT::f16 && \"Do not know how to custom lower FP_ROUND for non-f16 type\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3542, __extension__ __PRETTY_FUNCTION__))
3542 "Do not know how to custom lower FP_ROUND for non-f16 type")(static_cast <bool> (Op.getValueType() == MVT::f16 &&
"Do not know how to custom lower FP_ROUND for non-f16 type")
? void (0) : __assert_fail ("Op.getValueType() == MVT::f16 && \"Do not know how to custom lower FP_ROUND for non-f16 type\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3542, __extension__ __PRETTY_FUNCTION__))
;
3543
3544 SDValue Src = Op.getOperand(0);
3545 EVT SrcVT = Src.getValueType();
3546 if (SrcVT != MVT::f64)
3547 return Op;
3548
3549 SDLoc DL(Op);
3550
3551 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
3552 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
3553 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
3554}
3555
3556SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
3557 SDLoc SL(Op);
3558 MachineFunction &MF = DAG.getMachineFunction();
3559 SDValue Chain = Op.getOperand(0);
3560
3561 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ?
3562 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap;
3563
3564 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
3565 Subtarget->isTrapHandlerEnabled()) {
3566 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3567 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
3568 assert(UserSGPR != AMDGPU::NoRegister)(static_cast <bool> (UserSGPR != AMDGPU::NoRegister) ? void
(0) : __assert_fail ("UserSGPR != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3568, __extension__ __PRETTY_FUNCTION__))
;
3569
3570 SDValue QueuePtr = CreateLiveInRegister(
3571 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
3572
3573 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
3574
3575 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
3576 QueuePtr, SDValue());
3577
3578 SDValue Ops[] = {
3579 ToReg,
3580 DAG.getTargetConstant(TrapID, SL, MVT::i16),
3581 SGPR01,
3582 ToReg.getValue(1)
3583 };
3584
3585 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
3586 }
3587
3588 switch (TrapID) {
3589 case SISubtarget::TrapIDLLVMTrap:
3590 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
3591 case SISubtarget::TrapIDLLVMDebugTrap: {
3592 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(),
3593 "debugtrap handler not supported",
3594 Op.getDebugLoc(),
3595 DS_Warning);
3596 LLVMContext &Ctx = MF.getFunction()->getContext();
3597 Ctx.diagnose(NoTrap);
3598 return Chain;
3599 }
3600 default:
3601 llvm_unreachable("unsupported trap handler type!")::llvm::llvm_unreachable_internal("unsupported trap handler type!"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3601)
;
3602 }
3603
3604 return Chain;
3605}
3606
3607SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
3608 SelectionDAG &DAG) const {
3609 // FIXME: Use inline constants (src_{shared, private}_base) instead.
3610 if (Subtarget->hasApertureRegs()) {
3611 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
3612 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
3613 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
3614 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
3615 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
3616 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
3617 unsigned Encoding =
3618 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
3619 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
3620 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
3621
3622 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
3623 SDValue ApertureReg = SDValue(
3624 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
3625 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
3626 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
3627 }
3628
3629 MachineFunction &MF = DAG.getMachineFunction();
3630 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3631 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
3632 assert(UserSGPR != AMDGPU::NoRegister)(static_cast <bool> (UserSGPR != AMDGPU::NoRegister) ? void
(0) : __assert_fail ("UserSGPR != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3632, __extension__ __PRETTY_FUNCTION__))
;
3633
3634 SDValue QueuePtr = CreateLiveInRegister(
3635 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
3636
3637 // Offset into amd_queue_t for group_segment_aperture_base_hi /
3638 // private_segment_aperture_base_hi.
3639 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
3640
3641 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
3642
3643 // TODO: Use custom target PseudoSourceValue.
3644 // TODO: We should use the value from the IR intrinsic call, but it might not
3645 // be available and how do we get it?
3646 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
3647 AMDGPUASI.CONSTANT_ADDRESS));
3648
3649 MachinePointerInfo PtrInfo(V, StructOffset);
3650 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
3651 MinAlign(64, StructOffset),
3652 MachineMemOperand::MODereferenceable |
3653 MachineMemOperand::MOInvariant);
3654}
3655
3656SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
3657 SelectionDAG &DAG) const {
3658 SDLoc SL(Op);
3659 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
3660
3661 SDValue Src = ASC->getOperand(0);
3662 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
3663
3664 const AMDGPUTargetMachine &TM =
3665 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
3666
3667 // flat -> local/private
3668 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
3669 unsigned DestAS = ASC->getDestAddressSpace();
3670
3671 if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
3672 DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
3673 unsigned NullVal = TM.getNullPointerValue(DestAS);
3674 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
3675 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
3676 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
3677
3678 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
3679 NonNull, Ptr, SegmentNullPtr);
3680 }
3681 }
3682
3683 // local/private -> flat
3684 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
3685 unsigned SrcAS = ASC->getSrcAddressSpace();
3686
3687 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
3688 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
3689 unsigned NullVal = TM.getNullPointerValue(SrcAS);
3690 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
3691
3692 SDValue NonNull
3693 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
3694
3695 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
3696 SDValue CvtPtr
3697 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
3698
3699 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
3700 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
3701 FlatNullPtr);
3702 }
3703 }
3704
3705 // global <-> flat are no-ops and never emitted.
3706
3707 const MachineFunction &MF = DAG.getMachineFunction();
3708 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
3709 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
3710 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
3711
3712 return DAG.getUNDEF(ASC->getValueType(0));
3713}
3714
3715SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3716 SelectionDAG &DAG) const {
3717 SDValue Idx = Op.getOperand(2);
3718 if (isa<ConstantSDNode>(Idx))
3719 return SDValue();
3720
3721 // Avoid stack access for dynamic indexing.
3722 SDLoc SL(Op);
3723 SDValue Vec = Op.getOperand(0);
3724 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
3725
3726 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
3727 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
3728
3729 // Convert vector index to bit-index.
3730 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
3731 DAG.getConstant(16, SL, MVT::i32));
3732
3733 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3734
3735 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
3736 DAG.getConstant(0xffff, SL, MVT::i32),
3737 ScaledIdx);
3738
3739 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
3740 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
3741 DAG.getNOT(SL, BFM, MVT::i32), BCVec);
3742
3743 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
3744 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
3745}
3746
3747SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3748 SelectionDAG &DAG) const {
3749 SDLoc SL(Op);
3750
3751 EVT ResultVT = Op.getValueType();
3752 SDValue Vec = Op.getOperand(0);
3753 SDValue Idx = Op.getOperand(1);
3754
3755 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
3756
3757 // Make sure we we do any optimizations that will make it easier to fold
3758 // source modifiers before obscuring it with bit operations.
3759
3760 // XXX - Why doesn't this get called when vector_shuffle is expanded?
3761 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
3762 return Combined;
3763
3764 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
3765 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3766
3767 if (CIdx->getZExtValue() == 1) {
3768 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
3769 DAG.getConstant(16, SL, MVT::i32));
3770 } else {
3771 assert(CIdx->getZExtValue() == 0)(static_cast <bool> (CIdx->getZExtValue() == 0) ? void
(0) : __assert_fail ("CIdx->getZExtValue() == 0", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3771, __extension__ __PRETTY_FUNCTION__))
;
3772 }
3773
3774 if (ResultVT.bitsLT(MVT::i32))
3775 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
3776 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
3777 }
3778
3779 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
3780
3781 // Convert vector index to bit-index.
3782 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
3783
3784 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3785 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
3786
3787 SDValue Result = Elt;
3788 if (ResultVT.bitsLT(MVT::i32))
3789 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
3790
3791 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
3792}
3793
3794bool
3795SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3796 // We can fold offsets for anything that doesn't require a GOT relocation.
3797 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
3798 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
3799 !shouldEmitGOTReloc(GA->getGlobal());
3800}
3801
3802static SDValue
3803buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
3804 const SDLoc &DL, unsigned Offset, EVT PtrVT,
3805 unsigned GAFlags = SIInstrInfo::MO_NONE) {
3806 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
3807 // lowered to the following code sequence:
3808 //
3809 // For constant address space:
3810 // s_getpc_b64 s[0:1]
3811 // s_add_u32 s0, s0, $symbol
3812 // s_addc_u32 s1, s1, 0
3813 //
3814 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
3815 // a fixup or relocation is emitted to replace $symbol with a literal
3816 // constant, which is a pc-relative offset from the encoding of the $symbol
3817 // operand to the global variable.
3818 //
3819 // For global address space:
3820 // s_getpc_b64 s[0:1]
3821 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
3822 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
3823 //
3824 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
3825 // fixups or relocations are emitted to replace $symbol@*@lo and
3826 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
3827 // which is a 64-bit pc-relative offset from the encoding of the $symbol
3828 // operand to the global variable.
3829 //
3830 // What we want here is an offset from the value returned by s_getpc
3831 // (which is the address of the s_add_u32 instruction) to the global
3832 // variable, but since the encoding of $symbol starts 4 bytes after the start
3833 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
3834 // small. This requires us to add 4 to the global variable offset in order to
3835 // compute the correct address.
3836 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
3837 GAFlags);
3838 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
3839 GAFlags == SIInstrInfo::MO_NONE ?
3840 GAFlags : GAFlags + 1);
3841 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
3842}
3843
3844SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
3845 SDValue Op,
3846 SelectionDAG &DAG) const {
3847 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
3848 const GlobalValue *GV = GSD->getGlobal();
3849
3850 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
3851 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS &&
3852 // FIXME: It isn't correct to rely on the type of the pointer. This should
3853 // be removed when address space 0 is 64-bit.
3854 !GV->getType()->getElementType()->isFunctionTy())
3855 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
3856
3857 SDLoc DL(GSD);
3858 EVT PtrVT = Op.getValueType();
3859
3860 if (shouldEmitFixup(GV))
3861 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
3862 else if (shouldEmitPCReloc(GV))
3863 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
3864 SIInstrInfo::MO_REL32);
3865
3866 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
3867 SIInstrInfo::MO_GOTPCREL32);
3868
3869 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
3870 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
3871 const DataLayout &DataLayout = DAG.getDataLayout();
3872 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
3873 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
3874 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
3875
3876 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
3877 MachineMemOperand::MODereferenceable |
3878 MachineMemOperand::MOInvariant);
3879}
3880
3881SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
3882 const SDLoc &DL, SDValue V) const {
3883 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
3884 // the destination register.
3885 //
3886 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
3887 // so we will end up with redundant moves to m0.
3888 //
3889 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
3890
3891 // A Null SDValue creates a glue result.
3892 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
3893 V, Chain);
3894 return SDValue(M0, 0);
3895}
3896
3897SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
3898 SDValue Op,
3899 MVT VT,
3900 unsigned Offset) const {
3901 SDLoc SL(Op);
3902 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
3903 DAG.getEntryNode(), Offset, false);
3904 // The local size values will have the hi 16-bits as zero.
3905 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
3906 DAG.getValueType(VT));
3907}
3908
3909static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
3910 EVT VT) {
3911 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
3912 "non-hsa intrinsic with hsa target",
3913 DL.getDebugLoc());
3914 DAG.getContext()->diagnose(BadIntrin);
3915 return DAG.getUNDEF(VT);
3916}
3917
3918static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
3919 EVT VT) {
3920 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
3921 "intrinsic not supported on subtarget",
3922 DL.getDebugLoc());
3923 DAG.getContext()->diagnose(BadIntrin);
3924 return DAG.getUNDEF(VT);
3925}
3926
3927SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3928 SelectionDAG &DAG) const {
3929 MachineFunction &MF = DAG.getMachineFunction();
3930 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
3931
3932 EVT VT = Op.getValueType();
3933 SDLoc DL(Op);
3934 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3935
3936 // TODO: Should this propagate fast-math-flags?
3937
3938 switch (IntrinsicID) {
3939 case Intrinsic::amdgcn_implicit_buffer_ptr: {
3940 if (getSubtarget()->isAmdCodeObjectV2(MF))
3941 return emitNonHSAIntrinsicError(DAG, DL, VT);
3942 return getPreloadedValue(DAG, *MFI, VT,
3943 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
3944 }
3945 case Intrinsic::amdgcn_dispatch_ptr:
3946 case Intrinsic::amdgcn_queue_ptr: {
3947 if (!Subtarget->isAmdCodeObjectV2(MF)) {
3948 DiagnosticInfoUnsupported BadIntrin(
3949 *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
3950 DL.getDebugLoc());
3951 DAG.getContext()->diagnose(BadIntrin);
3952 return DAG.getUNDEF(VT);
3953 }
3954
3955 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
3956 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
3957 return getPreloadedValue(DAG, *MFI, VT, RegID);
3958 }
3959 case Intrinsic::amdgcn_implicitarg_ptr: {
3960 if (MFI->isEntryFunction())
3961 return getImplicitArgPtr(DAG, DL);
3962 return getPreloadedValue(DAG, *MFI, VT,
3963 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
3964 }
3965 case Intrinsic::amdgcn_kernarg_segment_ptr: {
3966 return getPreloadedValue(DAG, *MFI, VT,
3967 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
3968 }
3969 case Intrinsic::amdgcn_dispatch_id: {
3970 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
3971 }
3972 case Intrinsic::amdgcn_rcp:
3973 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
3974 case Intrinsic::amdgcn_rsq:
3975 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
3976 case Intrinsic::amdgcn_rsq_legacy:
3977 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3978 return emitRemovedIntrinsicError(DAG, DL, VT);
3979
3980 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
3981 case Intrinsic::amdgcn_rcp_legacy:
3982 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3983 return emitRemovedIntrinsicError(DAG, DL, VT);
3984 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
3985 case Intrinsic::amdgcn_rsq_clamp: {
3986 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
3987 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
3988
3989 Type *Type = VT.getTypeForEVT(*DAG.getContext());
3990 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
3991 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
3992
3993 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
3994 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
3995 DAG.getConstantFP(Max, DL, VT));
3996 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
3997 DAG.getConstantFP(Min, DL, VT));
3998 }
3999 case Intrinsic::r600_read_ngroups_x:
4000 if (Subtarget->isAmdHsaOS())
4001 return emitNonHSAIntrinsicError(DAG, DL, VT);
4002
4003 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4004 SI::KernelInputOffsets::NGROUPS_X, false);
4005 case Intrinsic::r600_read_ngroups_y:
4006 if (Subtarget->isAmdHsaOS())
4007 return emitNonHSAIntrinsicError(DAG, DL, VT);
4008
4009 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4010 SI::KernelInputOffsets::NGROUPS_Y, false);
4011 case Intrinsic::r600_read_ngroups_z:
4012 if (Subtarget->isAmdHsaOS())
4013 return emitNonHSAIntrinsicError(DAG, DL, VT);
4014
4015 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4016 SI::KernelInputOffsets::NGROUPS_Z, false);
4017 case Intrinsic::r600_read_global_size_x:
4018 if (Subtarget->isAmdHsaOS())
4019 return emitNonHSAIntrinsicError(DAG, DL, VT);
4020
4021 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4022 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
4023 case Intrinsic::r600_read_global_size_y:
4024 if (Subtarget->isAmdHsaOS())
4025 return emitNonHSAIntrinsicError(DAG, DL, VT);
4026
4027 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4028 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
4029 case Intrinsic::r600_read_global_size_z:
4030 if (Subtarget->isAmdHsaOS())
4031 return emitNonHSAIntrinsicError(DAG, DL, VT);
4032
4033 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4034 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
4035 case Intrinsic::r600_read_local_size_x:
4036 if (Subtarget->isAmdHsaOS())
4037 return emitNonHSAIntrinsicError(DAG, DL, VT);
4038
4039 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4040 SI::KernelInputOffsets::LOCAL_SIZE_X);
4041 case Intrinsic::r600_read_local_size_y:
4042 if (Subtarget->isAmdHsaOS())
4043 return emitNonHSAIntrinsicError(DAG, DL, VT);
4044
4045 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4046 SI::KernelInputOffsets::LOCAL_SIZE_Y);
4047 case Intrinsic::r600_read_local_size_z:
4048 if (Subtarget->isAmdHsaOS())
4049 return emitNonHSAIntrinsicError(DAG, DL, VT);
4050
4051 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4052 SI::KernelInputOffsets::LOCAL_SIZE_Z);
4053 case Intrinsic::amdgcn_workgroup_id_x:
4054 case Intrinsic::r600_read_tgid_x:
4055 return getPreloadedValue(DAG, *MFI, VT,
4056 AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
4057 case Intrinsic::amdgcn_workgroup_id_y:
4058 case Intrinsic::r600_read_tgid_y:
4059 return getPreloadedValue(DAG, *MFI, VT,
4060 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
4061 case Intrinsic::amdgcn_workgroup_id_z:
4062 case Intrinsic::r600_read_tgid_z:
4063 return getPreloadedValue(DAG, *MFI, VT,
4064 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
4065 case Intrinsic::amdgcn_workitem_id_x: {
4066 case Intrinsic::r600_read_tidig_x:
4067 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4068 SDLoc(DAG.getEntryNode()),
4069 MFI->getArgInfo().WorkItemIDX);
4070 }
4071 case Intrinsic::amdgcn_workitem_id_y:
4072 case Intrinsic::r600_read_tidig_y:
4073 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4074 SDLoc(DAG.getEntryNode()),
4075 MFI->getArgInfo().WorkItemIDY);
4076 case Intrinsic::amdgcn_workitem_id_z:
4077 case Intrinsic::r600_read_tidig_z:
4078 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4079 SDLoc(DAG.getEntryNode()),
4080 MFI->getArgInfo().WorkItemIDZ);
4081 case AMDGPUIntrinsic::SI_load_const: {
4082 SDValue Ops[] = {
4083 Op.getOperand(1),
4084 Op.getOperand(2)
4085 };
4086
4087 MachineMemOperand *MMO = MF.getMachineMemOperand(
4088 MachinePointerInfo(),
4089 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
4090 MachineMemOperand::MOInvariant,
4091 VT.getStoreSize(), 4);
4092 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
4093 Op->getVTList(), Ops, VT, MMO);
4094 }
4095 case Intrinsic::amdgcn_fdiv_fast:
4096 return lowerFDIV_FAST(Op, DAG);
4097 case Intrinsic::amdgcn_interp_mov: {
4098 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4099 SDValue Glue = M0.getValue(1);
4100 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
4101 Op.getOperand(2), Op.getOperand(3), Glue);
4102 }
4103 case Intrinsic::amdgcn_interp_p1: {
4104 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4105 SDValue Glue = M0.getValue(1);
4106 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
4107 Op.getOperand(2), Op.getOperand(3), Glue);
4108 }
4109 case Intrinsic::amdgcn_interp_p2: {
4110 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
4111 SDValue Glue = SDValue(M0.getNode(), 1);
4112 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
4113 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
4114 Glue);
4115 }
4116 case Intrinsic::amdgcn_sin:
4117 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
4118
4119 case Intrinsic::amdgcn_cos:
4120 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
4121
4122 case Intrinsic::amdgcn_log_clamp: {
4123 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
4124 return SDValue();
4125
4126 DiagnosticInfoUnsupported BadIntrin(
4127 *MF.getFunction(), "intrinsic not supported on subtarget",
4128 DL.getDebugLoc());
4129 DAG.getContext()->diagnose(BadIntrin);
4130 return DAG.getUNDEF(VT);
4131 }
4132 case Intrinsic::amdgcn_ldexp:
4133 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
4134 Op.getOperand(1), Op.getOperand(2));
4135
4136 case Intrinsic::amdgcn_fract:
4137 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
4138
4139 case Intrinsic::amdgcn_class:
4140 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
4141 Op.getOperand(1), Op.getOperand(2));
4142 case Intrinsic::amdgcn_div_fmas:
4143 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
4144 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
4145 Op.getOperand(4));
4146
4147 case Intrinsic::amdgcn_div_fixup:
4148 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
4149 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4150
4151 case Intrinsic::amdgcn_trig_preop:
4152 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
4153 Op.getOperand(1), Op.getOperand(2));
4154 case Intrinsic::amdgcn_div_scale: {
4155 // 3rd parameter required to be a constant.
4156 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4157 if (!Param)
4158 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL);
4159
4160 // Translate to the operands expected by the machine instruction. The
4161 // first parameter must be the same as the first instruction.
4162 SDValue Numerator = Op.getOperand(1);
4163 SDValue Denominator = Op.getOperand(2);
4164
4165 // Note this order is opposite of the machine instruction's operations,
4166 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
4167 // intrinsic has the numerator as the first operand to match a normal
4168 // division operation.
4169
4170 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
4171
4172 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
4173 Denominator, Numerator);
4174 }
4175 case Intrinsic::amdgcn_icmp: {
4176 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4177 if (!CD)
4178 return DAG.getUNDEF(VT);
4179
4180 int CondCode = CD->getSExtValue();
4181 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4182 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4183 return DAG.getUNDEF(VT);
4184
4185 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4186 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4187 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4188 Op.getOperand(2), DAG.getCondCode(CCOpcode));
4189 }
4190 case Intrinsic::amdgcn_fcmp: {
4191 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4192 if (!CD)
4193 return DAG.getUNDEF(VT);
4194
4195 int CondCode = CD->getSExtValue();
4196 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4197 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
4198 return DAG.getUNDEF(VT);
4199
4200 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4201 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4202 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4203 Op.getOperand(2), DAG.getCondCode(CCOpcode));
4204 }
4205 case Intrinsic::amdgcn_fmed3:
4206 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
4207 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4208 case Intrinsic::amdgcn_fmul_legacy:
4209 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
4210 Op.getOperand(1), Op.getOperand(2));
4211 case Intrinsic::amdgcn_sffbh:
4212 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
4213 case Intrinsic::amdgcn_sbfe:
4214 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
4215 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4216 case Intrinsic::amdgcn_ubfe:
4217 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
4218 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4219 case Intrinsic::amdgcn_cvt_pkrtz: {
4220 // FIXME: Stop adding cast if v2f16 legal.
4221 EVT VT = Op.getValueType();
4222 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32,
4223 Op.getOperand(1), Op.getOperand(2));
4224 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
4225 }
4226 case Intrinsic::amdgcn_wqm: {
4227 SDValue Src = Op.getOperand(1);
4228 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
4229 0);
4230 }
4231 case Intrinsic::amdgcn_wwm: {
4232 SDValue Src = Op.getOperand(1);
4233 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
4234 0);
4235 }
4236 default:
4237 return Op;
4238 }
4239}
4240
4241SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4242 SelectionDAG &DAG) const {
4243 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4244 SDLoc DL(Op);
4245 MachineFunction &MF = DAG.getMachineFunction();
4246
4247 switch (IntrID) {
4248 case Intrinsic::amdgcn_atomic_inc:
4249 case Intrinsic::amdgcn_atomic_dec: {
4250 MemSDNode *M = cast<MemSDNode>(Op);
4251 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
4252 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
4253 SDValue Ops[] = {
4254 M->getOperand(0), // Chain
4255 M->getOperand(2), // Ptr
4256 M->getOperand(3) // Value
4257 };
4258
4259 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
4260 M->getMemoryVT(), M->getMemOperand());
4261 }
4262 case Intrinsic::amdgcn_buffer_load:
4263 case Intrinsic::amdgcn_buffer_load_format: {
4264 SDValue Ops[] = {
4265 Op.getOperand(0), // Chain
4266 Op.getOperand(2), // rsrc
4267 Op.getOperand(3), // vindex
4268 Op.getOperand(4), // offset
4269 Op.getOperand(5), // glc
4270 Op.getOperand(6) // slc
4271 };
4272 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4273
4274 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
4275 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
4276 EVT VT = Op.getValueType();
4277 EVT IntVT = VT.changeTypeToInteger();
4278
4279 MachineMemOperand *MMO = MF.getMachineMemOperand(
4280 MachinePointerInfo(MFI->getBufferPSV()),
4281 MachineMemOperand::MOLoad,
4282 VT.getStoreSize(), VT.getStoreSize());
4283
4284 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO);
4285 }
4286 case Intrinsic::amdgcn_tbuffer_load: {
4287 SDValue Ops[] = {
4288 Op.getOperand(0), // Chain
4289 Op.getOperand(2), // rsrc
4290 Op.getOperand(3), // vindex
4291 Op.getOperand(4), // voffset
4292 Op.getOperand(5), // soffset
4293 Op.getOperand(6), // offset
4294 Op.getOperand(7), // dfmt
4295 Op.getOperand(8), // nfmt
4296 Op.getOperand(9), // glc
4297 Op.getOperand(10) // slc
4298 };
4299
4300 EVT VT = Op.getOperand(2).getValueType();
4301
4302 MachineMemOperand *MMO = MF.getMachineMemOperand(
4303 MachinePointerInfo(),
4304 MachineMemOperand::MOLoad,
4305 VT.getStoreSize(), VT.getStoreSize());
4306 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
4307 Op->getVTList(), Ops, VT, MMO);
4308 }
4309 case Intrinsic::amdgcn_buffer_atomic_swap:
4310 case Intrinsic::amdgcn_buffer_atomic_add:
4311 case Intrinsic::amdgcn_buffer_atomic_sub:
4312 case Intrinsic::amdgcn_buffer_atomic_smin:
4313 case Intrinsic::amdgcn_buffer_atomic_umin:
4314 case Intrinsic::amdgcn_buffer_atomic_smax:
4315 case Intrinsic::amdgcn_buffer_atomic_umax:
4316 case Intrinsic::amdgcn_buffer_atomic_and:
4317 case Intrinsic::amdgcn_buffer_atomic_or:
4318 case Intrinsic::amdgcn_buffer_atomic_xor: {
4319 SDValue Ops[] = {
4320 Op.getOperand(0), // Chain
4321 Op.getOperand(2), // vdata
4322 Op.getOperand(3), // rsrc
4323 Op.getOperand(4), // vindex
4324 Op.getOperand(5), // offset
4325 Op.getOperand(6) // slc
4326 };
4327 EVT VT = Op.getOperand(3).getValueType();
4328 MachineMemOperand *MMO = MF.getMachineMemOperand(
4329 MachinePointerInfo(),
4330 MachineMemOperand::MOLoad |
4331 MachineMemOperand::MOStore |
4332 MachineMemOperand::MODereferenceable |
4333 MachineMemOperand::MOVolatile,
4334 VT.getStoreSize(), 4);
4335 unsigned Opcode = 0;
4336
4337 switch (IntrID) {
4338 case Intrinsic::amdgcn_buffer_atomic_swap:
4339 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
4340 break;
4341 case Intrinsic::amdgcn_buffer_atomic_add:
4342 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
4343 break;
4344 case Intrinsic::amdgcn_buffer_atomic_sub:
4345 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
4346 break;
4347 case Intrinsic::amdgcn_buffer_atomic_smin:
4348 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
4349 break;
4350 case Intrinsic::amdgcn_buffer_atomic_umin:
4351 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
4352 break;
4353 case Intrinsic::amdgcn_buffer_atomic_smax:
4354 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
4355 break;
4356 case Intrinsic::amdgcn_buffer_atomic_umax:
4357 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
4358 break;
4359 case Intrinsic::amdgcn_buffer_atomic_and:
4360 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
4361 break;
4362 case Intrinsic::amdgcn_buffer_atomic_or:
4363 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
4364 break;
4365 case Intrinsic::amdgcn_buffer_atomic_xor:
4366 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
4367 break;
4368 default:
4369 llvm_unreachable("unhandled atomic opcode")::llvm::llvm_unreachable_internal("unhandled atomic opcode", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4369)
;
4370 }
4371
4372 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, MMO);
4373 }
4374
4375 case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
4376 SDValue Ops[] = {
4377 Op.getOperand(0), // Chain
4378 Op.getOperand(2), // src
4379 Op.getOperand(3), // cmp
4380 Op.getOperand(4), // rsrc
4381 Op.getOperand(5), // vindex
4382 Op.getOperand(6), // offset
4383 Op.getOperand(7) // slc
4384 };
4385 EVT VT = Op.getOperand(4).getValueType();
4386 MachineMemOperand *MMO = MF.getMachineMemOperand(
4387 MachinePointerInfo(),
4388 MachineMemOperand::MOLoad |
4389 MachineMemOperand::MOStore |
4390 MachineMemOperand::MODereferenceable |
4391 MachineMemOperand::MOVolatile,
4392 VT.getStoreSize(), 4);
4393
4394 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
4395 Op->getVTList(), Ops, VT, MMO);
4396 }
4397
4398 // Basic sample.
4399 case Intrinsic::amdgcn_image_sample:
4400 case Intrinsic::amdgcn_image_sample_cl:
4401 case Intrinsic::amdgcn_image_sample_d:
4402 case Intrinsic::amdgcn_image_sample_d_cl:
4403 case Intrinsic::amdgcn_image_sample_l:
4404 case Intrinsic::amdgcn_image_sample_b:
4405 case Intrinsic::amdgcn_image_sample_b_cl:
4406 case Intrinsic::amdgcn_image_sample_lz:
4407 case Intrinsic::amdgcn_image_sample_cd:
4408 case Intrinsic::amdgcn_image_sample_cd_cl:
4409
4410 // Sample with comparison.
4411 case Intrinsic::amdgcn_image_sample_c:
4412 case Intrinsic::amdgcn_image_sample_c_cl:
4413 case Intrinsic::amdgcn_image_sample_c_d:
4414 case Intrinsic::amdgcn_image_sample_c_d_cl:
4415 case Intrinsic::amdgcn_image_sample_c_l:
4416 case Intrinsic::amdgcn_image_sample_c_b:
4417 case Intrinsic::amdgcn_image_sample_c_b_cl:
4418 case Intrinsic::amdgcn_image_sample_c_lz:
4419 case Intrinsic::amdgcn_image_sample_c_cd:
4420 case Intrinsic::amdgcn_image_sample_c_cd_cl:
4421
4422 // Sample with offsets.
4423 case Intrinsic::amdgcn_image_sample_o:
4424 case Intrinsic::amdgcn_image_sample_cl_o:
4425 case Intrinsic::amdgcn_image_sample_d_o:
4426 case Intrinsic::amdgcn_image_sample_d_cl_o:
4427 case Intrinsic::amdgcn_image_sample_l_o:
4428 case Intrinsic::amdgcn_image_sample_b_o:
4429 case Intrinsic::amdgcn_image_sample_b_cl_o:
4430 case Intrinsic::amdgcn_image_sample_lz_o:
4431 case Intrinsic::amdgcn_image_sample_cd_o:
4432 case Intrinsic::amdgcn_image_sample_cd_cl_o:
4433
4434 // Sample with comparison and offsets.
4435 case Intrinsic::amdgcn_image_sample_c_o:
4436 case Intrinsic::amdgcn_image_sample_c_cl_o:
4437 case Intrinsic::amdgcn_image_sample_c_d_o:
4438 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
4439 case Intrinsic::amdgcn_image_sample_c_l_o:
4440 case Intrinsic::amdgcn_image_sample_c_b_o:
4441 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
4442 case Intrinsic::amdgcn_image_sample_c_lz_o:
4443 case Intrinsic::amdgcn_image_sample_c_cd_o:
4444 case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
4445
4446 case Intrinsic::amdgcn_image_getlod: {
4447 // Replace dmask with everything disabled with undef.
4448 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5));
4449 if (!DMask || DMask->isNullValue()) {
4450 SDValue Undef = DAG.getUNDEF(Op.getValueType());
4451 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op));
4452 }
4453
4454 return SDValue();
4455 }
4456 default:
4457 return SDValue();
4458 }
4459}
4460
4461SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4462 SelectionDAG &DAG) const {
4463 SDLoc DL(Op);
4464 SDValue Chain = Op.getOperand(0);
4465 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4466 MachineFunction &MF = DAG.getMachineFunction();
4467
4468 switch (IntrinsicID) {
4469 case Intrinsic::amdgcn_exp: {
4470 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
4471 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
4472 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
4473 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
4474
4475 const SDValue Ops[] = {
4476 Chain,
4477 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
4478 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
4479 Op.getOperand(4), // src0
4480 Op.getOperand(5), // src1
4481 Op.getOperand(6), // src2
4482 Op.getOperand(7), // src3
4483 DAG.getTargetConstant(0, DL, MVT::i1), // compr
4484 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
4485 };
4486
4487 unsigned Opc = Done->isNullValue() ?
4488 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
4489 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
4490 }
4491 case Intrinsic::amdgcn_exp_compr: {
4492 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
4493 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
4494 SDValue Src0 = Op.getOperand(4);
4495 SDValue Src1 = Op.getOperand(5);
4496 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
4497 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
4498
4499 SDValue Undef = DAG.getUNDEF(MVT::f32);
4500 const SDValue Ops[] = {
4501 Chain,
4502 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
4503 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
4504 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
4505 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
4506 Undef, // src2
4507 Undef, // src3
4508 DAG.getTargetConstant(1, DL, MVT::i1), // compr
4509 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
4510 };
4511
4512 unsigned Opc = Done->isNullValue() ?
4513 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
4514 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
4515 }
4516 case Intrinsic::amdgcn_s_sendmsg:
4517 case Intrinsic::amdgcn_s_sendmsghalt: {
4518 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
4519 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
4520 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
4521 SDValue Glue = Chain.getValue(1);
4522 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
4523 Op.getOperand(2), Glue);
4524 }
4525 case Intrinsic::amdgcn_init_exec: {
4526 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
4527 Op.getOperand(2));
4528 }
4529 case Intrinsic::amdgcn_init_exec_from_input: {
4530 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
4531 Op.getOperand(2), Op.getOperand(3));
4532 }
4533 case AMDGPUIntrinsic::AMDGPU_kill: {
4534 SDValue Src = Op.getOperand(2);
4535 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
4536 if (!K->isNegative())
4537 return Chain;
4538
4539 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
4540 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
4541 }
4542
4543 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
4544 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
4545 }
4546 case Intrinsic::amdgcn_s_barrier: {
4547 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
4548 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
4549 unsigned WGSize = ST.getFlatWorkGroupSizes(*MF.getFunction()).second;
4550 if (WGSize <= ST.getWavefrontSize())
4551 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
4552 Op.getOperand(0)), 0);
4553 }
4554 return SDValue();
4555 };
4556 case AMDGPUIntrinsic::SI_tbuffer_store: {
4557
4558 // Extract vindex and voffset from vaddr as appropriate
4559 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10));
4560 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11));
4561 SDValue VAddr = Op.getOperand(5);
4562
4563 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
4564
4565 assert(!(OffEn->isOne() && IdxEn->isOne()) &&(static_cast <bool> (!(OffEn->isOne() && IdxEn
->isOne()) && "Legacy intrinsic doesn't support both offset and index - use new version"
) ? void (0) : __assert_fail ("!(OffEn->isOne() && IdxEn->isOne()) && \"Legacy intrinsic doesn't support both offset and index - use new version\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4566, __extension__ __PRETTY_FUNCTION__))
4566 "Legacy intrinsic doesn't support both offset and index - use new version")(static_cast <bool> (!(OffEn->isOne() && IdxEn
->isOne()) && "Legacy intrinsic doesn't support both offset and index - use new version"
) ? void (0) : __assert_fail ("!(OffEn->isOne() && IdxEn->isOne()) && \"Legacy intrinsic doesn't support both offset and index - use new version\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4566, __extension__ __PRETTY_FUNCTION__))
;
4567
4568 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero;
4569 SDValue VOffset = OffEn->isOne() ? VAddr : Zero;
4570
4571 // Deal with the vec-3 case
4572 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4));
4573 auto Opcode = NumChannels->getZExtValue() == 3 ?
4574 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT;
4575
4576 SDValue Ops[] = {
4577 Chain,
4578 Op.getOperand(3), // vdata
4579 Op.getOperand(2), // rsrc
4580 VIndex,
4581 VOffset,
4582 Op.getOperand(6), // soffset
4583 Op.getOperand(7), // inst_offset
4584 Op.getOperand(8), // dfmt
4585 Op.getOperand(9), // nfmt
4586 Op.getOperand(12), // glc
4587 Op.getOperand(13), // slc
4588 };
4589
4590 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 &&(static_cast <bool> ((cast<ConstantSDNode>(Op.getOperand
(14)))->getZExtValue() == 0 && "Value of tfe other than zero is unsupported"
) ? void (0) : __assert_fail ("(cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 && \"Value of tfe other than zero is unsupported\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4591, __extension__ __PRETTY_FUNCTION__))
4591 "Value of tfe other than zero is unsupported")(static_cast <bool> ((cast<ConstantSDNode>(Op.getOperand
(14)))->getZExtValue() == 0 && "Value of tfe other than zero is unsupported"
) ? void (0) : __assert_fail ("(cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 && \"Value of tfe other than zero is unsupported\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4591, __extension__ __PRETTY_FUNCTION__))
;
4592
4593 EVT VT = Op.getOperand(3).getValueType();
4594 MachineMemOperand *MMO = MF.getMachineMemOperand(
4595 MachinePointerInfo(),
4596 MachineMemOperand::MOStore,
4597 VT.getStoreSize(), 4);
4598 return DAG.getMemIntrinsicNode(Opcode, DL,
4599 Op->getVTList(), Ops, VT, MMO);
4600 }
4601
4602 case Intrinsic::amdgcn_tbuffer_store: {
4603 SDValue Ops[] = {
4604 Chain,
4605 Op.getOperand(2), // vdata
4606 Op.getOperand(3), // rsrc
4607 Op.getOperand(4), // vindex
4608 Op.getOperand(5), // voffset
4609 Op.getOperand(6), // soffset
4610 Op.getOperand(7), // offset
4611 Op.getOperand(8), // dfmt
4612 Op.getOperand(9), // nfmt
4613 Op.getOperand(10), // glc
4614 Op.getOperand(11) // slc
4615 };
4616 EVT VT = Op.getOperand(3).getValueType();
4617 MachineMemOperand *MMO = MF.getMachineMemOperand(
4618 MachinePointerInfo(),
4619 MachineMemOperand::MOStore,
4620 VT.getStoreSize(), 4);
4621 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
4622 Op->getVTList(), Ops, VT, MMO);
4623 }
4624
4625 case Intrinsic::amdgcn_buffer_store:
4626 case Intrinsic::amdgcn_buffer_store_format: {
4627 SDValue Ops[] = {
4628 Chain,
4629 Op.getOperand(2), // vdata
4630 Op.getOperand(3), // rsrc
4631 Op.getOperand(4), // vindex
4632 Op.getOperand(5), // offset
4633 Op.getOperand(6), // glc
4634 Op.getOperand(7) // slc
4635 };
4636 EVT VT = Op.getOperand(3).getValueType();
4637 MachineMemOperand *MMO = MF.getMachineMemOperand(
4638 MachinePointerInfo(),
4639 MachineMemOperand::MOStore |
4640 MachineMemOperand::MODereferenceable,
4641 VT.getStoreSize(), 4);
4642
4643 unsigned Opcode = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
4644 AMDGPUISD::BUFFER_STORE :
4645 AMDGPUISD::BUFFER_STORE_FORMAT;
4646 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, MMO);
4647 }
4648
4649 default:
4650 return Op;
4651 }
4652}
4653
4654SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4655 SDLoc DL(Op);
4656 LoadSDNode *Load = cast<LoadSDNode>(Op);
4657 ISD::LoadExtType ExtType = Load->getExtensionType();
4658 EVT MemVT = Load->getMemoryVT();
4659
4660 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
4661 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
4662 return SDValue();
4663
4664 // FIXME: Copied from PPC
4665 // First, load into 32 bits, then truncate to 1 bit.
4666
4667 SDValue Chain = Load->getChain();
4668 SDValue BasePtr = Load->getBasePtr();
4669 MachineMemOperand *MMO = Load->getMemOperand();
4670
4671 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
4672
4673 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
4674 BasePtr, RealMemVT, MMO);
4675
4676 SDValue Ops[] = {
4677 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
4678 NewLD.getValue(1)
4679 };
4680
4681 return DAG.getMergeValues(Ops, DL);
4682 }
4683
4684 if (!MemVT.isVector())
4685 return SDValue();
4686
4687 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&(static_cast <bool> (Op.getValueType().getVectorElementType
() == MVT::i32 && "Custom lowering for non-i32 vectors hasn't been implemented."
) ? void (0) : __assert_fail ("Op.getValueType().getVectorElementType() == MVT::i32 && \"Custom lowering for non-i32 vectors hasn't been implemented.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4688, __extension__ __PRETTY_FUNCTION__))
4688 "Custom lowering for non-i32 vectors hasn't been implemented.")(static_cast <bool> (Op.getValueType().getVectorElementType
() == MVT::i32 && "Custom lowering for non-i32 vectors hasn't been implemented."
) ? void (0) : __assert_fail ("Op.getValueType().getVectorElementType() == MVT::i32 && \"Custom lowering for non-i32 vectors hasn't been implemented.\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4688, __extension__ __PRETTY_FUNCTION__))
;
4689
4690 unsigned AS = Load->getAddressSpace();
4691 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
4692 AS, Load->getAlignment())) {
4693 SDValue Ops[2];
4694 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
4695 return DAG.getMergeValues(Ops, DL);
4696 }
4697
4698 MachineFunction &MF = DAG.getMachineFunction();
4699 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4700 // If there is a possibilty that flat instruction access scratch memory
4701 // then we need to use the same legalization rules we use for private.
4702 if (AS == AMDGPUASI.FLAT_ADDRESS)
4703 AS = MFI->hasFlatScratchInit() ?
4704 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
4705
4706 unsigned NumElements = MemVT.getVectorNumElements();
4707 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
4708 if (isMemOpUniform(Load))
4709 return SDValue();
4710 // Non-uniform loads will be selected to MUBUF instructions, so they
4711 // have the same legalization requirements as global and private
4712 // loads.
4713 //
4714 }
4715 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) {
4716 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
4717 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load))
4718 return SDValue();
4719 // Non-uniform loads will be selected to MUBUF instructions, so they
4720 // have the same legalization requirements as global and private
4721 // loads.
4722 //
4723 }
4724 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS ||
4725 AS == AMDGPUASI.FLAT_ADDRESS) {
4726 if (NumElements > 4)
4727 return SplitVectorLoad(Op, DAG);
4728 // v4 loads are supported for private and global memory.
4729 return SDValue();
4730 }
4731 if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
4732 // Depending on the setting of the private_element_size field in the
4733 // resource descriptor, we can only make private accesses up to a certain
4734 // size.
4735 switch (Subtarget->getMaxPrivateElementSize()) {
4736 case 4:
4737 return scalarizeVectorLoad(Load, DAG);
4738 case 8:
4739 if (NumElements > 2)
4740 return SplitVectorLoad(Op, DAG);
4741 return SDValue();
4742 case 16:
4743 // Same as global/flat
4744 if (NumElements > 4)
4745 return SplitVectorLoad(Op, DAG);
4746 return SDValue();
4747 default:
4748 llvm_unreachable("unsupported private_element_size")::llvm::llvm_unreachable_internal("unsupported private_element_size"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4748)
;
4749 }
4750 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
4751 if (NumElements > 2)
4752 return SplitVectorLoad(Op, DAG);
4753
4754 if (NumElements == 2)
4755 return SDValue();
4756
4757 // If properly aligned, if we split we might be able to use ds_read_b64.
4758 return SplitVectorLoad(Op, DAG);
4759 }
4760 return SDValue();
4761}
4762
4763SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4764 if (Op.getValueType() != MVT::i64)
4765 return SDValue();
4766
4767 SDLoc DL(Op);
4768 SDValue Cond = Op.getOperand(0);
4769
4770 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
4771 SDValue One = DAG.getConstant(1, DL, MVT::i32);
4772
4773 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
4774 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
4775
4776 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
4777 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
4778
4779 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
4780
4781 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
4782 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
4783
4784 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
4785
4786 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
4787 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
4788}
4789
4790// Catch division cases where we can use shortcuts with rcp and rsq
4791// instructions.
4792SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
4793 SelectionDAG &DAG) const {
4794 SDLoc SL(Op);
4795 SDValue LHS = Op.getOperand(0);
4796 SDValue RHS = Op.getOperand(1);
4797 EVT VT = Op.getValueType();
4798 const SDNodeFlags Flags = Op->getFlags();
4799 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath ||
4800 Flags.hasUnsafeAlgebra() || Flags.hasAllowReciprocal();
4801
4802 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
4803 return SDValue();
4804
4805 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
4806 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
4807 if (CLHS->isExactlyValue(1.0)) {
4808 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
4809 // the CI documentation has a worst case error of 1 ulp.
4810 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
4811 // use it as long as we aren't trying to use denormals.
4812 //
4813 // v_rcp_f16 and v_rsq_f16 DO support denormals.
4814
4815 // 1.0 / sqrt(x) -> rsq(x)
4816
4817 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
4818 // error seems really high at 2^29 ULP.
4819 if (RHS.getOpcode() == ISD::FSQRT)
4820 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
4821
4822 // 1.0 / x -> rcp(x)
4823 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
4824 }
4825
4826 // Same as for 1.0, but expand the sign out of the constant.
4827 if (CLHS->isExactlyValue(-1.0)) {
4828 // -1.0 / x -> rcp (fneg x)
4829 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
4830 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
4831 }
4832 }
4833 }
4834
4835 if (Unsafe) {
4836 // Turn into multiply by the reciprocal.
4837 // x / y -> x * (1.0 / y)
4838 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
4839 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
4840 }
4841
4842 return SDValue();
4843}
4844
4845static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
4846 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
4847 if (GlueChain->getNumValues() <= 1) {
4848 return DAG.getNode(Opcode, SL, VT, A, B);
4849 }
4850
4851 assert(GlueChain->getNumValues() == 3)(static_cast <bool> (GlueChain->getNumValues() == 3)
? void (0) : __assert_fail ("GlueChain->getNumValues() == 3"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4851, __extension__ __PRETTY_FUNCTION__))
;
4852
4853 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
4854 switch (Opcode) {
4855 default: llvm_unreachable("no chain equivalent for opcode")::llvm::llvm_unreachable_internal("no chain equivalent for opcode"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4855)
;
4856 case ISD::FMUL:
4857 Opcode = AMDGPUISD::FMUL_W_CHAIN;
4858 break;
4859 }
4860
4861 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
4862 GlueChain.getValue(2));
4863}
4864
4865static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
4866 EVT VT, SDValue A, SDValue B, SDValue C,
4867 SDValue GlueChain) {
4868 if (GlueChain->getNumValues() <= 1) {
4869 return DAG.getNode(Opcode, SL, VT, A, B, C);
4870 }
4871
4872 assert(GlueChain->getNumValues() == 3)(static_cast <bool> (GlueChain->getNumValues() == 3)
? void (0) : __assert_fail ("GlueChain->getNumValues() == 3"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4872, __extension__ __PRETTY_FUNCTION__))
;
4873
4874 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
4875 switch (Opcode) {
4876 default: llvm_unreachable("no chain equivalent for opcode")::llvm::llvm_unreachable_internal("no chain equivalent for opcode"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4876)
;
4877 case ISD::FMA:
4878 Opcode = AMDGPUISD::FMA_W_CHAIN;
4879 break;
4880 }
4881
4882 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
4883 GlueChain.getValue(2));
4884}
4885
4886SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
4887 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
4888 return FastLowered;
4889
4890 SDLoc SL(Op);
4891 SDValue Src0 = Op.getOperand(0);
4892 SDValue Src1 = Op.getOperand(1);
4893
4894 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4895 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4896
4897 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
4898 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
4899
4900 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
4901 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
4902
4903 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
4904}
4905
4906// Faster 2.5 ULP division that does not support denormals.
4907SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
4908 SDLoc SL(Op);
4909 SDValue LHS = Op.getOperand(1);
4910 SDValue RHS = Op.getOperand(2);
4911
4912 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
4913
4914 const APFloat K0Val(BitsToFloat(0x6f800000));
4915 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
4916
4917 const APFloat K1Val(BitsToFloat(0x2f800000));
4918 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
4919
4920 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
4921
4922 EVT SetCCVT =
4923 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
4924
4925 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
4926
4927 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
4928
4929 // TODO: Should this propagate fast-math-flags?
4930 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
4931
4932 // rcp does not support denormals.
4933 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
4934
4935 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
4936
4937 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
4938}
4939
4940SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
4941 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
4942 return FastLowered;
4943
4944 SDLoc SL(Op);
4945 SDValue LHS = Op.getOperand(0);
4946 SDValue RHS = Op.getOperand(1);
4947
4948 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
4949
4950 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
4951
4952 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
4953 RHS, RHS, LHS);
4954 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
4955 LHS, RHS, LHS);
4956
4957 // Denominator is scaled to not be denormal, so using rcp is ok.
4958 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
4959 DenominatorScaled);
4960 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
4961 DenominatorScaled);
4962
4963 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
4964 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
4965 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
4966
4967 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
4968
4969 if (!Subtarget->hasFP32Denormals()) {
4970 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
4971 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE3,
4972 SL, MVT::i32);
4973 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
4974 DAG.getEntryNode(),
4975 EnableDenormValue, BitField);
4976 SDValue Ops[3] = {
4977 NegDivScale0,
4978 EnableDenorm.getValue(0),
4979 EnableDenorm.getValue(1)
4980 };
4981
4982 NegDivScale0 = DAG.getMergeValues(Ops, SL);
4983 }
4984
4985 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
4986 ApproxRcp, One, NegDivScale0);
4987
4988 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
4989 ApproxRcp, Fma0);
4990
4991 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
4992 Fma1, Fma1);
4993
4994 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
4995 NumeratorScaled, Mul);
4996
4997 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
4998
4999 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
5000 NumeratorScaled, Fma3);
5001
5002 if (!Subtarget->hasFP32Denormals()) {
5003 const SDValue DisableDenormValue =
5004 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT0, SL, MVT::i32);
5005 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
5006 Fma4.getValue(1),
5007 DisableDenormValue,
5008 BitField,
5009 Fma4.getValue(2));
5010
5011 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
5012 DisableDenorm, DAG.getRoot());
5013 DAG.setRoot(OutputChain);
5014 }
5015
5016 SDValue Scale = NumeratorScaled.getValue(1);
5017 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
5018 Fma4, Fma1, Fma3, Scale);
5019
5020 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
5021}
5022
5023SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
5024 if (DAG.getTarget().Options.UnsafeFPMath)
5025 return lowerFastUnsafeFDIV(Op, DAG);
5026
5027 SDLoc SL(Op);
5028 SDValue X = Op.getOperand(0);
5029 SDValue Y = Op.getOperand(1);
5030
5031 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
5032
5033 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
5034
5035 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
5036
5037 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
5038
5039 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
5040
5041 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
5042
5043 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
5044
5045 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
5046
5047 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
5048
5049 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
5050 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
5051
5052 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
5053 NegDivScale0, Mul, DivScale1);
5054
5055 SDValue Scale;
5056
5057 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
5058 // Workaround a hardware bug on SI where the condition output from div_scale
5059 // is not usable.
5060
5061 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
5062
5063 // Figure out if the scale to use for div_fmas.
5064 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
5065 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
5066 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
5067 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
5068
5069 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
5070 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
5071
5072 SDValue Scale0Hi
5073 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
5074 SDValue Scale1Hi
5075 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
5076
5077 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
5078 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
5079 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
5080 } else {
5081 Scale = DivScale1.getValue(1);
5082 }
5083
5084 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
5085 Fma4, Fma3, Mul, Scale);
5086
5087 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
5088}
5089
5090SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
5091 EVT VT = Op.getValueType();
5092
5093 if (VT == MVT::f32)
5094 return LowerFDIV32(Op, DAG);
5095
5096 if (VT == MVT::f64)
5097 return LowerFDIV64(Op, DAG);
5098
5099 if (VT == MVT::f16)
5100 return LowerFDIV16(Op, DAG);
5101
5102 llvm_unreachable("Unexpected type for fdiv")::llvm::llvm_unreachable_internal("Unexpected type for fdiv",
"/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5102)
;
5103}
5104
5105SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5106 SDLoc DL(Op);
5107 StoreSDNode *Store = cast<StoreSDNode>(Op);
5108 EVT VT = Store->getMemoryVT();
5109
5110 if (VT == MVT::i1) {
5111 return DAG.getTruncStore(Store->getChain(), DL,
5112 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
5113 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
5114 }
5115
5116 assert(VT.isVector() &&(static_cast <bool> (VT.isVector() && Store->
getValue().getValueType().getScalarType() == MVT::i32) ? void
(0) : __assert_fail ("VT.isVector() && Store->getValue().getValueType().getScalarType() == MVT::i32"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5117, __extension__ __PRETTY_FUNCTION__))
5117 Store->getValue().getValueType().getScalarType() == MVT::i32)(static_cast <bool> (VT.isVector() && Store->
getValue().getValueType().getScalarType() == MVT::i32) ? void
(0) : __assert_fail ("VT.isVector() && Store->getValue().getValueType().getScalarType() == MVT::i32"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5117, __extension__ __PRETTY_FUNCTION__))
;
5118
5119 unsigned AS = Store->getAddressSpace();
5120 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
5121 AS, Store->getAlignment())) {
5122 return expandUnalignedStore(Store, DAG);
5123 }
5124
5125 MachineFunction &MF = DAG.getMachineFunction();
5126 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5127 // If there is a possibilty that flat instruction access scratch memory
5128 // then we need to use the same legalization rules we use for private.
5129 if (AS == AMDGPUASI.FLAT_ADDRESS)
5130 AS = MFI->hasFlatScratchInit() ?
5131 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5132
5133 unsigned NumElements = VT.getVectorNumElements();
5134 if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
5135 AS == AMDGPUASI.FLAT_ADDRESS) {
5136 if (NumElements > 4)
5137 return SplitVectorStore(Op, DAG);
5138 return SDValue();
5139 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5140 switch (Subtarget->getMaxPrivateElementSize()) {
5141 case 4:
5142 return scalarizeVectorStore(Store, DAG);
5143 case 8:
5144 if (NumElements > 2)
5145 return SplitVectorStore(Op, DAG);
5146 return SDValue();
5147 case 16:
5148 if (NumElements > 4)
5149 return SplitVectorStore(Op, DAG);
5150 return SDValue();
5151 default:
5152 llvm_unreachable("unsupported private_element_size")::llvm::llvm_unreachable_internal("unsupported private_element_size"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5152)
;
5153 }
5154 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
5155 if (NumElements > 2)
5156 return SplitVectorStore(Op, DAG);
5157
5158 if (NumElements == 2)
5159 return Op;
5160
5161 // If properly aligned, if we split we might be able to use ds_write_b64.
5162 return SplitVectorStore(Op, DAG);
5163 } else {
5164 llvm_unreachable("unhandled address space")::llvm::llvm_unreachable_internal("unhandled address space", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5164)
;
5165 }
5166}
5167
5168SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
5169 SDLoc DL(Op);
5170 EVT VT = Op.getValueType();
5171 SDValue Arg = Op.getOperand(0);
5172 // TODO: Should this propagate fast-math-flags?
5173 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
5174 DAG.getNode(ISD::FMUL, DL, VT, Arg,
5175 DAG.getConstantFP(0.5/M_PI3.14159265358979323846, DL,
5176 VT)));
5177
5178 switch (Op.getOpcode()) {
5179 case ISD::FCOS:
5180 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
5181 case ISD::FSIN:
5182 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
5183 default:
5184 llvm_unreachable("Wrong trig opcode")::llvm::llvm_unreachable_internal("Wrong trig opcode", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5184)
;
5185 }
5186}
5187
5188SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
5189 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
5190 assert(AtomicNode->isCompareAndSwap())(static_cast <bool> (AtomicNode->isCompareAndSwap())
? void (0) : __assert_fail ("AtomicNode->isCompareAndSwap()"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5190, __extension__ __PRETTY_FUNCTION__))
;
5191 unsigned AS = AtomicNode->getAddressSpace();
5192
5193 // No custom lowering required for local address space
5194 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
5195 return Op;
5196
5197 // Non-local address space requires custom lowering for atomic compare
5198 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
5199 SDLoc DL(Op);
5200 SDValue ChainIn = Op.getOperand(0);
5201 SDValue Addr = Op.getOperand(1);
5202 SDValue Old = Op.getOperand(2);
5203 SDValue New = Op.getOperand(3);
5204 EVT VT = Op.getValueType();
5205 MVT SimpleVT = VT.getSimpleVT();
5206 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
5207
5208 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
5209 SDValue Ops[] = { ChainIn, Addr, NewOld };
5210
5211 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
5212 Ops, VT, AtomicNode->getMemOperand());
5213}
5214
5215//===----------------------------------------------------------------------===//
5216// Custom DAG optimizations
5217//===----------------------------------------------------------------------===//
5218
5219SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
5220 DAGCombinerInfo &DCI) const {
5221 EVT VT = N->getValueType(0);
5222 EVT ScalarVT = VT.getScalarType();
5223 if (ScalarVT != MVT::f32)
5224 return SDValue();
5225
5226 SelectionDAG &DAG = DCI.DAG;
5227 SDLoc DL(N);
5228
5229 SDValue Src = N->getOperand(0);
5230 EVT SrcVT = Src.getValueType();
5231
5232 // TODO: We could try to match extracting the higher bytes, which would be
5233 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
5234 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
5235 // about in practice.
5236 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
5237 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
5238 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
5239 DCI.AddToWorklist(Cvt.getNode());
5240 return Cvt;
5241 }
5242 }
5243
5244 return SDValue();
5245}
5246
5247// (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
5248
5249// This is a variant of
5250// (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
5251//
5252// The normal DAG combiner will do this, but only if the add has one use since
5253// that would increase the number of instructions.
5254//
5255// This prevents us from seeing a constant offset that can be folded into a
5256// memory instruction's addressing mode. If we know the resulting add offset of
5257// a pointer can be folded into an addressing offset, we can replace the pointer
5258// operand with the add of new constant offset. This eliminates one of the uses,
5259// and may allow the remaining use to also be simplified.
5260//
5261SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
5262 unsigned AddrSpace,
5263 EVT MemVT,
5264 DAGCombinerInfo &DCI) const {
5265 SDValue N0 = N->getOperand(0);
5266 SDValue N1 = N->getOperand(1);
5267
5268 // We only do this to handle cases where it's profitable when there are
5269 // multiple uses of the add, so defer to the standard combine.
5270 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
5271 N0->hasOneUse())
5272 return SDValue();
5273
5274 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
5275 if (!CN1)
5276 return SDValue();
5277
5278 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5279 if (!CAdd)
5280 return SDValue();
5281
5282 // If the resulting offset is too large, we can't fold it into the addressing
5283 // mode offset.
5284 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
5285 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
5286
5287 AddrMode AM;
5288 AM.HasBaseReg = true;
5289 AM.BaseOffs = Offset.getSExtValue();
5290 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
5291 return SDValue();
5292
5293 SelectionDAG &DAG = DCI.DAG;
5294 SDLoc SL(N);
5295 EVT VT = N->getValueType(0);
5296
5297 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
5298 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
5299
5300 SDNodeFlags Flags;
5301 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
5302 (N0.getOpcode() == ISD::OR ||
5303 N0->getFlags().hasNoUnsignedWrap()));
5304
5305 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
5306}
5307
5308SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
5309 DAGCombinerInfo &DCI) const {
5310 SDValue Ptr = N->getBasePtr();
5311 SelectionDAG &DAG = DCI.DAG;
5312 SDLoc SL(N);
5313
5314 // TODO: We could also do this for multiplies.
5315 if (Ptr.getOpcode() == ISD::SHL) {
5316 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
5317 N->getMemoryVT(), DCI);
5318 if (NewPtr) {
5319 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
5320
5321 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
5322 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
5323 }
5324 }
5325
5326 return SDValue();
5327}
5328
5329static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
5330 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
5331 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
5332 (Opc == ISD::XOR && Val == 0);
5333}
5334
5335// Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
5336// will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
5337// integer combine opportunities since most 64-bit operations are decomposed
5338// this way. TODO: We won't want this for SALU especially if it is an inline
5339// immediate.
5340SDValue SITargetLowering::splitBinaryBitConstantOp(
5341 DAGCombinerInfo &DCI,
5342 const SDLoc &SL,
5343 unsigned Opc, SDValue LHS,
5344 const ConstantSDNode *CRHS) const {
5345 uint64_t Val = CRHS->getZExtValue();
5346 uint32_t ValLo = Lo_32(Val);
5347 uint32_t ValHi = Hi_32(Val);
5348 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5349
5350 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
5351 bitOpWithConstantIsReducible(Opc, ValHi)) ||
5352 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
5353 // If we need to materialize a 64-bit immediate, it will be split up later
5354 // anyway. Avoid creating the harder to understand 64-bit immediate
5355 // materialization.
5356 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
5357 }
5358
5359 return SDValue();
5360}
5361
5362// Returns true if argument is a boolean value which is not serialized into
5363// memory or argument and does not require v_cmdmask_b32 to be deserialized.
5364static bool isBoolSGPR(SDValue V) {
5365 if (V.getValueType() != MVT::i1)
5366 return false;
5367 switch (V.getOpcode()) {
5368 default: break;
5369 case ISD::SETCC:
5370 case ISD::AND:
5371 case ISD::OR:
5372 case ISD::XOR:
5373 case AMDGPUISD::FP_CLASS:
5374 return true;
5375 }
5376 return false;
5377}
5378
5379SDValue SITargetLowering::performAndCombine(SDNode *N,
5380 DAGCombinerInfo &DCI) const {
5381 if (DCI.isBeforeLegalize())
5382 return SDValue();
5383
5384 SelectionDAG &DAG = DCI.DAG;
5385 EVT VT = N->getValueType(0);
5386 SDValue LHS = N->getOperand(0);
5387 SDValue RHS = N->getOperand(1);
5388
5389
5390 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
5391 if (VT == MVT::i64 && CRHS) {
5392 if (SDValue Split
5393 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
5394 return Split;
5395 }
5396
5397 if (CRHS && VT == MVT::i32) {
5398 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
5399 // nb = number of trailing zeroes in mask
5400 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
5401 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
5402 uint64_t Mask = CRHS->getZExtValue();
5403 unsigned Bits = countPopulation(Mask);
5404 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
5405 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
5406 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
5407 unsigned Shift = CShift->getZExtValue();
5408 unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
5409 unsigned Offset = NB + Shift;
5410 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
5411 SDLoc SL(N);
5412 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
5413 LHS->getOperand(0),
5414 DAG.getConstant(Offset, SL, MVT::i32),
5415 DAG.getConstant(Bits, SL, MVT::i32));
5416 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
5417 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
5418 DAG.getValueType(NarrowVT));
5419 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
5420 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
5421 return Shl;
5422 }
5423 }
5424 }
5425 }
5426
5427 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
5428 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
5429 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
5430 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
5431 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
5432
5433 SDValue X = LHS.getOperand(0);
5434 SDValue Y = RHS.getOperand(0);
5435 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
5436 return SDValue();
5437
5438 if (LCC == ISD::SETO) {
5439 if (X != LHS.getOperand(1))
5440 return SDValue();
5441
5442 if (RCC == ISD::SETUNE) {
5443 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
5444 if (!C1 || !C1->isInfinity() || C1->isNegative())
5445 return SDValue();
5446
5447 const uint32_t Mask = SIInstrFlags::N_NORMAL |
5448 SIInstrFlags::N_SUBNORMAL |
5449 SIInstrFlags::N_ZERO |
5450 SIInstrFlags::P_ZERO |
5451 SIInstrFlags::P_SUBNORMAL |
5452 SIInstrFlags::P_NORMAL;
5453
5454 static_assert(((~(SIInstrFlags::S_NAN |
5455 SIInstrFlags::Q_NAN |
5456 SIInstrFlags::N_INFINITY |
5457 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
5458 "mask not equal");
5459
5460 SDLoc DL(N);
5461 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
5462 X, DAG.getConstant(Mask, DL, MVT::i32));
5463 }
5464 }
5465 }
5466
5467 if (VT == MVT::i32 &&
5468 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
5469 // and x, (sext cc from i1) => select cc, x, 0
5470 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
5471 std::swap(LHS, RHS);
5472 if (isBoolSGPR(RHS.getOperand(0)))
5473 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
5474 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
5475 }
5476
5477 return SDValue();
5478}
5479
5480SDValue SITargetLowering::performOrCombine(SDNode *N,
5481 DAGCombinerInfo &DCI) const {
5482 SelectionDAG &DAG = DCI.DAG;
5483 SDValue LHS = N->getOperand(0);
5484 SDValue RHS = N->getOperand(1);
5485
5486 EVT VT = N->getValueType(0);
5487 if (VT == MVT::i1) {
5488 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
5489 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
5490 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
5491 SDValue Src = LHS.getOperand(0);
5492 if (Src != RHS.getOperand(0))
5493 return SDValue();
5494
5495 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
5496 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
5497 if (!CLHS || !CRHS)
5498 return SDValue();
5499
5500 // Only 10 bits are used.
5501 static const uint32_t MaxMask = 0x3ff;
5502
5503 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
5504 SDLoc DL(N);
5505 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
5506 Src, DAG.getConstant(NewMask, DL, MVT::i32));
5507 }
5508
5509 return SDValue();
5510 }
5511
5512 if (VT != MVT::i64)
5513 return SDValue();
5514
5515 // TODO: This could be a generic combine with a predicate for extracting the
5516 // high half of an integer being free.
5517
5518 // (or i64:x, (zero_extend i32:y)) ->
5519 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
5520 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
5521 RHS.getOpcode() != ISD::ZERO_EXTEND)
5522 std::swap(LHS, RHS);
5523
5524 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
5525 SDValue ExtSrc = RHS.getOperand(0);
5526 EVT SrcVT = ExtSrc.getValueType();
5527 if (SrcVT == MVT::i32) {
5528 SDLoc SL(N);
5529 SDValue LowLHS, HiBits;
5530 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
5531 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
5532
5533 DCI.AddToWorklist(LowOr.getNode());
5534 DCI.AddToWorklist(HiBits.getNode());
5535
5536 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
5537 LowOr, HiBits);
5538 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5539 }
5540 }
5541
5542 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
5543 if (CRHS) {
5544 if (SDValue Split
5545 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
5546 return Split;
5547 }
5548
5549 return SDValue();
5550}
5551
5552SDValue SITargetLowering::performXorCombine(SDNode *N,
5553 DAGCombinerInfo &DCI) const {
5554 EVT VT = N->getValueType(0);
5555 if (VT != MVT::i64)
5556 return SDValue();
5557
5558 SDValue LHS = N->getOperand(0);
5559 SDValue RHS = N->getOperand(1);
5560
5561 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
5562 if (CRHS) {
5563 if (SDValue Split
5564 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
5565 return Split;
5566 }
5567
5568 return SDValue();
5569}
5570
5571// Instructions that will be lowered with a final instruction that zeros the
5572// high result bits.
5573// XXX - probably only need to list legal operations.
5574static bool fp16SrcZerosHighBits(unsigned Opc) {
5575 switch (Opc) {
5576 case ISD::FADD:
5577 case ISD::FSUB:
5578 case ISD::FMUL:
5579 case ISD::FDIV:
5580 case ISD::FREM:
5581 case ISD::FMA:
5582 case ISD::FMAD:
5583 case ISD::FCANONICALIZE:
5584 case ISD::FP_ROUND:
5585 case ISD::UINT_TO_FP:
5586 case ISD::SINT_TO_FP:
5587 case ISD::FABS:
5588 // Fabs is lowered to a bit operation, but it's an and which will clear the
5589 // high bits anyway.
5590 case ISD::FSQRT:
5591 case ISD::FSIN:
5592 case ISD::FCOS:
5593 case ISD::FPOWI:
5594 case ISD::FPOW:
5595 case ISD::FLOG:
5596 case ISD::FLOG2:
5597 case ISD::FLOG10:
5598 case ISD::FEXP:
5599 case ISD::FEXP2:
5600 case ISD::FCEIL:
5601 case ISD::FTRUNC:
5602 case ISD::FRINT:
5603 case ISD::FNEARBYINT:
5604 case ISD::FROUND:
5605 case ISD::FFLOOR:
5606 case ISD::FMINNUM:
5607 case ISD::FMAXNUM:
5608 case AMDGPUISD::FRACT:
5609 case AMDGPUISD::CLAMP:
5610 case AMDGPUISD::COS_HW:
5611 case AMDGPUISD::SIN_HW:
5612 case AMDGPUISD::FMIN3:
5613 case AMDGPUISD::FMAX3:
5614 case AMDGPUISD::FMED3:
5615 case AMDGPUISD::FMAD_FTZ:
5616 case AMDGPUISD::RCP:
5617 case AMDGPUISD::RSQ:
5618 case AMDGPUISD::LDEXP:
5619 return true;
5620 default:
5621 // fcopysign, select and others may be lowered to 32-bit bit operations
5622 // which don't zero the high bits.
5623 return false;
5624 }
5625}
5626
5627SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
5628 DAGCombinerInfo &DCI) const {
5629 if (!Subtarget->has16BitInsts() ||
5630 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
5631 return SDValue();
5632
5633 EVT VT = N->getValueType(0);
5634 if (VT != MVT::i32)
5635 return SDValue();
5636
5637 SDValue Src = N->getOperand(0);
5638 if (Src.getValueType() != MVT::i16)
5639 return SDValue();
5640
5641 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
5642 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
5643 if (Src.getOpcode() == ISD::BITCAST) {
5644 SDValue BCSrc = Src.getOperand(0);
5645 if (BCSrc.getValueType() == MVT::f16 &&
5646 fp16SrcZerosHighBits(BCSrc.getOpcode()))
5647 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
5648 }
5649
5650 return SDValue();
5651}
5652
5653SDValue SITargetLowering::performClassCombine(SDNode *N,
5654 DAGCombinerInfo &DCI) const {
5655 SelectionDAG &DAG = DCI.DAG;
5656 SDValue Mask = N->getOperand(1);
5657
5658 // fp_class x, 0 -> false
5659 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
5660 if (CMask->isNullValue())
5661 return DAG.getConstant(0, SDLoc(N), MVT::i1);
5662 }
5663
5664 if (N->getOperand(0).isUndef())
5665 return DAG.getUNDEF(MVT::i1);
5666
5667 return SDValue();
5668}
5669
5670static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
5671 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
5672 return true;
5673
5674 return DAG.isKnownNeverNaN(Op);
5675}
5676
5677static bool isCanonicalized(SelectionDAG &DAG, SDValue Op,
5678 const SISubtarget *ST, unsigned MaxDepth=5) {
5679 // If source is a result of another standard FP operation it is already in
5680 // canonical form.
5681
5682 switch (Op.getOpcode()) {
5683 default:
5684 break;
5685
5686 // These will flush denorms if required.
5687 case ISD::FADD:
5688 case ISD::FSUB:
5689 case ISD::FMUL:
5690 case ISD::FSQRT:
5691 case ISD::FCEIL:
5692 case ISD::FFLOOR:
5693 case ISD::FMA:
5694 case ISD::FMAD:
5695
5696 case ISD::FCANONICALIZE:
5697 return true;
5698
5699 case ISD::FP_ROUND:
5700 return Op.getValueType().getScalarType() != MVT::f16 ||
5701 ST->hasFP16Denormals();
5702
5703 case ISD::FP_EXTEND:
5704 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 ||
5705 ST->hasFP16Denormals();
5706
5707 case ISD::FP16_TO_FP:
5708 case ISD::FP_TO_FP16:
5709 return ST->hasFP16Denormals();
5710
5711 // It can/will be lowered or combined as a bit operation.
5712 // Need to check their input recursively to handle.
5713 case ISD::FNEG:
5714 case ISD::FABS:
5715 return (MaxDepth > 0) &&
5716 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1);
5717
5718 case ISD::FSIN:
5719 case ISD::FCOS:
5720 case ISD::FSINCOS:
5721 return Op.getValueType().getScalarType() != MVT::f16;
5722
5723 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms.
5724 // For such targets need to check their input recursively.
5725 case ISD::FMINNUM:
5726 case ISD::FMAXNUM:
5727 case ISD::FMINNAN:
5728 case ISD::FMAXNAN:
5729
5730 if (ST->supportsMinMaxDenormModes() &&
5731 DAG.isKnownNeverNaN(Op.getOperand(0)) &&
5732 DAG.isKnownNeverNaN(Op.getOperand(1)))
5733 return true;
5734
5735 return (MaxDepth > 0) &&
5736 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) &&
5737 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1);
5738
5739 case ISD::ConstantFP: {
5740 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF();
5741 return !F.isDenormal() && !(F.isNaN() && F.isSignaling());
5742 }
5743 }
5744 return false;
5745}
5746
5747// Constant fold canonicalize.
5748SDValue SITargetLowering::performFCanonicalizeCombine(
5749 SDNode *N,
5750 DAGCombinerInfo &DCI) const {
5751 SelectionDAG &DAG = DCI.DAG;
5752 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
5753
5754 if (!CFP) {
5755 SDValue N0 = N->getOperand(0);
5756 EVT VT = N0.getValueType().getScalarType();
5757 auto ST = getSubtarget();
5758
5759 if (((VT == MVT::f32 && ST->hasFP32Denormals()) ||
5760 (VT == MVT::f64 && ST->hasFP64Denormals()) ||
5761 (VT == MVT::f16 && ST->hasFP16Denormals())) &&
5762 DAG.isKnownNeverNaN(N0))
5763 return N0;
5764
5765 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction());
5766
5767 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) &&
5768 isCanonicalized(DAG, N0, ST))
5769 return N0;
5770
5771 return SDValue();
5772 }
5773
5774 const APFloat &C = CFP->getValueAPF();
5775
5776 // Flush denormals to 0 if not enabled.
5777 if (C.isDenormal()) {
5778 EVT VT = N->getValueType(0);
5779 EVT SVT = VT.getScalarType();
5780 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
5781 return DAG.getConstantFP(0.0, SDLoc(N), VT);
5782
5783 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
5784 return DAG.getConstantFP(0.0, SDLoc(N), VT);
5785
5786 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
5787 return DAG.getConstantFP(0.0, SDLoc(N), VT);
5788 }
5789
5790 if (C.isNaN()) {
5791 EVT VT = N->getValueType(0);
5792 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
5793 if (C.isSignaling()) {
5794 // Quiet a signaling NaN.
5795 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
5796 }
5797
5798 // Make sure it is the canonical NaN bitpattern.
5799 //
5800 // TODO: Can we use -1 as the canonical NaN value since it's an inline
5801 // immediate?
5802 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
5803 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
5804 }
5805
5806 return N->getOperand(0);
5807}
5808
5809static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
5810 switch (Opc) {
5811 case ISD::FMAXNUM:
5812 return AMDGPUISD::FMAX3;
5813 case ISD::SMAX:
5814 return AMDGPUISD::SMAX3;
5815 case ISD::UMAX:
5816 return AMDGPUISD::UMAX3;
5817 case ISD::FMINNUM:
5818 return AMDGPUISD::FMIN3;
5819 case ISD::SMIN:
5820 return AMDGPUISD::SMIN3;
5821 case ISD::UMIN:
5822 return AMDGPUISD::UMIN3;
5823 default:
5824 llvm_unreachable("Not a min/max opcode")::llvm::llvm_unreachable_internal("Not a min/max opcode", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5824)
;
5825 }
5826}
5827
5828SDValue SITargetLowering::performIntMed3ImmCombine(
5829 SelectionDAG &DAG, const SDLoc &SL,
5830 SDValue Op0, SDValue Op1, bool Signed) const {
5831 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
5832 if (!K1)
5833 return SDValue();
5834
5835 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
5836 if (!K0)
5837 return SDValue();
5838
5839 if (Signed) {
5840 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
5841 return SDValue();
5842 } else {
5843 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
5844 return SDValue();
5845 }
5846
5847 EVT VT = K0->getValueType(0);
5848 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
5849 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
5850 return DAG.getNode(Med3Opc, SL, VT,
5851 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
5852 }
5853
5854 // If there isn't a 16-bit med3 operation, convert to 32-bit.
5855 MVT NVT = MVT::i32;
5856 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5857
5858 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
5859 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
5860 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
5861
5862 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
5863 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
5864}
5865
5866static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
5867 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
5868 return C;
5869
5870 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
5871 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
5872 return C;
5873 }
5874
5875 return nullptr;
5876}
5877
5878SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
5879 const SDLoc &SL,
5880 SDValue Op0,
5881 SDValue Op1) const {
5882 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
5883 if (!K1)
5884 return SDValue();
5885
5886 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
5887 if (!K0)
5888 return SDValue();
5889
5890 // Ordered >= (although NaN inputs should have folded away by now).
5891 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
5892 if (Cmp == APFloat::cmpGreaterThan)
5893 return SDValue();
5894
5895 // TODO: Check IEEE bit enabled?
5896 EVT VT = Op0.getValueType();
5897 if (Subtarget->enableDX10Clamp()) {
5898 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
5899 // hardware fmed3 behavior converting to a min.
5900 // FIXME: Should this be allowing -0.0?
5901 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
5902 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
5903 }
5904
5905 // med3 for f16 is only available on gfx9+, and not available for v2f16.
5906 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
5907 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
5908 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
5909 // then give the other result, which is different from med3 with a NaN
5910 // input.
5911 SDValue Var = Op0.getOperand(0);
5912 if (!isKnownNeverSNan(DAG, Var))
5913 return SDValue();
5914
5915 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
5916 Var, SDValue(K0, 0), SDValue(K1, 0));
5917 }
5918
5919 return SDValue();
5920}
5921
5922SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
5923 DAGCombinerInfo &DCI) const {
5924 SelectionDAG &DAG = DCI.DAG;
5925
5926 EVT VT = N->getValueType(0);
5927 unsigned Opc = N->getOpcode();
5928 SDValue Op0 = N->getOperand(0);
5929 SDValue Op1 = N->getOperand(1);
5930
5931 // Only do this if the inner op has one use since this will just increases
5932 // register pressure for no benefit.
5933
5934
5935 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
5936 VT != MVT::f64 &&
5937 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) {
5938 // max(max(a, b), c) -> max3(a, b, c)
5939 // min(min(a, b), c) -> min3(a, b, c)
5940 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
5941 SDLoc DL(N);
5942 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
5943 DL,
5944 N->getValueType(0),
5945 Op0.getOperand(0),
5946 Op0.getOperand(1),
5947 Op1);
5948 }
5949
5950 // Try commuted.
5951 // max(a, max(b, c)) -> max3(a, b, c)
5952 // min(a, min(b, c)) -> min3(a, b, c)
5953 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
5954 SDLoc DL(N);
5955 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
5956 DL,
5957 N->getValueType(0),
5958 Op0,
5959 Op1.getOperand(0),
5960 Op1.getOperand(1));
5961 }
5962 }
5963
5964 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
5965 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
5966 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
5967 return Med3;
5968 }
5969
5970 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
5971 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
5972 return Med3;
5973 }
5974
5975 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
5976 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
5977 (Opc == AMDGPUISD::FMIN_LEGACY &&
5978 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
5979 (VT == MVT::f32 || VT == MVT::f64 ||
5980 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
5981 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
5982 Op0.hasOneUse()) {
5983 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
5984 return Res;
5985 }
5986
5987 return SDValue();
5988}
5989
5990static bool isClampZeroToOne(SDValue A, SDValue B) {
5991 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
5992 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
5993 // FIXME: Should this be allowing -0.0?
5994 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
5995 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
5996 }
5997 }
5998
5999 return false;
6000}
6001
6002// FIXME: Should only worry about snans for version with chain.
6003SDValue SITargetLowering::performFMed3Combine(SDNode *N,
6004 DAGCombinerInfo &DCI) const {
6005 EVT VT = N->getValueType(0);
6006 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
6007 // NaNs. With a NaN input, the order of the operands may change the result.
6008
6009 SelectionDAG &DAG = DCI.DAG;
6010 SDLoc SL(N);
6011
6012 SDValue Src0 = N->getOperand(0);
6013 SDValue Src1 = N->getOperand(1);
6014 SDValue Src2 = N->getOperand(2);
6015
6016 if (isClampZeroToOne(Src0, Src1)) {
6017 // const_a, const_b, x -> clamp is safe in all cases including signaling
6018 // nans.
6019 // FIXME: Should this be allowing -0.0?
6020 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
6021 }
6022
6023 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
6024 // handling no dx10-clamp?
6025 if (Subtarget->enableDX10Clamp()) {
6026 // If NaNs is clamped to 0, we are free to reorder the inputs.
6027
6028 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
6029 std::swap(Src0, Src1);
6030
6031 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
6032 std::swap(Src1, Src2);
6033
6034 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
6035 std::swap(Src0, Src1);
6036
6037 if (isClampZeroToOne(Src1, Src2))
6038 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
6039 }
6040
6041 return SDValue();
6042}
6043
6044SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
6045 DAGCombinerInfo &DCI) const {
6046 SDValue Src0 = N->getOperand(0);
6047 SDValue Src1 = N->getOperand(1);
6048 if (Src0.isUndef() && Src1.isUndef())
6049 return DCI.DAG.getUNDEF(N->getValueType(0));
6050 return SDValue();
6051}
6052
6053SDValue SITargetLowering::performExtractVectorEltCombine(
6054 SDNode *N, DAGCombinerInfo &DCI) const {
6055 SDValue Vec = N->getOperand(0);
6056
6057 SelectionDAG &DAG = DCI.DAG;
6058 if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) {
6059 SDLoc SL(N);
6060 EVT EltVT = N->getValueType(0);
6061 SDValue Idx = N->getOperand(1);
6062 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
6063 Vec.getOperand(0), Idx);
6064 return DAG.getNode(ISD::FNEG, SL, EltVT, Elt);
6065 }
6066
6067 return SDValue();
6068}
6069
6070static bool convertBuildVectorCastElt(SelectionDAG &DAG,
6071 SDValue &Lo, SDValue &Hi) {
6072 if (Hi.getOpcode() == ISD::BITCAST &&
6073 Hi.getOperand(0).getValueType() == MVT::f16 &&
6074 (isa<ConstantSDNode>(Lo) || Lo.isUndef())) {
6075 Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo);
6076 Hi = Hi.getOperand(0);
6077 return true;
6078 }
6079
6080 return false;
6081}
6082
6083SDValue SITargetLowering::performBuildVectorCombine(
6084 SDNode *N, DAGCombinerInfo &DCI) const {
6085 SDLoc SL(N);
6086
6087 if (!isTypeLegal(MVT::v2i16))
6088 return SDValue();
6089 SelectionDAG &DAG = DCI.DAG;
6090 EVT VT = N->getValueType(0);
6091
6092 if (VT == MVT::v2i16) {
6093 SDValue Lo = N->getOperand(0);
6094 SDValue Hi = N->getOperand(1);
6095
6096 // v2i16 build_vector (const|undef), (bitcast f16:$x)
6097 // -> bitcast (v2f16 build_vector const|undef, $x
6098 if (convertBuildVectorCastElt(DAG, Lo, Hi)) {
6099 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi });
6100 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
6101 }
6102
6103 if (convertBuildVectorCastElt(DAG, Hi, Lo)) {
6104 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo });
6105 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
6106 }
6107 }
6108
6109 return SDValue();
6110}
6111
6112unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
6113 const SDNode *N0,
6114 const SDNode *N1) const {
6115 EVT VT = N0->getValueType(0);
6116
6117 // Only do this if we are not trying to support denormals. v_mad_f32 does not
6118 // support denormals ever.
6119 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
6120 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
6121 return ISD::FMAD;
6122
6123 const TargetOptions &Options = DAG.getTarget().Options;
6124 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
6125 (N0->getFlags().hasUnsafeAlgebra() &&
6126 N1->getFlags().hasUnsafeAlgebra())) &&
6127 isFMAFasterThanFMulAndFAdd(VT)) {
6128 return ISD::FMA;
6129 }
6130
6131 return 0;
6132}
6133
6134static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
6135 EVT VT,
6136 SDValue N0, SDValue N1, SDValue N2,
6137 bool Signed) {
6138 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
6139 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
6140 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
6141 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
6142}
6143
6144SDValue SITargetLowering::performAddCombine(SDNode *N,
6145 DAGCombinerInfo &DCI) const {
6146 SelectionDAG &DAG = DCI.DAG;
6147 EVT VT = N->getValueType(0);
6148 SDLoc SL(N);
6149 SDValue LHS = N->getOperand(0);
6150 SDValue RHS = N->getOperand(1);
6151
6152 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
6153 && Subtarget->hasMad64_32() &&
6154 !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
6155 VT.getScalarSizeInBits() <= 64) {
6156 if (LHS.getOpcode() != ISD::MUL)
6157 std::swap(LHS, RHS);
6158
6159 SDValue MulLHS = LHS.getOperand(0);
6160 SDValue MulRHS = LHS.getOperand(1);
6161 SDValue AddRHS = RHS;
6162
6163 // TODO: Maybe restrict if SGPR inputs.
6164 if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
6165 numBitsUnsigned(MulRHS, DAG) <= 32) {
6166 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
6167 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
6168 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
6169 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
6170 }
6171
6172 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
6173 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
6174 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
6175 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
6176 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
6177 }
6178
6179 return SDValue();
6180 }
6181
6182 if (VT != MVT::i32)
6183 return SDValue();
6184
6185 // add x, zext (setcc) => addcarry x, 0, setcc
6186 // add x, sext (setcc) => subcarry x, 0, setcc
6187 unsigned Opc = LHS.getOpcode();
6188 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
6189 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
6190 std::swap(RHS, LHS);
6191
6192 Opc = RHS.getOpcode();
6193 switch (Opc) {
6194 default: break;
6195 case ISD::ZERO_EXTEND:
6196 case ISD::SIGN_EXTEND:
6197 case ISD::ANY_EXTEND: {
6198 auto Cond = RHS.getOperand(0);
6199 if (!isBoolSGPR(Cond))
6200 break;
6201 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
6202 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
6203 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
6204 return DAG.getNode(Opc, SL, VTList, Args);
6205 }
6206 case ISD::ADDCARRY: {
6207 // add x, (addcarry y, 0, cc) => addcarry x, y, cc
6208 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
6209 if (!C || C->getZExtValue() != 0) break;
6210 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
6211 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
6212 }
6213 }
6214 return SDValue();
6215}
6216
6217SDValue SITargetLowering::performSubCombine(SDNode *N,
6218 DAGCombinerInfo &DCI) const {
6219 SelectionDAG &DAG = DCI.DAG;
6220 EVT VT = N->getValueType(0);
6221
6222 if (VT != MVT::i32)
6223 return SDValue();
6224
6225 SDLoc SL(N);
6226 SDValue LHS = N->getOperand(0);
6227 SDValue RHS = N->getOperand(1);
6228
6229 unsigned Opc = LHS.getOpcode();
6230 if (Opc != ISD::SUBCARRY)
6231 std::swap(RHS, LHS);
6232
6233 if (LHS.getOpcode() == ISD::SUBCARRY) {
6234 // sub (subcarry x, 0, cc), y => subcarry x, y, cc
6235 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
6236 if (!C || C->getZExtValue() != 0)
6237 return SDValue();
6238 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
6239 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
6240 }
6241 return SDValue();
6242}
6243
6244SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
6245 DAGCombinerInfo &DCI) const {
6246
6247 if (N->getValueType(0) != MVT::i32)
6248 return SDValue();
6249
6250 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6251 if (!C || C->getZExtValue() != 0)
6252 return SDValue();
6253
6254 SelectionDAG &DAG = DCI.DAG;
6255 SDValue LHS = N->getOperand(0);
6256
6257 // addcarry (add x, y), 0, cc => addcarry x, y, cc
6258 // subcarry (sub x, y), 0, cc => subcarry x, y, cc
6259 unsigned LHSOpc = LHS.getOpcode();
6260 unsigned Opc = N->getOpcode();
6261 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
6262 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
6263 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
6264 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
6265 }
6266 return SDValue();
6267}
6268
6269SDValue SITargetLowering::performFAddCombine(SDNode *N,
6270 DAGCombinerInfo &DCI) const {
6271 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6272 return SDValue();
6273
6274 SelectionDAG &DAG = DCI.DAG;
6275 EVT VT = N->getValueType(0);
6276
6277 SDLoc SL(N);
6278 SDValue LHS = N->getOperand(0);
6279 SDValue RHS = N->getOperand(1);
6280
6281 // These should really be instruction patterns, but writing patterns with
6282 // source modiifiers is a pain.
6283
6284 // fadd (fadd (a, a), b) -> mad 2.0, a, b
6285 if (LHS.getOpcode() == ISD::FADD) {
6286 SDValue A = LHS.getOperand(0);
6287 if (A == LHS.getOperand(1)) {
6288 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
6289 if (FusedOp != 0) {
6290 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6291 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
6292 }
6293 }
6294 }
6295
6296 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
6297 if (RHS.getOpcode() == ISD::FADD) {
6298 SDValue A = RHS.getOperand(0);
6299 if (A == RHS.getOperand(1)) {
6300 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
6301 if (FusedOp != 0) {
6302 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6303 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
6304 }
6305 }
6306 }
6307
6308 return SDValue();
6309}
6310
6311SDValue SITargetLowering::performFSubCombine(SDNode *N,
6312 DAGCombinerInfo &DCI) const {
6313 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6314 return SDValue();
6315
6316 SelectionDAG &DAG = DCI.DAG;
6317 SDLoc SL(N);
6318 EVT VT = N->getValueType(0);
6319 assert(!VT.isVector())(static_cast <bool> (!VT.isVector()) ? void (0) : __assert_fail
("!VT.isVector()", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6319, __extension__ __PRETTY_FUNCTION__))
;
6320
6321 // Try to get the fneg to fold into the source modifier. This undoes generic
6322 // DAG combines and folds them into the mad.
6323 //
6324 // Only do this if we are not trying to support denormals. v_mad_f32 does
6325 // not support denormals ever.
6326 SDValue LHS = N->getOperand(0);
6327 SDValue RHS = N->getOperand(1);
6328 if (LHS.getOpcode() == ISD::FADD) {
6329 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
6330 SDValue A = LHS.getOperand(0);
6331 if (A == LHS.getOperand(1)) {
6332 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
6333 if (FusedOp != 0){
6334 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6335 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
6336
6337 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
6338 }
6339 }
6340 }
6341
6342 if (RHS.getOpcode() == ISD::FADD) {
6343 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
6344
6345 SDValue A = RHS.getOperand(0);
6346 if (A == RHS.getOperand(1)) {
6347 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
6348 if (FusedOp != 0){
6349 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
6350 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
6351 }
6352 }
6353 }
6354
6355 return SDValue();
6356}
6357
6358SDValue SITargetLowering::performSetCCCombine(SDNode *N,
6359 DAGCombinerInfo &DCI) const {
6360 SelectionDAG &DAG = DCI.DAG;
6361 SDLoc SL(N);
6362
6363 SDValue LHS = N->getOperand(0);
6364 SDValue RHS = N->getOperand(1);
6365 EVT VT = LHS.getValueType();
6366 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
6367
6368 auto CRHS = dyn_cast<ConstantSDNode>(RHS);
6369 if (!CRHS) {
6370 CRHS = dyn_cast<ConstantSDNode>(LHS);
6371 if (CRHS) {
6372 std::swap(LHS, RHS);
6373 CC = getSetCCSwappedOperands(CC);
6374 }
6375 }
6376
6377 if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
6378 isBoolSGPR(LHS.getOperand(0))) {
6379 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
6380 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
6381 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
6382 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
6383 if ((CRHS->isAllOnesValue() &&
6384 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
6385 (CRHS->isNullValue() &&
6386 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
6387 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
6388 DAG.getConstant(-1, SL, MVT::i1));
6389 if ((CRHS->isAllOnesValue() &&
6390 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
6391 (CRHS->isNullValue() &&
6392 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
6393 return LHS.getOperand(0);
6394 }
6395
6396 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
6397 VT != MVT::f16))
6398 return SDValue();
6399
6400 // Match isinf pattern
6401 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
6402 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
6403 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
6404 if (!CRHS)
6405 return SDValue();
6406
6407 const APFloat &APF = CRHS->getValueAPF();
6408 if (APF.isInfinity() && !APF.isNegative()) {
6409 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
6410 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
6411 DAG.getConstant(Mask, SL, MVT::i32));
6412 }
6413 }
6414
6415 return SDValue();
6416}
6417
6418SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
6419 DAGCombinerInfo &DCI) const {
6420 SelectionDAG &DAG = DCI.DAG;
6421 SDLoc SL(N);
6422 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
6423
6424 SDValue Src = N->getOperand(0);
6425 SDValue Srl = N->getOperand(0);
6426 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
6427 Srl = Srl.getOperand(0);
6428
6429 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
6430 if (Srl.getOpcode() == ISD::SRL) {
6431 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
6432 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
6433 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
6434
6435 if (const ConstantSDNode *C =
6436 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
6437 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
6438 EVT(MVT::i32));
6439
6440 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
6441 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
6442 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
6443 MVT::f32, Srl);
6444 }
6445 }
6446 }
6447
6448 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
6449
6450 KnownBits Known;
6451 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
6452 !DCI.isBeforeLegalizeOps());
6453 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6454 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
6455 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
6456 DCI.CommitTargetLoweringOpt(TLO);
6457 }
6458
6459 return SDValue();
6460}
6461
6462SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
6463 DAGCombinerInfo &DCI) const {
6464 switch (N->getOpcode()) {
6465 default:
6466 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
6467 case ISD::ADD:
6468 return performAddCombine(N, DCI);
6469 case ISD::SUB:
6470 return performSubCombine(N, DCI);
6471 case ISD::ADDCARRY:
6472 case ISD::SUBCARRY:
6473 return performAddCarrySubCarryCombine(N, DCI);
6474 case ISD::FADD:
6475 return performFAddCombine(N, DCI);
6476 case ISD::FSUB:
6477 return performFSubCombine(N, DCI);
6478 case ISD::SETCC:
6479 return performSetCCCombine(N, DCI);
6480 case ISD::FMAXNUM:
6481 case ISD::FMINNUM:
6482 case ISD::SMAX:
6483 case ISD::SMIN:
6484 case ISD::UMAX:
6485 case ISD::UMIN:
6486 case AMDGPUISD::FMIN_LEGACY:
6487 case AMDGPUISD::FMAX_LEGACY: {
6488 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
6489 getTargetMachine().getOptLevel() > CodeGenOpt::None)
6490 return performMinMaxCombine(N, DCI);
6491 break;
6492 }
6493 case ISD::LOAD:
6494 case ISD::STORE:
6495 case ISD::ATOMIC_LOAD:
6496 case ISD::ATOMIC_STORE:
6497 case ISD::ATOMIC_CMP_SWAP:
6498 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
6499 case ISD::ATOMIC_SWAP:
6500 case ISD::ATOMIC_LOAD_ADD:
6501 case ISD::ATOMIC_LOAD_SUB:
6502 case ISD::ATOMIC_LOAD_AND:
6503 case ISD::ATOMIC_LOAD_OR:
6504 case ISD::ATOMIC_LOAD_XOR:
6505 case ISD::ATOMIC_LOAD_NAND:
6506 case ISD::ATOMIC_LOAD_MIN:
6507 case ISD::ATOMIC_LOAD_MAX:
6508 case ISD::ATOMIC_LOAD_UMIN:
6509 case ISD::ATOMIC_LOAD_UMAX:
6510 case AMDGPUISD::ATOMIC_INC:
6511 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics.
6512 if (DCI.isBeforeLegalize())
6513 break;
6514 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
6515 case ISD::AND:
6516 return performAndCombine(N, DCI);
6517 case ISD::OR:
6518 return performOrCombine(N, DCI);
6519 case ISD::XOR:
6520 return performXorCombine(N, DCI);
6521 case ISD::ZERO_EXTEND:
6522 return performZeroExtendCombine(N, DCI);
6523 case AMDGPUISD::FP_CLASS:
6524 return performClassCombine(N, DCI);
6525 case ISD::FCANONICALIZE:
6526 return performFCanonicalizeCombine(N, DCI);
6527 case AMDGPUISD::FRACT:
6528 case AMDGPUISD::RCP:
6529 case AMDGPUISD::RSQ:
6530 case AMDGPUISD::RCP_LEGACY:
6531 case AMDGPUISD::RSQ_LEGACY:
6532 case AMDGPUISD::RSQ_CLAMP:
6533 case AMDGPUISD::LDEXP: {
6534 SDValue Src = N->getOperand(0);
6535 if (Src.isUndef())
6536 return Src;
6537 break;
6538 }
6539 case ISD::SINT_TO_FP:
6540 case ISD::UINT_TO_FP:
6541 return performUCharToFloatCombine(N, DCI);
6542 case AMDGPUISD::CVT_F32_UBYTE0:
6543 case AMDGPUISD::CVT_F32_UBYTE1:
6544 case AMDGPUISD::CVT_F32_UBYTE2:
6545 case AMDGPUISD::CVT_F32_UBYTE3:
6546 return performCvtF32UByteNCombine(N, DCI);
6547 case AMDGPUISD::FMED3:
6548 return performFMed3Combine(N, DCI);
6549 case AMDGPUISD::CVT_PKRTZ_F16_F32:
6550 return performCvtPkRTZCombine(N, DCI);
6551 case ISD::SCALAR_TO_VECTOR: {
6552 SelectionDAG &DAG = DCI.DAG;
6553 EVT VT = N->getValueType(0);
6554
6555 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
6556 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
6557 SDLoc SL(N);
6558 SDValue Src = N->getOperand(0);
6559 EVT EltVT = Src.getValueType();
6560 if (EltVT == MVT::f16)
6561 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
6562
6563 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
6564 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
6565 }
6566
6567 break;
6568 }
6569 case ISD::EXTRACT_VECTOR_ELT:
6570 return performExtractVectorEltCombine(N, DCI);
6571 case ISD::BUILD_VECTOR:
6572 return performBuildVectorCombine(N, DCI);
6573 }
6574 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
6575}
6576
6577/// \brief Helper function for adjustWritemask
6578static unsigned SubIdx2Lane(unsigned Idx) {
6579 switch (Idx) {
6580 default: return 0;
6581 case AMDGPU::sub0: return 0;
6582 case AMDGPU::sub1: return 1;
6583 case AMDGPU::sub2: return 2;
6584 case AMDGPU::sub3: return 3;
6585 }
6586}
6587
6588/// \brief Adjust the writemask of MIMG instructions
6589SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
6590 SelectionDAG &DAG) const {
6591 SDNode *Users[4] = { nullptr };
6592 unsigned Lane = 0;
6593 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
1
'?' condition is false
6594 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
6595 unsigned NewDmask = 0;
6596
6597 // Try to figure out the used register components
6598 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
2
Loop condition is false. Execution continues on line 6633
6599 I != E; ++I) {
6600
6601 // Don't look at users of the chain.
6602 if (I.getUse().getResNo() != 0)
6603 continue;
6604
6605 // Abort if we can't understand the usage
6606 if (!I->isMachineOpcode() ||
6607 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
6608 return Node;
6609
6610 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
6611 // Note that subregs are packed, i.e. Lane==0 is the first bit set
6612 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
6613 // set, etc.
6614 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
6615
6616 // Set which texture component corresponds to the lane.
6617 unsigned Comp;
6618 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
6619 assert(Dmask)(static_cast <bool> (Dmask) ? void (0) : __assert_fail (
"Dmask", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6619, __extension__ __PRETTY_FUNCTION__))
;
6620 Comp = countTrailingZeros(Dmask);
6621 Dmask &= ~(1 << Comp);
6622 }
6623
6624 // Abort if we have more than one user per component
6625 if (Users[Lane])
6626 return Node;
6627
6628 Users[Lane] = *I;
6629 NewDmask |= 1 << Comp;
6630 }
6631
6632 // Abort if there's no change
6633 if (NewDmask == OldDmask)
3
Assuming 'NewDmask' is not equal to 'OldDmask'
4
Taking false branch
6634 return Node;
6635
6636 unsigned BitsSet = countPopulation(NewDmask);
6637
6638 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6639 int NewOpcode = TII->getMaskedMIMGOp(Node->getMachineOpcode(), BitsSet);
6640 assert(NewOpcode != -1 &&(static_cast <bool> (NewOpcode != -1 && NewOpcode
!= static_cast<int>(Node->getMachineOpcode()) &&
"failed to find equivalent MIMG op") ? void (0) : __assert_fail
("NewOpcode != -1 && NewOpcode != static_cast<int>(Node->getMachineOpcode()) && \"failed to find equivalent MIMG op\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6642, __extension__ __PRETTY_FUNCTION__))
6641 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&(static_cast <bool> (NewOpcode != -1 && NewOpcode
!= static_cast<int>(Node->getMachineOpcode()) &&
"failed to find equivalent MIMG op") ? void (0) : __assert_fail
("NewOpcode != -1 && NewOpcode != static_cast<int>(Node->getMachineOpcode()) && \"failed to find equivalent MIMG op\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6642, __extension__ __PRETTY_FUNCTION__))
6642 "failed to find equivalent MIMG op")(static_cast <bool> (NewOpcode != -1 && NewOpcode
!= static_cast<int>(Node->getMachineOpcode()) &&
"failed to find equivalent MIMG op") ? void (0) : __assert_fail
("NewOpcode != -1 && NewOpcode != static_cast<int>(Node->getMachineOpcode()) && \"failed to find equivalent MIMG op\""
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6642, __extension__ __PRETTY_FUNCTION__))
;
6643
6644 // Adjust the writemask in the node
6645 SmallVector<SDValue, 12> Ops;
6646 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
6647 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
6648 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
6649
6650 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
6651
6652 auto NewVTList =
6653 DAG.getVTList(BitsSet == 1 ?
5
Assuming 'BitsSet' is equal to 1
6
'?' condition is true
6654 SVT : MVT::getVectorVT(SVT, BitsSet == 3 ? 4 : BitsSet),
6655 MVT::Other);
6656
6657 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
6658 NewVTList, Ops);
6659 // Update chain.
6660 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
6661
6662 if (BitsSet == 1) {
7
Taking true branch
6663 assert(Node->hasNUsesOfValue(1, 0))(static_cast <bool> (Node->hasNUsesOfValue(1, 0)) ? void
(0) : __assert_fail ("Node->hasNUsesOfValue(1, 0)", "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6663, __extension__ __PRETTY_FUNCTION__))
;
6664 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
6665 SDLoc(Node), Users[Lane]->getValueType(0),
8
Called C++ object pointer is null
6666 SDValue(NewNode, 0));
6667 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
6668 return nullptr;
6669 }
6670
6671 // Update the users of the node with the new indices
6672 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
6673 SDNode *User = Users[i];
6674 if (!User)
6675 continue;
6676
6677 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
6678 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
6679
6680 switch (Idx) {
6681 default: break;
6682 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
6683 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
6684 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
6685 }
6686 }
6687
6688 DAG.RemoveDeadNode(Node);
6689 return nullptr;
6690}
6691
6692static bool isFrameIndexOp(SDValue Op) {
6693 if (Op.getOpcode() == ISD::AssertZext)
6694 Op = Op.getOperand(0);
6695
6696 return isa<FrameIndexSDNode>(Op);
6697}
6698
6699/// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
6700/// with frame index operands.
6701/// LLVM assumes that inputs are to these instructions are registers.
6702SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
6703 SelectionDAG &DAG) const {
6704 if (Node->getOpcode() == ISD::CopyToReg) {
6705 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
6706 SDValue SrcVal = Node->getOperand(2);
6707
6708 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
6709 // to try understanding copies to physical registers.
6710 if (SrcVal.getValueType() == MVT::i1 &&
6711 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
6712 SDLoc SL(Node);
6713 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
6714 SDValue VReg = DAG.getRegister(
6715 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
6716
6717 SDNode *Glued = Node->getGluedNode();
6718 SDValue ToVReg
6719 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
6720 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
6721 SDValue ToResultReg
6722 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
6723 VReg, ToVReg.getValue(1));
6724 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
6725 DAG.RemoveDeadNode(Node);
6726 return ToResultReg.getNode();
6727 }
6728 }
6729
6730 SmallVector<SDValue, 8> Ops;
6731 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
6732 if (!isFrameIndexOp(Node->getOperand(i))) {
6733 Ops.push_back(Node->getOperand(i));
6734 continue;
6735 }
6736
6737 SDLoc DL(Node);
6738 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
6739 Node->getOperand(i).getValueType(),
6740 Node->getOperand(i)), 0));
6741 }
6742
6743 return DAG.UpdateNodeOperands(Node, Ops);
6744}
6745
6746/// \brief Fold the instructions after selecting them.
6747/// Returns null if users were already updated.
6748SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
6749 SelectionDAG &DAG) const {
6750 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6751 unsigned Opcode = Node->getMachineOpcode();
6752
6753 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
6754 !TII->isGather4(Opcode)) {
6755 return adjustWritemask(Node, DAG);
6756 }
6757
6758 if (Opcode == AMDGPU::INSERT_SUBREG ||
6759 Opcode == AMDGPU::REG_SEQUENCE) {
6760 legalizeTargetIndependentNode(Node, DAG);
6761 return Node;
6762 }
6763
6764 switch (Opcode) {
6765 case AMDGPU::V_DIV_SCALE_F32:
6766 case AMDGPU::V_DIV_SCALE_F64: {
6767 // Satisfy the operand register constraint when one of the inputs is
6768 // undefined. Ordinarily each undef value will have its own implicit_def of
6769 // a vreg, so force these to use a single register.
6770 SDValue Src0 = Node->getOperand(0);
6771 SDValue Src1 = Node->getOperand(1);
6772 SDValue Src2 = Node->getOperand(2);
6773
6774 if ((Src0.isMachineOpcode() &&
6775 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
6776 (Src0 == Src1 || Src0 == Src2))
6777 break;
6778
6779 MVT VT = Src0.getValueType().getSimpleVT();
6780 const TargetRegisterClass *RC = getRegClassFor(VT);
6781
6782 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
6783 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
6784
6785 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
6786 UndefReg, Src0, SDValue());
6787
6788 // src0 must be the same register as src1 or src2, even if the value is
6789 // undefined, so make sure we don't violate this constraint.
6790 if (Src0.isMachineOpcode() &&
6791 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
6792 if (Src1.isMachineOpcode() &&
6793 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
6794 Src0 = Src1;
6795 else if (Src2.isMachineOpcode() &&
6796 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
6797 Src0 = Src2;
6798 else {
6799 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF)(static_cast <bool> (Src1.getMachineOpcode() == AMDGPU::
IMPLICIT_DEF) ? void (0) : __assert_fail ("Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6799, __extension__ __PRETTY_FUNCTION__))
;
6800 Src0 = UndefReg;
6801 Src1 = UndefReg;
6802 }
6803 } else
6804 break;
6805
6806 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
6807 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
6808 Ops.push_back(Node->getOperand(I));
6809
6810 Ops.push_back(ImpDef.getValue(1));
6811 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
6812 }
6813 default:
6814 break;
6815 }
6816
6817 return Node;
6818}
6819
6820/// \brief Assign the register class depending on the number of
6821/// bits set in the writemask
6822void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
6823 SDNode *Node) const {
6824 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6825
6826 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
6827
6828 if (TII->isVOP3(MI.getOpcode())) {
6829 // Make sure constant bus requirements are respected.
6830 TII->legalizeOperandsVOP3(MRI, MI);
6831 return;
6832 }
6833
6834 // Replace unused atomics with the no return version.
6835 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
6836 if (NoRetAtomicOp != -1) {
6837 if (!Node->hasAnyUseOfValue(0)) {
6838 MI.setDesc(TII->get(NoRetAtomicOp));
6839 MI.RemoveOperand(0);
6840 return;
6841 }
6842
6843 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
6844 // instruction, because the return type of these instructions is a vec2 of
6845 // the memory type, so it can be tied to the input operand.
6846 // This means these instructions always have a use, so we need to add a
6847 // special case to check if the atomic has only one extract_subreg use,
6848 // which itself has no uses.
6849 if ((Node->hasNUsesOfValue(1, 0) &&
6850 Node->use_begin()->isMachineOpcode() &&
6851 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
6852 !Node->use_begin()->hasAnyUseOfValue(0))) {
6853 unsigned Def = MI.getOperand(0).getReg();
6854
6855 // Change this into a noret atomic.
6856 MI.setDesc(TII->get(NoRetAtomicOp));
6857 MI.RemoveOperand(0);
6858
6859 // If we only remove the def operand from the atomic instruction, the
6860 // extract_subreg will be left with a use of a vreg without a def.
6861 // So we need to insert an implicit_def to avoid machine verifier
6862 // errors.
6863 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
6864 TII->get(AMDGPU::IMPLICIT_DEF), Def);
6865 }
6866 return;
6867 }
6868}
6869
6870static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
6871 uint64_t Val) {
6872 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
6873 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
6874}
6875
6876MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
6877 const SDLoc &DL,
6878 SDValue Ptr) const {
6879 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6880
6881 // Build the half of the subregister with the constants before building the
6882 // full 128-bit register. If we are building multiple resource descriptors,
6883 // this will allow CSEing of the 2-component register.
6884 const SDValue Ops0[] = {
6885 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
6886 buildSMovImm32(DAG, DL, 0),
6887 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
6888 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
6889 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
6890 };
6891
6892 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
6893 MVT::v2i32, Ops0), 0);
6894
6895 // Combine the constants and the pointer.
6896 const SDValue Ops1[] = {
6897 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
6898 Ptr,
6899 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
6900 SubRegHi,
6901 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
6902 };
6903
6904 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
6905}
6906
6907/// \brief Return a resource descriptor with the 'Add TID' bit enabled
6908/// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
6909/// of the resource descriptor) to create an offset, which is added to
6910/// the resource pointer.
6911MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
6912 SDValue Ptr, uint32_t RsrcDword1,
6913 uint64_t RsrcDword2And3) const {
6914 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
6915 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
6916 if (RsrcDword1) {
6917 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
6918 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
6919 0);
6920 }
6921
6922 SDValue DataLo = buildSMovImm32(DAG, DL,
6923 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)0xFFFFFFFFUL);
6924 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
6925
6926 const SDValue Ops[] = {
6927 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
6928 PtrLo,
6929 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
6930 PtrHi,
6931 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
6932 DataLo,
6933 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
6934 DataHi,
6935 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
6936 };
6937
6938 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
6939}
6940
6941//===----------------------------------------------------------------------===//
6942// SI Inline Assembly Support
6943//===----------------------------------------------------------------------===//
6944
6945std::pair<unsigned, const TargetRegisterClass *>
6946SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
6947 StringRef Constraint,
6948 MVT VT) const {
6949 if (!isTypeLegal(VT))
6950 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6951
6952 if (Constraint.size() == 1) {
6953 switch (Constraint[0]) {
6954 case 's':
6955 case 'r':
6956 switch (VT.getSizeInBits()) {
6957 default:
6958 return std::make_pair(0U, nullptr);
6959 case 32:
6960 case 16:
6961 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
6962 case 64:
6963 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
6964 case 128:
6965 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
6966 case 256:
6967 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
6968 case 512:
6969 return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
6970 }
6971
6972 case 'v':
6973 switch (VT.getSizeInBits()) {
6974 default:
6975 return std::make_pair(0U, nullptr);
6976 case 32:
6977 case 16:
6978 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
6979 case 64:
6980 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
6981 case 96:
6982 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
6983 case 128:
6984 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
6985 case 256:
6986 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
6987 case 512:
6988 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
6989 }
6990 }
6991 }
6992
6993 if (Constraint.size() > 1) {
6994 const TargetRegisterClass *RC = nullptr;
6995 if (Constraint[1] == 'v') {
6996 RC = &AMDGPU::VGPR_32RegClass;
6997 } else if (Constraint[1] == 's') {
6998 RC = &AMDGPU::SGPR_32RegClass;
6999 }
7000
7001 if (RC) {
7002 uint32_t Idx;
7003 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
7004 if (!Failed && Idx < RC->getNumRegs())
7005 return std::make_pair(RC->getRegister(Idx), RC);
7006 }
7007 }
7008 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7009}
7010
7011SITargetLowering::ConstraintType
7012SITargetLowering::getConstraintType(StringRef Constraint) const {
7013 if (Constraint.size() == 1) {
7014 switch (Constraint[0]) {
7015 default: break;
7016 case 's':
7017 case 'v':
7018 return C_RegisterClass;
7019 }
7020 }
7021 return TargetLowering::getConstraintType(Constraint);
7022}
7023
7024// Figure out which registers should be reserved for stack access. Only after
7025// the function is legalized do we know all of the non-spill stack objects or if
7026// calls are present.
7027void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
7028 MachineRegisterInfo &MRI = MF.getRegInfo();
7029 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
7030 const MachineFrameInfo &MFI = MF.getFrameInfo();
7031 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
7032 const SIRegisterInfo *TRI = ST.getRegisterInfo();
7033
7034 if (Info->isEntryFunction()) {
7035 // Callable functions have fixed registers used for stack access.
7036 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
7037 }
7038
7039 // We have to assume the SP is needed in case there are calls in the function
7040 // during lowering. Calls are only detected after the function is
7041 // lowered. We're about to reserve registers, so don't bother using it if we
7042 // aren't really going to use it.
7043 bool NeedSP = !Info->isEntryFunction() ||
7044 MFI.hasVarSizedObjects() ||
7045 MFI.hasCalls();
7046
7047 if (NeedSP) {
7048 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF);
7049 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
7050
7051 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg())(static_cast <bool> (Info->getStackPtrOffsetReg() !=
Info->getFrameOffsetReg()) ? void (0) : __assert_fail ("Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg()"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7051, __extension__ __PRETTY_FUNCTION__))
;
7052 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),(static_cast <bool> (!TRI->isSubRegister(Info->getScratchRSrcReg
(), Info->getStackPtrOffsetReg())) ? void (0) : __assert_fail
("!TRI->isSubRegister(Info->getScratchRSrcReg(), Info->getStackPtrOffsetReg())"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7053, __extension__ __PRETTY_FUNCTION__))
7053 Info->getStackPtrOffsetReg()))(static_cast <bool> (!TRI->isSubRegister(Info->getScratchRSrcReg
(), Info->getStackPtrOffsetReg())) ? void (0) : __assert_fail
("!TRI->isSubRegister(Info->getScratchRSrcReg(), Info->getStackPtrOffsetReg())"
, "/build/llvm-toolchain-snapshot-6.0~svn320085/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7053, __extension__ __PRETTY_FUNCTION__))
;
7054 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
7055 }
7056
7057 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
7058 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
7059 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
7060 Info->getScratchWaveOffsetReg());
7061
7062 TargetLoweringBase::finalizeLowering(MF);
7063}
7064
7065void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
7066 KnownBits &Known,
7067 const APInt &DemandedElts,
7068 const SelectionDAG &DAG,
7069 unsigned Depth) const {
7070 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
7071 DAG, Depth);
7072
7073 if (getSubtarget()->enableHugePrivateBuffer())
7074 return;
7075
7076 // Technically it may be possible to have a dispatch with a single workitem
7077 // that uses the full private memory size, but that's not really useful. We
7078 // can't use vaddr in MUBUF instructions if we don't know the address
7079 // calculation won't overflow, so assume the sign bit is never set.
7080 Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits);
7081}