Bug Summary

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

Annotated Source Code

[?] Use j/k keys for keyboard navigation

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