1//===-- R600ISelLowering.cpp - R600 DAG Lowering Implementation -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Custom DAG lowering for R600
11//
12//===----------------------------------------------------------------------===//
13
14#include "R600ISelLowering.h"
15#include "AMDGPU.h"
16#include "AMDGPUSelectionDAGInfo.h"
17#include "MCTargetDesc/R600MCTargetDesc.h"
18#include "R600Defines.h"
19#include "R600MachineFunctionInfo.h"
20#include "R600Subtarget.h"
21#include "R600TargetMachine.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/IR/IntrinsicsAMDGPU.h"
24#include "llvm/IR/IntrinsicsR600.h"
25#include "llvm/Passes/CodeGenPassBuilder.h"
26
27using namespace llvm;
28
29#include "R600GenCallingConv.inc"
30
31R600TargetLowering::R600TargetLowering(const TargetMachine &TM,
32 const R600Subtarget &STI)
33 : AMDGPUTargetLowering(TM, STI, STI), Subtarget(&STI),
34 Gen(STI.getGeneration()) {
35 addRegisterClass(VT: MVT::f32, RC: &R600::R600_Reg32RegClass);
36 addRegisterClass(VT: MVT::i32, RC: &R600::R600_Reg32RegClass);
37 addRegisterClass(VT: MVT::v2f32, RC: &R600::R600_Reg64RegClass);
38 addRegisterClass(VT: MVT::v2i32, RC: &R600::R600_Reg64RegClass);
39 addRegisterClass(VT: MVT::v4f32, RC: &R600::R600_Reg128RegClass);
40 addRegisterClass(VT: MVT::v4i32, RC: &R600::R600_Reg128RegClass);
41
42 setBooleanContents(ZeroOrNegativeOneBooleanContent);
43 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
44
45 computeRegisterProperties(TRI: Subtarget->getRegisterInfo());
46
47 // Legalize loads and stores to the private address space.
48 setOperationAction(Ops: ISD::LOAD, VTs: {MVT::i32, MVT::v2i32, MVT::v4i32}, Action: Custom);
49
50 // EXTLOAD should be the same as ZEXTLOAD. It is legal for some address
51 // spaces, so it is custom lowered to handle those where it isn't.
52 for (auto Op : {ISD::SEXTLOAD, ISD::ZEXTLOAD, ISD::EXTLOAD})
53 for (MVT VT : MVT::integer_valuetypes()) {
54 setLoadExtAction(ExtType: Op, ValVT: VT, MemVT: MVT::i1, Action: Promote);
55 setLoadExtAction(ExtType: Op, ValVT: VT, MemVT: MVT::i8, Action: Custom);
56 setLoadExtAction(ExtType: Op, ValVT: VT, MemVT: MVT::i16, Action: Custom);
57 }
58
59 // Workaround for LegalizeDAG asserting on expansion of i1 vector loads.
60 setLoadExtAction(ExtTypes: {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, ValVT: MVT::v2i32,
61 MemVT: MVT::v2i1, Action: Expand);
62
63 setLoadExtAction(ExtTypes: {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, ValVT: MVT::v4i32,
64 MemVT: MVT::v4i1, Action: Expand);
65
66 setOperationAction(Ops: ISD::STORE, VTs: {MVT::i8, MVT::i32, MVT::v2i32, MVT::v4i32},
67 Action: Custom);
68
69 setTruncStoreAction(ValVT: MVT::i32, MemVT: MVT::i8, Action: Custom);
70 setTruncStoreAction(ValVT: MVT::i32, MemVT: MVT::i16, Action: Custom);
71 // We need to include these since trunc STORES to PRIVATE need
72 // special handling to accommodate RMW
73 setTruncStoreAction(ValVT: MVT::v2i32, MemVT: MVT::v2i16, Action: Custom);
74 setTruncStoreAction(ValVT: MVT::v4i32, MemVT: MVT::v4i16, Action: Custom);
75 setTruncStoreAction(ValVT: MVT::v8i32, MemVT: MVT::v8i16, Action: Custom);
76 setTruncStoreAction(ValVT: MVT::v16i32, MemVT: MVT::v16i16, Action: Custom);
77 setTruncStoreAction(ValVT: MVT::v32i32, MemVT: MVT::v32i16, Action: Custom);
78 setTruncStoreAction(ValVT: MVT::v2i32, MemVT: MVT::v2i8, Action: Custom);
79 setTruncStoreAction(ValVT: MVT::v4i32, MemVT: MVT::v4i8, Action: Custom);
80 setTruncStoreAction(ValVT: MVT::v8i32, MemVT: MVT::v8i8, Action: Custom);
81 setTruncStoreAction(ValVT: MVT::v16i32, MemVT: MVT::v16i8, Action: Custom);
82 setTruncStoreAction(ValVT: MVT::v32i32, MemVT: MVT::v32i8, Action: Custom);
83
84 // Workaround for LegalizeDAG asserting on expansion of i1 vector stores.
85 setTruncStoreAction(ValVT: MVT::v2i32, MemVT: MVT::v2i1, Action: Expand);
86 setTruncStoreAction(ValVT: MVT::v4i32, MemVT: MVT::v4i1, Action: Expand);
87
88 // Set condition code actions
89 setCondCodeAction(CCs: {ISD::SETO, ISD::SETUO, ISD::SETLT, ISD::SETLE, ISD::SETOLT,
90 ISD::SETOLE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGE,
91 ISD::SETUGT, ISD::SETULT, ISD::SETULE},
92 VT: MVT::f32, Action: Expand);
93
94 setCondCodeAction(CCs: {ISD::SETLE, ISD::SETLT, ISD::SETULE, ISD::SETULT},
95 VT: MVT::i32, Action: Expand);
96
97 setOperationAction(Ops: {ISD::FCOS, ISD::FSIN}, VT: MVT::f32, Action: Custom);
98
99 setOperationAction(Ops: ISD::SETCC, VTs: {MVT::v4i32, MVT::v2i32}, Action: Expand);
100
101 setOperationAction(Ops: ISD::BR_CC, VTs: {MVT::i32, MVT::f32}, Action: Expand);
102 setOperationAction(Op: ISD::BRCOND, VT: MVT::Other, Action: Custom);
103
104 setOperationAction(Op: ISD::FSUB, VT: MVT::f32, Action: Expand);
105
106 setOperationAction(Ops: ISD::IS_FPCLASS,
107 VTs: {MVT::f32, MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32,
108 MVT::v6f32, MVT::v7f32, MVT::v8f32, MVT::v16f32},
109 Action: Expand);
110
111 setOperationAction(Ops: {ISD::FCEIL, ISD::FTRUNC, ISD::FROUNDEVEN, ISD::FFLOOR},
112 VT: MVT::f64, Action: Custom);
113
114 setOperationAction(Ops: ISD::SELECT_CC, VTs: {MVT::f32, MVT::i32}, Action: Custom);
115
116 setOperationAction(Ops: ISD::SETCC, VTs: {MVT::i32, MVT::f32}, Action: Expand);
117 setOperationAction(Ops: {ISD::FP_TO_UINT, ISD::FP_TO_SINT}, VTs: {MVT::i1, MVT::i64},
118 Action: Custom);
119
120 setOperationAction(Ops: ISD::SELECT, VTs: {MVT::i32, MVT::f32, MVT::v2i32, MVT::v4i32},
121 Action: Expand);
122
123 // ADD, SUB overflow.
124 // TODO: turn these into Legal?
125 if (Subtarget->hasCARRY())
126 setOperationAction(Op: ISD::UADDO, VT: MVT::i32, Action: Custom);
127
128 if (Subtarget->hasBORROW())
129 setOperationAction(Op: ISD::USUBO, VT: MVT::i32, Action: Custom);
130
131 // Expand sign extension of vectors
132 if (!Subtarget->hasBFE())
133 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i1, Action: Expand);
134
135 setOperationAction(Ops: ISD::SIGN_EXTEND_INREG, VTs: {MVT::v2i1, MVT::v4i1}, Action: Expand);
136
137 if (!Subtarget->hasBFE())
138 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i8, Action: Expand);
139 setOperationAction(Ops: ISD::SIGN_EXTEND_INREG, VTs: {MVT::v2i8, MVT::v4i8}, Action: Expand);
140
141 if (!Subtarget->hasBFE())
142 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i16, Action: Expand);
143 setOperationAction(Ops: ISD::SIGN_EXTEND_INREG, VTs: {MVT::v2i16, MVT::v4i16}, Action: Expand);
144
145 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i32, Action: Legal);
146 setOperationAction(Ops: ISD::SIGN_EXTEND_INREG, VTs: {MVT::v2i32, MVT::v4i32}, Action: Expand);
147
148 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::Other, Action: Expand);
149
150 setOperationAction(Op: ISD::FrameIndex, VT: MVT::i32, Action: Custom);
151
152 setOperationAction(Ops: ISD::EXTRACT_VECTOR_ELT,
153 VTs: {MVT::v2i32, MVT::v2f32, MVT::v4i32, MVT::v4f32}, Action: Custom);
154
155 setOperationAction(Ops: ISD::INSERT_VECTOR_ELT,
156 VTs: {MVT::v2i32, MVT::v2f32, MVT::v4i32, MVT::v4f32}, Action: Custom);
157
158 // We don't have 64-bit shifts. Thus we need either SHX i64 or SHX_PARTS i32
159 // to be Legal/Custom in order to avoid library calls.
160 setOperationAction(Ops: {ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, VT: MVT::i32,
161 Action: Custom);
162
163 if (!Subtarget->hasFMA())
164 setOperationAction(Ops: ISD::FMA, VTs: {MVT::f32, MVT::f64}, Action: Expand);
165
166 // FIXME: May need no denormals check
167 setOperationAction(Op: ISD::FMAD, VT: MVT::f32, Action: Legal);
168
169 if (!Subtarget->hasBFI())
170 // fcopysign can be done in a single instruction with BFI.
171 setOperationAction(Ops: ISD::FCOPYSIGN, VTs: {MVT::f32, MVT::f64}, Action: Expand);
172
173 if (!Subtarget->hasBCNT(Size: 32))
174 setOperationAction(Op: ISD::CTPOP, VT: MVT::i32, Action: Expand);
175
176 if (!Subtarget->hasBCNT(Size: 64))
177 setOperationAction(Op: ISD::CTPOP, VT: MVT::i64, Action: Expand);
178
179 if (Subtarget->hasFFBH())
180 setOperationAction(Op: ISD::CTLZ_ZERO_UNDEF, VT: MVT::i32, Action: Custom);
181
182 if (Subtarget->hasFFBL())
183 setOperationAction(Op: ISD::CTTZ_ZERO_UNDEF, VT: MVT::i32, Action: Custom);
184
185 // FIXME: This was moved from AMDGPUTargetLowering, I'm not sure if we
186 // need it for R600.
187 if (Subtarget->hasBFE())
188 setHasExtractBitsInsn(true);
189
190 setOperationAction(Op: ISD::GlobalAddress, VT: MVT::i32, Action: Custom);
191 setOperationAction(Op: ISD::ADDRSPACECAST, VT: MVT::i32, Action: Custom);
192
193 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
194 for (MVT VT : ScalarIntVTs)
195 setOperationAction(Ops: {ISD::ADDC, ISD::SUBC, ISD::ADDE, ISD::SUBE}, VT,
196 Action: Expand);
197
198 // LLVM will expand these to atomic_cmp_swap(0)
199 // and atomic_swap, respectively.
200 setOperationAction(Ops: {ISD::ATOMIC_LOAD, ISD::ATOMIC_STORE}, VT: MVT::i32, Action: Expand);
201
202 // We need to custom lower some of the intrinsics
203 setOperationAction(Ops: {ISD::INTRINSIC_VOID, ISD::INTRINSIC_WO_CHAIN}, VT: MVT::Other,
204 Action: Custom);
205
206 setSchedulingPreference(Sched::Source);
207
208 setTargetDAGCombine({ISD::FP_ROUND, ISD::FP_TO_SINT, ISD::EXTRACT_VECTOR_ELT,
209 ISD::SELECT_CC, ISD::INSERT_VECTOR_ELT, ISD::LOAD});
210}
211
212static inline bool isEOP(MachineBasicBlock::iterator I) {
213 if (std::next(x: I) == I->getParent()->end())
214 return false;
215 return std::next(x: I)->getOpcode() == R600::RETURN;
216}
217
218MachineBasicBlock *
219R600TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
220 MachineBasicBlock *BB) const {
221 MachineFunction *MF = BB->getParent();
222 MachineRegisterInfo &MRI = MF->getRegInfo();
223 MachineBasicBlock::iterator I = MI;
224 const R600InstrInfo *TII = Subtarget->getInstrInfo();
225
226 switch (MI.getOpcode()) {
227 default:
228 // Replace LDS_*_RET instruction that don't have any uses with the
229 // equivalent LDS_*_NORET instruction.
230 if (TII->isLDSRetInstr(Opcode: MI.getOpcode())) {
231 int DstIdx = TII->getOperandIdx(Opcode: MI.getOpcode(), Op: R600::OpName::dst);
232 assert(DstIdx != -1);
233 MachineInstrBuilder NewMI;
234 // FIXME: getLDSNoRetOp method only handles LDS_1A1D LDS ops. Add
235 // LDS_1A2D support and remove this special case.
236 if (!MRI.use_empty(RegNo: MI.getOperand(i: DstIdx).getReg()) ||
237 MI.getOpcode() == R600::LDS_CMPST_RET)
238 return BB;
239
240 NewMI = BuildMI(BB&: *BB, I, MIMD: BB->findDebugLoc(MBBI: I),
241 MCID: TII->get(Opcode: R600::getLDSNoRetOp(Opcode: MI.getOpcode())));
242 for (const MachineOperand &MO : llvm::drop_begin(RangeOrContainer: MI.operands()))
243 NewMI.add(MO);
244 } else {
245 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, MBB: BB);
246 }
247 break;
248
249 case R600::FABS_R600: {
250 MachineInstr *NewMI = TII->buildDefaultInstruction(
251 MBB&: *BB, I, Opcode: R600::MOV, DstReg: MI.getOperand(i: 0).getReg(),
252 Src0Reg: MI.getOperand(i: 1).getReg());
253 TII->addFlag(MI&: *NewMI, SrcIdx: 0, MO_FLAG_ABS);
254 break;
255 }
256
257 case R600::FNEG_R600: {
258 MachineInstr *NewMI = TII->buildDefaultInstruction(
259 MBB&: *BB, I, Opcode: R600::MOV, DstReg: MI.getOperand(i: 0).getReg(),
260 Src0Reg: MI.getOperand(i: 1).getReg());
261 TII->addFlag(MI&: *NewMI, SrcIdx: 0, MO_FLAG_NEG);
262 break;
263 }
264
265 case R600::MASK_WRITE: {
266 Register maskedRegister = MI.getOperand(i: 0).getReg();
267 assert(maskedRegister.isVirtual());
268 MachineInstr * defInstr = MRI.getVRegDef(Reg: maskedRegister);
269 TII->addFlag(MI&: *defInstr, SrcIdx: 0, MO_FLAG_MASK);
270 break;
271 }
272
273 case R600::MOV_IMM_F32:
274 TII->buildMovImm(BB&: *BB, I, DstReg: MI.getOperand(i: 0).getReg(), Imm: MI.getOperand(i: 1)
275 .getFPImm()
276 ->getValueAPF()
277 .bitcastToAPInt()
278 .getZExtValue());
279 break;
280
281 case R600::MOV_IMM_I32:
282 TII->buildMovImm(BB&: *BB, I, DstReg: MI.getOperand(i: 0).getReg(),
283 Imm: MI.getOperand(i: 1).getImm());
284 break;
285
286 case R600::MOV_IMM_GLOBAL_ADDR: {
287 //TODO: Perhaps combine this instruction with the next if possible
288 auto MIB = TII->buildDefaultInstruction(
289 MBB&: *BB, I: MI, Opcode: R600::MOV, DstReg: MI.getOperand(i: 0).getReg(), Src0Reg: R600::ALU_LITERAL_X);
290 int Idx = TII->getOperandIdx(MI: *MIB, Op: R600::OpName::literal);
291 //TODO: Ugh this is rather ugly
292 const MachineOperand &MO = MI.getOperand(i: 1);
293 MIB->getOperand(i: Idx).ChangeToGA(GV: MO.getGlobal(), Offset: MO.getOffset(),
294 TargetFlags: MO.getTargetFlags());
295 break;
296 }
297
298 case R600::CONST_COPY: {
299 MachineInstr *NewMI = TII->buildDefaultInstruction(
300 MBB&: *BB, I: MI, Opcode: R600::MOV, DstReg: MI.getOperand(i: 0).getReg(), Src0Reg: R600::ALU_CONST);
301 TII->setImmOperand(MI&: *NewMI, Op: R600::OpName::src0_sel,
302 Imm: MI.getOperand(i: 1).getImm());
303 break;
304 }
305
306 case R600::RAT_WRITE_CACHELESS_32_eg:
307 case R600::RAT_WRITE_CACHELESS_64_eg:
308 case R600::RAT_WRITE_CACHELESS_128_eg:
309 BuildMI(BB&: *BB, I, MIMD: BB->findDebugLoc(MBBI: I), MCID: TII->get(Opcode: MI.getOpcode()))
310 .add(MO: MI.getOperand(i: 0))
311 .add(MO: MI.getOperand(i: 1))
312 .addImm(Val: isEOP(I)); // Set End of program bit
313 break;
314
315 case R600::RAT_STORE_TYPED_eg:
316 BuildMI(BB&: *BB, I, MIMD: BB->findDebugLoc(MBBI: I), MCID: TII->get(Opcode: MI.getOpcode()))
317 .add(MO: MI.getOperand(i: 0))
318 .add(MO: MI.getOperand(i: 1))
319 .add(MO: MI.getOperand(i: 2))
320 .addImm(Val: isEOP(I)); // Set End of program bit
321 break;
322
323 case R600::BRANCH:
324 BuildMI(BB&: *BB, I, MIMD: BB->findDebugLoc(MBBI: I), MCID: TII->get(Opcode: R600::JUMP))
325 .add(MO: MI.getOperand(i: 0));
326 break;
327
328 case R600::BRANCH_COND_f32: {
329 MachineInstr *NewMI =
330 BuildMI(BB&: *BB, I, MIMD: BB->findDebugLoc(MBBI: I), MCID: TII->get(Opcode: R600::PRED_X),
331 DestReg: R600::PREDICATE_BIT)
332 .add(MO: MI.getOperand(i: 1))
333 .addImm(Val: R600::PRED_SETNE)
334 .addImm(Val: 0); // Flags
335 TII->addFlag(MI&: *NewMI, SrcIdx: 0, MO_FLAG_PUSH);
336 BuildMI(BB&: *BB, I, MIMD: BB->findDebugLoc(MBBI: I), MCID: TII->get(Opcode: R600::JUMP_COND))
337 .add(MO: MI.getOperand(i: 0))
338 .addReg(RegNo: R600::PREDICATE_BIT, Flags: RegState::Kill);
339 break;
340 }
341
342 case R600::BRANCH_COND_i32: {
343 MachineInstr *NewMI =
344 BuildMI(BB&: *BB, I, MIMD: BB->findDebugLoc(MBBI: I), MCID: TII->get(Opcode: R600::PRED_X),
345 DestReg: R600::PREDICATE_BIT)
346 .add(MO: MI.getOperand(i: 1))
347 .addImm(Val: R600::PRED_SETNE_INT)
348 .addImm(Val: 0); // Flags
349 TII->addFlag(MI&: *NewMI, SrcIdx: 0, MO_FLAG_PUSH);
350 BuildMI(BB&: *BB, I, MIMD: BB->findDebugLoc(MBBI: I), MCID: TII->get(Opcode: R600::JUMP_COND))
351 .add(MO: MI.getOperand(i: 0))
352 .addReg(RegNo: R600::PREDICATE_BIT, Flags: RegState::Kill);
353 break;
354 }
355
356 case R600::EG_ExportSwz:
357 case R600::R600_ExportSwz: {
358 // Instruction is left unmodified if its not the last one of its type
359 bool isLastInstructionOfItsType = true;
360 unsigned InstExportType = MI.getOperand(i: 1).getImm();
361 for (MachineBasicBlock::iterator NextExportInst = std::next(x: I),
362 EndBlock = BB->end(); NextExportInst != EndBlock;
363 NextExportInst = std::next(x: NextExportInst)) {
364 if (NextExportInst->getOpcode() == R600::EG_ExportSwz ||
365 NextExportInst->getOpcode() == R600::R600_ExportSwz) {
366 unsigned CurrentInstExportType = NextExportInst->getOperand(i: 1)
367 .getImm();
368 if (CurrentInstExportType == InstExportType) {
369 isLastInstructionOfItsType = false;
370 break;
371 }
372 }
373 }
374 bool EOP = isEOP(I);
375 if (!EOP && !isLastInstructionOfItsType)
376 return BB;
377 unsigned CfInst = (MI.getOpcode() == R600::EG_ExportSwz) ? 84 : 40;
378 BuildMI(BB&: *BB, I, MIMD: BB->findDebugLoc(MBBI: I), MCID: TII->get(Opcode: MI.getOpcode()))
379 .add(MO: MI.getOperand(i: 0))
380 .add(MO: MI.getOperand(i: 1))
381 .add(MO: MI.getOperand(i: 2))
382 .add(MO: MI.getOperand(i: 3))
383 .add(MO: MI.getOperand(i: 4))
384 .add(MO: MI.getOperand(i: 5))
385 .add(MO: MI.getOperand(i: 6))
386 .addImm(Val: CfInst)
387 .addImm(Val: EOP);
388 break;
389 }
390 case R600::RETURN: {
391 return BB;
392 }
393 }
394
395 MI.eraseFromParent();
396 return BB;
397}
398
399//===----------------------------------------------------------------------===//
400// Custom DAG Lowering Operations
401//===----------------------------------------------------------------------===//
402
403SDValue R600TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
404 MachineFunction &MF = DAG.getMachineFunction();
405 R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
406 switch (Op.getOpcode()) {
407 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
408 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
409 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
410 case ISD::SHL_PARTS:
411 case ISD::SRA_PARTS:
412 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
413 case ISD::UADDO: return LowerUADDSUBO(Op, DAG, mainop: ISD::ADD, ovf: AMDGPUISD::CARRY);
414 case ISD::USUBO: return LowerUADDSUBO(Op, DAG, mainop: ISD::SUB, ovf: AMDGPUISD::BORROW);
415 case ISD::FCOS:
416 case ISD::FSIN: return LowerTrig(Op, DAG);
417 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
418 case ISD::STORE: return LowerSTORE(Op, DAG);
419 case ISD::LOAD: {
420 SDValue Result = LowerLOAD(Op, DAG);
421 assert((!Result.getNode() ||
422 Result.getNode()->getNumValues() == 2) &&
423 "Load should return a value and a chain");
424 return Result;
425 }
426
427 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
428 case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
429 case ISD::FrameIndex: return lowerFrameIndex(Op, DAG);
430 case ISD::ADDRSPACECAST:
431 return lowerADDRSPACECAST(Op, DAG);
432 case ISD::INTRINSIC_VOID: {
433 SDValue Chain = Op.getOperand(i: 0);
434 unsigned IntrinsicID = Op.getConstantOperandVal(i: 1);
435 switch (IntrinsicID) {
436 case Intrinsic::r600_store_swizzle: {
437 SDLoc DL(Op);
438 const SDValue Args[8] = {
439 Chain,
440 Op.getOperand(i: 2), // Export Value
441 Op.getOperand(i: 3), // ArrayBase
442 Op.getOperand(i: 4), // Type
443 DAG.getConstant(Val: 0, DL, VT: MVT::i32), // SWZ_X
444 DAG.getConstant(Val: 1, DL, VT: MVT::i32), // SWZ_Y
445 DAG.getConstant(Val: 2, DL, VT: MVT::i32), // SWZ_Z
446 DAG.getConstant(Val: 3, DL, VT: MVT::i32) // SWZ_W
447 };
448 return DAG.getNode(Opcode: AMDGPUISD::R600_EXPORT, DL, VT: Op.getValueType(), Ops: Args);
449 }
450
451 // default for switch(IntrinsicID)
452 default: break;
453 }
454 // break out of case ISD::INTRINSIC_VOID in switch(Op.getOpcode())
455 break;
456 }
457 case ISD::INTRINSIC_WO_CHAIN: {
458 unsigned IntrinsicID = Op.getConstantOperandVal(i: 0);
459 EVT VT = Op.getValueType();
460 SDLoc DL(Op);
461 switch (IntrinsicID) {
462 case Intrinsic::r600_tex:
463 case Intrinsic::r600_texc: {
464 unsigned TextureOp;
465 switch (IntrinsicID) {
466 case Intrinsic::r600_tex:
467 TextureOp = 0;
468 break;
469 case Intrinsic::r600_texc:
470 TextureOp = 1;
471 break;
472 default:
473 llvm_unreachable("unhandled texture operation");
474 }
475
476 SDValue TexArgs[19] = {
477 DAG.getConstant(Val: TextureOp, DL, VT: MVT::i32),
478 Op.getOperand(i: 1),
479 DAG.getConstant(Val: 0, DL, VT: MVT::i32),
480 DAG.getConstant(Val: 1, DL, VT: MVT::i32),
481 DAG.getConstant(Val: 2, DL, VT: MVT::i32),
482 DAG.getConstant(Val: 3, DL, VT: MVT::i32),
483 Op.getOperand(i: 2),
484 Op.getOperand(i: 3),
485 Op.getOperand(i: 4),
486 DAG.getConstant(Val: 0, DL, VT: MVT::i32),
487 DAG.getConstant(Val: 1, DL, VT: MVT::i32),
488 DAG.getConstant(Val: 2, DL, VT: MVT::i32),
489 DAG.getConstant(Val: 3, DL, VT: MVT::i32),
490 Op.getOperand(i: 5),
491 Op.getOperand(i: 6),
492 Op.getOperand(i: 7),
493 Op.getOperand(i: 8),
494 Op.getOperand(i: 9),
495 Op.getOperand(i: 10)
496 };
497 return DAG.getNode(Opcode: AMDGPUISD::TEXTURE_FETCH, DL, VT: MVT::v4f32, Ops: TexArgs);
498 }
499 case Intrinsic::r600_dot4: {
500 SDValue Args[8] = {
501 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: Op.getOperand(i: 1),
502 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32)),
503 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: Op.getOperand(i: 2),
504 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32)),
505 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: Op.getOperand(i: 1),
506 N2: DAG.getConstant(Val: 1, DL, VT: MVT::i32)),
507 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: Op.getOperand(i: 2),
508 N2: DAG.getConstant(Val: 1, DL, VT: MVT::i32)),
509 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: Op.getOperand(i: 1),
510 N2: DAG.getConstant(Val: 2, DL, VT: MVT::i32)),
511 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: Op.getOperand(i: 2),
512 N2: DAG.getConstant(Val: 2, DL, VT: MVT::i32)),
513 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: Op.getOperand(i: 1),
514 N2: DAG.getConstant(Val: 3, DL, VT: MVT::i32)),
515 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: Op.getOperand(i: 2),
516 N2: DAG.getConstant(Val: 3, DL, VT: MVT::i32))
517 };
518 return DAG.getNode(Opcode: AMDGPUISD::DOT4, DL, VT: MVT::f32, Ops: Args);
519 }
520
521 case Intrinsic::r600_implicitarg_ptr: {
522 MVT PtrVT = getPointerTy(DL: DAG.getDataLayout(), AS: AMDGPUAS::PARAM_I_ADDRESS);
523 uint32_t ByteOffset = getImplicitParameterOffset(MF, Param: FIRST_IMPLICIT);
524 return DAG.getConstant(Val: ByteOffset, DL, VT: PtrVT);
525 }
526 case Intrinsic::r600_read_ngroups_x:
527 return LowerImplicitParameter(DAG, VT, DL, DwordOffset: 0);
528 case Intrinsic::r600_read_ngroups_y:
529 return LowerImplicitParameter(DAG, VT, DL, DwordOffset: 1);
530 case Intrinsic::r600_read_ngroups_z:
531 return LowerImplicitParameter(DAG, VT, DL, DwordOffset: 2);
532 case Intrinsic::r600_read_global_size_x:
533 return LowerImplicitParameter(DAG, VT, DL, DwordOffset: 3);
534 case Intrinsic::r600_read_global_size_y:
535 return LowerImplicitParameter(DAG, VT, DL, DwordOffset: 4);
536 case Intrinsic::r600_read_global_size_z:
537 return LowerImplicitParameter(DAG, VT, DL, DwordOffset: 5);
538 case Intrinsic::r600_read_local_size_x:
539 return LowerImplicitParameter(DAG, VT, DL, DwordOffset: 6);
540 case Intrinsic::r600_read_local_size_y:
541 return LowerImplicitParameter(DAG, VT, DL, DwordOffset: 7);
542 case Intrinsic::r600_read_local_size_z:
543 return LowerImplicitParameter(DAG, VT, DL, DwordOffset: 8);
544
545 case Intrinsic::r600_read_tgid_x:
546 case Intrinsic::amdgcn_workgroup_id_x:
547 return CreateLiveInRegisterRaw(DAG, RC: &R600::R600_TReg32RegClass,
548 Reg: R600::T1_X, VT);
549 case Intrinsic::r600_read_tgid_y:
550 case Intrinsic::amdgcn_workgroup_id_y:
551 return CreateLiveInRegisterRaw(DAG, RC: &R600::R600_TReg32RegClass,
552 Reg: R600::T1_Y, VT);
553 case Intrinsic::r600_read_tgid_z:
554 case Intrinsic::amdgcn_workgroup_id_z:
555 return CreateLiveInRegisterRaw(DAG, RC: &R600::R600_TReg32RegClass,
556 Reg: R600::T1_Z, VT);
557 case Intrinsic::r600_read_tidig_x:
558 case Intrinsic::amdgcn_workitem_id_x:
559 return CreateLiveInRegisterRaw(DAG, RC: &R600::R600_TReg32RegClass,
560 Reg: R600::T0_X, VT);
561 case Intrinsic::r600_read_tidig_y:
562 case Intrinsic::amdgcn_workitem_id_y:
563 return CreateLiveInRegisterRaw(DAG, RC: &R600::R600_TReg32RegClass,
564 Reg: R600::T0_Y, VT);
565 case Intrinsic::r600_read_tidig_z:
566 case Intrinsic::amdgcn_workitem_id_z:
567 return CreateLiveInRegisterRaw(DAG, RC: &R600::R600_TReg32RegClass,
568 Reg: R600::T0_Z, VT);
569
570 case Intrinsic::r600_recipsqrt_ieee:
571 return DAG.getNode(Opcode: AMDGPUISD::RSQ, DL, VT, Operand: Op.getOperand(i: 1));
572
573 case Intrinsic::r600_recipsqrt_clamped:
574 return DAG.getNode(Opcode: AMDGPUISD::RSQ_CLAMP, DL, VT, Operand: Op.getOperand(i: 1));
575 default:
576 return Op;
577 }
578
579 // break out of case ISD::INTRINSIC_WO_CHAIN in switch(Op.getOpcode())
580 break;
581 }
582 } // end switch(Op.getOpcode())
583 return SDValue();
584}
585
586void R600TargetLowering::ReplaceNodeResults(SDNode *N,
587 SmallVectorImpl<SDValue> &Results,
588 SelectionDAG &DAG) const {
589 switch (N->getOpcode()) {
590 default:
591 AMDGPUTargetLowering::ReplaceNodeResults(N, Results, DAG);
592 return;
593 case ISD::FP_TO_UINT:
594 if (N->getValueType(ResNo: 0) == MVT::i1) {
595 Results.push_back(Elt: lowerFP_TO_UINT(Op: N->getOperand(Num: 0), DAG));
596 return;
597 }
598 // Since we don't care about out of bounds values we can use FP_TO_SINT for
599 // uints too. The DAGLegalizer code for uint considers some extra cases
600 // which are not necessary here.
601 [[fallthrough]];
602 case ISD::FP_TO_SINT: {
603 if (N->getValueType(ResNo: 0) == MVT::i1) {
604 Results.push_back(Elt: lowerFP_TO_SINT(Op: N->getOperand(Num: 0), DAG));
605 return;
606 }
607
608 SDValue Result;
609 if (expandFP_TO_SINT(N, Result, DAG))
610 Results.push_back(Elt: Result);
611 return;
612 }
613 case ISD::SDIVREM: {
614 SDValue Op = SDValue(N, 1);
615 SDValue RES = LowerSDIVREM(Op, DAG);
616 Results.push_back(Elt: RES);
617 Results.push_back(Elt: RES.getValue(R: 1));
618 break;
619 }
620 case ISD::UDIVREM: {
621 SDValue Op = SDValue(N, 0);
622 LowerUDIVREM64(Op, DAG, Results);
623 break;
624 }
625 }
626}
627
628SDValue R600TargetLowering::vectorToVerticalVector(SelectionDAG &DAG,
629 SDValue Vector) const {
630 SDLoc DL(Vector);
631 EVT VecVT = Vector.getValueType();
632 EVT EltVT = VecVT.getVectorElementType();
633 SmallVector<SDValue, 8> Args;
634
635 for (unsigned i = 0, e = VecVT.getVectorNumElements(); i != e; ++i) {
636 Args.push_back(Elt: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: EltVT, N1: Vector,
637 N2: DAG.getVectorIdxConstant(Val: i, DL)));
638 }
639
640 return DAG.getNode(Opcode: AMDGPUISD::BUILD_VERTICAL_VECTOR, DL, VT: VecVT, Ops: Args);
641}
642
643SDValue R600TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
644 SelectionDAG &DAG) const {
645 SDLoc DL(Op);
646 SDValue Vector = Op.getOperand(i: 0);
647 SDValue Index = Op.getOperand(i: 1);
648
649 if (isa<ConstantSDNode>(Val: Index) ||
650 Vector.getOpcode() == AMDGPUISD::BUILD_VERTICAL_VECTOR)
651 return Op;
652
653 Vector = vectorToVerticalVector(DAG, Vector);
654 return DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: Op.getValueType(),
655 N1: Vector, N2: Index);
656}
657
658SDValue R600TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
659 SelectionDAG &DAG) const {
660 SDLoc DL(Op);
661 SDValue Vector = Op.getOperand(i: 0);
662 SDValue Value = Op.getOperand(i: 1);
663 SDValue Index = Op.getOperand(i: 2);
664
665 if (isa<ConstantSDNode>(Val: Index) ||
666 Vector.getOpcode() == AMDGPUISD::BUILD_VERTICAL_VECTOR)
667 return Op;
668
669 Vector = vectorToVerticalVector(DAG, Vector);
670 SDValue Insert = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL, VT: Op.getValueType(),
671 N1: Vector, N2: Value, N3: Index);
672 return vectorToVerticalVector(DAG, Vector: Insert);
673}
674
675SDValue R600TargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
676 SDValue Op,
677 SelectionDAG &DAG) const {
678 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Val&: Op);
679 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
680 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
681
682 const DataLayout &DL = DAG.getDataLayout();
683 const GlobalValue *GV = GSD->getGlobal();
684 MVT ConstPtrVT = getPointerTy(DL, AS: AMDGPUAS::CONSTANT_ADDRESS);
685
686 SDValue GA = DAG.getTargetGlobalAddress(GV, DL: SDLoc(GSD), VT: ConstPtrVT);
687 return DAG.getNode(Opcode: AMDGPUISD::CONST_DATA_PTR, DL: SDLoc(GSD), VT: ConstPtrVT, Operand: GA);
688}
689
690SDValue R600TargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
691 // On hw >= R700, COS/SIN input must be between -1. and 1.
692 // Thus we lower them to TRIG ( FRACT ( x / 2Pi + 0.5) - 0.5)
693 EVT VT = Op.getValueType();
694 SDValue Arg = Op.getOperand(i: 0);
695 SDLoc DL(Op);
696
697 // TODO: Should this propagate fast-math-flags?
698 SDValue FractPart = DAG.getNode(Opcode: AMDGPUISD::FRACT, DL, VT,
699 Operand: DAG.getNode(Opcode: ISD::FADD, DL, VT,
700 N1: DAG.getNode(Opcode: ISD::FMUL, DL, VT, N1: Arg,
701 N2: DAG.getConstantFP(Val: 0.15915494309, DL, VT: MVT::f32)),
702 N2: DAG.getConstantFP(Val: 0.5, DL, VT: MVT::f32)));
703 unsigned TrigNode;
704 switch (Op.getOpcode()) {
705 case ISD::FCOS:
706 TrigNode = AMDGPUISD::COS_HW;
707 break;
708 case ISD::FSIN:
709 TrigNode = AMDGPUISD::SIN_HW;
710 break;
711 default:
712 llvm_unreachable("Wrong trig opcode");
713 }
714 SDValue TrigVal = DAG.getNode(Opcode: TrigNode, DL, VT,
715 Operand: DAG.getNode(Opcode: ISD::FADD, DL, VT, N1: FractPart,
716 N2: DAG.getConstantFP(Val: -0.5, DL, VT: MVT::f32)));
717 if (Gen >= AMDGPUSubtarget::R700)
718 return TrigVal;
719 // On R600 hw, COS/SIN input must be between -Pi and Pi.
720 return DAG.getNode(Opcode: ISD::FMUL, DL, VT, N1: TrigVal,
721 N2: DAG.getConstantFP(Val: numbers::pif, DL, VT: MVT::f32));
722}
723
724SDValue R600TargetLowering::LowerShiftParts(SDValue Op,
725 SelectionDAG &DAG) const {
726 SDValue Lo, Hi;
727 expandShiftParts(N: Op.getNode(), Lo, Hi, DAG);
728 return DAG.getMergeValues(Ops: {Lo, Hi}, dl: SDLoc(Op));
729}
730
731SDValue R600TargetLowering::LowerUADDSUBO(SDValue Op, SelectionDAG &DAG,
732 unsigned mainop, unsigned ovf) const {
733 SDLoc DL(Op);
734 EVT VT = Op.getValueType();
735
736 SDValue Lo = Op.getOperand(i: 0);
737 SDValue Hi = Op.getOperand(i: 1);
738
739 SDValue OVF = DAG.getNode(Opcode: ovf, DL, VT, N1: Lo, N2: Hi);
740 // Extend sign.
741 OVF = DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL, VT, N1: OVF,
742 N2: DAG.getValueType(MVT::i1));
743
744 SDValue Res = DAG.getNode(Opcode: mainop, DL, VT, N1: Lo, N2: Hi);
745
746 return DAG.getNode(Opcode: ISD::MERGE_VALUES, DL, VTList: DAG.getVTList(VT1: VT, VT2: VT), N1: Res, N2: OVF);
747}
748
749SDValue R600TargetLowering::lowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) const {
750 SDLoc DL(Op);
751 return DAG.getNode(
752 Opcode: ISD::SETCC,
753 DL,
754 VT: MVT::i1,
755 N1: Op, N2: DAG.getConstantFP(Val: 1.0f, DL, VT: MVT::f32),
756 N3: DAG.getCondCode(Cond: ISD::SETEQ));
757}
758
759SDValue R600TargetLowering::lowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) const {
760 SDLoc DL(Op);
761 return DAG.getNode(
762 Opcode: ISD::SETCC,
763 DL,
764 VT: MVT::i1,
765 N1: Op, N2: DAG.getConstantFP(Val: -1.0f, DL, VT: MVT::f32),
766 N3: DAG.getCondCode(Cond: ISD::SETEQ));
767}
768
769SDValue R600TargetLowering::LowerImplicitParameter(SelectionDAG &DAG, EVT VT,
770 const SDLoc &DL,
771 unsigned DwordOffset) const {
772 unsigned ByteOffset = DwordOffset * 4;
773 PointerType *PtrType =
774 PointerType::get(C&: *DAG.getContext(), AddressSpace: AMDGPUAS::PARAM_I_ADDRESS);
775
776 // We shouldn't be using an offset wider than 16-bits for implicit parameters.
777 assert(isInt<16>(ByteOffset));
778
779 return DAG.getLoad(VT, dl: DL, Chain: DAG.getEntryNode(),
780 Ptr: DAG.getConstant(Val: ByteOffset, DL, VT: MVT::i32), // PTR
781 PtrInfo: MachinePointerInfo(ConstantPointerNull::get(T: PtrType)));
782}
783
784bool R600TargetLowering::isZero(SDValue Op) const {
785 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Val&: Op))
786 return Cst->isZero();
787 if (ConstantFPSDNode *CstFP = dyn_cast<ConstantFPSDNode>(Val&: Op))
788 return CstFP->isZero();
789 return false;
790}
791
792bool R600TargetLowering::isHWTrueValue(SDValue Op) const {
793 if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Val&: Op)) {
794 return CFP->isExactlyValue(V: 1.0);
795 }
796 return isAllOnesConstant(V: Op);
797}
798
799bool R600TargetLowering::isHWFalseValue(SDValue Op) const {
800 if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Val&: Op)) {
801 return CFP->getValueAPF().isZero();
802 }
803 return isNullConstant(V: Op);
804}
805
806SDValue R600TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
807 SDLoc DL(Op);
808 EVT VT = Op.getValueType();
809
810 SDValue LHS = Op.getOperand(i: 0);
811 SDValue RHS = Op.getOperand(i: 1);
812 SDValue True = Op.getOperand(i: 2);
813 SDValue False = Op.getOperand(i: 3);
814 SDValue CC = Op.getOperand(i: 4);
815 SDValue Temp;
816
817 if (VT == MVT::f32) {
818 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
819 SDValue MinMax = combineFMinMaxLegacy(DL, VT, LHS, RHS, True, False, CC, DCI);
820 if (MinMax)
821 return MinMax;
822 }
823
824 // LHS and RHS are guaranteed to be the same value type
825 EVT CompareVT = LHS.getValueType();
826
827 // Check if we can lower this to a native operation.
828
829 // Try to lower to a SET* instruction:
830 //
831 // SET* can match the following patterns:
832 //
833 // select_cc f32, f32, -1, 0, cc_supported
834 // select_cc f32, f32, 1.0f, 0.0f, cc_supported
835 // select_cc i32, i32, -1, 0, cc_supported
836 //
837
838 // Move hardware True/False values to the correct operand.
839 if (isHWTrueValue(Op: False) && isHWFalseValue(Op: True)) {
840 ISD::CondCode CCOpcode = cast<CondCodeSDNode>(Val&: CC)->get();
841 ISD::CondCode InverseCC = ISD::getSetCCInverse(Operation: CCOpcode, Type: CompareVT);
842 if (isCondCodeLegal(CC: InverseCC, VT: CompareVT.getSimpleVT())) {
843 std::swap(a&: False, b&: True);
844 CC = DAG.getCondCode(Cond: InverseCC);
845 } else {
846 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(Operation: InverseCC);
847 if (isCondCodeLegal(CC: SwapInvCC, VT: CompareVT.getSimpleVT())) {
848 std::swap(a&: False, b&: True);
849 std::swap(a&: LHS, b&: RHS);
850 CC = DAG.getCondCode(Cond: SwapInvCC);
851 }
852 }
853 }
854
855 if (isHWTrueValue(Op: True) && isHWFalseValue(Op: False) &&
856 (CompareVT == VT || VT == MVT::i32)) {
857 // This can be matched by a SET* instruction.
858 return DAG.getNode(Opcode: ISD::SELECT_CC, DL, VT, N1: LHS, N2: RHS, N3: True, N4: False, N5: CC);
859 }
860
861 // Try to lower to a CND* instruction:
862 //
863 // CND* can match the following patterns:
864 //
865 // select_cc f32, 0.0, f32, f32, cc_supported
866 // select_cc f32, 0.0, i32, i32, cc_supported
867 // select_cc i32, 0, f32, f32, cc_supported
868 // select_cc i32, 0, i32, i32, cc_supported
869 //
870
871 // Try to move the zero value to the RHS
872 if (isZero(Op: LHS)) {
873 ISD::CondCode CCOpcode = cast<CondCodeSDNode>(Val&: CC)->get();
874 // Try swapping the operands
875 ISD::CondCode CCSwapped = ISD::getSetCCSwappedOperands(Operation: CCOpcode);
876 if (isCondCodeLegal(CC: CCSwapped, VT: CompareVT.getSimpleVT())) {
877 std::swap(a&: LHS, b&: RHS);
878 CC = DAG.getCondCode(Cond: CCSwapped);
879 } else {
880 // Try inverting the condition and then swapping the operands
881 ISD::CondCode CCInv = ISD::getSetCCInverse(Operation: CCOpcode, Type: CompareVT);
882 CCSwapped = ISD::getSetCCSwappedOperands(Operation: CCInv);
883 if (isCondCodeLegal(CC: CCSwapped, VT: CompareVT.getSimpleVT())) {
884 std::swap(a&: True, b&: False);
885 std::swap(a&: LHS, b&: RHS);
886 CC = DAG.getCondCode(Cond: CCSwapped);
887 }
888 }
889 }
890 if (isZero(Op: RHS)) {
891 SDValue Cond = LHS;
892 SDValue Zero = RHS;
893 ISD::CondCode CCOpcode = cast<CondCodeSDNode>(Val&: CC)->get();
894 if (CompareVT != VT) {
895 // Bitcast True / False to the correct types. This will end up being
896 // a nop, but it allows us to define only a single pattern in the
897 // .TD files for each CND* instruction rather than having to have
898 // one pattern for integer True/False and one for fp True/False
899 True = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: CompareVT, Operand: True);
900 False = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: CompareVT, Operand: False);
901 }
902
903 switch (CCOpcode) {
904 case ISD::SETONE:
905 case ISD::SETUNE:
906 case ISD::SETNE:
907 CCOpcode = ISD::getSetCCInverse(Operation: CCOpcode, Type: CompareVT);
908 Temp = True;
909 True = False;
910 False = Temp;
911 break;
912 default:
913 break;
914 }
915 SDValue SelectNode = DAG.getNode(Opcode: ISD::SELECT_CC, DL, VT: CompareVT,
916 N1: Cond, N2: Zero,
917 N3: True, N4: False,
918 N5: DAG.getCondCode(Cond: CCOpcode));
919 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT, Operand: SelectNode);
920 }
921
922 // If we make it this for it means we have no native instructions to handle
923 // this SELECT_CC, so we must lower it.
924 SDValue HWTrue, HWFalse;
925
926 if (CompareVT == MVT::f32) {
927 HWTrue = DAG.getConstantFP(Val: 1.0f, DL, VT: CompareVT);
928 HWFalse = DAG.getConstantFP(Val: 0.0f, DL, VT: CompareVT);
929 } else if (CompareVT == MVT::i32) {
930 HWTrue = DAG.getAllOnesConstant(DL, VT: CompareVT);
931 HWFalse = DAG.getConstant(Val: 0, DL, VT: CompareVT);
932 }
933 else {
934 llvm_unreachable("Unhandled value type in LowerSELECT_CC");
935 }
936
937 // Lower this unsupported SELECT_CC into a combination of two supported
938 // SELECT_CC operations.
939 SDValue Cond = DAG.getNode(Opcode: ISD::SELECT_CC, DL, VT: CompareVT, N1: LHS, N2: RHS, N3: HWTrue, N4: HWFalse, N5: CC);
940
941 return DAG.getNode(Opcode: ISD::SELECT_CC, DL, VT,
942 N1: Cond, N2: HWFalse,
943 N3: True, N4: False,
944 N5: DAG.getCondCode(Cond: ISD::SETNE));
945}
946
947SDValue R600TargetLowering::lowerADDRSPACECAST(SDValue Op,
948 SelectionDAG &DAG) const {
949 SDLoc SL(Op);
950 EVT VT = Op.getValueType();
951
952 const R600TargetMachine &TM =
953 static_cast<const R600TargetMachine &>(getTargetMachine());
954
955 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Val&: Op);
956 unsigned SrcAS = ASC->getSrcAddressSpace();
957 unsigned DestAS = ASC->getDestAddressSpace();
958
959 if (isNullConstant(V: Op.getOperand(i: 0)) && SrcAS == AMDGPUAS::FLAT_ADDRESS)
960 return DAG.getSignedConstant(Val: TM.getNullPointerValue(AddrSpace: DestAS), DL: SL, VT);
961
962 return Op;
963}
964
965/// LLVM generates byte-addressed pointers. For indirect addressing, we need to
966/// convert these pointers to a register index. Each register holds
967/// 16 bytes, (4 x 32bit sub-register), but we need to take into account the
968/// \p StackWidth, which tells us how many of the 4 sub-registers will be used
969/// for indirect addressing.
970SDValue R600TargetLowering::stackPtrToRegIndex(SDValue Ptr,
971 unsigned StackWidth,
972 SelectionDAG &DAG) const {
973 unsigned SRLPad;
974 switch(StackWidth) {
975 case 1:
976 SRLPad = 2;
977 break;
978 case 2:
979 SRLPad = 3;
980 break;
981 case 4:
982 SRLPad = 4;
983 break;
984 default: llvm_unreachable("Invalid stack width");
985 }
986
987 SDLoc DL(Ptr);
988 return DAG.getNode(Opcode: ISD::SRL, DL, VT: Ptr.getValueType(), N1: Ptr,
989 N2: DAG.getConstant(Val: SRLPad, DL, VT: MVT::i32));
990}
991
992void R600TargetLowering::getStackAddress(unsigned StackWidth,
993 unsigned ElemIdx,
994 unsigned &Channel,
995 unsigned &PtrIncr) const {
996 switch (StackWidth) {
997 default:
998 case 1:
999 Channel = 0;
1000 if (ElemIdx > 0) {
1001 PtrIncr = 1;
1002 } else {
1003 PtrIncr = 0;
1004 }
1005 break;
1006 case 2:
1007 Channel = ElemIdx % 2;
1008 if (ElemIdx == 2) {
1009 PtrIncr = 1;
1010 } else {
1011 PtrIncr = 0;
1012 }
1013 break;
1014 case 4:
1015 Channel = ElemIdx;
1016 PtrIncr = 0;
1017 break;
1018 }
1019}
1020
1021SDValue R600TargetLowering::lowerPrivateTruncStore(StoreSDNode *Store,
1022 SelectionDAG &DAG) const {
1023 SDLoc DL(Store);
1024 //TODO: Who creates the i8 stores?
1025 assert(Store->isTruncatingStore()
1026 || Store->getValue().getValueType() == MVT::i8);
1027 assert(Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS);
1028
1029 SDValue Mask;
1030 if (Store->getMemoryVT() == MVT::i8) {
1031 assert(Store->getAlign() >= 1);
1032 Mask = DAG.getConstant(Val: 0xff, DL, VT: MVT::i32);
1033 } else if (Store->getMemoryVT() == MVT::i16) {
1034 assert(Store->getAlign() >= 2);
1035 Mask = DAG.getConstant(Val: 0xffff, DL, VT: MVT::i32);
1036 } else {
1037 llvm_unreachable("Unsupported private trunc store");
1038 }
1039
1040 SDValue OldChain = Store->getChain();
1041 bool VectorTrunc = (OldChain.getOpcode() == AMDGPUISD::DUMMY_CHAIN);
1042 // Skip dummy
1043 SDValue Chain = VectorTrunc ? OldChain->getOperand(Num: 0) : OldChain;
1044 SDValue BasePtr = Store->getBasePtr();
1045 SDValue Offset = Store->getOffset();
1046 EVT MemVT = Store->getMemoryVT();
1047
1048 SDValue LoadPtr = BasePtr;
1049 if (!Offset.isUndef()) {
1050 LoadPtr = DAG.getNode(Opcode: ISD::ADD, DL, VT: MVT::i32, N1: BasePtr, N2: Offset);
1051 }
1052
1053 // Get dword location
1054 // TODO: this should be eliminated by the future SHR ptr, 2
1055 SDValue Ptr = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: LoadPtr,
1056 N2: DAG.getConstant(Val: 0xfffffffc, DL, VT: MVT::i32));
1057
1058 // Load dword
1059 // TODO: can we be smarter about machine pointer info?
1060 MachinePointerInfo PtrInfo(AMDGPUAS::PRIVATE_ADDRESS);
1061 SDValue Dst = DAG.getLoad(VT: MVT::i32, dl: DL, Chain, Ptr, PtrInfo);
1062
1063 Chain = Dst.getValue(R: 1);
1064
1065 // Get offset in dword
1066 SDValue ByteIdx = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: LoadPtr,
1067 N2: DAG.getConstant(Val: 0x3, DL, VT: MVT::i32));
1068
1069 // Convert byte offset to bit shift
1070 SDValue ShiftAmt = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: ByteIdx,
1071 N2: DAG.getConstant(Val: 3, DL, VT: MVT::i32));
1072
1073 // TODO: Contrary to the name of the function,
1074 // it also handles sub i32 non-truncating stores (like i1)
1075 SDValue SExtValue = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT: MVT::i32,
1076 Operand: Store->getValue());
1077
1078 // Mask the value to the right type
1079 SDValue MaskedValue = DAG.getZeroExtendInReg(Op: SExtValue, DL, VT: MemVT);
1080
1081 // Shift the value in place
1082 SDValue ShiftedValue = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32,
1083 N1: MaskedValue, N2: ShiftAmt);
1084
1085 // Shift the mask in place
1086 SDValue DstMask = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: Mask, N2: ShiftAmt);
1087
1088 // Invert the mask. NOTE: if we had native ROL instructions we could
1089 // use inverted mask
1090 DstMask = DAG.getNOT(DL, Val: DstMask, VT: MVT::i32);
1091
1092 // Cleanup the target bits
1093 Dst = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: Dst, N2: DstMask);
1094
1095 // Add the new bits
1096 SDValue Value = DAG.getNode(Opcode: ISD::OR, DL, VT: MVT::i32, N1: Dst, N2: ShiftedValue);
1097
1098 // Store dword
1099 // TODO: Can we be smarter about MachinePointerInfo?
1100 SDValue NewStore = DAG.getStore(Chain, dl: DL, Val: Value, Ptr, PtrInfo);
1101
1102 // If we are part of expanded vector, make our neighbors depend on this store
1103 if (VectorTrunc) {
1104 // Make all other vector elements depend on this store
1105 Chain = DAG.getNode(Opcode: AMDGPUISD::DUMMY_CHAIN, DL, VT: MVT::Other, Operand: NewStore);
1106 DAG.ReplaceAllUsesOfValueWith(From: OldChain, To: Chain);
1107 }
1108 return NewStore;
1109}
1110
1111SDValue R600TargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1112 StoreSDNode *StoreNode = cast<StoreSDNode>(Val&: Op);
1113 unsigned AS = StoreNode->getAddressSpace();
1114
1115 SDValue Chain = StoreNode->getChain();
1116 SDValue Ptr = StoreNode->getBasePtr();
1117 SDValue Value = StoreNode->getValue();
1118
1119 EVT VT = Value.getValueType();
1120 EVT MemVT = StoreNode->getMemoryVT();
1121 EVT PtrVT = Ptr.getValueType();
1122
1123 SDLoc DL(Op);
1124
1125 const bool TruncatingStore = StoreNode->isTruncatingStore();
1126
1127 // Neither LOCAL nor PRIVATE can do vectors at the moment
1128 if ((AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::PRIVATE_ADDRESS ||
1129 TruncatingStore) &&
1130 VT.isVector()) {
1131 if ((AS == AMDGPUAS::PRIVATE_ADDRESS) && TruncatingStore) {
1132 // Add an extra level of chain to isolate this vector
1133 SDValue NewChain = DAG.getNode(Opcode: AMDGPUISD::DUMMY_CHAIN, DL, VT: MVT::Other, Operand: Chain);
1134 SmallVector<SDValue, 4> NewOps(StoreNode->ops());
1135 NewOps[0] = NewChain;
1136 StoreNode = cast<StoreSDNode>(Val: DAG.UpdateNodeOperands(N: StoreNode, Ops: NewOps));
1137 }
1138
1139 return scalarizeVectorStore(ST: StoreNode, DAG);
1140 }
1141
1142 Align Alignment = StoreNode->getAlign();
1143 if (Alignment < MemVT.getStoreSize() &&
1144 !allowsMisalignedMemoryAccesses(VT: MemVT, AS, Alignment,
1145 Flags: StoreNode->getMemOperand()->getFlags(),
1146 IsFast: nullptr)) {
1147 return expandUnalignedStore(ST: StoreNode, DAG);
1148 }
1149
1150 SDValue DWordAddr = DAG.getNode(Opcode: ISD::SRL, DL, VT: PtrVT, N1: Ptr,
1151 N2: DAG.getConstant(Val: 2, DL, VT: PtrVT));
1152
1153 if (AS == AMDGPUAS::GLOBAL_ADDRESS) {
1154 // It is beneficial to create MSKOR here instead of combiner to avoid
1155 // artificial dependencies introduced by RMW
1156 if (TruncatingStore) {
1157 assert(VT.bitsLE(MVT::i32));
1158 SDValue MaskConstant;
1159 if (MemVT == MVT::i8) {
1160 MaskConstant = DAG.getConstant(Val: 0xFF, DL, VT: MVT::i32);
1161 } else {
1162 assert(MemVT == MVT::i16);
1163 assert(StoreNode->getAlign() >= 2);
1164 MaskConstant = DAG.getConstant(Val: 0xFFFF, DL, VT: MVT::i32);
1165 }
1166
1167 SDValue ByteIndex = DAG.getNode(Opcode: ISD::AND, DL, VT: PtrVT, N1: Ptr,
1168 N2: DAG.getConstant(Val: 0x00000003, DL, VT: PtrVT));
1169 SDValue BitShift = DAG.getNode(Opcode: ISD::SHL, DL, VT, N1: ByteIndex,
1170 N2: DAG.getConstant(Val: 3, DL, VT));
1171
1172 // Put the mask in correct place
1173 SDValue Mask = DAG.getNode(Opcode: ISD::SHL, DL, VT, N1: MaskConstant, N2: BitShift);
1174
1175 // Put the value bits in correct place
1176 SDValue TruncValue = DAG.getNode(Opcode: ISD::AND, DL, VT, N1: Value, N2: MaskConstant);
1177 SDValue ShiftedValue = DAG.getNode(Opcode: ISD::SHL, DL, VT, N1: TruncValue, N2: BitShift);
1178
1179 // XXX: If we add a 64-bit ZW register class, then we could use a 2 x i32
1180 // vector instead.
1181 SDValue Src[4] = {
1182 ShiftedValue,
1183 DAG.getConstant(Val: 0, DL, VT: MVT::i32),
1184 DAG.getConstant(Val: 0, DL, VT: MVT::i32),
1185 Mask
1186 };
1187 SDValue Input = DAG.getBuildVector(VT: MVT::v4i32, DL, Ops: Src);
1188 SDValue Args[3] = { Chain, Input, DWordAddr };
1189 return DAG.getMemIntrinsicNode(Opcode: AMDGPUISD::STORE_MSKOR, dl: DL,
1190 VTList: Op->getVTList(), Ops: Args, MemVT,
1191 MMO: StoreNode->getMemOperand());
1192 }
1193 if (Ptr->getOpcode() != AMDGPUISD::DWORDADDR && VT.bitsGE(VT: MVT::i32)) {
1194 // Convert pointer from byte address to dword address.
1195 Ptr = DAG.getNode(Opcode: AMDGPUISD::DWORDADDR, DL, VT: PtrVT, Operand: DWordAddr);
1196
1197 if (StoreNode->isIndexed()) {
1198 llvm_unreachable("Indexed stores not supported yet");
1199 } else {
1200 Chain = DAG.getStore(Chain, dl: DL, Val: Value, Ptr, MMO: StoreNode->getMemOperand());
1201 }
1202 return Chain;
1203 }
1204 }
1205
1206 // GLOBAL_ADDRESS has been handled above, LOCAL_ADDRESS allows all sizes
1207 if (AS != AMDGPUAS::PRIVATE_ADDRESS)
1208 return SDValue();
1209
1210 if (MemVT.bitsLT(VT: MVT::i32))
1211 return lowerPrivateTruncStore(Store: StoreNode, DAG);
1212
1213 // Standard i32+ store, tag it with DWORDADDR to note that the address
1214 // has been shifted
1215 if (Ptr.getOpcode() != AMDGPUISD::DWORDADDR) {
1216 Ptr = DAG.getNode(Opcode: AMDGPUISD::DWORDADDR, DL, VT: PtrVT, Operand: DWordAddr);
1217 return DAG.getStore(Chain, dl: DL, Val: Value, Ptr, MMO: StoreNode->getMemOperand());
1218 }
1219
1220 // Tagged i32+ stores will be matched by patterns
1221 return SDValue();
1222}
1223
1224// return (512 + (kc_bank << 12)
1225static int
1226ConstantAddressBlock(unsigned AddressSpace) {
1227 switch (AddressSpace) {
1228 case AMDGPUAS::CONSTANT_BUFFER_0:
1229 return 512;
1230 case AMDGPUAS::CONSTANT_BUFFER_1:
1231 return 512 + 4096;
1232 case AMDGPUAS::CONSTANT_BUFFER_2:
1233 return 512 + 4096 * 2;
1234 case AMDGPUAS::CONSTANT_BUFFER_3:
1235 return 512 + 4096 * 3;
1236 case AMDGPUAS::CONSTANT_BUFFER_4:
1237 return 512 + 4096 * 4;
1238 case AMDGPUAS::CONSTANT_BUFFER_5:
1239 return 512 + 4096 * 5;
1240 case AMDGPUAS::CONSTANT_BUFFER_6:
1241 return 512 + 4096 * 6;
1242 case AMDGPUAS::CONSTANT_BUFFER_7:
1243 return 512 + 4096 * 7;
1244 case AMDGPUAS::CONSTANT_BUFFER_8:
1245 return 512 + 4096 * 8;
1246 case AMDGPUAS::CONSTANT_BUFFER_9:
1247 return 512 + 4096 * 9;
1248 case AMDGPUAS::CONSTANT_BUFFER_10:
1249 return 512 + 4096 * 10;
1250 case AMDGPUAS::CONSTANT_BUFFER_11:
1251 return 512 + 4096 * 11;
1252 case AMDGPUAS::CONSTANT_BUFFER_12:
1253 return 512 + 4096 * 12;
1254 case AMDGPUAS::CONSTANT_BUFFER_13:
1255 return 512 + 4096 * 13;
1256 case AMDGPUAS::CONSTANT_BUFFER_14:
1257 return 512 + 4096 * 14;
1258 case AMDGPUAS::CONSTANT_BUFFER_15:
1259 return 512 + 4096 * 15;
1260 default:
1261 return -1;
1262 }
1263}
1264
1265SDValue R600TargetLowering::lowerPrivateExtLoad(SDValue Op,
1266 SelectionDAG &DAG) const {
1267 SDLoc DL(Op);
1268 LoadSDNode *Load = cast<LoadSDNode>(Val&: Op);
1269 ISD::LoadExtType ExtType = Load->getExtensionType();
1270 EVT MemVT = Load->getMemoryVT();
1271 assert(Load->getAlign() >= MemVT.getStoreSize());
1272
1273 SDValue BasePtr = Load->getBasePtr();
1274 SDValue Chain = Load->getChain();
1275 SDValue Offset = Load->getOffset();
1276
1277 SDValue LoadPtr = BasePtr;
1278 if (!Offset.isUndef()) {
1279 LoadPtr = DAG.getNode(Opcode: ISD::ADD, DL, VT: MVT::i32, N1: BasePtr, N2: Offset);
1280 }
1281
1282 // Get dword location
1283 // NOTE: this should be eliminated by the future SHR ptr, 2
1284 SDValue Ptr = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: LoadPtr,
1285 N2: DAG.getConstant(Val: 0xfffffffc, DL, VT: MVT::i32));
1286
1287 // Load dword
1288 // TODO: can we be smarter about machine pointer info?
1289 MachinePointerInfo PtrInfo(AMDGPUAS::PRIVATE_ADDRESS);
1290 SDValue Read = DAG.getLoad(VT: MVT::i32, dl: DL, Chain, Ptr, PtrInfo);
1291
1292 // Get offset within the register.
1293 SDValue ByteIdx = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32,
1294 N1: LoadPtr, N2: DAG.getConstant(Val: 0x3, DL, VT: MVT::i32));
1295
1296 // Bit offset of target byte (byteIdx * 8).
1297 SDValue ShiftAmt = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: ByteIdx,
1298 N2: DAG.getConstant(Val: 3, DL, VT: MVT::i32));
1299
1300 // Shift to the right.
1301 SDValue Ret = DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: Read, N2: ShiftAmt);
1302
1303 // Eliminate the upper bits by setting them to ...
1304 EVT MemEltVT = MemVT.getScalarType();
1305
1306 if (ExtType == ISD::SEXTLOAD) { // ... ones.
1307 SDValue MemEltVTNode = DAG.getValueType(MemEltVT);
1308 Ret = DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL, VT: MVT::i32, N1: Ret, N2: MemEltVTNode);
1309 } else { // ... or zeros.
1310 Ret = DAG.getZeroExtendInReg(Op: Ret, DL, VT: MemEltVT);
1311 }
1312
1313 SDValue Ops[] = {
1314 Ret,
1315 Read.getValue(R: 1) // This should be our output chain
1316 };
1317
1318 return DAG.getMergeValues(Ops, dl: DL);
1319}
1320
1321SDValue R600TargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1322 LoadSDNode *LoadNode = cast<LoadSDNode>(Val&: Op);
1323 unsigned AS = LoadNode->getAddressSpace();
1324 EVT MemVT = LoadNode->getMemoryVT();
1325 ISD::LoadExtType ExtType = LoadNode->getExtensionType();
1326
1327 if (AS == AMDGPUAS::PRIVATE_ADDRESS &&
1328 ExtType != ISD::NON_EXTLOAD && MemVT.bitsLT(VT: MVT::i32)) {
1329 return lowerPrivateExtLoad(Op, DAG);
1330 }
1331
1332 SDLoc DL(Op);
1333 EVT VT = Op.getValueType();
1334 SDValue Chain = LoadNode->getChain();
1335 SDValue Ptr = LoadNode->getBasePtr();
1336
1337 if ((LoadNode->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
1338 LoadNode->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) &&
1339 VT.isVector()) {
1340 SDValue Ops[2];
1341 std::tie(args&: Ops[0], args&: Ops[1]) = scalarizeVectorLoad(LD: LoadNode, DAG);
1342 return DAG.getMergeValues(Ops, dl: DL);
1343 }
1344
1345 // This is still used for explicit load from addrspace(8)
1346 int ConstantBlock = ConstantAddressBlock(AddressSpace: LoadNode->getAddressSpace());
1347 if (ConstantBlock > -1 &&
1348 ((LoadNode->getExtensionType() == ISD::NON_EXTLOAD) ||
1349 (LoadNode->getExtensionType() == ISD::ZEXTLOAD))) {
1350 SDValue Result;
1351 if (isa<Constant>(Val: LoadNode->getMemOperand()->getValue()) ||
1352 isa<ConstantSDNode>(Val: Ptr)) {
1353 return constBufferLoad(LoadNode, Block: LoadNode->getAddressSpace(), DAG);
1354 }
1355 // TODO: Does this even work?
1356 // non-constant ptr can't be folded, keeps it as a v4f32 load
1357 Result = DAG.getNode(Opcode: AMDGPUISD::CONST_ADDRESS, DL, VT: MVT::v4i32,
1358 N1: DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: Ptr,
1359 N2: DAG.getConstant(Val: 4, DL, VT: MVT::i32)),
1360 N2: DAG.getConstant(Val: LoadNode->getAddressSpace() -
1361 AMDGPUAS::CONSTANT_BUFFER_0,
1362 DL, VT: MVT::i32));
1363
1364 if (!VT.isVector()) {
1365 Result = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i32, N1: Result,
1366 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
1367 }
1368
1369 SDValue MergedValues[2] = {
1370 Result,
1371 Chain
1372 };
1373 return DAG.getMergeValues(Ops: MergedValues, dl: DL);
1374 }
1375
1376 // For most operations returning SDValue() will result in the node being
1377 // expanded by the DAG Legalizer. This is not the case for ISD::LOAD, so we
1378 // need to manually expand loads that may be legal in some address spaces and
1379 // illegal in others. SEXT loads from CONSTANT_BUFFER_0 are supported for
1380 // compute shaders, since the data is sign extended when it is uploaded to the
1381 // buffer. However SEXT loads from other address spaces are not supported, so
1382 // we need to expand them here.
1383 if (LoadNode->getExtensionType() == ISD::SEXTLOAD) {
1384 assert(!MemVT.isVector() && (MemVT == MVT::i16 || MemVT == MVT::i8));
1385 SDValue NewLoad = DAG.getExtLoad(
1386 ExtType: ISD::EXTLOAD, dl: DL, VT, Chain, Ptr, PtrInfo: LoadNode->getPointerInfo(), MemVT,
1387 Alignment: LoadNode->getAlign(), MMOFlags: LoadNode->getMemOperand()->getFlags());
1388 SDValue Res = DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL, VT, N1: NewLoad,
1389 N2: DAG.getValueType(MemVT));
1390
1391 SDValue MergedValues[2] = { Res, Chain };
1392 return DAG.getMergeValues(Ops: MergedValues, dl: DL);
1393 }
1394
1395 if (LoadNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
1396 return SDValue();
1397 }
1398
1399 // DWORDADDR ISD marks already shifted address
1400 if (Ptr.getOpcode() != AMDGPUISD::DWORDADDR) {
1401 assert(VT == MVT::i32);
1402 Ptr = DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: Ptr, N2: DAG.getConstant(Val: 2, DL, VT: MVT::i32));
1403 Ptr = DAG.getNode(Opcode: AMDGPUISD::DWORDADDR, DL, VT: MVT::i32, Operand: Ptr);
1404 return DAG.getLoad(VT: MVT::i32, dl: DL, Chain, Ptr, MMO: LoadNode->getMemOperand());
1405 }
1406 return SDValue();
1407}
1408
1409SDValue R600TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1410 SDValue Chain = Op.getOperand(i: 0);
1411 SDValue Cond = Op.getOperand(i: 1);
1412 SDValue Jump = Op.getOperand(i: 2);
1413
1414 return DAG.getNode(Opcode: AMDGPUISD::BRANCH_COND, DL: SDLoc(Op), VT: Op.getValueType(),
1415 N1: Chain, N2: Jump, N3: Cond);
1416}
1417
1418SDValue R600TargetLowering::lowerFrameIndex(SDValue Op,
1419 SelectionDAG &DAG) const {
1420 MachineFunction &MF = DAG.getMachineFunction();
1421 const R600FrameLowering *TFL = Subtarget->getFrameLowering();
1422
1423 FrameIndexSDNode *FIN = cast<FrameIndexSDNode>(Val&: Op);
1424
1425 unsigned FrameIndex = FIN->getIndex();
1426 Register IgnoredFrameReg;
1427 StackOffset Offset =
1428 TFL->getFrameIndexReference(MF, FI: FrameIndex, FrameReg&: IgnoredFrameReg);
1429 return DAG.getConstant(Val: Offset.getFixed() * 4 * TFL->getStackWidth(MF),
1430 DL: SDLoc(Op), VT: Op.getValueType());
1431}
1432
1433CCAssignFn *R600TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1434 bool IsVarArg) const {
1435 switch (CC) {
1436 case CallingConv::AMDGPU_KERNEL:
1437 case CallingConv::SPIR_KERNEL:
1438 case CallingConv::C:
1439 case CallingConv::Fast:
1440 case CallingConv::Cold:
1441 llvm_unreachable("kernels should not be handled here");
1442 case CallingConv::AMDGPU_VS:
1443 case CallingConv::AMDGPU_GS:
1444 case CallingConv::AMDGPU_PS:
1445 case CallingConv::AMDGPU_CS:
1446 case CallingConv::AMDGPU_HS:
1447 case CallingConv::AMDGPU_ES:
1448 case CallingConv::AMDGPU_LS:
1449 return CC_R600;
1450 default:
1451 reportFatalUsageError(reason: "unsupported calling convention");
1452 }
1453}
1454
1455/// XXX Only kernel functions are supported, so we can assume for now that
1456/// every function is a kernel function, but in the future we should use
1457/// separate calling conventions for kernel and non-kernel functions.
1458SDValue R600TargetLowering::LowerFormalArguments(
1459 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1460 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1461 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1462 SmallVector<CCValAssign, 16> ArgLocs;
1463 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1464 *DAG.getContext());
1465 MachineFunction &MF = DAG.getMachineFunction();
1466
1467 if (AMDGPU::isShader(CC: CallConv)) {
1468 CCInfo.AnalyzeFormalArguments(Ins, Fn: CCAssignFnForCall(CC: CallConv, IsVarArg: isVarArg));
1469 } else {
1470 analyzeFormalArgumentsCompute(State&: CCInfo, Ins);
1471 }
1472
1473 for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
1474 CCValAssign &VA = ArgLocs[i];
1475 const ISD::InputArg &In = Ins[i];
1476 EVT VT = In.VT;
1477 EVT MemVT = VA.getLocVT();
1478 if (!VT.isVector() && MemVT.isVector()) {
1479 // Get load source type if scalarized.
1480 MemVT = MemVT.getVectorElementType();
1481 }
1482
1483 if (VT.isInteger() && !MemVT.isInteger())
1484 MemVT = MemVT.changeTypeToInteger();
1485
1486 if (AMDGPU::isShader(CC: CallConv)) {
1487 Register Reg = MF.addLiveIn(PReg: VA.getLocReg(), RC: &R600::R600_Reg128RegClass);
1488 SDValue Register = DAG.getCopyFromReg(Chain, dl: DL, Reg, VT);
1489 InVals.push_back(Elt: Register);
1490 continue;
1491 }
1492
1493 // i64 isn't a legal type, so the register type used ends up as i32, which
1494 // isn't expected here. It attempts to create this sextload, but it ends up
1495 // being invalid. Somehow this seems to work with i64 arguments, but breaks
1496 // for <1 x i64>.
1497
1498 // The first 36 bytes of the input buffer contains information about
1499 // thread group and global sizes.
1500 ISD::LoadExtType Ext = ISD::NON_EXTLOAD;
1501 if (MemVT.getScalarSizeInBits() != VT.getScalarSizeInBits()) {
1502 if (VT.isFloatingPoint()) {
1503 Ext = ISD::EXTLOAD;
1504 } else {
1505 // FIXME: This should really check the extload type, but the handling of
1506 // extload vector parameters seems to be broken.
1507
1508 // Ext = In.Flags.isSExt() ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
1509 Ext = ISD::SEXTLOAD;
1510 }
1511 }
1512
1513 // Compute the offset from the value.
1514 // XXX - I think PartOffset should give you this, but it seems to give the
1515 // size of the register which isn't useful.
1516
1517 unsigned PartOffset = VA.getLocMemOffset();
1518 Align Alignment = commonAlignment(A: Align(VT.getStoreSize()), Offset: PartOffset);
1519
1520 MachinePointerInfo PtrInfo(AMDGPUAS::PARAM_I_ADDRESS);
1521 SDValue Arg = DAG.getLoad(
1522 AM: ISD::UNINDEXED, ExtType: Ext, VT, dl: DL, Chain,
1523 Ptr: DAG.getConstant(Val: PartOffset, DL, VT: MVT::i32), Offset: DAG.getUNDEF(VT: MVT::i32),
1524 PtrInfo,
1525 MemVT, Alignment, MMOFlags: MachineMemOperand::MONonTemporal |
1526 MachineMemOperand::MODereferenceable |
1527 MachineMemOperand::MOInvariant);
1528
1529 InVals.push_back(Elt: Arg);
1530 }
1531 return Chain;
1532}
1533
1534EVT R600TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1535 EVT VT) const {
1536 if (!VT.isVector())
1537 return MVT::i32;
1538 return VT.changeVectorElementTypeToInteger();
1539}
1540
1541bool R600TargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1542 const MachineFunction &MF) const {
1543 // Local and Private addresses do not handle vectors. Limit to i32
1544 if ((AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::PRIVATE_ADDRESS)) {
1545 return (MemVT.getSizeInBits() <= 32);
1546 }
1547 return true;
1548}
1549
1550bool R600TargetLowering::allowsMisalignedMemoryAccesses(
1551 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1552 unsigned *IsFast) const {
1553 if (IsFast)
1554 *IsFast = 0;
1555
1556 if (!VT.isSimple() || VT == MVT::Other)
1557 return false;
1558
1559 if (VT.bitsLT(VT: MVT::i32))
1560 return false;
1561
1562 // TODO: This is a rough estimate.
1563 if (IsFast)
1564 *IsFast = 1;
1565
1566 return VT.bitsGT(VT: MVT::i32) && Alignment >= Align(4);
1567}
1568
1569static SDValue CompactSwizzlableVector(
1570 SelectionDAG &DAG, SDValue VectorEntry,
1571 DenseMap<unsigned, unsigned> &RemapSwizzle) {
1572 assert(RemapSwizzle.empty());
1573
1574 SDLoc DL(VectorEntry);
1575 EVT EltTy = VectorEntry.getValueType().getVectorElementType();
1576
1577 SDValue NewBldVec[4];
1578 for (unsigned i = 0; i < 4; i++)
1579 NewBldVec[i] = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: EltTy, N1: VectorEntry,
1580 N2: DAG.getIntPtrConstant(Val: i, DL));
1581
1582 for (unsigned i = 0; i < 4; i++) {
1583 if (NewBldVec[i].isUndef())
1584 // We mask write here to teach later passes that the ith element of this
1585 // vector is undef. Thus we can use it to reduce 128 bits reg usage,
1586 // break false dependencies and additionally make assembly easier to read.
1587 RemapSwizzle[i] = 7; // SEL_MASK_WRITE
1588 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val&: NewBldVec[i])) {
1589 if (C->isZero()) {
1590 RemapSwizzle[i] = 4; // SEL_0
1591 NewBldVec[i] = DAG.getUNDEF(VT: MVT::f32);
1592 } else if (C->isExactlyValue(V: 1.0)) {
1593 RemapSwizzle[i] = 5; // SEL_1
1594 NewBldVec[i] = DAG.getUNDEF(VT: MVT::f32);
1595 }
1596 }
1597
1598 if (NewBldVec[i].isUndef())
1599 continue;
1600
1601 for (unsigned j = 0; j < i; j++) {
1602 if (NewBldVec[i] == NewBldVec[j]) {
1603 NewBldVec[i] = DAG.getUNDEF(VT: NewBldVec[i].getValueType());
1604 RemapSwizzle[i] = j;
1605 break;
1606 }
1607 }
1608 }
1609
1610 return DAG.getBuildVector(VT: VectorEntry.getValueType(), DL: SDLoc(VectorEntry),
1611 Ops: NewBldVec);
1612}
1613
1614static SDValue ReorganizeVector(SelectionDAG &DAG, SDValue VectorEntry,
1615 DenseMap<unsigned, unsigned> &RemapSwizzle) {
1616 assert(RemapSwizzle.empty());
1617
1618 SDLoc DL(VectorEntry);
1619 EVT EltTy = VectorEntry.getValueType().getVectorElementType();
1620
1621 SDValue NewBldVec[4];
1622 bool isUnmovable[4] = {false, false, false, false};
1623 for (unsigned i = 0; i < 4; i++)
1624 NewBldVec[i] = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: EltTy, N1: VectorEntry,
1625 N2: DAG.getIntPtrConstant(Val: i, DL));
1626
1627 for (unsigned i = 0; i < 4; i++) {
1628 RemapSwizzle[i] = i;
1629 if (NewBldVec[i].getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
1630 unsigned Idx = NewBldVec[i].getConstantOperandVal(i: 1);
1631 if (i == Idx)
1632 isUnmovable[Idx] = true;
1633 }
1634 }
1635
1636 for (unsigned i = 0; i < 4; i++) {
1637 if (NewBldVec[i].getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
1638 unsigned Idx = NewBldVec[i].getConstantOperandVal(i: 1);
1639 if (isUnmovable[Idx])
1640 continue;
1641 // Swap i and Idx
1642 std::swap(a&: NewBldVec[Idx], b&: NewBldVec[i]);
1643 std::swap(a&: RemapSwizzle[i], b&: RemapSwizzle[Idx]);
1644 break;
1645 }
1646 }
1647
1648 return DAG.getBuildVector(VT: VectorEntry.getValueType(), DL: SDLoc(VectorEntry),
1649 Ops: NewBldVec);
1650}
1651
1652SDValue R600TargetLowering::OptimizeSwizzle(SDValue BuildVector, SDValue Swz[],
1653 SelectionDAG &DAG,
1654 const SDLoc &DL) const {
1655 // Old -> New swizzle values
1656 DenseMap<unsigned, unsigned> SwizzleRemap;
1657
1658 BuildVector = CompactSwizzlableVector(DAG, VectorEntry: BuildVector, RemapSwizzle&: SwizzleRemap);
1659 for (unsigned i = 0; i < 4; i++) {
1660 unsigned Idx = Swz[i]->getAsZExtVal();
1661 auto It = SwizzleRemap.find(Val: Idx);
1662 if (It != SwizzleRemap.end())
1663 Swz[i] = DAG.getConstant(Val: It->second, DL, VT: MVT::i32);
1664 }
1665
1666 SwizzleRemap.clear();
1667 BuildVector = ReorganizeVector(DAG, VectorEntry: BuildVector, RemapSwizzle&: SwizzleRemap);
1668 for (unsigned i = 0; i < 4; i++) {
1669 unsigned Idx = Swz[i]->getAsZExtVal();
1670 auto It = SwizzleRemap.find(Val: Idx);
1671 if (It != SwizzleRemap.end())
1672 Swz[i] = DAG.getConstant(Val: It->second, DL, VT: MVT::i32);
1673 }
1674
1675 return BuildVector;
1676}
1677
1678SDValue R600TargetLowering::constBufferLoad(LoadSDNode *LoadNode, int Block,
1679 SelectionDAG &DAG) const {
1680 SDLoc DL(LoadNode);
1681 EVT VT = LoadNode->getValueType(ResNo: 0);
1682 SDValue Chain = LoadNode->getChain();
1683 SDValue Ptr = LoadNode->getBasePtr();
1684 assert (isa<ConstantSDNode>(Ptr));
1685
1686 //TODO: Support smaller loads
1687 if (LoadNode->getMemoryVT().getScalarType() != MVT::i32 || !ISD::isNON_EXTLoad(N: LoadNode))
1688 return SDValue();
1689
1690 if (LoadNode->getAlign() < Align(4))
1691 return SDValue();
1692
1693 int ConstantBlock = ConstantAddressBlock(AddressSpace: Block);
1694
1695 SDValue Slots[4];
1696 for (unsigned i = 0; i < 4; i++) {
1697 // We want Const position encoded with the following formula :
1698 // (((512 + (kc_bank << 12) + const_index) << 2) + chan)
1699 // const_index is Ptr computed by llvm using an alignment of 16.
1700 // Thus we add (((512 + (kc_bank << 12)) + chan ) * 4 here and
1701 // then div by 4 at the ISel step
1702 SDValue NewPtr = DAG.getNode(Opcode: ISD::ADD, DL, VT: Ptr.getValueType(), N1: Ptr,
1703 N2: DAG.getConstant(Val: 4 * i + ConstantBlock * 16, DL, VT: MVT::i32));
1704 Slots[i] = DAG.getNode(Opcode: AMDGPUISD::CONST_ADDRESS, DL, VT: MVT::i32, Operand: NewPtr);
1705 }
1706 EVT NewVT = MVT::v4i32;
1707 unsigned NumElements = 4;
1708 if (VT.isVector()) {
1709 NewVT = VT;
1710 NumElements = VT.getVectorNumElements();
1711 }
1712 SDValue Result = DAG.getBuildVector(VT: NewVT, DL, Ops: ArrayRef(Slots, NumElements));
1713 if (!VT.isVector()) {
1714 Result = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i32, N1: Result,
1715 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
1716 }
1717 SDValue MergedValues[2] = {
1718 Result,
1719 Chain
1720 };
1721 return DAG.getMergeValues(Ops: MergedValues, dl: DL);
1722}
1723
1724//===----------------------------------------------------------------------===//
1725// Custom DAG Optimizations
1726//===----------------------------------------------------------------------===//
1727
1728SDValue R600TargetLowering::PerformDAGCombine(SDNode *N,
1729 DAGCombinerInfo &DCI) const {
1730 SelectionDAG &DAG = DCI.DAG;
1731 SDLoc DL(N);
1732
1733 switch (N->getOpcode()) {
1734 // (f32 fp_round (f64 uint_to_fp a)) -> (f32 uint_to_fp a)
1735 case ISD::FP_ROUND: {
1736 SDValue Arg = N->getOperand(Num: 0);
1737 if (Arg.getOpcode() == ISD::UINT_TO_FP && Arg.getValueType() == MVT::f64) {
1738 return DAG.getNode(Opcode: ISD::UINT_TO_FP, DL, VT: N->getValueType(ResNo: 0),
1739 Operand: Arg.getOperand(i: 0));
1740 }
1741 break;
1742 }
1743
1744 // (i32 fp_to_sint (fneg (select_cc f32, f32, 1.0, 0.0 cc))) ->
1745 // (i32 select_cc f32, f32, -1, 0 cc)
1746 //
1747 // Mesa's GLSL frontend generates the above pattern a lot and we can lower
1748 // this to one of the SET*_DX10 instructions.
1749 case ISD::FP_TO_SINT: {
1750 SDValue FNeg = N->getOperand(Num: 0);
1751 if (FNeg.getOpcode() != ISD::FNEG) {
1752 return SDValue();
1753 }
1754 SDValue SelectCC = FNeg.getOperand(i: 0);
1755 if (SelectCC.getOpcode() != ISD::SELECT_CC ||
1756 SelectCC.getOperand(i: 0).getValueType() != MVT::f32 || // LHS
1757 SelectCC.getOperand(i: 2).getValueType() != MVT::f32 || // True
1758 !isHWTrueValue(Op: SelectCC.getOperand(i: 2)) ||
1759 !isHWFalseValue(Op: SelectCC.getOperand(i: 3))) {
1760 return SDValue();
1761 }
1762
1763 return DAG.getNode(Opcode: ISD::SELECT_CC, DL, VT: N->getValueType(ResNo: 0),
1764 N1: SelectCC.getOperand(i: 0), // LHS
1765 N2: SelectCC.getOperand(i: 1), // RHS
1766 N3: DAG.getAllOnesConstant(DL, VT: MVT::i32), // True
1767 N4: DAG.getConstant(Val: 0, DL, VT: MVT::i32), // False
1768 N5: SelectCC.getOperand(i: 4)); // CC
1769 }
1770
1771 // insert_vector_elt (build_vector elt0, ... , eltN), NewEltIdx, idx
1772 // => build_vector elt0, ... , NewEltIdx, ... , eltN
1773 case ISD::INSERT_VECTOR_ELT: {
1774 SDValue InVec = N->getOperand(Num: 0);
1775 SDValue InVal = N->getOperand(Num: 1);
1776 SDValue EltNo = N->getOperand(Num: 2);
1777
1778 // If the inserted element is an UNDEF, just use the input vector.
1779 if (InVal.isUndef())
1780 return InVec;
1781
1782 EVT VT = InVec.getValueType();
1783
1784 // If we can't generate a legal BUILD_VECTOR, exit
1785 if (!isOperationLegal(Op: ISD::BUILD_VECTOR, VT))
1786 return SDValue();
1787
1788 // Check that we know which element is being inserted
1789 if (!isa<ConstantSDNode>(Val: EltNo))
1790 return SDValue();
1791 unsigned Elt = EltNo->getAsZExtVal();
1792
1793 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
1794 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
1795 // vector elements.
1796 SmallVector<SDValue, 8> Ops;
1797 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
1798 Ops.append(in_start: InVec.getNode()->op_begin(),
1799 in_end: InVec.getNode()->op_end());
1800 } else if (InVec.isUndef()) {
1801 unsigned NElts = VT.getVectorNumElements();
1802 Ops.append(NumInputs: NElts, Elt: DAG.getUNDEF(VT: InVal.getValueType()));
1803 } else {
1804 return SDValue();
1805 }
1806
1807 // Insert the element
1808 if (Elt < Ops.size()) {
1809 // All the operands of BUILD_VECTOR must have the same type;
1810 // we enforce that here.
1811 EVT OpVT = Ops[0].getValueType();
1812 if (InVal.getValueType() != OpVT)
1813 InVal = OpVT.bitsGT(VT: InVal.getValueType()) ?
1814 DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: OpVT, Operand: InVal) :
1815 DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: OpVT, Operand: InVal);
1816 Ops[Elt] = InVal;
1817 }
1818
1819 // Return the new vector
1820 return DAG.getBuildVector(VT, DL, Ops);
1821 }
1822
1823 // Extract_vec (Build_vector) generated by custom lowering
1824 // also needs to be customly combined
1825 case ISD::EXTRACT_VECTOR_ELT: {
1826 SDValue Arg = N->getOperand(Num: 0);
1827 if (Arg.getOpcode() == ISD::BUILD_VECTOR) {
1828 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1))) {
1829 unsigned Element = Const->getZExtValue();
1830 return Arg->getOperand(Num: Element);
1831 }
1832 }
1833 if (Arg.getOpcode() == ISD::BITCAST &&
1834 Arg.getOperand(i: 0).getOpcode() == ISD::BUILD_VECTOR &&
1835 (Arg.getOperand(i: 0).getValueType().getVectorNumElements() ==
1836 Arg.getValueType().getVectorNumElements())) {
1837 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1))) {
1838 unsigned Element = Const->getZExtValue();
1839 return DAG.getNode(Opcode: ISD::BITCAST, DL, VTList: N->getVTList(),
1840 N: Arg->getOperand(Num: 0).getOperand(i: Element));
1841 }
1842 }
1843 break;
1844 }
1845
1846 case ISD::SELECT_CC: {
1847 // Try common optimizations
1848 if (SDValue Ret = AMDGPUTargetLowering::PerformDAGCombine(N, DCI))
1849 return Ret;
1850
1851 // fold selectcc (selectcc x, y, a, b, cc), b, a, b, seteq ->
1852 // selectcc x, y, a, b, inv(cc)
1853 //
1854 // fold selectcc (selectcc x, y, a, b, cc), b, a, b, setne ->
1855 // selectcc x, y, a, b, cc
1856 SDValue LHS = N->getOperand(Num: 0);
1857 if (LHS.getOpcode() != ISD::SELECT_CC) {
1858 return SDValue();
1859 }
1860
1861 SDValue RHS = N->getOperand(Num: 1);
1862 SDValue True = N->getOperand(Num: 2);
1863 SDValue False = N->getOperand(Num: 3);
1864 ISD::CondCode NCC = cast<CondCodeSDNode>(Val: N->getOperand(Num: 4))->get();
1865
1866 if (LHS.getOperand(i: 2).getNode() != True.getNode() ||
1867 LHS.getOperand(i: 3).getNode() != False.getNode() ||
1868 RHS.getNode() != False.getNode()) {
1869 return SDValue();
1870 }
1871
1872 switch (NCC) {
1873 default: return SDValue();
1874 case ISD::SETNE: return LHS;
1875 case ISD::SETEQ: {
1876 ISD::CondCode LHSCC = cast<CondCodeSDNode>(Val: LHS.getOperand(i: 4))->get();
1877 LHSCC = ISD::getSetCCInverse(Operation: LHSCC, Type: LHS.getOperand(i: 0).getValueType());
1878 if (DCI.isBeforeLegalizeOps() ||
1879 isCondCodeLegal(CC: LHSCC, VT: LHS.getOperand(i: 0).getSimpleValueType()))
1880 return DAG.getSelectCC(DL,
1881 LHS: LHS.getOperand(i: 0),
1882 RHS: LHS.getOperand(i: 1),
1883 True: LHS.getOperand(i: 2),
1884 False: LHS.getOperand(i: 3),
1885 Cond: LHSCC);
1886 break;
1887 }
1888 }
1889 return SDValue();
1890 }
1891
1892 case AMDGPUISD::R600_EXPORT: {
1893 SDValue Arg = N->getOperand(Num: 1);
1894 if (Arg.getOpcode() != ISD::BUILD_VECTOR)
1895 break;
1896
1897 SDValue NewArgs[8] = {
1898 N->getOperand(Num: 0), // Chain
1899 SDValue(),
1900 N->getOperand(Num: 2), // ArrayBase
1901 N->getOperand(Num: 3), // Type
1902 N->getOperand(Num: 4), // SWZ_X
1903 N->getOperand(Num: 5), // SWZ_Y
1904 N->getOperand(Num: 6), // SWZ_Z
1905 N->getOperand(Num: 7) // SWZ_W
1906 };
1907 NewArgs[1] = OptimizeSwizzle(BuildVector: N->getOperand(Num: 1), Swz: &NewArgs[4], DAG, DL);
1908 return DAG.getNode(Opcode: AMDGPUISD::R600_EXPORT, DL, VTList: N->getVTList(), Ops: NewArgs);
1909 }
1910 case AMDGPUISD::TEXTURE_FETCH: {
1911 SDValue Arg = N->getOperand(Num: 1);
1912 if (Arg.getOpcode() != ISD::BUILD_VECTOR)
1913 break;
1914
1915 SDValue NewArgs[19] = {
1916 N->getOperand(Num: 0),
1917 N->getOperand(Num: 1),
1918 N->getOperand(Num: 2),
1919 N->getOperand(Num: 3),
1920 N->getOperand(Num: 4),
1921 N->getOperand(Num: 5),
1922 N->getOperand(Num: 6),
1923 N->getOperand(Num: 7),
1924 N->getOperand(Num: 8),
1925 N->getOperand(Num: 9),
1926 N->getOperand(Num: 10),
1927 N->getOperand(Num: 11),
1928 N->getOperand(Num: 12),
1929 N->getOperand(Num: 13),
1930 N->getOperand(Num: 14),
1931 N->getOperand(Num: 15),
1932 N->getOperand(Num: 16),
1933 N->getOperand(Num: 17),
1934 N->getOperand(Num: 18),
1935 };
1936 NewArgs[1] = OptimizeSwizzle(BuildVector: N->getOperand(Num: 1), Swz: &NewArgs[2], DAG, DL);
1937 return DAG.getNode(Opcode: AMDGPUISD::TEXTURE_FETCH, DL, VTList: N->getVTList(), Ops: NewArgs);
1938 }
1939
1940 case ISD::LOAD: {
1941 LoadSDNode *LoadNode = cast<LoadSDNode>(Val: N);
1942 SDValue Ptr = LoadNode->getBasePtr();
1943 if (LoadNode->getAddressSpace() == AMDGPUAS::PARAM_I_ADDRESS &&
1944 isa<ConstantSDNode>(Val: Ptr))
1945 return constBufferLoad(LoadNode, Block: AMDGPUAS::CONSTANT_BUFFER_0, DAG);
1946 break;
1947 }
1948
1949 default: break;
1950 }
1951
1952 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1953}
1954
1955bool R600TargetLowering::FoldOperand(SDNode *ParentNode, unsigned SrcIdx,
1956 SDValue &Src, SDValue &Neg, SDValue &Abs,
1957 SDValue &Sel, SDValue &Imm,
1958 SelectionDAG &DAG) const {
1959 const R600InstrInfo *TII = Subtarget->getInstrInfo();
1960 if (!Src.isMachineOpcode())
1961 return false;
1962
1963 switch (Src.getMachineOpcode()) {
1964 case R600::FNEG_R600:
1965 if (!Neg.getNode())
1966 return false;
1967 Src = Src.getOperand(i: 0);
1968 Neg = DAG.getTargetConstant(Val: 1, DL: SDLoc(ParentNode), VT: MVT::i32);
1969 return true;
1970 case R600::FABS_R600:
1971 if (!Abs.getNode())
1972 return false;
1973 Src = Src.getOperand(i: 0);
1974 Abs = DAG.getTargetConstant(Val: 1, DL: SDLoc(ParentNode), VT: MVT::i32);
1975 return true;
1976 case R600::CONST_COPY: {
1977 unsigned Opcode = ParentNode->getMachineOpcode();
1978 bool HasDst = TII->getOperandIdx(Opcode, Op: R600::OpName::dst) > -1;
1979
1980 if (!Sel.getNode())
1981 return false;
1982
1983 SDValue CstOffset = Src.getOperand(i: 0);
1984 if (ParentNode->getValueType(ResNo: 0).isVector())
1985 return false;
1986
1987 // Gather constants values
1988 int SrcIndices[] = {
1989 TII->getOperandIdx(Opcode, Op: R600::OpName::src0),
1990 TII->getOperandIdx(Opcode, Op: R600::OpName::src1),
1991 TII->getOperandIdx(Opcode, Op: R600::OpName::src2),
1992 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_X),
1993 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_Y),
1994 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_Z),
1995 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_W),
1996 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_X),
1997 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_Y),
1998 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_Z),
1999 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_W)
2000 };
2001 std::vector<unsigned> Consts;
2002 for (int OtherSrcIdx : SrcIndices) {
2003 int OtherSelIdx = TII->getSelIdx(Opcode, SrcIdx: OtherSrcIdx);
2004 if (OtherSrcIdx < 0 || OtherSelIdx < 0)
2005 continue;
2006 if (HasDst) {
2007 OtherSrcIdx--;
2008 OtherSelIdx--;
2009 }
2010 if (RegisterSDNode *Reg =
2011 dyn_cast<RegisterSDNode>(Val: ParentNode->getOperand(Num: OtherSrcIdx))) {
2012 if (Reg->getReg() == R600::ALU_CONST) {
2013 Consts.push_back(x: ParentNode->getConstantOperandVal(Num: OtherSelIdx));
2014 }
2015 }
2016 }
2017
2018 ConstantSDNode *Cst = cast<ConstantSDNode>(Val&: CstOffset);
2019 Consts.push_back(x: Cst->getZExtValue());
2020 if (!TII->fitsConstReadLimitations(Consts)) {
2021 return false;
2022 }
2023
2024 Sel = CstOffset;
2025 Src = DAG.getRegister(Reg: R600::ALU_CONST, VT: MVT::f32);
2026 return true;
2027 }
2028 case R600::MOV_IMM_GLOBAL_ADDR:
2029 // Check if the Imm slot is used. Taken from below.
2030 if (Imm->getAsZExtVal())
2031 return false;
2032 Imm = Src.getOperand(i: 0);
2033 Src = DAG.getRegister(Reg: R600::ALU_LITERAL_X, VT: MVT::i32);
2034 return true;
2035 case R600::MOV_IMM_I32:
2036 case R600::MOV_IMM_F32: {
2037 unsigned ImmReg = R600::ALU_LITERAL_X;
2038 uint64_t ImmValue = 0;
2039
2040 if (Src.getMachineOpcode() == R600::MOV_IMM_F32) {
2041 ConstantFPSDNode *FPC = cast<ConstantFPSDNode>(Val: Src.getOperand(i: 0));
2042 float FloatValue = FPC->getValueAPF().convertToFloat();
2043 if (FloatValue == 0.0) {
2044 ImmReg = R600::ZERO;
2045 } else if (FloatValue == 0.5) {
2046 ImmReg = R600::HALF;
2047 } else if (FloatValue == 1.0) {
2048 ImmReg = R600::ONE;
2049 } else {
2050 ImmValue = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2051 }
2052 } else {
2053 uint64_t Value = Src.getConstantOperandVal(i: 0);
2054 if (Value == 0) {
2055 ImmReg = R600::ZERO;
2056 } else if (Value == 1) {
2057 ImmReg = R600::ONE_INT;
2058 } else {
2059 ImmValue = Value;
2060 }
2061 }
2062
2063 // Check that we aren't already using an immediate.
2064 // XXX: It's possible for an instruction to have more than one
2065 // immediate operand, but this is not supported yet.
2066 if (ImmReg == R600::ALU_LITERAL_X) {
2067 if (!Imm.getNode())
2068 return false;
2069 ConstantSDNode *C = cast<ConstantSDNode>(Val&: Imm);
2070 if (C->getZExtValue())
2071 return false;
2072 Imm = DAG.getTargetConstant(Val: ImmValue, DL: SDLoc(ParentNode), VT: MVT::i32);
2073 }
2074 Src = DAG.getRegister(Reg: ImmReg, VT: MVT::i32);
2075 return true;
2076 }
2077 default:
2078 return false;
2079 }
2080}
2081
2082/// Fold the instructions after selecting them
2083SDNode *R600TargetLowering::PostISelFolding(MachineSDNode *Node,
2084 SelectionDAG &DAG) const {
2085 const R600InstrInfo *TII = Subtarget->getInstrInfo();
2086 if (!Node->isMachineOpcode())
2087 return Node;
2088
2089 unsigned Opcode = Node->getMachineOpcode();
2090 SDValue FakeOp;
2091
2092 std::vector<SDValue> Ops(Node->op_begin(), Node->op_end());
2093
2094 if (Opcode == R600::DOT_4) {
2095 int OperandIdx[] = {
2096 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_X),
2097 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_Y),
2098 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_Z),
2099 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_W),
2100 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_X),
2101 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_Y),
2102 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_Z),
2103 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_W)
2104 };
2105 int NegIdx[] = {
2106 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_neg_X),
2107 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_neg_Y),
2108 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_neg_Z),
2109 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_neg_W),
2110 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_neg_X),
2111 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_neg_Y),
2112 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_neg_Z),
2113 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_neg_W)
2114 };
2115 int AbsIdx[] = {
2116 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_abs_X),
2117 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_abs_Y),
2118 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_abs_Z),
2119 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_abs_W),
2120 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_abs_X),
2121 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_abs_Y),
2122 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_abs_Z),
2123 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_abs_W)
2124 };
2125 for (unsigned i = 0; i < 8; i++) {
2126 if (OperandIdx[i] < 0)
2127 return Node;
2128 SDValue &Src = Ops[OperandIdx[i] - 1];
2129 SDValue &Neg = Ops[NegIdx[i] - 1];
2130 SDValue &Abs = Ops[AbsIdx[i] - 1];
2131 bool HasDst = TII->getOperandIdx(Opcode, Op: R600::OpName::dst) > -1;
2132 int SelIdx = TII->getSelIdx(Opcode, SrcIdx: OperandIdx[i]);
2133 if (HasDst)
2134 SelIdx--;
2135 SDValue &Sel = (SelIdx > -1) ? Ops[SelIdx] : FakeOp;
2136 if (FoldOperand(ParentNode: Node, SrcIdx: i, Src, Neg, Abs, Sel, Imm&: FakeOp, DAG))
2137 return DAG.getMachineNode(Opcode, dl: SDLoc(Node), VTs: Node->getVTList(), Ops);
2138 }
2139 } else if (Opcode == R600::REG_SEQUENCE) {
2140 for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2) {
2141 SDValue &Src = Ops[i];
2142 if (FoldOperand(ParentNode: Node, SrcIdx: i, Src, Neg&: FakeOp, Abs&: FakeOp, Sel&: FakeOp, Imm&: FakeOp, DAG))
2143 return DAG.getMachineNode(Opcode, dl: SDLoc(Node), VTs: Node->getVTList(), Ops);
2144 }
2145 } else {
2146 if (!TII->hasInstrModifiers(Opcode))
2147 return Node;
2148 int OperandIdx[] = {
2149 TII->getOperandIdx(Opcode, Op: R600::OpName::src0),
2150 TII->getOperandIdx(Opcode, Op: R600::OpName::src1),
2151 TII->getOperandIdx(Opcode, Op: R600::OpName::src2)
2152 };
2153 int NegIdx[] = {
2154 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_neg),
2155 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_neg),
2156 TII->getOperandIdx(Opcode, Op: R600::OpName::src2_neg)
2157 };
2158 int AbsIdx[] = {
2159 TII->getOperandIdx(Opcode, Op: R600::OpName::src0_abs),
2160 TII->getOperandIdx(Opcode, Op: R600::OpName::src1_abs),
2161 -1
2162 };
2163 for (unsigned i = 0; i < 3; i++) {
2164 if (OperandIdx[i] < 0)
2165 return Node;
2166 SDValue &Src = Ops[OperandIdx[i] - 1];
2167 SDValue &Neg = Ops[NegIdx[i] - 1];
2168 SDValue FakeAbs;
2169 SDValue &Abs = (AbsIdx[i] > -1) ? Ops[AbsIdx[i] - 1] : FakeAbs;
2170 bool HasDst = TII->getOperandIdx(Opcode, Op: R600::OpName::dst) > -1;
2171 int SelIdx = TII->getSelIdx(Opcode, SrcIdx: OperandIdx[i]);
2172 int ImmIdx = TII->getOperandIdx(Opcode, Op: R600::OpName::literal);
2173 if (HasDst) {
2174 SelIdx--;
2175 ImmIdx--;
2176 }
2177 SDValue &Sel = (SelIdx > -1) ? Ops[SelIdx] : FakeOp;
2178 SDValue &Imm = Ops[ImmIdx];
2179 if (FoldOperand(ParentNode: Node, SrcIdx: i, Src, Neg, Abs, Sel, Imm, DAG))
2180 return DAG.getMachineNode(Opcode, dl: SDLoc(Node), VTs: Node->getVTList(), Ops);
2181 }
2182 }
2183
2184 return Node;
2185}
2186
2187TargetLowering::AtomicExpansionKind
2188R600TargetLowering::shouldExpandAtomicRMWInIR(const AtomicRMWInst *RMW) const {
2189 switch (RMW->getOperation()) {
2190 case AtomicRMWInst::Nand:
2191 case AtomicRMWInst::FAdd:
2192 case AtomicRMWInst::FSub:
2193 case AtomicRMWInst::FMax:
2194 case AtomicRMWInst::FMin:
2195 case AtomicRMWInst::USubCond:
2196 case AtomicRMWInst::USubSat:
2197 return AtomicExpansionKind::CmpXChg;
2198 case AtomicRMWInst::UIncWrap:
2199 case AtomicRMWInst::UDecWrap:
2200 // FIXME: Cayman at least appears to have instructions for this, but the
2201 // instruction definitions appear to be missing.
2202 return AtomicExpansionKind::CmpXChg;
2203 case AtomicRMWInst::Xchg: {
2204 const DataLayout &DL = RMW->getFunction()->getDataLayout();
2205 unsigned ValSize = DL.getTypeSizeInBits(Ty: RMW->getType());
2206 if (ValSize == 32 || ValSize == 64)
2207 return AtomicExpansionKind::None;
2208 return AtomicExpansionKind::CmpXChg;
2209 }
2210 default:
2211 if (auto *IntTy = dyn_cast<IntegerType>(Val: RMW->getType())) {
2212 unsigned Size = IntTy->getBitWidth();
2213 if (Size == 32 || Size == 64)
2214 return AtomicExpansionKind::None;
2215 }
2216
2217 return AtomicExpansionKind::CmpXChg;
2218 }
2219
2220 llvm_unreachable("covered atomicrmw op switch");
2221}
2222