LLVM 22.0.0git
SPIRVInstructionSelector.cpp
Go to the documentation of this file.
1//===- SPIRVInstructionSelector.cpp ------------------------------*- C++ -*-==//
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// This file implements the targeting of the InstructionSelector class for
10// SPIRV.
11// TODO: This should be generated by TableGen.
12//
13//===----------------------------------------------------------------------===//
14
17#include "SPIRV.h"
18#include "SPIRVGlobalRegistry.h"
19#include "SPIRVInstrInfo.h"
20#include "SPIRVRegisterInfo.h"
21#include "SPIRVTargetMachine.h"
22#include "SPIRVUtils.h"
23#include "llvm/ADT/APFloat.h"
32#include "llvm/IR/IntrinsicsSPIRV.h"
33#include "llvm/Support/Debug.h"
35
36#define DEBUG_TYPE "spirv-isel"
37
38using namespace llvm;
39namespace CL = SPIRV::OpenCLExtInst;
40namespace GL = SPIRV::GLSLExtInst;
41
43 std::vector<std::pair<SPIRV::InstructionSet::InstructionSet, uint32_t>>;
44
45namespace {
46
47llvm::SPIRV::SelectionControl::SelectionControl
48getSelectionOperandForImm(int Imm) {
49 if (Imm == 2)
50 return SPIRV::SelectionControl::Flatten;
51 if (Imm == 1)
52 return SPIRV::SelectionControl::DontFlatten;
53 if (Imm == 0)
54 return SPIRV::SelectionControl::None;
55 llvm_unreachable("Invalid immediate");
56}
57
58#define GET_GLOBALISEL_PREDICATE_BITSET
59#include "SPIRVGenGlobalISel.inc"
60#undef GET_GLOBALISEL_PREDICATE_BITSET
61
62class SPIRVInstructionSelector : public InstructionSelector {
63 const SPIRVSubtarget &STI;
64 const SPIRVInstrInfo &TII;
66 const RegisterBankInfo &RBI;
69 MachineFunction *HasVRegsReset = nullptr;
70
71 /// We need to keep track of the number we give to anonymous global values to
72 /// generate the same name every time when this is needed.
73 mutable DenseMap<const GlobalValue *, unsigned> UnnamedGlobalIDs;
75
76public:
77 SPIRVInstructionSelector(const SPIRVTargetMachine &TM,
78 const SPIRVSubtarget &ST,
79 const RegisterBankInfo &RBI);
80 void setupMF(MachineFunction &MF, GISelValueTracking *VT,
81 CodeGenCoverage *CoverageInfo, ProfileSummaryInfo *PSI,
82 BlockFrequencyInfo *BFI) override;
83 // Common selection code. Instruction-specific selection occurs in spvSelect.
84 bool select(MachineInstr &I) override;
85 static const char *getName() { return DEBUG_TYPE; }
86
87#define GET_GLOBALISEL_PREDICATES_DECL
88#include "SPIRVGenGlobalISel.inc"
89#undef GET_GLOBALISEL_PREDICATES_DECL
90
91#define GET_GLOBALISEL_TEMPORARIES_DECL
92#include "SPIRVGenGlobalISel.inc"
93#undef GET_GLOBALISEL_TEMPORARIES_DECL
94
95private:
96 void resetVRegsType(MachineFunction &MF);
97
98 // tblgen-erated 'select' implementation, used as the initial selector for
99 // the patterns that don't require complex C++.
100 bool selectImpl(MachineInstr &I, CodeGenCoverage &CoverageInfo) const;
101
102 // All instruction-specific selection that didn't happen in "select()".
103 // Is basically a large Switch/Case delegating to all other select method.
104 bool spvSelect(Register ResVReg, const SPIRVType *ResType,
105 MachineInstr &I) const;
106
107 bool selectFirstBitHigh(Register ResVReg, const SPIRVType *ResType,
108 MachineInstr &I, bool IsSigned) const;
109
110 bool selectFirstBitLow(Register ResVReg, const SPIRVType *ResType,
111 MachineInstr &I) const;
112
113 bool selectFirstBitSet16(Register ResVReg, const SPIRVType *ResType,
114 MachineInstr &I, unsigned ExtendOpcode,
115 unsigned BitSetOpcode) const;
116
117 bool selectFirstBitSet32(Register ResVReg, const SPIRVType *ResType,
118 MachineInstr &I, Register SrcReg,
119 unsigned BitSetOpcode) const;
120
121 bool selectFirstBitSet64(Register ResVReg, const SPIRVType *ResType,
122 MachineInstr &I, Register SrcReg,
123 unsigned BitSetOpcode, bool SwapPrimarySide) const;
124
125 bool selectFirstBitSet64Overflow(Register ResVReg, const SPIRVType *ResType,
126 MachineInstr &I, Register SrcReg,
127 unsigned BitSetOpcode,
128 bool SwapPrimarySide) const;
129
130 bool selectGlobalValue(Register ResVReg, MachineInstr &I,
131 const MachineInstr *Init = nullptr) const;
132
133 bool selectOpWithSrcs(Register ResVReg, const SPIRVType *ResType,
134 MachineInstr &I, std::vector<Register> SrcRegs,
135 unsigned Opcode) const;
136
137 bool selectUnOp(Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
138 unsigned Opcode) const;
139
140 bool selectBitcast(Register ResVReg, const SPIRVType *ResType,
141 MachineInstr &I) const;
142
143 bool selectLoad(Register ResVReg, const SPIRVType *ResType,
144 MachineInstr &I) const;
145 bool selectStore(MachineInstr &I) const;
146
147 bool selectStackSave(Register ResVReg, const SPIRVType *ResType,
148 MachineInstr &I) const;
149 bool selectStackRestore(MachineInstr &I) const;
150
151 bool selectMemOperation(Register ResVReg, MachineInstr &I) const;
152
153 bool selectAtomicRMW(Register ResVReg, const SPIRVType *ResType,
154 MachineInstr &I, unsigned NewOpcode,
155 unsigned NegateOpcode = 0) const;
156
157 bool selectAtomicCmpXchg(Register ResVReg, const SPIRVType *ResType,
158 MachineInstr &I) const;
159
160 bool selectFence(MachineInstr &I) const;
161
162 bool selectAddrSpaceCast(Register ResVReg, const SPIRVType *ResType,
163 MachineInstr &I) const;
164
165 bool selectAnyOrAll(Register ResVReg, const SPIRVType *ResType,
166 MachineInstr &I, unsigned OpType) const;
167
168 bool selectAll(Register ResVReg, const SPIRVType *ResType,
169 MachineInstr &I) const;
170
171 bool selectAny(Register ResVReg, const SPIRVType *ResType,
172 MachineInstr &I) const;
173
174 bool selectBitreverse(Register ResVReg, const SPIRVType *ResType,
175 MachineInstr &I) const;
176
177 bool selectBuildVector(Register ResVReg, const SPIRVType *ResType,
178 MachineInstr &I) const;
179 bool selectSplatVector(Register ResVReg, const SPIRVType *ResType,
180 MachineInstr &I) const;
181
182 bool selectCmp(Register ResVReg, const SPIRVType *ResType,
183 unsigned comparisonOpcode, MachineInstr &I) const;
184 bool selectDiscard(Register ResVReg, const SPIRVType *ResType,
185 MachineInstr &I) const;
186
187 bool selectICmp(Register ResVReg, const SPIRVType *ResType,
188 MachineInstr &I) const;
189 bool selectFCmp(Register ResVReg, const SPIRVType *ResType,
190 MachineInstr &I) const;
191
192 bool selectSign(Register ResVReg, const SPIRVType *ResType,
193 MachineInstr &I) const;
194
195 bool selectFloatDot(Register ResVReg, const SPIRVType *ResType,
196 MachineInstr &I) const;
197
198 bool selectOverflowArith(Register ResVReg, const SPIRVType *ResType,
199 MachineInstr &I, unsigned Opcode) const;
200 bool selectDebugTrap(Register ResVReg, const SPIRVType *ResType,
201 MachineInstr &I) const;
202
203 bool selectIntegerDot(Register ResVReg, const SPIRVType *ResType,
204 MachineInstr &I, bool Signed) const;
205
206 bool selectIntegerDotExpansion(Register ResVReg, const SPIRVType *ResType,
207 MachineInstr &I) const;
208
209 bool selectOpIsInf(Register ResVReg, const SPIRVType *ResType,
210 MachineInstr &I) const;
211
212 bool selectOpIsNan(Register ResVReg, const SPIRVType *ResType,
213 MachineInstr &I) const;
214
215 template <bool Signed>
216 bool selectDot4AddPacked(Register ResVReg, const SPIRVType *ResType,
217 MachineInstr &I) const;
218 template <bool Signed>
219 bool selectDot4AddPackedExpansion(Register ResVReg, const SPIRVType *ResType,
220 MachineInstr &I) const;
221
222 bool selectWaveReduceMax(Register ResVReg, const SPIRVType *ResType,
223 MachineInstr &I, bool IsUnsigned) const;
224
225 bool selectWaveReduceMin(Register ResVReg, const SPIRVType *ResType,
226 MachineInstr &I, bool IsUnsigned) const;
227
228 bool selectWaveReduceSum(Register ResVReg, const SPIRVType *ResType,
229 MachineInstr &I) const;
230
231 bool selectConst(Register ResVReg, const SPIRVType *ResType,
232 MachineInstr &I) const;
233
234 bool selectSelect(Register ResVReg, const SPIRVType *ResType,
235 MachineInstr &I) const;
236 bool selectSelectDefaultArgs(Register ResVReg, const SPIRVType *ResType,
237 MachineInstr &I, bool IsSigned) const;
238 bool selectIToF(Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
239 bool IsSigned, unsigned Opcode) const;
240 bool selectExt(Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
241 bool IsSigned) const;
242
243 bool selectTrunc(Register ResVReg, const SPIRVType *ResType,
244 MachineInstr &I) const;
245
246 bool selectSUCmp(Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
247 bool IsSigned) const;
248
249 bool selectIntToBool(Register IntReg, Register ResVReg, MachineInstr &I,
250 const SPIRVType *intTy, const SPIRVType *boolTy) const;
251
252 bool selectOpUndef(Register ResVReg, const SPIRVType *ResType,
253 MachineInstr &I) const;
254 bool selectFreeze(Register ResVReg, const SPIRVType *ResType,
255 MachineInstr &I) const;
256 bool selectIntrinsic(Register ResVReg, const SPIRVType *ResType,
257 MachineInstr &I) const;
258 bool selectExtractVal(Register ResVReg, const SPIRVType *ResType,
259 MachineInstr &I) const;
260 bool selectInsertVal(Register ResVReg, const SPIRVType *ResType,
261 MachineInstr &I) const;
262 bool selectExtractElt(Register ResVReg, const SPIRVType *ResType,
263 MachineInstr &I) const;
264 bool selectInsertElt(Register ResVReg, const SPIRVType *ResType,
265 MachineInstr &I) const;
266 bool selectGEP(Register ResVReg, const SPIRVType *ResType,
267 MachineInstr &I) const;
268
269 bool selectFrameIndex(Register ResVReg, const SPIRVType *ResType,
270 MachineInstr &I) const;
271 bool selectAllocaArray(Register ResVReg, const SPIRVType *ResType,
272 MachineInstr &I) const;
273
274 bool selectBranch(MachineInstr &I) const;
275 bool selectBranchCond(MachineInstr &I) const;
276
277 bool selectPhi(Register ResVReg, const SPIRVType *ResType,
278 MachineInstr &I) const;
279
280 bool selectExtInst(Register ResVReg, const SPIRVType *RestType,
281 MachineInstr &I, GL::GLSLExtInst GLInst) const;
282 bool selectExtInst(Register ResVReg, const SPIRVType *ResType,
283 MachineInstr &I, CL::OpenCLExtInst CLInst) const;
284 bool selectExtInst(Register ResVReg, const SPIRVType *ResType,
285 MachineInstr &I, CL::OpenCLExtInst CLInst,
286 GL::GLSLExtInst GLInst) const;
287 bool selectExtInst(Register ResVReg, const SPIRVType *ResType,
288 MachineInstr &I, const ExtInstList &ExtInsts) const;
289 bool selectExtInstForLRound(Register ResVReg, const SPIRVType *ResType,
290 MachineInstr &I, CL::OpenCLExtInst CLInst,
291 GL::GLSLExtInst GLInst) const;
292 bool selectExtInstForLRound(Register ResVReg, const SPIRVType *ResType,
294 const ExtInstList &ExtInsts) const;
295
296 bool selectLog10(Register ResVReg, const SPIRVType *ResType,
297 MachineInstr &I) const;
298
299 bool selectSaturate(Register ResVReg, const SPIRVType *ResType,
300 MachineInstr &I) const;
301
302 bool selectWaveOpInst(Register ResVReg, const SPIRVType *ResType,
303 MachineInstr &I, unsigned Opcode) const;
304
305 bool selectWaveActiveCountBits(Register ResVReg, const SPIRVType *ResType,
306 MachineInstr &I) const;
307
309
310 bool selectHandleFromBinding(Register &ResVReg, const SPIRVType *ResType,
311 MachineInstr &I) const;
312
313 bool selectCounterHandleFromBinding(Register &ResVReg,
314 const SPIRVType *ResType,
315 MachineInstr &I) const;
316
317 bool selectReadImageIntrinsic(Register &ResVReg, const SPIRVType *ResType,
318 MachineInstr &I) const;
319 bool selectImageWriteIntrinsic(MachineInstr &I) const;
320 bool selectResourceGetPointer(Register &ResVReg, const SPIRVType *ResType,
321 MachineInstr &I) const;
322 bool selectResourceNonUniformIndex(Register &ResVReg,
323 const SPIRVType *ResType,
324 MachineInstr &I) const;
325 bool selectModf(Register ResVReg, const SPIRVType *ResType,
326 MachineInstr &I) const;
327 bool selectUpdateCounter(Register &ResVReg, const SPIRVType *ResType,
328 MachineInstr &I) const;
329 bool selectFrexp(Register ResVReg, const SPIRVType *ResType,
330 MachineInstr &I) const;
331 // Utilities
332 std::pair<Register, bool>
333 buildI32Constant(uint32_t Val, MachineInstr &I,
334 const SPIRVType *ResType = nullptr) const;
335
336 Register buildZerosVal(const SPIRVType *ResType, MachineInstr &I) const;
337 Register buildZerosValF(const SPIRVType *ResType, MachineInstr &I) const;
338 Register buildOnesVal(bool AllOnes, const SPIRVType *ResType,
339 MachineInstr &I) const;
340 Register buildOnesValF(const SPIRVType *ResType, MachineInstr &I) const;
341
342 bool wrapIntoSpecConstantOp(MachineInstr &I,
343 SmallVector<Register> &CompositeArgs) const;
344
345 Register getUcharPtrTypeReg(MachineInstr &I,
346 SPIRV::StorageClass::StorageClass SC) const;
347 MachineInstrBuilder buildSpecConstantOp(MachineInstr &I, Register Dest,
348 Register Src, Register DestType,
349 uint32_t Opcode) const;
350 MachineInstrBuilder buildConstGenericPtr(MachineInstr &I, Register SrcPtr,
351 SPIRVType *SrcPtrTy) const;
352 Register buildPointerToResource(const SPIRVType *ResType,
353 SPIRV::StorageClass::StorageClass SC,
355 uint32_t ArraySize, Register IndexReg,
356 StringRef Name,
357 MachineIRBuilder MIRBuilder) const;
358 SPIRVType *widenTypeToVec4(const SPIRVType *Type, MachineInstr &I) const;
359 bool extractSubvector(Register &ResVReg, const SPIRVType *ResType,
360 Register &ReadReg, MachineInstr &InsertionPoint) const;
361 bool generateImageReadOrFetch(Register &ResVReg, const SPIRVType *ResType,
362 Register ImageReg, Register IdxReg,
363 DebugLoc Loc, MachineInstr &Pos) const;
364 bool BuildCOPY(Register DestReg, Register SrcReg, MachineInstr &I) const;
365 bool loadVec3BuiltinInputID(SPIRV::BuiltIn::BuiltIn BuiltInValue,
366 Register ResVReg, const SPIRVType *ResType,
367 MachineInstr &I) const;
368 bool loadBuiltinInputID(SPIRV::BuiltIn::BuiltIn BuiltInValue,
369 Register ResVReg, const SPIRVType *ResType,
370 MachineInstr &I) const;
371 bool loadHandleBeforePosition(Register &HandleReg, const SPIRVType *ResType,
372 GIntrinsic &HandleDef, MachineInstr &Pos) const;
373 void decorateUsesAsNonUniform(Register &NonUniformReg) const;
374};
375
376bool sampledTypeIsSignedInteger(const llvm::Type *HandleType) {
377 const TargetExtType *TET = cast<TargetExtType>(HandleType);
378 if (TET->getTargetExtName() == "spirv.Image") {
379 return false;
380 }
381 assert(TET->getTargetExtName() == "spirv.SignedImage");
382 return TET->getTypeParameter(0)->isIntegerTy();
383}
384} // end anonymous namespace
385
386#define GET_GLOBALISEL_IMPL
387#include "SPIRVGenGlobalISel.inc"
388#undef GET_GLOBALISEL_IMPL
389
390SPIRVInstructionSelector::SPIRVInstructionSelector(const SPIRVTargetMachine &TM,
391 const SPIRVSubtarget &ST,
392 const RegisterBankInfo &RBI)
393 : InstructionSelector(), STI(ST), TII(*ST.getInstrInfo()),
394 TRI(*ST.getRegisterInfo()), RBI(RBI), GR(*ST.getSPIRVGlobalRegistry()),
395 MRI(nullptr),
397#include "SPIRVGenGlobalISel.inc"
400#include "SPIRVGenGlobalISel.inc"
402{
403}
404
405void SPIRVInstructionSelector::setupMF(MachineFunction &MF,
407 CodeGenCoverage *CoverageInfo,
409 BlockFrequencyInfo *BFI) {
410 MRI = &MF.getRegInfo();
411 GR.setCurrentFunc(MF);
412 InstructionSelector::setupMF(MF, VT, CoverageInfo, PSI, BFI);
413}
414
415// Ensure that register classes correspond to pattern matching rules.
416void SPIRVInstructionSelector::resetVRegsType(MachineFunction &MF) {
417 if (HasVRegsReset == &MF)
418 return;
419 HasVRegsReset = &MF;
420
421 MachineRegisterInfo &MRI = MF.getRegInfo();
422 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
423 Register Reg = Register::index2VirtReg(I);
424 LLT RegType = MRI.getType(Reg);
425 if (RegType.isScalar())
426 MRI.setType(Reg, LLT::scalar(64));
427 else if (RegType.isPointer())
428 MRI.setType(Reg, LLT::pointer(0, 64));
429 else if (RegType.isVector())
430 MRI.setType(Reg, LLT::fixed_vector(2, LLT::scalar(64)));
431 }
432 for (const auto &MBB : MF) {
433 for (const auto &MI : MBB) {
434 if (isPreISelGenericOpcode(MI.getOpcode()))
435 GR.erase(&MI);
436 if (MI.getOpcode() != SPIRV::ASSIGN_TYPE)
437 continue;
438
439 Register DstReg = MI.getOperand(0).getReg();
440 LLT DstType = MRI.getType(DstReg);
441 Register SrcReg = MI.getOperand(1).getReg();
442 LLT SrcType = MRI.getType(SrcReg);
443 if (DstType != SrcType)
444 MRI.setType(DstReg, MRI.getType(SrcReg));
445
446 const TargetRegisterClass *DstRC = MRI.getRegClassOrNull(DstReg);
447 const TargetRegisterClass *SrcRC = MRI.getRegClassOrNull(SrcReg);
448 if (DstRC != SrcRC && SrcRC)
449 MRI.setRegClass(DstReg, SrcRC);
450 }
451 }
452}
453
454// Return true if the type represents a constant register
457 OpDef = passCopy(OpDef, MRI);
458
459 if (Visited.contains(OpDef))
460 return true;
461 Visited.insert(OpDef);
462
463 unsigned Opcode = OpDef->getOpcode();
464 switch (Opcode) {
465 case TargetOpcode::G_CONSTANT:
466 case TargetOpcode::G_FCONSTANT:
467 return true;
468 case TargetOpcode::G_INTRINSIC:
469 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
470 case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS:
471 return cast<GIntrinsic>(*OpDef).getIntrinsicID() ==
472 Intrinsic::spv_const_composite;
473 case TargetOpcode::G_BUILD_VECTOR:
474 case TargetOpcode::G_SPLAT_VECTOR: {
475 for (unsigned i = OpDef->getNumExplicitDefs(); i < OpDef->getNumOperands();
476 i++) {
477 MachineInstr *OpNestedDef =
478 OpDef->getOperand(i).isReg()
479 ? MRI->getVRegDef(OpDef->getOperand(i).getReg())
480 : nullptr;
481 if (OpNestedDef && !isConstReg(MRI, OpNestedDef, Visited))
482 return false;
483 }
484 return true;
485 case SPIRV::OpConstantTrue:
486 case SPIRV::OpConstantFalse:
487 case SPIRV::OpConstantI:
488 case SPIRV::OpConstantF:
489 case SPIRV::OpConstantComposite:
490 case SPIRV::OpConstantCompositeContinuedINTEL:
491 case SPIRV::OpConstantSampler:
492 case SPIRV::OpConstantNull:
493 case SPIRV::OpUndef:
494 case SPIRV::OpConstantFunctionPointerINTEL:
495 return true;
496 }
497 }
498 return false;
499}
500
501// Return true if the virtual register represents a constant
504 if (MachineInstr *OpDef = MRI->getVRegDef(OpReg))
505 return isConstReg(MRI, OpDef, Visited);
506 return false;
507}
508
510 for (const auto &MO : MI.all_defs()) {
511 Register Reg = MO.getReg();
512 if (Reg.isPhysical() || !MRI.use_nodbg_empty(Reg))
513 return false;
514 }
515 if (MI.getOpcode() == TargetOpcode::LOCAL_ESCAPE || MI.isFakeUse() ||
516 MI.isLifetimeMarker())
517 return false;
518 if (MI.isPHI())
519 return true;
520 if (MI.mayStore() || MI.isCall() ||
521 (MI.mayLoad() && MI.hasOrderedMemoryRef()) || MI.isPosition() ||
522 MI.isDebugInstr() || MI.isTerminator() || MI.isJumpTableDebugInfo())
523 return false;
524 return true;
525}
526
527bool SPIRVInstructionSelector::select(MachineInstr &I) {
528 resetVRegsType(*I.getParent()->getParent());
529
530 assert(I.getParent() && "Instruction should be in a basic block!");
531 assert(I.getParent()->getParent() && "Instruction should be in a function!");
532
533 Register Opcode = I.getOpcode();
534 // If it's not a GMIR instruction, we've selected it already.
535 if (!isPreISelGenericOpcode(Opcode)) {
536 if (Opcode == SPIRV::ASSIGN_TYPE) { // These pseudos aren't needed any more.
537 Register DstReg = I.getOperand(0).getReg();
538 Register SrcReg = I.getOperand(1).getReg();
539 auto *Def = MRI->getVRegDef(SrcReg);
540 if (isTypeFoldingSupported(Def->getOpcode()) &&
541 Def->getOpcode() != TargetOpcode::G_CONSTANT &&
542 Def->getOpcode() != TargetOpcode::G_FCONSTANT) {
543 bool Res = false;
544 if (Def->getOpcode() == TargetOpcode::G_SELECT) {
545 Register SelectDstReg = Def->getOperand(0).getReg();
546 Res = selectSelect(SelectDstReg, GR.getSPIRVTypeForVReg(SelectDstReg),
547 *Def);
549 Def->removeFromParent();
550 MRI->replaceRegWith(DstReg, SelectDstReg);
552 I.removeFromParent();
553 } else
554 Res = selectImpl(I, *CoverageInfo);
555 LLVM_DEBUG({
556 if (!Res && Def->getOpcode() != TargetOpcode::G_CONSTANT) {
557 dbgs() << "Unexpected pattern in ASSIGN_TYPE.\nInstruction: ";
558 I.print(dbgs());
559 }
560 });
561 assert(Res || Def->getOpcode() == TargetOpcode::G_CONSTANT);
562 if (Res) {
563 if (!isTriviallyDead(*Def, *MRI) && isDead(*Def, *MRI))
564 DeadMIs.insert(Def);
565 return Res;
566 }
567 }
568 MRI->setRegClass(SrcReg, MRI->getRegClass(DstReg));
569 MRI->replaceRegWith(SrcReg, DstReg);
571 I.removeFromParent();
572 return true;
573 } else if (I.getNumDefs() == 1) {
574 // Make all vregs 64 bits (for SPIR-V IDs).
575 MRI->setType(I.getOperand(0).getReg(), LLT::scalar(64));
576 }
578 }
579
580 if (DeadMIs.contains(&I)) {
581 // if the instruction has been already made dead by folding it away
582 // erase it
583 LLVM_DEBUG(dbgs() << "Instruction is folded and dead.\n");
586 I.eraseFromParent();
587 return true;
588 }
589
590 if (I.getNumOperands() != I.getNumExplicitOperands()) {
591 LLVM_DEBUG(errs() << "Generic instr has unexpected implicit operands\n");
592 return false;
593 }
594
595 // Common code for getting return reg+type, and removing selected instr
596 // from parent occurs here. Instr-specific selection happens in spvSelect().
597 bool HasDefs = I.getNumDefs() > 0;
598 Register ResVReg = HasDefs ? I.getOperand(0).getReg() : Register(0);
599 SPIRVType *ResType = HasDefs ? GR.getSPIRVTypeForVReg(ResVReg) : nullptr;
600 assert(!HasDefs || ResType || I.getOpcode() == TargetOpcode::G_GLOBAL_VALUE ||
601 I.getOpcode() == TargetOpcode::G_IMPLICIT_DEF);
602 if (spvSelect(ResVReg, ResType, I)) {
603 if (HasDefs) // Make all vregs 64 bits (for SPIR-V IDs).
604 for (unsigned i = 0; i < I.getNumDefs(); ++i)
605 MRI->setType(I.getOperand(i).getReg(), LLT::scalar(64));
607 I.removeFromParent();
608 return true;
609 }
610 return false;
611}
612
613static bool mayApplyGenericSelection(unsigned Opcode) {
614 switch (Opcode) {
615 case TargetOpcode::G_CONSTANT:
616 case TargetOpcode::G_FCONSTANT:
617 return false;
618 case TargetOpcode::G_SADDO:
619 case TargetOpcode::G_SSUBO:
620 return true;
621 }
622 return isTypeFoldingSupported(Opcode);
623}
624
625bool SPIRVInstructionSelector::BuildCOPY(Register DestReg, Register SrcReg,
626 MachineInstr &I) const {
627 const TargetRegisterClass *DstRC = MRI->getRegClassOrNull(DestReg);
628 const TargetRegisterClass *SrcRC = MRI->getRegClassOrNull(SrcReg);
629 if (DstRC != SrcRC && SrcRC)
630 MRI->setRegClass(DestReg, SrcRC);
631 return BuildMI(*I.getParent(), I, I.getDebugLoc(),
632 TII.get(TargetOpcode::COPY))
633 .addDef(DestReg)
634 .addUse(SrcReg)
635 .constrainAllUses(TII, TRI, RBI);
636}
637
638bool SPIRVInstructionSelector::spvSelect(Register ResVReg,
639 const SPIRVType *ResType,
640 MachineInstr &I) const {
641 const unsigned Opcode = I.getOpcode();
642 if (mayApplyGenericSelection(Opcode))
643 return selectImpl(I, *CoverageInfo);
644 switch (Opcode) {
645 case TargetOpcode::G_CONSTANT:
646 case TargetOpcode::G_FCONSTANT:
647 return selectConst(ResVReg, ResType, I);
648 case TargetOpcode::G_GLOBAL_VALUE:
649 return selectGlobalValue(ResVReg, I);
650 case TargetOpcode::G_IMPLICIT_DEF:
651 return selectOpUndef(ResVReg, ResType, I);
652 case TargetOpcode::G_FREEZE:
653 return selectFreeze(ResVReg, ResType, I);
654
655 case TargetOpcode::G_INTRINSIC:
656 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
657 case TargetOpcode::G_INTRINSIC_CONVERGENT:
658 case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS:
659 return selectIntrinsic(ResVReg, ResType, I);
660 case TargetOpcode::G_BITREVERSE:
661 return selectBitreverse(ResVReg, ResType, I);
662
663 case TargetOpcode::G_BUILD_VECTOR:
664 return selectBuildVector(ResVReg, ResType, I);
665 case TargetOpcode::G_SPLAT_VECTOR:
666 return selectSplatVector(ResVReg, ResType, I);
667
668 case TargetOpcode::G_SHUFFLE_VECTOR: {
669 MachineBasicBlock &BB = *I.getParent();
670 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpVectorShuffle))
671 .addDef(ResVReg)
672 .addUse(GR.getSPIRVTypeID(ResType))
673 .addUse(I.getOperand(1).getReg())
674 .addUse(I.getOperand(2).getReg());
675 for (auto V : I.getOperand(3).getShuffleMask())
676 MIB.addImm(V);
677 return MIB.constrainAllUses(TII, TRI, RBI);
678 }
679 case TargetOpcode::G_MEMMOVE:
680 case TargetOpcode::G_MEMCPY:
681 case TargetOpcode::G_MEMSET:
682 return selectMemOperation(ResVReg, I);
683
684 case TargetOpcode::G_ICMP:
685 return selectICmp(ResVReg, ResType, I);
686 case TargetOpcode::G_FCMP:
687 return selectFCmp(ResVReg, ResType, I);
688
689 case TargetOpcode::G_FRAME_INDEX:
690 return selectFrameIndex(ResVReg, ResType, I);
691
692 case TargetOpcode::G_LOAD:
693 return selectLoad(ResVReg, ResType, I);
694 case TargetOpcode::G_STORE:
695 return selectStore(I);
696
697 case TargetOpcode::G_BR:
698 return selectBranch(I);
699 case TargetOpcode::G_BRCOND:
700 return selectBranchCond(I);
701
702 case TargetOpcode::G_PHI:
703 return selectPhi(ResVReg, ResType, I);
704
705 case TargetOpcode::G_FPTOSI:
706 return selectUnOp(ResVReg, ResType, I, SPIRV::OpConvertFToS);
707 case TargetOpcode::G_FPTOUI:
708 return selectUnOp(ResVReg, ResType, I, SPIRV::OpConvertFToU);
709
710 case TargetOpcode::G_FPTOSI_SAT:
711 return selectUnOp(ResVReg, ResType, I, SPIRV::OpConvertFToS);
712 case TargetOpcode::G_FPTOUI_SAT:
713 return selectUnOp(ResVReg, ResType, I, SPIRV::OpConvertFToU);
714
715 case TargetOpcode::G_SITOFP:
716 return selectIToF(ResVReg, ResType, I, true, SPIRV::OpConvertSToF);
717 case TargetOpcode::G_UITOFP:
718 return selectIToF(ResVReg, ResType, I, false, SPIRV::OpConvertUToF);
719
720 case TargetOpcode::G_CTPOP:
721 return selectUnOp(ResVReg, ResType, I, SPIRV::OpBitCount);
722 case TargetOpcode::G_SMIN:
723 return selectExtInst(ResVReg, ResType, I, CL::s_min, GL::SMin);
724 case TargetOpcode::G_UMIN:
725 return selectExtInst(ResVReg, ResType, I, CL::u_min, GL::UMin);
726
727 case TargetOpcode::G_SMAX:
728 return selectExtInst(ResVReg, ResType, I, CL::s_max, GL::SMax);
729 case TargetOpcode::G_UMAX:
730 return selectExtInst(ResVReg, ResType, I, CL::u_max, GL::UMax);
731
732 case TargetOpcode::G_SCMP:
733 return selectSUCmp(ResVReg, ResType, I, true);
734 case TargetOpcode::G_UCMP:
735 return selectSUCmp(ResVReg, ResType, I, false);
736 case TargetOpcode::G_LROUND:
737 case TargetOpcode::G_LLROUND: {
738 Register regForLround =
739 MRI->createVirtualRegister(MRI->getRegClass(ResVReg), "lround");
740 MRI->setRegClass(regForLround, &SPIRV::iIDRegClass);
741 GR.assignSPIRVTypeToVReg(GR.getSPIRVTypeForVReg(I.getOperand(1).getReg()),
742 regForLround, *(I.getParent()->getParent()));
743 selectExtInstForLRound(regForLround, GR.getSPIRVTypeForVReg(regForLround),
744 I, CL::round, GL::Round);
745 MachineBasicBlock &BB = *I.getParent();
746 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpConvertFToS))
747 .addDef(ResVReg)
748 .addUse(GR.getSPIRVTypeID(ResType))
749 .addUse(regForLround);
750 return MIB.constrainAllUses(TII, TRI, RBI);
751 }
752 case TargetOpcode::G_STRICT_FMA:
753 case TargetOpcode::G_FMA:
754 return selectExtInst(ResVReg, ResType, I, CL::fma, GL::Fma);
755
756 case TargetOpcode::G_STRICT_FLDEXP:
757 return selectExtInst(ResVReg, ResType, I, CL::ldexp);
758
759 case TargetOpcode::G_FPOW:
760 return selectExtInst(ResVReg, ResType, I, CL::pow, GL::Pow);
761 case TargetOpcode::G_FPOWI:
762 return selectExtInst(ResVReg, ResType, I, CL::pown);
763
764 case TargetOpcode::G_FEXP:
765 return selectExtInst(ResVReg, ResType, I, CL::exp, GL::Exp);
766 case TargetOpcode::G_FEXP2:
767 return selectExtInst(ResVReg, ResType, I, CL::exp2, GL::Exp2);
768 case TargetOpcode::G_FMODF:
769 return selectModf(ResVReg, ResType, I);
770
771 case TargetOpcode::G_FLOG:
772 return selectExtInst(ResVReg, ResType, I, CL::log, GL::Log);
773 case TargetOpcode::G_FLOG2:
774 return selectExtInst(ResVReg, ResType, I, CL::log2, GL::Log2);
775 case TargetOpcode::G_FLOG10:
776 return selectLog10(ResVReg, ResType, I);
777
778 case TargetOpcode::G_FABS:
779 return selectExtInst(ResVReg, ResType, I, CL::fabs, GL::FAbs);
780 case TargetOpcode::G_ABS:
781 return selectExtInst(ResVReg, ResType, I, CL::s_abs, GL::SAbs);
782
783 case TargetOpcode::G_FMINNUM:
784 case TargetOpcode::G_FMINIMUM:
785 return selectExtInst(ResVReg, ResType, I, CL::fmin, GL::NMin);
786 case TargetOpcode::G_FMAXNUM:
787 case TargetOpcode::G_FMAXIMUM:
788 return selectExtInst(ResVReg, ResType, I, CL::fmax, GL::NMax);
789
790 case TargetOpcode::G_FCOPYSIGN:
791 return selectExtInst(ResVReg, ResType, I, CL::copysign);
792
793 case TargetOpcode::G_FCEIL:
794 return selectExtInst(ResVReg, ResType, I, CL::ceil, GL::Ceil);
795 case TargetOpcode::G_FFLOOR:
796 return selectExtInst(ResVReg, ResType, I, CL::floor, GL::Floor);
797
798 case TargetOpcode::G_FCOS:
799 return selectExtInst(ResVReg, ResType, I, CL::cos, GL::Cos);
800 case TargetOpcode::G_FSIN:
801 return selectExtInst(ResVReg, ResType, I, CL::sin, GL::Sin);
802 case TargetOpcode::G_FTAN:
803 return selectExtInst(ResVReg, ResType, I, CL::tan, GL::Tan);
804 case TargetOpcode::G_FACOS:
805 return selectExtInst(ResVReg, ResType, I, CL::acos, GL::Acos);
806 case TargetOpcode::G_FASIN:
807 return selectExtInst(ResVReg, ResType, I, CL::asin, GL::Asin);
808 case TargetOpcode::G_FATAN:
809 return selectExtInst(ResVReg, ResType, I, CL::atan, GL::Atan);
810 case TargetOpcode::G_FATAN2:
811 return selectExtInst(ResVReg, ResType, I, CL::atan2, GL::Atan2);
812 case TargetOpcode::G_FCOSH:
813 return selectExtInst(ResVReg, ResType, I, CL::cosh, GL::Cosh);
814 case TargetOpcode::G_FSINH:
815 return selectExtInst(ResVReg, ResType, I, CL::sinh, GL::Sinh);
816 case TargetOpcode::G_FTANH:
817 return selectExtInst(ResVReg, ResType, I, CL::tanh, GL::Tanh);
818
819 case TargetOpcode::G_STRICT_FSQRT:
820 case TargetOpcode::G_FSQRT:
821 return selectExtInst(ResVReg, ResType, I, CL::sqrt, GL::Sqrt);
822
823 case TargetOpcode::G_CTTZ:
824 case TargetOpcode::G_CTTZ_ZERO_UNDEF:
825 return selectExtInst(ResVReg, ResType, I, CL::ctz);
826 case TargetOpcode::G_CTLZ:
827 case TargetOpcode::G_CTLZ_ZERO_UNDEF:
828 return selectExtInst(ResVReg, ResType, I, CL::clz);
829
830 case TargetOpcode::G_INTRINSIC_ROUND:
831 return selectExtInst(ResVReg, ResType, I, CL::round, GL::Round);
832 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
833 return selectExtInst(ResVReg, ResType, I, CL::rint, GL::RoundEven);
834 case TargetOpcode::G_INTRINSIC_TRUNC:
835 return selectExtInst(ResVReg, ResType, I, CL::trunc, GL::Trunc);
836 case TargetOpcode::G_FRINT:
837 case TargetOpcode::G_FNEARBYINT:
838 return selectExtInst(ResVReg, ResType, I, CL::rint, GL::RoundEven);
839
840 case TargetOpcode::G_SMULH:
841 return selectExtInst(ResVReg, ResType, I, CL::s_mul_hi);
842 case TargetOpcode::G_UMULH:
843 return selectExtInst(ResVReg, ResType, I, CL::u_mul_hi);
844
845 case TargetOpcode::G_SADDSAT:
846 return selectExtInst(ResVReg, ResType, I, CL::s_add_sat);
847 case TargetOpcode::G_UADDSAT:
848 return selectExtInst(ResVReg, ResType, I, CL::u_add_sat);
849 case TargetOpcode::G_SSUBSAT:
850 return selectExtInst(ResVReg, ResType, I, CL::s_sub_sat);
851 case TargetOpcode::G_USUBSAT:
852 return selectExtInst(ResVReg, ResType, I, CL::u_sub_sat);
853
854 case TargetOpcode::G_FFREXP:
855 return selectFrexp(ResVReg, ResType, I);
856
857 case TargetOpcode::G_UADDO:
858 return selectOverflowArith(ResVReg, ResType, I,
859 ResType->getOpcode() == SPIRV::OpTypeVector
860 ? SPIRV::OpIAddCarryV
861 : SPIRV::OpIAddCarryS);
862 case TargetOpcode::G_USUBO:
863 return selectOverflowArith(ResVReg, ResType, I,
864 ResType->getOpcode() == SPIRV::OpTypeVector
865 ? SPIRV::OpISubBorrowV
866 : SPIRV::OpISubBorrowS);
867 case TargetOpcode::G_UMULO:
868 return selectOverflowArith(ResVReg, ResType, I, SPIRV::OpUMulExtended);
869 case TargetOpcode::G_SMULO:
870 return selectOverflowArith(ResVReg, ResType, I, SPIRV::OpSMulExtended);
871
872 case TargetOpcode::G_SEXT:
873 return selectExt(ResVReg, ResType, I, true);
874 case TargetOpcode::G_ANYEXT:
875 case TargetOpcode::G_ZEXT:
876 return selectExt(ResVReg, ResType, I, false);
877 case TargetOpcode::G_TRUNC:
878 return selectTrunc(ResVReg, ResType, I);
879 case TargetOpcode::G_FPTRUNC:
880 case TargetOpcode::G_FPEXT:
881 return selectUnOp(ResVReg, ResType, I, SPIRV::OpFConvert);
882
883 case TargetOpcode::G_PTRTOINT:
884 return selectUnOp(ResVReg, ResType, I, SPIRV::OpConvertPtrToU);
885 case TargetOpcode::G_INTTOPTR:
886 return selectUnOp(ResVReg, ResType, I, SPIRV::OpConvertUToPtr);
887 case TargetOpcode::G_BITCAST:
888 return selectBitcast(ResVReg, ResType, I);
889 case TargetOpcode::G_ADDRSPACE_CAST:
890 return selectAddrSpaceCast(ResVReg, ResType, I);
891 case TargetOpcode::G_PTR_ADD: {
892 // Currently, we get G_PTR_ADD only applied to global variables.
893 assert(I.getOperand(1).isReg() && I.getOperand(2).isReg());
894 Register GV = I.getOperand(1).getReg();
895 MachineRegisterInfo::def_instr_iterator II = MRI->def_instr_begin(GV);
896 (void)II;
897 assert(((*II).getOpcode() == TargetOpcode::G_GLOBAL_VALUE ||
898 (*II).getOpcode() == TargetOpcode::COPY ||
899 (*II).getOpcode() == SPIRV::OpVariable) &&
900 getImm(I.getOperand(2), MRI));
901 // It may be the initialization of a global variable.
902 bool IsGVInit = false;
904 UseIt = MRI->use_instr_begin(I.getOperand(0).getReg()),
905 UseEnd = MRI->use_instr_end();
906 UseIt != UseEnd; UseIt = std::next(UseIt)) {
907 if ((*UseIt).getOpcode() == TargetOpcode::G_GLOBAL_VALUE ||
908 (*UseIt).getOpcode() == SPIRV::OpVariable) {
909 IsGVInit = true;
910 break;
911 }
912 }
913 MachineBasicBlock &BB = *I.getParent();
914 if (!IsGVInit) {
915 SPIRVType *GVType = GR.getSPIRVTypeForVReg(GV);
916 SPIRVType *GVPointeeType = GR.getPointeeType(GVType);
917 SPIRVType *ResPointeeType = GR.getPointeeType(ResType);
918 if (GVPointeeType && ResPointeeType && GVPointeeType != ResPointeeType) {
919 // Build a new virtual register that is associated with the required
920 // data type.
921 Register NewVReg = MRI->createGenericVirtualRegister(MRI->getType(GV));
922 MRI->setRegClass(NewVReg, MRI->getRegClass(GV));
923 // Having a correctly typed base we are ready to build the actually
924 // required GEP. It may not be a constant though, because all Operands
925 // of OpSpecConstantOp is to originate from other const instructions,
926 // and only the AccessChain named opcodes accept a global OpVariable
927 // instruction. We can't use an AccessChain opcode because of the type
928 // mismatch between result and base types.
929 if (!GR.isBitcastCompatible(ResType, GVType))
931 "incompatible result and operand types in a bitcast");
932 Register ResTypeReg = GR.getSPIRVTypeID(ResType);
933 MachineInstrBuilder MIB =
934 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpBitcast))
935 .addDef(NewVReg)
936 .addUse(ResTypeReg)
937 .addUse(GV);
938 return MIB.constrainAllUses(TII, TRI, RBI) &&
939 BuildMI(BB, I, I.getDebugLoc(),
940 TII.get(STI.isLogicalSPIRV()
941 ? SPIRV::OpInBoundsAccessChain
942 : SPIRV::OpInBoundsPtrAccessChain))
943 .addDef(ResVReg)
944 .addUse(ResTypeReg)
945 .addUse(NewVReg)
946 .addUse(I.getOperand(2).getReg())
947 .constrainAllUses(TII, TRI, RBI);
948 } else {
949 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpSpecConstantOp))
950 .addDef(ResVReg)
951 .addUse(GR.getSPIRVTypeID(ResType))
952 .addImm(
953 static_cast<uint32_t>(SPIRV::Opcode::InBoundsPtrAccessChain))
954 .addUse(GV)
955 .addUse(I.getOperand(2).getReg())
956 .constrainAllUses(TII, TRI, RBI);
957 }
958 }
959 // It's possible to translate G_PTR_ADD to OpSpecConstantOp: either to
960 // initialize a global variable with a constant expression (e.g., the test
961 // case opencl/basic/progvar_prog_scope_init.ll), or for another use case
962 Register Idx = buildZerosVal(GR.getOrCreateSPIRVIntegerType(32, I, TII), I);
963 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpSpecConstantOp))
964 .addDef(ResVReg)
965 .addUse(GR.getSPIRVTypeID(ResType))
966 .addImm(static_cast<uint32_t>(
967 SPIRV::Opcode::InBoundsPtrAccessChain))
968 .addUse(GV)
969 .addUse(Idx)
970 .addUse(I.getOperand(2).getReg());
971 return MIB.constrainAllUses(TII, TRI, RBI);
972 }
973
974 case TargetOpcode::G_ATOMICRMW_OR:
975 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicOr);
976 case TargetOpcode::G_ATOMICRMW_ADD:
977 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicIAdd);
978 case TargetOpcode::G_ATOMICRMW_AND:
979 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicAnd);
980 case TargetOpcode::G_ATOMICRMW_MAX:
981 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicSMax);
982 case TargetOpcode::G_ATOMICRMW_MIN:
983 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicSMin);
984 case TargetOpcode::G_ATOMICRMW_SUB:
985 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicISub);
986 case TargetOpcode::G_ATOMICRMW_XOR:
987 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicXor);
988 case TargetOpcode::G_ATOMICRMW_UMAX:
989 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicUMax);
990 case TargetOpcode::G_ATOMICRMW_UMIN:
991 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicUMin);
992 case TargetOpcode::G_ATOMICRMW_XCHG:
993 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicExchange);
994 case TargetOpcode::G_ATOMIC_CMPXCHG:
995 return selectAtomicCmpXchg(ResVReg, ResType, I);
996
997 case TargetOpcode::G_ATOMICRMW_FADD:
998 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicFAddEXT);
999 case TargetOpcode::G_ATOMICRMW_FSUB:
1000 // Translate G_ATOMICRMW_FSUB to OpAtomicFAddEXT with negative value operand
1001 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicFAddEXT,
1002 SPIRV::OpFNegate);
1003 case TargetOpcode::G_ATOMICRMW_FMIN:
1004 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicFMinEXT);
1005 case TargetOpcode::G_ATOMICRMW_FMAX:
1006 return selectAtomicRMW(ResVReg, ResType, I, SPIRV::OpAtomicFMaxEXT);
1007
1008 case TargetOpcode::G_FENCE:
1009 return selectFence(I);
1010
1011 case TargetOpcode::G_STACKSAVE:
1012 return selectStackSave(ResVReg, ResType, I);
1013 case TargetOpcode::G_STACKRESTORE:
1014 return selectStackRestore(I);
1015
1016 case TargetOpcode::G_UNMERGE_VALUES:
1017 return selectUnmergeValues(I);
1018
1019 // Discard gen opcodes for intrinsics which we do not expect to actually
1020 // represent code after lowering or intrinsics which are not implemented but
1021 // should not crash when found in a customer's LLVM IR input.
1022 case TargetOpcode::G_TRAP:
1023 case TargetOpcode::G_UBSANTRAP:
1024 case TargetOpcode::DBG_LABEL:
1025 return true;
1026 case TargetOpcode::G_DEBUGTRAP:
1027 return selectDebugTrap(ResVReg, ResType, I);
1028
1029 default:
1030 return false;
1031 }
1032}
1033
1034bool SPIRVInstructionSelector::selectDebugTrap(Register ResVReg,
1035 const SPIRVType *ResType,
1036 MachineInstr &I) const {
1037 unsigned Opcode = SPIRV::OpNop;
1038 MachineBasicBlock &BB = *I.getParent();
1039 return BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
1040 .constrainAllUses(TII, TRI, RBI);
1041}
1042
1043bool SPIRVInstructionSelector::selectExtInst(Register ResVReg,
1044 const SPIRVType *ResType,
1045 MachineInstr &I,
1046 GL::GLSLExtInst GLInst) const {
1047 if (!STI.canUseExtInstSet(
1048 SPIRV::InstructionSet::InstructionSet::GLSL_std_450)) {
1049 std::string DiagMsg;
1050 raw_string_ostream OS(DiagMsg);
1051 I.print(OS, true, false, false, false);
1052 DiagMsg += " is only supported with the GLSL extended instruction set.\n";
1053 report_fatal_error(DiagMsg.c_str(), false);
1054 }
1055 return selectExtInst(ResVReg, ResType, I,
1056 {{SPIRV::InstructionSet::GLSL_std_450, GLInst}});
1057}
1058
1059bool SPIRVInstructionSelector::selectExtInst(Register ResVReg,
1060 const SPIRVType *ResType,
1061 MachineInstr &I,
1062 CL::OpenCLExtInst CLInst) const {
1063 return selectExtInst(ResVReg, ResType, I,
1064 {{SPIRV::InstructionSet::OpenCL_std, CLInst}});
1065}
1066
1067bool SPIRVInstructionSelector::selectExtInst(Register ResVReg,
1068 const SPIRVType *ResType,
1069 MachineInstr &I,
1070 CL::OpenCLExtInst CLInst,
1071 GL::GLSLExtInst GLInst) const {
1072 ExtInstList ExtInsts = {{SPIRV::InstructionSet::OpenCL_std, CLInst},
1073 {SPIRV::InstructionSet::GLSL_std_450, GLInst}};
1074 return selectExtInst(ResVReg, ResType, I, ExtInsts);
1075}
1076
1077bool SPIRVInstructionSelector::selectExtInst(Register ResVReg,
1078 const SPIRVType *ResType,
1079 MachineInstr &I,
1080 const ExtInstList &Insts) const {
1081
1082 for (const auto &Ex : Insts) {
1083 SPIRV::InstructionSet::InstructionSet Set = Ex.first;
1084 uint32_t Opcode = Ex.second;
1085 if (STI.canUseExtInstSet(Set)) {
1086 MachineBasicBlock &BB = *I.getParent();
1087 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpExtInst))
1088 .addDef(ResVReg)
1089 .addUse(GR.getSPIRVTypeID(ResType))
1090 .addImm(static_cast<uint32_t>(Set))
1091 .addImm(Opcode)
1092 .setMIFlags(I.getFlags());
1093 const unsigned NumOps = I.getNumOperands();
1094 unsigned Index = 1;
1095 if (Index < NumOps &&
1096 I.getOperand(Index).getType() ==
1097 MachineOperand::MachineOperandType::MO_IntrinsicID)
1098 Index = 2;
1099 for (; Index < NumOps; ++Index)
1100 MIB.add(I.getOperand(Index));
1101 return MIB.constrainAllUses(TII, TRI, RBI);
1102 }
1103 }
1104 return false;
1105}
1106bool SPIRVInstructionSelector::selectExtInstForLRound(
1107 Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
1108 CL::OpenCLExtInst CLInst, GL::GLSLExtInst GLInst) const {
1109 ExtInstList ExtInsts = {{SPIRV::InstructionSet::OpenCL_std, CLInst},
1110 {SPIRV::InstructionSet::GLSL_std_450, GLInst}};
1111 return selectExtInstForLRound(ResVReg, ResType, I, ExtInsts);
1112}
1113
1114bool SPIRVInstructionSelector::selectExtInstForLRound(
1115 Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
1116 const ExtInstList &Insts) const {
1117 for (const auto &Ex : Insts) {
1118 SPIRV::InstructionSet::InstructionSet Set = Ex.first;
1119 uint32_t Opcode = Ex.second;
1120 if (STI.canUseExtInstSet(Set)) {
1121 MachineBasicBlock &BB = *I.getParent();
1122 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpExtInst))
1123 .addDef(ResVReg)
1124 .addUse(GR.getSPIRVTypeID(ResType))
1125 .addImm(static_cast<uint32_t>(Set))
1126 .addImm(Opcode);
1127 const unsigned NumOps = I.getNumOperands();
1128 unsigned Index = 1;
1129 if (Index < NumOps &&
1130 I.getOperand(Index).getType() ==
1131 MachineOperand::MachineOperandType::MO_IntrinsicID)
1132 Index = 2;
1133 for (; Index < NumOps; ++Index)
1134 MIB.add(I.getOperand(Index));
1135 MIB.constrainAllUses(TII, TRI, RBI);
1136 return true;
1137 }
1138 }
1139 return false;
1140}
1141
1142bool SPIRVInstructionSelector::selectFrexp(Register ResVReg,
1143 const SPIRVType *ResType,
1144 MachineInstr &I) const {
1145 ExtInstList ExtInsts = {{SPIRV::InstructionSet::OpenCL_std, CL::frexp},
1146 {SPIRV::InstructionSet::GLSL_std_450, GL::Frexp}};
1147 for (const auto &Ex : ExtInsts) {
1148 SPIRV::InstructionSet::InstructionSet Set = Ex.first;
1149 uint32_t Opcode = Ex.second;
1150 if (!STI.canUseExtInstSet(Set))
1151 continue;
1152
1153 MachineIRBuilder MIRBuilder(I);
1154 SPIRVType *PointeeTy = GR.getSPIRVTypeForVReg(I.getOperand(1).getReg());
1156 PointeeTy, MIRBuilder, SPIRV::StorageClass::Function);
1157 Register PointerVReg =
1158 createVirtualRegister(PointerType, &GR, MRI, MRI->getMF());
1159
1160 auto It = getOpVariableMBBIt(I);
1161 auto MIB = BuildMI(*It->getParent(), It, It->getDebugLoc(),
1162 TII.get(SPIRV::OpVariable))
1163 .addDef(PointerVReg)
1164 .addUse(GR.getSPIRVTypeID(PointerType))
1165 .addImm(static_cast<uint32_t>(SPIRV::StorageClass::Function))
1166 .constrainAllUses(TII, TRI, RBI);
1167
1168 MIB = MIB &
1169 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpExtInst))
1170 .addDef(ResVReg)
1171 .addUse(GR.getSPIRVTypeID(ResType))
1172 .addImm(static_cast<uint32_t>(Ex.first))
1173 .addImm(Opcode)
1174 .add(I.getOperand(2))
1175 .addUse(PointerVReg)
1176 .constrainAllUses(TII, TRI, RBI);
1177
1178 MIB = MIB &
1179 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpLoad))
1180 .addDef(I.getOperand(1).getReg())
1181 .addUse(GR.getSPIRVTypeID(PointeeTy))
1182 .addUse(PointerVReg)
1183 .constrainAllUses(TII, TRI, RBI);
1184 return MIB;
1185 }
1186 return false;
1187}
1188
1189bool SPIRVInstructionSelector::selectOpWithSrcs(Register ResVReg,
1190 const SPIRVType *ResType,
1191 MachineInstr &I,
1192 std::vector<Register> Srcs,
1193 unsigned Opcode) const {
1194 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(Opcode))
1195 .addDef(ResVReg)
1196 .addUse(GR.getSPIRVTypeID(ResType));
1197 for (Register SReg : Srcs) {
1198 MIB.addUse(SReg);
1199 }
1200 return MIB.constrainAllUses(TII, TRI, RBI);
1201}
1202
1203bool SPIRVInstructionSelector::selectUnOp(Register ResVReg,
1204 const SPIRVType *ResType,
1205 MachineInstr &I,
1206 unsigned Opcode) const {
1207 if (STI.isPhysicalSPIRV() && I.getOperand(1).isReg()) {
1208 Register SrcReg = I.getOperand(1).getReg();
1209 bool IsGV = false;
1211 MRI->def_instr_begin(SrcReg);
1212 DefIt != MRI->def_instr_end(); DefIt = std::next(DefIt)) {
1213 unsigned DefOpCode = DefIt->getOpcode();
1214 if (DefOpCode == SPIRV::ASSIGN_TYPE) {
1215 // We need special handling to look through the type assignment and see
1216 // if this is a constant or a global
1217 if (auto *VRD = getVRegDef(*MRI, DefIt->getOperand(1).getReg()))
1218 DefOpCode = VRD->getOpcode();
1219 }
1220 if (DefOpCode == TargetOpcode::G_GLOBAL_VALUE ||
1221 DefOpCode == TargetOpcode::G_CONSTANT ||
1222 DefOpCode == SPIRV::OpVariable || DefOpCode == SPIRV::OpConstantI) {
1223 IsGV = true;
1224 break;
1225 }
1226 }
1227 if (IsGV) {
1228 uint32_t SpecOpcode = 0;
1229 switch (Opcode) {
1230 case SPIRV::OpConvertPtrToU:
1231 SpecOpcode = static_cast<uint32_t>(SPIRV::Opcode::ConvertPtrToU);
1232 break;
1233 case SPIRV::OpConvertUToPtr:
1234 SpecOpcode = static_cast<uint32_t>(SPIRV::Opcode::ConvertUToPtr);
1235 break;
1236 }
1237 if (SpecOpcode)
1238 return BuildMI(*I.getParent(), I, I.getDebugLoc(),
1239 TII.get(SPIRV::OpSpecConstantOp))
1240 .addDef(ResVReg)
1241 .addUse(GR.getSPIRVTypeID(ResType))
1242 .addImm(SpecOpcode)
1243 .addUse(SrcReg)
1244 .constrainAllUses(TII, TRI, RBI);
1245 }
1246 }
1247 return selectOpWithSrcs(ResVReg, ResType, I, {I.getOperand(1).getReg()},
1248 Opcode);
1249}
1250
1251bool SPIRVInstructionSelector::selectBitcast(Register ResVReg,
1252 const SPIRVType *ResType,
1253 MachineInstr &I) const {
1254 Register OpReg = I.getOperand(1).getReg();
1255 SPIRVType *OpType = OpReg.isValid() ? GR.getSPIRVTypeForVReg(OpReg) : nullptr;
1256 if (!GR.isBitcastCompatible(ResType, OpType))
1257 report_fatal_error("incompatible result and operand types in a bitcast");
1258 return selectUnOp(ResVReg, ResType, I, SPIRV::OpBitcast);
1259}
1260
1263 MachineIRBuilder &MIRBuilder,
1264 SPIRVGlobalRegistry &GR) {
1265 uint32_t SpvMemOp = static_cast<uint32_t>(SPIRV::MemoryOperand::None);
1266 if (MemOp->isVolatile())
1267 SpvMemOp |= static_cast<uint32_t>(SPIRV::MemoryOperand::Volatile);
1268 if (MemOp->isNonTemporal())
1269 SpvMemOp |= static_cast<uint32_t>(SPIRV::MemoryOperand::Nontemporal);
1270 if (MemOp->getAlign().value())
1271 SpvMemOp |= static_cast<uint32_t>(SPIRV::MemoryOperand::Aligned);
1272
1273 [[maybe_unused]] MachineInstr *AliasList = nullptr;
1274 [[maybe_unused]] MachineInstr *NoAliasList = nullptr;
1275 const SPIRVSubtarget *ST =
1276 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
1277 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing)) {
1278 if (auto *MD = MemOp->getAAInfo().Scope) {
1279 AliasList = GR.getOrAddMemAliasingINTELInst(MIRBuilder, MD);
1280 if (AliasList)
1281 SpvMemOp |=
1282 static_cast<uint32_t>(SPIRV::MemoryOperand::AliasScopeINTELMask);
1283 }
1284 if (auto *MD = MemOp->getAAInfo().NoAlias) {
1285 NoAliasList = GR.getOrAddMemAliasingINTELInst(MIRBuilder, MD);
1286 if (NoAliasList)
1287 SpvMemOp |=
1288 static_cast<uint32_t>(SPIRV::MemoryOperand::NoAliasINTELMask);
1289 }
1290 }
1291
1292 if (SpvMemOp != static_cast<uint32_t>(SPIRV::MemoryOperand::None)) {
1293 MIB.addImm(SpvMemOp);
1294 if (SpvMemOp & static_cast<uint32_t>(SPIRV::MemoryOperand::Aligned))
1295 MIB.addImm(MemOp->getAlign().value());
1296 if (AliasList)
1297 MIB.addUse(AliasList->getOperand(0).getReg());
1298 if (NoAliasList)
1299 MIB.addUse(NoAliasList->getOperand(0).getReg());
1300 }
1301}
1302
1304 uint32_t SpvMemOp = static_cast<uint32_t>(SPIRV::MemoryOperand::None);
1306 SpvMemOp |= static_cast<uint32_t>(SPIRV::MemoryOperand::Volatile);
1308 SpvMemOp |= static_cast<uint32_t>(SPIRV::MemoryOperand::Nontemporal);
1309
1310 if (SpvMemOp != static_cast<uint32_t>(SPIRV::MemoryOperand::None))
1311 MIB.addImm(SpvMemOp);
1312}
1313
1314bool SPIRVInstructionSelector::selectLoad(Register ResVReg,
1315 const SPIRVType *ResType,
1316 MachineInstr &I) const {
1317 unsigned OpOffset = isa<GIntrinsic>(I) ? 1 : 0;
1318 Register Ptr = I.getOperand(1 + OpOffset).getReg();
1319
1320 auto *PtrDef = getVRegDef(*MRI, Ptr);
1321 auto *IntPtrDef = dyn_cast<GIntrinsic>(PtrDef);
1322 if (IntPtrDef &&
1323 IntPtrDef->getIntrinsicID() == Intrinsic::spv_resource_getpointer) {
1324 Register HandleReg = IntPtrDef->getOperand(2).getReg();
1325 SPIRVType *HandleType = GR.getSPIRVTypeForVReg(HandleReg);
1326 if (HandleType->getOpcode() == SPIRV::OpTypeImage) {
1327 Register NewHandleReg =
1328 MRI->createVirtualRegister(MRI->getRegClass(HandleReg));
1329 auto *HandleDef = cast<GIntrinsic>(getVRegDef(*MRI, HandleReg));
1330 if (!loadHandleBeforePosition(NewHandleReg, HandleType, *HandleDef, I)) {
1331 return false;
1332 }
1333
1334 Register IdxReg = IntPtrDef->getOperand(3).getReg();
1335 return generateImageReadOrFetch(ResVReg, ResType, NewHandleReg, IdxReg,
1336 I.getDebugLoc(), I);
1337 }
1338 }
1339
1340 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpLoad))
1341 .addDef(ResVReg)
1342 .addUse(GR.getSPIRVTypeID(ResType))
1343 .addUse(Ptr);
1344 if (!I.getNumMemOperands()) {
1345 assert(I.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS ||
1346 I.getOpcode() ==
1347 TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS);
1348 addMemoryOperands(I.getOperand(2 + OpOffset).getImm(), MIB);
1349 } else {
1350 MachineIRBuilder MIRBuilder(I);
1351 addMemoryOperands(*I.memoperands_begin(), MIB, MIRBuilder, GR);
1352 }
1353 return MIB.constrainAllUses(TII, TRI, RBI);
1354}
1355
1356bool SPIRVInstructionSelector::selectStore(MachineInstr &I) const {
1357 unsigned OpOffset = isa<GIntrinsic>(I) ? 1 : 0;
1358 Register StoreVal = I.getOperand(0 + OpOffset).getReg();
1359 Register Ptr = I.getOperand(1 + OpOffset).getReg();
1360
1361 auto *PtrDef = getVRegDef(*MRI, Ptr);
1362 auto *IntPtrDef = dyn_cast<GIntrinsic>(PtrDef);
1363 if (IntPtrDef &&
1364 IntPtrDef->getIntrinsicID() == Intrinsic::spv_resource_getpointer) {
1365 Register HandleReg = IntPtrDef->getOperand(2).getReg();
1366 Register NewHandleReg =
1367 MRI->createVirtualRegister(MRI->getRegClass(HandleReg));
1368 auto *HandleDef = cast<GIntrinsic>(getVRegDef(*MRI, HandleReg));
1369 SPIRVType *HandleType = GR.getSPIRVTypeForVReg(HandleReg);
1370 if (!loadHandleBeforePosition(NewHandleReg, HandleType, *HandleDef, I)) {
1371 return false;
1372 }
1373
1374 Register IdxReg = IntPtrDef->getOperand(3).getReg();
1375 if (HandleType->getOpcode() == SPIRV::OpTypeImage) {
1376 auto BMI = BuildMI(*I.getParent(), I, I.getDebugLoc(),
1377 TII.get(SPIRV::OpImageWrite))
1378 .addUse(NewHandleReg)
1379 .addUse(IdxReg)
1380 .addUse(StoreVal);
1381
1382 const llvm::Type *LLVMHandleType = GR.getTypeForSPIRVType(HandleType);
1383 if (sampledTypeIsSignedInteger(LLVMHandleType))
1384 BMI.addImm(0x1000); // SignExtend
1385
1386 return BMI.constrainAllUses(TII, TRI, RBI);
1387 }
1388 }
1389
1390 MachineBasicBlock &BB = *I.getParent();
1391 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpStore))
1392 .addUse(Ptr)
1393 .addUse(StoreVal);
1394 if (!I.getNumMemOperands()) {
1395 assert(I.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS ||
1396 I.getOpcode() ==
1397 TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS);
1398 addMemoryOperands(I.getOperand(2 + OpOffset).getImm(), MIB);
1399 } else {
1400 MachineIRBuilder MIRBuilder(I);
1401 addMemoryOperands(*I.memoperands_begin(), MIB, MIRBuilder, GR);
1402 }
1403 return MIB.constrainAllUses(TII, TRI, RBI);
1404}
1405
1406bool SPIRVInstructionSelector::selectStackSave(Register ResVReg,
1407 const SPIRVType *ResType,
1408 MachineInstr &I) const {
1409 if (!STI.canUseExtension(SPIRV::Extension::SPV_INTEL_variable_length_array))
1411 "llvm.stacksave intrinsic: this instruction requires the following "
1412 "SPIR-V extension: SPV_INTEL_variable_length_array",
1413 false);
1414 MachineBasicBlock &BB = *I.getParent();
1415 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpSaveMemoryINTEL))
1416 .addDef(ResVReg)
1417 .addUse(GR.getSPIRVTypeID(ResType))
1418 .constrainAllUses(TII, TRI, RBI);
1419}
1420
1421bool SPIRVInstructionSelector::selectStackRestore(MachineInstr &I) const {
1422 if (!STI.canUseExtension(SPIRV::Extension::SPV_INTEL_variable_length_array))
1424 "llvm.stackrestore intrinsic: this instruction requires the following "
1425 "SPIR-V extension: SPV_INTEL_variable_length_array",
1426 false);
1427 if (!I.getOperand(0).isReg())
1428 return false;
1429 MachineBasicBlock &BB = *I.getParent();
1430 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpRestoreMemoryINTEL))
1431 .addUse(I.getOperand(0).getReg())
1432 .constrainAllUses(TII, TRI, RBI);
1433}
1434
1435bool SPIRVInstructionSelector::selectMemOperation(Register ResVReg,
1436 MachineInstr &I) const {
1437 MachineBasicBlock &BB = *I.getParent();
1438 Register SrcReg = I.getOperand(1).getReg();
1439 bool Result = true;
1440 if (I.getOpcode() == TargetOpcode::G_MEMSET) {
1441 MachineIRBuilder MIRBuilder(I);
1442 assert(I.getOperand(1).isReg() && I.getOperand(2).isReg());
1443 unsigned Val = getIConstVal(I.getOperand(1).getReg(), MRI);
1444 unsigned Num = getIConstVal(I.getOperand(2).getReg(), MRI);
1445 Type *ValTy = Type::getInt8Ty(I.getMF()->getFunction().getContext());
1446 Type *ArrTy = ArrayType::get(ValTy, Num);
1448 ArrTy, MIRBuilder, SPIRV::StorageClass::UniformConstant);
1449
1450 SPIRVType *SpvArrTy = GR.getOrCreateSPIRVType(
1451 ArrTy, MIRBuilder, SPIRV::AccessQualifier::None, false);
1452 Register Const = GR.getOrCreateConstIntArray(Val, Num, I, SpvArrTy, TII);
1453 // TODO: check if we have such GV, add init, use buildGlobalVariable.
1454 Function &CurFunction = GR.CurMF->getFunction();
1455 Type *LLVMArrTy =
1456 ArrayType::get(IntegerType::get(CurFunction.getContext(), 8), Num);
1457 // Module takes ownership of the global var.
1458 GlobalVariable *GV = new GlobalVariable(*CurFunction.getParent(), LLVMArrTy,
1460 Constant::getNullValue(LLVMArrTy));
1461 Register VarReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
1462 auto MIBVar =
1463 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpVariable))
1464 .addDef(VarReg)
1465 .addUse(GR.getSPIRVTypeID(VarTy))
1466 .addImm(SPIRV::StorageClass::UniformConstant)
1467 .addUse(Const);
1468 Result &= MIBVar.constrainAllUses(TII, TRI, RBI);
1469
1470 GR.add(GV, MIBVar);
1471 GR.addGlobalObject(GV, GR.CurMF, VarReg);
1472
1473 buildOpDecorate(VarReg, I, TII, SPIRV::Decoration::Constant, {});
1475 ValTy, I, SPIRV::StorageClass::UniformConstant);
1476 SrcReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
1477 selectOpWithSrcs(SrcReg, SourceTy, I, {VarReg}, SPIRV::OpBitcast);
1478 }
1479 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCopyMemorySized))
1480 .addUse(I.getOperand(0).getReg())
1481 .addUse(SrcReg)
1482 .addUse(I.getOperand(2).getReg());
1483 if (I.getNumMemOperands()) {
1484 MachineIRBuilder MIRBuilder(I);
1485 addMemoryOperands(*I.memoperands_begin(), MIB, MIRBuilder, GR);
1486 }
1487 Result &= MIB.constrainAllUses(TII, TRI, RBI);
1488 if (ResVReg.isValid() && ResVReg != MIB->getOperand(0).getReg())
1489 Result &= BuildCOPY(ResVReg, MIB->getOperand(0).getReg(), I);
1490 return Result;
1491}
1492
1493bool SPIRVInstructionSelector::selectAtomicRMW(Register ResVReg,
1494 const SPIRVType *ResType,
1495 MachineInstr &I,
1496 unsigned NewOpcode,
1497 unsigned NegateOpcode) const {
1498 bool Result = true;
1499 assert(I.hasOneMemOperand());
1500 const MachineMemOperand *MemOp = *I.memoperands_begin();
1501 uint32_t Scope = static_cast<uint32_t>(getMemScope(
1502 GR.CurMF->getFunction().getContext(), MemOp->getSyncScopeID()));
1503 auto ScopeConstant = buildI32Constant(Scope, I);
1504 Register ScopeReg = ScopeConstant.first;
1505 Result &= ScopeConstant.second;
1506
1507 Register Ptr = I.getOperand(1).getReg();
1508 // TODO: Changed as it's implemented in the translator. See test/atomicrmw.ll
1509 // auto ScSem =
1510 // getMemSemanticsForStorageClass(GR.getPointerStorageClass(Ptr));
1511 AtomicOrdering AO = MemOp->getSuccessOrdering();
1512 uint32_t MemSem = static_cast<uint32_t>(getMemSemantics(AO));
1513 auto MemSemConstant = buildI32Constant(MemSem /*| ScSem*/, I);
1514 Register MemSemReg = MemSemConstant.first;
1515 Result &= MemSemConstant.second;
1516
1517 Register ValueReg = I.getOperand(2).getReg();
1518 if (NegateOpcode != 0) {
1519 // Translation with negative value operand is requested
1520 Register TmpReg = createVirtualRegister(ResType, &GR, MRI, MRI->getMF());
1521 Result &= selectOpWithSrcs(TmpReg, ResType, I, {ValueReg}, NegateOpcode);
1522 ValueReg = TmpReg;
1523 }
1524
1525 return Result &&
1526 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(NewOpcode))
1527 .addDef(ResVReg)
1528 .addUse(GR.getSPIRVTypeID(ResType))
1529 .addUse(Ptr)
1530 .addUse(ScopeReg)
1531 .addUse(MemSemReg)
1532 .addUse(ValueReg)
1533 .constrainAllUses(TII, TRI, RBI);
1534}
1535
1536bool SPIRVInstructionSelector::selectUnmergeValues(MachineInstr &I) const {
1537 unsigned ArgI = I.getNumOperands() - 1;
1538 Register SrcReg =
1539 I.getOperand(ArgI).isReg() ? I.getOperand(ArgI).getReg() : Register(0);
1540 SPIRVType *DefType =
1541 SrcReg.isValid() ? GR.getSPIRVTypeForVReg(SrcReg) : nullptr;
1542 if (!DefType || DefType->getOpcode() != SPIRV::OpTypeVector)
1544 "cannot select G_UNMERGE_VALUES with a non-vector argument");
1545
1546 SPIRVType *ScalarType =
1547 GR.getSPIRVTypeForVReg(DefType->getOperand(1).getReg());
1548 MachineBasicBlock &BB = *I.getParent();
1549 bool Res = false;
1550 for (unsigned i = 0; i < I.getNumDefs(); ++i) {
1551 Register ResVReg = I.getOperand(i).getReg();
1552 SPIRVType *ResType = GR.getSPIRVTypeForVReg(ResVReg);
1553 if (!ResType) {
1554 // There was no "assign type" actions, let's fix this now
1555 ResType = ScalarType;
1556 MRI->setRegClass(ResVReg, GR.getRegClass(ResType));
1557 MRI->setType(ResVReg, LLT::scalar(GR.getScalarOrVectorBitWidth(ResType)));
1558 GR.assignSPIRVTypeToVReg(ResType, ResVReg, *GR.CurMF);
1559 }
1560 auto MIB =
1561 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeExtract))
1562 .addDef(ResVReg)
1563 .addUse(GR.getSPIRVTypeID(ResType))
1564 .addUse(SrcReg)
1565 .addImm(static_cast<int64_t>(i));
1566 Res |= MIB.constrainAllUses(TII, TRI, RBI);
1567 }
1568 return Res;
1569}
1570
1571bool SPIRVInstructionSelector::selectFence(MachineInstr &I) const {
1572 AtomicOrdering AO = AtomicOrdering(I.getOperand(0).getImm());
1573 uint32_t MemSem = static_cast<uint32_t>(getMemSemantics(AO));
1574 auto MemSemConstant = buildI32Constant(MemSem, I);
1575 Register MemSemReg = MemSemConstant.first;
1576 bool Result = MemSemConstant.second;
1577 SyncScope::ID Ord = SyncScope::ID(I.getOperand(1).getImm());
1578 uint32_t Scope = static_cast<uint32_t>(
1579 getMemScope(GR.CurMF->getFunction().getContext(), Ord));
1580 auto ScopeConstant = buildI32Constant(Scope, I);
1581 Register ScopeReg = ScopeConstant.first;
1582 Result &= ScopeConstant.second;
1583 MachineBasicBlock &BB = *I.getParent();
1584 return Result &&
1585 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpMemoryBarrier))
1586 .addUse(ScopeReg)
1587 .addUse(MemSemReg)
1588 .constrainAllUses(TII, TRI, RBI);
1589}
1590
1591bool SPIRVInstructionSelector::selectOverflowArith(Register ResVReg,
1592 const SPIRVType *ResType,
1593 MachineInstr &I,
1594 unsigned Opcode) const {
1595 Type *ResTy = nullptr;
1596 StringRef ResName;
1597 if (!GR.findValueAttrs(&I, ResTy, ResName))
1599 "Not enough info to select the arithmetic with overflow instruction");
1600 if (!ResTy || !ResTy->isStructTy())
1601 report_fatal_error("Expect struct type result for the arithmetic "
1602 "with overflow instruction");
1603 // "Result Type must be from OpTypeStruct. The struct must have two members,
1604 // and the two members must be the same type."
1605 Type *ResElemTy = cast<StructType>(ResTy)->getElementType(0);
1606 ResTy = StructType::get(ResElemTy, ResElemTy);
1607 // Build SPIR-V types and constant(s) if needed.
1608 MachineIRBuilder MIRBuilder(I);
1609 SPIRVType *StructType = GR.getOrCreateSPIRVType(
1610 ResTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false);
1611 assert(I.getNumDefs() > 1 && "Not enought operands");
1612 SPIRVType *BoolType = GR.getOrCreateSPIRVBoolType(I, TII);
1613 unsigned N = GR.getScalarOrVectorComponentCount(ResType);
1614 if (N > 1)
1615 BoolType = GR.getOrCreateSPIRVVectorType(BoolType, N, I, TII);
1616 Register BoolTypeReg = GR.getSPIRVTypeID(BoolType);
1617 Register ZeroReg = buildZerosVal(ResType, I);
1618 // A new virtual register to store the result struct.
1619 Register StructVReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
1620 MRI->setRegClass(StructVReg, &SPIRV::IDRegClass);
1621 // Build the result name if needed.
1622 if (ResName.size() > 0)
1623 buildOpName(StructVReg, ResName, MIRBuilder);
1624 // Build the arithmetic with overflow instruction.
1625 MachineBasicBlock &BB = *I.getParent();
1626 auto MIB =
1627 BuildMI(BB, MIRBuilder.getInsertPt(), I.getDebugLoc(), TII.get(Opcode))
1628 .addDef(StructVReg)
1629 .addUse(GR.getSPIRVTypeID(StructType));
1630 for (unsigned i = I.getNumDefs(); i < I.getNumOperands(); ++i)
1631 MIB.addUse(I.getOperand(i).getReg());
1632 bool Result = MIB.constrainAllUses(TII, TRI, RBI);
1633 // Build instructions to extract fields of the instruction's result.
1634 // A new virtual register to store the higher part of the result struct.
1635 Register HigherVReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
1636 MRI->setRegClass(HigherVReg, &SPIRV::iIDRegClass);
1637 for (unsigned i = 0; i < I.getNumDefs(); ++i) {
1638 auto MIB =
1639 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeExtract))
1640 .addDef(i == 1 ? HigherVReg : I.getOperand(i).getReg())
1641 .addUse(GR.getSPIRVTypeID(ResType))
1642 .addUse(StructVReg)
1643 .addImm(i);
1644 Result &= MIB.constrainAllUses(TII, TRI, RBI);
1645 }
1646 // Build boolean value from the higher part.
1647 return Result && BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpINotEqual))
1648 .addDef(I.getOperand(1).getReg())
1649 .addUse(BoolTypeReg)
1650 .addUse(HigherVReg)
1651 .addUse(ZeroReg)
1652 .constrainAllUses(TII, TRI, RBI);
1653}
1654
1655bool SPIRVInstructionSelector::selectAtomicCmpXchg(Register ResVReg,
1656 const SPIRVType *ResType,
1657 MachineInstr &I) const {
1658 bool Result = true;
1659 Register ScopeReg;
1660 Register MemSemEqReg;
1661 Register MemSemNeqReg;
1662 Register Ptr = I.getOperand(2).getReg();
1663 if (!isa<GIntrinsic>(I)) {
1664 assert(I.hasOneMemOperand());
1665 const MachineMemOperand *MemOp = *I.memoperands_begin();
1666 unsigned Scope = static_cast<uint32_t>(getMemScope(
1667 GR.CurMF->getFunction().getContext(), MemOp->getSyncScopeID()));
1668 auto ScopeConstant = buildI32Constant(Scope, I);
1669 ScopeReg = ScopeConstant.first;
1670 Result &= ScopeConstant.second;
1671
1672 unsigned ScSem = static_cast<uint32_t>(
1674 AtomicOrdering AO = MemOp->getSuccessOrdering();
1675 unsigned MemSemEq = static_cast<uint32_t>(getMemSemantics(AO)) | ScSem;
1676 auto MemSemEqConstant = buildI32Constant(MemSemEq, I);
1677 MemSemEqReg = MemSemEqConstant.first;
1678 Result &= MemSemEqConstant.second;
1679 AtomicOrdering FO = MemOp->getFailureOrdering();
1680 unsigned MemSemNeq = static_cast<uint32_t>(getMemSemantics(FO)) | ScSem;
1681 if (MemSemEq == MemSemNeq)
1682 MemSemNeqReg = MemSemEqReg;
1683 else {
1684 auto MemSemNeqConstant = buildI32Constant(MemSemEq, I);
1685 MemSemNeqReg = MemSemNeqConstant.first;
1686 Result &= MemSemNeqConstant.second;
1687 }
1688 } else {
1689 ScopeReg = I.getOperand(5).getReg();
1690 MemSemEqReg = I.getOperand(6).getReg();
1691 MemSemNeqReg = I.getOperand(7).getReg();
1692 }
1693
1694 Register Cmp = I.getOperand(3).getReg();
1695 Register Val = I.getOperand(4).getReg();
1696 SPIRVType *SpvValTy = GR.getSPIRVTypeForVReg(Val);
1697 Register ACmpRes = createVirtualRegister(SpvValTy, &GR, MRI, *I.getMF());
1698 const DebugLoc &DL = I.getDebugLoc();
1699 Result &=
1700 BuildMI(*I.getParent(), I, DL, TII.get(SPIRV::OpAtomicCompareExchange))
1701 .addDef(ACmpRes)
1702 .addUse(GR.getSPIRVTypeID(SpvValTy))
1703 .addUse(Ptr)
1704 .addUse(ScopeReg)
1705 .addUse(MemSemEqReg)
1706 .addUse(MemSemNeqReg)
1707 .addUse(Val)
1708 .addUse(Cmp)
1709 .constrainAllUses(TII, TRI, RBI);
1710 SPIRVType *BoolTy = GR.getOrCreateSPIRVBoolType(I, TII);
1711 Register CmpSuccReg = createVirtualRegister(BoolTy, &GR, MRI, *I.getMF());
1712 Result &= BuildMI(*I.getParent(), I, DL, TII.get(SPIRV::OpIEqual))
1713 .addDef(CmpSuccReg)
1714 .addUse(GR.getSPIRVTypeID(BoolTy))
1715 .addUse(ACmpRes)
1716 .addUse(Cmp)
1717 .constrainAllUses(TII, TRI, RBI);
1718 Register TmpReg = createVirtualRegister(ResType, &GR, MRI, *I.getMF());
1719 Result &= BuildMI(*I.getParent(), I, DL, TII.get(SPIRV::OpCompositeInsert))
1720 .addDef(TmpReg)
1721 .addUse(GR.getSPIRVTypeID(ResType))
1722 .addUse(ACmpRes)
1723 .addUse(GR.getOrCreateUndef(I, ResType, TII))
1724 .addImm(0)
1725 .constrainAllUses(TII, TRI, RBI);
1726 return Result &&
1727 BuildMI(*I.getParent(), I, DL, TII.get(SPIRV::OpCompositeInsert))
1728 .addDef(ResVReg)
1729 .addUse(GR.getSPIRVTypeID(ResType))
1730 .addUse(CmpSuccReg)
1731 .addUse(TmpReg)
1732 .addImm(1)
1733 .constrainAllUses(TII, TRI, RBI);
1734}
1735
1736static bool isUSMStorageClass(SPIRV::StorageClass::StorageClass SC) {
1737 switch (SC) {
1738 case SPIRV::StorageClass::DeviceOnlyINTEL:
1739 case SPIRV::StorageClass::HostOnlyINTEL:
1740 return true;
1741 default:
1742 return false;
1743 }
1744}
1745
1746// Returns true ResVReg is referred only from global vars and OpName's.
1748 bool IsGRef = false;
1749 bool IsAllowedRefs =
1750 llvm::all_of(MRI->use_instructions(ResVReg), [&IsGRef](auto const &It) {
1751 unsigned Opcode = It.getOpcode();
1752 if (Opcode == SPIRV::OpConstantComposite ||
1753 Opcode == SPIRV::OpVariable ||
1754 isSpvIntrinsic(It, Intrinsic::spv_init_global))
1755 return IsGRef = true;
1756 return Opcode == SPIRV::OpName;
1757 });
1758 return IsAllowedRefs && IsGRef;
1759}
1760
1761Register SPIRVInstructionSelector::getUcharPtrTypeReg(
1762 MachineInstr &I, SPIRV::StorageClass::StorageClass SC) const {
1764 Type::getInt8Ty(I.getMF()->getFunction().getContext()), I, SC));
1765}
1766
1767MachineInstrBuilder
1768SPIRVInstructionSelector::buildSpecConstantOp(MachineInstr &I, Register Dest,
1769 Register Src, Register DestType,
1770 uint32_t Opcode) const {
1771 return BuildMI(*I.getParent(), I, I.getDebugLoc(),
1772 TII.get(SPIRV::OpSpecConstantOp))
1773 .addDef(Dest)
1774 .addUse(DestType)
1775 .addImm(Opcode)
1776 .addUse(Src);
1777}
1778
1779MachineInstrBuilder
1780SPIRVInstructionSelector::buildConstGenericPtr(MachineInstr &I, Register SrcPtr,
1781 SPIRVType *SrcPtrTy) const {
1782 SPIRVType *GenericPtrTy =
1783 GR.changePointerStorageClass(SrcPtrTy, SPIRV::StorageClass::Generic, I);
1784 Register Tmp = MRI->createVirtualRegister(&SPIRV::pIDRegClass);
1786 SPIRV::StorageClass::Generic),
1787 GR.getPointerSize()));
1788 MachineFunction *MF = I.getParent()->getParent();
1789 GR.assignSPIRVTypeToVReg(GenericPtrTy, Tmp, *MF);
1790 MachineInstrBuilder MIB = buildSpecConstantOp(
1791 I, Tmp, SrcPtr, GR.getSPIRVTypeID(GenericPtrTy),
1792 static_cast<uint32_t>(SPIRV::Opcode::PtrCastToGeneric));
1793 GR.add(MIB.getInstr(), MIB);
1794 return MIB;
1795}
1796
1797// In SPIR-V address space casting can only happen to and from the Generic
1798// storage class. We can also only cast Workgroup, CrossWorkgroup, or Function
1799// pointers to and from Generic pointers. As such, we can convert e.g. from
1800// Workgroup to Function by going via a Generic pointer as an intermediary. All
1801// other combinations can only be done by a bitcast, and are probably not safe.
1802bool SPIRVInstructionSelector::selectAddrSpaceCast(Register ResVReg,
1803 const SPIRVType *ResType,
1804 MachineInstr &I) const {
1805 MachineBasicBlock &BB = *I.getParent();
1806 const DebugLoc &DL = I.getDebugLoc();
1807
1808 Register SrcPtr = I.getOperand(1).getReg();
1809 SPIRVType *SrcPtrTy = GR.getSPIRVTypeForVReg(SrcPtr);
1810
1811 // don't generate a cast for a null that may be represented by OpTypeInt
1812 if (SrcPtrTy->getOpcode() != SPIRV::OpTypePointer ||
1813 ResType->getOpcode() != SPIRV::OpTypePointer)
1814 return BuildCOPY(ResVReg, SrcPtr, I);
1815
1816 SPIRV::StorageClass::StorageClass SrcSC = GR.getPointerStorageClass(SrcPtrTy);
1817 SPIRV::StorageClass::StorageClass DstSC = GR.getPointerStorageClass(ResType);
1818
1819 if (isASCastInGVar(MRI, ResVReg)) {
1820 // AddrSpaceCast uses within OpVariable and OpConstantComposite instructions
1821 // are expressed by OpSpecConstantOp with an Opcode.
1822 // TODO: maybe insert a check whether the Kernel capability was declared and
1823 // so PtrCastToGeneric/GenericCastToPtr are available.
1824 unsigned SpecOpcode =
1825 DstSC == SPIRV::StorageClass::Generic && isGenericCastablePtr(SrcSC)
1826 ? static_cast<uint32_t>(SPIRV::Opcode::PtrCastToGeneric)
1827 : (SrcSC == SPIRV::StorageClass::Generic &&
1829 ? static_cast<uint32_t>(SPIRV::Opcode::GenericCastToPtr)
1830 : 0);
1831 // TODO: OpConstantComposite expects i8*, so we are forced to forget a
1832 // correct value of ResType and use general i8* instead. Maybe this should
1833 // be addressed in the emit-intrinsic step to infer a correct
1834 // OpConstantComposite type.
1835 if (SpecOpcode) {
1836 return buildSpecConstantOp(I, ResVReg, SrcPtr,
1837 getUcharPtrTypeReg(I, DstSC), SpecOpcode)
1838 .constrainAllUses(TII, TRI, RBI);
1839 } else if (isGenericCastablePtr(SrcSC) && isGenericCastablePtr(DstSC)) {
1840 MachineInstrBuilder MIB = buildConstGenericPtr(I, SrcPtr, SrcPtrTy);
1841 return MIB.constrainAllUses(TII, TRI, RBI) &&
1842 buildSpecConstantOp(
1843 I, ResVReg, MIB->getOperand(0).getReg(),
1844 getUcharPtrTypeReg(I, DstSC),
1845 static_cast<uint32_t>(SPIRV::Opcode::GenericCastToPtr))
1846 .constrainAllUses(TII, TRI, RBI);
1847 }
1848 }
1849
1850 // don't generate a cast between identical storage classes
1851 if (SrcSC == DstSC)
1852 return BuildCOPY(ResVReg, SrcPtr, I);
1853
1854 if ((SrcSC == SPIRV::StorageClass::Function &&
1855 DstSC == SPIRV::StorageClass::Private) ||
1856 (DstSC == SPIRV::StorageClass::Function &&
1857 SrcSC == SPIRV::StorageClass::Private))
1858 return BuildCOPY(ResVReg, SrcPtr, I);
1859
1860 // Casting from an eligible pointer to Generic.
1861 if (DstSC == SPIRV::StorageClass::Generic && isGenericCastablePtr(SrcSC))
1862 return selectUnOp(ResVReg, ResType, I, SPIRV::OpPtrCastToGeneric);
1863 // Casting from Generic to an eligible pointer.
1864 if (SrcSC == SPIRV::StorageClass::Generic && isGenericCastablePtr(DstSC))
1865 return selectUnOp(ResVReg, ResType, I, SPIRV::OpGenericCastToPtr);
1866 // Casting between 2 eligible pointers using Generic as an intermediary.
1867 if (isGenericCastablePtr(SrcSC) && isGenericCastablePtr(DstSC)) {
1868 SPIRVType *GenericPtrTy =
1869 GR.changePointerStorageClass(SrcPtrTy, SPIRV::StorageClass::Generic, I);
1870 Register Tmp = createVirtualRegister(GenericPtrTy, &GR, MRI, MRI->getMF());
1871 bool Result = BuildMI(BB, I, DL, TII.get(SPIRV::OpPtrCastToGeneric))
1872 .addDef(Tmp)
1873 .addUse(GR.getSPIRVTypeID(GenericPtrTy))
1874 .addUse(SrcPtr)
1875 .constrainAllUses(TII, TRI, RBI);
1876 return Result && BuildMI(BB, I, DL, TII.get(SPIRV::OpGenericCastToPtr))
1877 .addDef(ResVReg)
1878 .addUse(GR.getSPIRVTypeID(ResType))
1879 .addUse(Tmp)
1880 .constrainAllUses(TII, TRI, RBI);
1881 }
1882
1883 // Check if instructions from the SPV_INTEL_usm_storage_classes extension may
1884 // be applied
1885 if (isUSMStorageClass(SrcSC) && DstSC == SPIRV::StorageClass::CrossWorkgroup)
1886 return selectUnOp(ResVReg, ResType, I,
1887 SPIRV::OpPtrCastToCrossWorkgroupINTEL);
1888 if (SrcSC == SPIRV::StorageClass::CrossWorkgroup && isUSMStorageClass(DstSC))
1889 return selectUnOp(ResVReg, ResType, I,
1890 SPIRV::OpCrossWorkgroupCastToPtrINTEL);
1891 if (isUSMStorageClass(SrcSC) && DstSC == SPIRV::StorageClass::Generic)
1892 return selectUnOp(ResVReg, ResType, I, SPIRV::OpPtrCastToGeneric);
1893 if (SrcSC == SPIRV::StorageClass::Generic && isUSMStorageClass(DstSC))
1894 return selectUnOp(ResVReg, ResType, I, SPIRV::OpGenericCastToPtr);
1895
1896 // Bitcast for pointers requires that the address spaces must match
1897 return false;
1898}
1899
1900static unsigned getFCmpOpcode(unsigned PredNum) {
1901 auto Pred = static_cast<CmpInst::Predicate>(PredNum);
1902 switch (Pred) {
1903 case CmpInst::FCMP_OEQ:
1904 return SPIRV::OpFOrdEqual;
1905 case CmpInst::FCMP_OGE:
1906 return SPIRV::OpFOrdGreaterThanEqual;
1907 case CmpInst::FCMP_OGT:
1908 return SPIRV::OpFOrdGreaterThan;
1909 case CmpInst::FCMP_OLE:
1910 return SPIRV::OpFOrdLessThanEqual;
1911 case CmpInst::FCMP_OLT:
1912 return SPIRV::OpFOrdLessThan;
1913 case CmpInst::FCMP_ONE:
1914 return SPIRV::OpFOrdNotEqual;
1915 case CmpInst::FCMP_ORD:
1916 return SPIRV::OpOrdered;
1917 case CmpInst::FCMP_UEQ:
1918 return SPIRV::OpFUnordEqual;
1919 case CmpInst::FCMP_UGE:
1920 return SPIRV::OpFUnordGreaterThanEqual;
1921 case CmpInst::FCMP_UGT:
1922 return SPIRV::OpFUnordGreaterThan;
1923 case CmpInst::FCMP_ULE:
1924 return SPIRV::OpFUnordLessThanEqual;
1925 case CmpInst::FCMP_ULT:
1926 return SPIRV::OpFUnordLessThan;
1927 case CmpInst::FCMP_UNE:
1928 return SPIRV::OpFUnordNotEqual;
1929 case CmpInst::FCMP_UNO:
1930 return SPIRV::OpUnordered;
1931 default:
1932 llvm_unreachable("Unknown predicate type for FCmp");
1933 }
1934}
1935
1936static unsigned getICmpOpcode(unsigned PredNum) {
1937 auto Pred = static_cast<CmpInst::Predicate>(PredNum);
1938 switch (Pred) {
1939 case CmpInst::ICMP_EQ:
1940 return SPIRV::OpIEqual;
1941 case CmpInst::ICMP_NE:
1942 return SPIRV::OpINotEqual;
1943 case CmpInst::ICMP_SGE:
1944 return SPIRV::OpSGreaterThanEqual;
1945 case CmpInst::ICMP_SGT:
1946 return SPIRV::OpSGreaterThan;
1947 case CmpInst::ICMP_SLE:
1948 return SPIRV::OpSLessThanEqual;
1949 case CmpInst::ICMP_SLT:
1950 return SPIRV::OpSLessThan;
1951 case CmpInst::ICMP_UGE:
1952 return SPIRV::OpUGreaterThanEqual;
1953 case CmpInst::ICMP_UGT:
1954 return SPIRV::OpUGreaterThan;
1955 case CmpInst::ICMP_ULE:
1956 return SPIRV::OpULessThanEqual;
1957 case CmpInst::ICMP_ULT:
1958 return SPIRV::OpULessThan;
1959 default:
1960 llvm_unreachable("Unknown predicate type for ICmp");
1961 }
1962}
1963
1964static unsigned getPtrCmpOpcode(unsigned Pred) {
1965 switch (static_cast<CmpInst::Predicate>(Pred)) {
1966 case CmpInst::ICMP_EQ:
1967 return SPIRV::OpPtrEqual;
1968 case CmpInst::ICMP_NE:
1969 return SPIRV::OpPtrNotEqual;
1970 default:
1971 llvm_unreachable("Unknown predicate type for pointer comparison");
1972 }
1973}
1974
1975// Return the logical operation, or abort if none exists.
1976static unsigned getBoolCmpOpcode(unsigned PredNum) {
1977 auto Pred = static_cast<CmpInst::Predicate>(PredNum);
1978 switch (Pred) {
1979 case CmpInst::ICMP_EQ:
1980 return SPIRV::OpLogicalEqual;
1981 case CmpInst::ICMP_NE:
1982 return SPIRV::OpLogicalNotEqual;
1983 default:
1984 llvm_unreachable("Unknown predicate type for Bool comparison");
1985 }
1986}
1987
1988static APFloat getZeroFP(const Type *LLVMFloatTy) {
1989 if (!LLVMFloatTy)
1991 switch (LLVMFloatTy->getScalarType()->getTypeID()) {
1992 case Type::HalfTyID:
1994 default:
1995 case Type::FloatTyID:
1997 case Type::DoubleTyID:
1999 }
2000}
2001
2002static APFloat getOneFP(const Type *LLVMFloatTy) {
2003 if (!LLVMFloatTy)
2005 switch (LLVMFloatTy->getScalarType()->getTypeID()) {
2006 case Type::HalfTyID:
2008 default:
2009 case Type::FloatTyID:
2011 case Type::DoubleTyID:
2013 }
2014}
2015
2016bool SPIRVInstructionSelector::selectAnyOrAll(Register ResVReg,
2017 const SPIRVType *ResType,
2018 MachineInstr &I,
2019 unsigned OpAnyOrAll) const {
2020 assert(I.getNumOperands() == 3);
2021 assert(I.getOperand(2).isReg());
2022 MachineBasicBlock &BB = *I.getParent();
2023 Register InputRegister = I.getOperand(2).getReg();
2024 SPIRVType *InputType = GR.getSPIRVTypeForVReg(InputRegister);
2025
2026 if (!InputType)
2027 report_fatal_error("Input Type could not be determined.");
2028
2029 bool IsBoolTy = GR.isScalarOrVectorOfType(InputRegister, SPIRV::OpTypeBool);
2030 bool IsVectorTy = InputType->getOpcode() == SPIRV::OpTypeVector;
2031 if (IsBoolTy && !IsVectorTy) {
2032 assert(ResVReg == I.getOperand(0).getReg());
2033 return BuildCOPY(ResVReg, InputRegister, I);
2034 }
2035
2036 bool IsFloatTy = GR.isScalarOrVectorOfType(InputRegister, SPIRV::OpTypeFloat);
2037 unsigned SpirvNotEqualId =
2038 IsFloatTy ? SPIRV::OpFOrdNotEqual : SPIRV::OpINotEqual;
2039 SPIRVType *SpvBoolScalarTy = GR.getOrCreateSPIRVBoolType(I, TII);
2040 SPIRVType *SpvBoolTy = SpvBoolScalarTy;
2041 Register NotEqualReg = ResVReg;
2042
2043 if (IsVectorTy) {
2044 NotEqualReg =
2045 IsBoolTy ? InputRegister
2046 : createVirtualRegister(SpvBoolTy, &GR, MRI, MRI->getMF());
2047 const unsigned NumElts = InputType->getOperand(2).getImm();
2048 SpvBoolTy = GR.getOrCreateSPIRVVectorType(SpvBoolTy, NumElts, I, TII);
2049 }
2050
2051 bool Result = true;
2052 if (!IsBoolTy) {
2053 Register ConstZeroReg =
2054 IsFloatTy ? buildZerosValF(InputType, I) : buildZerosVal(InputType, I);
2055
2056 Result &= BuildMI(BB, I, I.getDebugLoc(), TII.get(SpirvNotEqualId))
2057 .addDef(NotEqualReg)
2058 .addUse(GR.getSPIRVTypeID(SpvBoolTy))
2059 .addUse(InputRegister)
2060 .addUse(ConstZeroReg)
2061 .constrainAllUses(TII, TRI, RBI);
2062 }
2063
2064 if (!IsVectorTy)
2065 return Result;
2066
2067 return Result && BuildMI(BB, I, I.getDebugLoc(), TII.get(OpAnyOrAll))
2068 .addDef(ResVReg)
2069 .addUse(GR.getSPIRVTypeID(SpvBoolScalarTy))
2070 .addUse(NotEqualReg)
2071 .constrainAllUses(TII, TRI, RBI);
2072}
2073
2074bool SPIRVInstructionSelector::selectAll(Register ResVReg,
2075 const SPIRVType *ResType,
2076 MachineInstr &I) const {
2077 return selectAnyOrAll(ResVReg, ResType, I, SPIRV::OpAll);
2078}
2079
2080bool SPIRVInstructionSelector::selectAny(Register ResVReg,
2081 const SPIRVType *ResType,
2082 MachineInstr &I) const {
2083 return selectAnyOrAll(ResVReg, ResType, I, SPIRV::OpAny);
2084}
2085
2086// Select the OpDot instruction for the given float dot
2087bool SPIRVInstructionSelector::selectFloatDot(Register ResVReg,
2088 const SPIRVType *ResType,
2089 MachineInstr &I) const {
2090 assert(I.getNumOperands() == 4);
2091 assert(I.getOperand(2).isReg());
2092 assert(I.getOperand(3).isReg());
2093
2094 [[maybe_unused]] SPIRVType *VecType =
2095 GR.getSPIRVTypeForVReg(I.getOperand(2).getReg());
2096
2097 assert(VecType->getOpcode() == SPIRV::OpTypeVector &&
2098 GR.getScalarOrVectorComponentCount(VecType) > 1 &&
2099 "dot product requires a vector of at least 2 components");
2100
2101 [[maybe_unused]] SPIRVType *EltType =
2102 GR.getSPIRVTypeForVReg(VecType->getOperand(1).getReg());
2103
2104 assert(EltType->getOpcode() == SPIRV::OpTypeFloat);
2105
2106 MachineBasicBlock &BB = *I.getParent();
2107 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpDot))
2108 .addDef(ResVReg)
2109 .addUse(GR.getSPIRVTypeID(ResType))
2110 .addUse(I.getOperand(2).getReg())
2111 .addUse(I.getOperand(3).getReg())
2112 .constrainAllUses(TII, TRI, RBI);
2113}
2114
2115bool SPIRVInstructionSelector::selectIntegerDot(Register ResVReg,
2116 const SPIRVType *ResType,
2117 MachineInstr &I,
2118 bool Signed) const {
2119 assert(I.getNumOperands() == 4);
2120 assert(I.getOperand(2).isReg());
2121 assert(I.getOperand(3).isReg());
2122 MachineBasicBlock &BB = *I.getParent();
2123
2124 auto DotOp = Signed ? SPIRV::OpSDot : SPIRV::OpUDot;
2125 return BuildMI(BB, I, I.getDebugLoc(), TII.get(DotOp))
2126 .addDef(ResVReg)
2127 .addUse(GR.getSPIRVTypeID(ResType))
2128 .addUse(I.getOperand(2).getReg())
2129 .addUse(I.getOperand(3).getReg())
2130 .constrainAllUses(TII, TRI, RBI);
2131}
2132
2133// Since pre-1.6 SPIRV has no integer dot implementation,
2134// expand by piecewise multiplying and adding the results
2135bool SPIRVInstructionSelector::selectIntegerDotExpansion(
2136 Register ResVReg, const SPIRVType *ResType, MachineInstr &I) const {
2137 assert(I.getNumOperands() == 4);
2138 assert(I.getOperand(2).isReg());
2139 assert(I.getOperand(3).isReg());
2140 MachineBasicBlock &BB = *I.getParent();
2141
2142 // Multiply the vectors, then sum the results
2143 Register Vec0 = I.getOperand(2).getReg();
2144 Register Vec1 = I.getOperand(3).getReg();
2145 Register TmpVec = MRI->createVirtualRegister(GR.getRegClass(ResType));
2146 SPIRVType *VecType = GR.getSPIRVTypeForVReg(Vec0);
2147
2148 bool Result = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpIMulV))
2149 .addDef(TmpVec)
2150 .addUse(GR.getSPIRVTypeID(VecType))
2151 .addUse(Vec0)
2152 .addUse(Vec1)
2153 .constrainAllUses(TII, TRI, RBI);
2154
2155 assert(VecType->getOpcode() == SPIRV::OpTypeVector &&
2156 GR.getScalarOrVectorComponentCount(VecType) > 1 &&
2157 "dot product requires a vector of at least 2 components");
2158
2159 Register Res = MRI->createVirtualRegister(GR.getRegClass(ResType));
2160 Result &= BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeExtract))
2161 .addDef(Res)
2162 .addUse(GR.getSPIRVTypeID(ResType))
2163 .addUse(TmpVec)
2164 .addImm(0)
2165 .constrainAllUses(TII, TRI, RBI);
2166
2167 for (unsigned i = 1; i < GR.getScalarOrVectorComponentCount(VecType); i++) {
2168 Register Elt = MRI->createVirtualRegister(GR.getRegClass(ResType));
2169
2170 Result &=
2171 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeExtract))
2172 .addDef(Elt)
2173 .addUse(GR.getSPIRVTypeID(ResType))
2174 .addUse(TmpVec)
2175 .addImm(i)
2176 .constrainAllUses(TII, TRI, RBI);
2177
2178 Register Sum = i < GR.getScalarOrVectorComponentCount(VecType) - 1
2179 ? MRI->createVirtualRegister(GR.getRegClass(ResType))
2180 : ResVReg;
2181
2182 Result &= BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpIAddS))
2183 .addDef(Sum)
2184 .addUse(GR.getSPIRVTypeID(ResType))
2185 .addUse(Res)
2186 .addUse(Elt)
2187 .constrainAllUses(TII, TRI, RBI);
2188 Res = Sum;
2189 }
2190
2191 return Result;
2192}
2193
2194bool SPIRVInstructionSelector::selectOpIsInf(Register ResVReg,
2195 const SPIRVType *ResType,
2196 MachineInstr &I) const {
2197 MachineBasicBlock &BB = *I.getParent();
2198 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpIsInf))
2199 .addDef(ResVReg)
2200 .addUse(GR.getSPIRVTypeID(ResType))
2201 .addUse(I.getOperand(2).getReg())
2202 .constrainAllUses(TII, TRI, RBI);
2203}
2204
2205bool SPIRVInstructionSelector::selectOpIsNan(Register ResVReg,
2206 const SPIRVType *ResType,
2207 MachineInstr &I) const {
2208 MachineBasicBlock &BB = *I.getParent();
2209 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpIsNan))
2210 .addDef(ResVReg)
2211 .addUse(GR.getSPIRVTypeID(ResType))
2212 .addUse(I.getOperand(2).getReg())
2213 .constrainAllUses(TII, TRI, RBI);
2214}
2215
2216template <bool Signed>
2217bool SPIRVInstructionSelector::selectDot4AddPacked(Register ResVReg,
2218 const SPIRVType *ResType,
2219 MachineInstr &I) const {
2220 assert(I.getNumOperands() == 5);
2221 assert(I.getOperand(2).isReg());
2222 assert(I.getOperand(3).isReg());
2223 assert(I.getOperand(4).isReg());
2224 MachineBasicBlock &BB = *I.getParent();
2225
2226 Register Acc = I.getOperand(2).getReg();
2227 Register X = I.getOperand(3).getReg();
2228 Register Y = I.getOperand(4).getReg();
2229
2230 auto DotOp = Signed ? SPIRV::OpSDot : SPIRV::OpUDot;
2231 Register Dot = MRI->createVirtualRegister(GR.getRegClass(ResType));
2232 bool Result = BuildMI(BB, I, I.getDebugLoc(), TII.get(DotOp))
2233 .addDef(Dot)
2234 .addUse(GR.getSPIRVTypeID(ResType))
2235 .addUse(X)
2236 .addUse(Y)
2237 .constrainAllUses(TII, TRI, RBI);
2238
2239 return Result && BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpIAddS))
2240 .addDef(ResVReg)
2241 .addUse(GR.getSPIRVTypeID(ResType))
2242 .addUse(Dot)
2243 .addUse(Acc)
2244 .constrainAllUses(TII, TRI, RBI);
2245}
2246
2247// Since pre-1.6 SPIRV has no DotProductInput4x8BitPacked implementation,
2248// extract the elements of the packed inputs, multiply them and add the result
2249// to the accumulator.
2250template <bool Signed>
2251bool SPIRVInstructionSelector::selectDot4AddPackedExpansion(
2252 Register ResVReg, const SPIRVType *ResType, MachineInstr &I) const {
2253 assert(I.getNumOperands() == 5);
2254 assert(I.getOperand(2).isReg());
2255 assert(I.getOperand(3).isReg());
2256 assert(I.getOperand(4).isReg());
2257 MachineBasicBlock &BB = *I.getParent();
2258
2259 bool Result = true;
2260
2261 Register Acc = I.getOperand(2).getReg();
2262 Register X = I.getOperand(3).getReg();
2263 Register Y = I.getOperand(4).getReg();
2264
2265 SPIRVType *EltType = GR.getOrCreateSPIRVIntegerType(8, I, TII);
2266 auto ExtractOp =
2267 Signed ? SPIRV::OpBitFieldSExtract : SPIRV::OpBitFieldUExtract;
2268
2269 bool ZeroAsNull = !STI.isShader();
2270 // Extract the i8 element, multiply and add it to the accumulator
2271 for (unsigned i = 0; i < 4; i++) {
2272 // A[i]
2273 Register AElt = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2274 Result &=
2275 BuildMI(BB, I, I.getDebugLoc(), TII.get(ExtractOp))
2276 .addDef(AElt)
2277 .addUse(GR.getSPIRVTypeID(ResType))
2278 .addUse(X)
2279 .addUse(GR.getOrCreateConstInt(i * 8, I, EltType, TII, ZeroAsNull))
2280 .addUse(GR.getOrCreateConstInt(8, I, EltType, TII, ZeroAsNull))
2281 .constrainAllUses(TII, TRI, RBI);
2282
2283 // B[i]
2284 Register BElt = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2285 Result &=
2286 BuildMI(BB, I, I.getDebugLoc(), TII.get(ExtractOp))
2287 .addDef(BElt)
2288 .addUse(GR.getSPIRVTypeID(ResType))
2289 .addUse(Y)
2290 .addUse(GR.getOrCreateConstInt(i * 8, I, EltType, TII, ZeroAsNull))
2291 .addUse(GR.getOrCreateConstInt(8, I, EltType, TII, ZeroAsNull))
2292 .constrainAllUses(TII, TRI, RBI);
2293
2294 // A[i] * B[i]
2295 Register Mul = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2296 Result &= BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpIMulS))
2297 .addDef(Mul)
2298 .addUse(GR.getSPIRVTypeID(ResType))
2299 .addUse(AElt)
2300 .addUse(BElt)
2301 .constrainAllUses(TII, TRI, RBI);
2302
2303 // Discard 24 highest-bits so that stored i32 register is i8 equivalent
2304 Register MaskMul = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2305 Result &=
2306 BuildMI(BB, I, I.getDebugLoc(), TII.get(ExtractOp))
2307 .addDef(MaskMul)
2308 .addUse(GR.getSPIRVTypeID(ResType))
2309 .addUse(Mul)
2310 .addUse(GR.getOrCreateConstInt(0, I, EltType, TII, ZeroAsNull))
2311 .addUse(GR.getOrCreateConstInt(8, I, EltType, TII, ZeroAsNull))
2312 .constrainAllUses(TII, TRI, RBI);
2313
2314 // Acc = Acc + A[i] * B[i]
2315 Register Sum =
2316 i < 3 ? MRI->createVirtualRegister(&SPIRV::IDRegClass) : ResVReg;
2317 Result &= BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpIAddS))
2318 .addDef(Sum)
2319 .addUse(GR.getSPIRVTypeID(ResType))
2320 .addUse(Acc)
2321 .addUse(MaskMul)
2322 .constrainAllUses(TII, TRI, RBI);
2323
2324 Acc = Sum;
2325 }
2326
2327 return Result;
2328}
2329
2330/// Transform saturate(x) to clamp(x, 0.0f, 1.0f) as SPIRV
2331/// does not have a saturate builtin.
2332bool SPIRVInstructionSelector::selectSaturate(Register ResVReg,
2333 const SPIRVType *ResType,
2334 MachineInstr &I) const {
2335 assert(I.getNumOperands() == 3);
2336 assert(I.getOperand(2).isReg());
2337 MachineBasicBlock &BB = *I.getParent();
2338 Register VZero = buildZerosValF(ResType, I);
2339 Register VOne = buildOnesValF(ResType, I);
2340
2341 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpExtInst))
2342 .addDef(ResVReg)
2343 .addUse(GR.getSPIRVTypeID(ResType))
2344 .addImm(static_cast<uint32_t>(SPIRV::InstructionSet::GLSL_std_450))
2345 .addImm(GL::FClamp)
2346 .addUse(I.getOperand(2).getReg())
2347 .addUse(VZero)
2348 .addUse(VOne)
2349 .constrainAllUses(TII, TRI, RBI);
2350}
2351
2352bool SPIRVInstructionSelector::selectSign(Register ResVReg,
2353 const SPIRVType *ResType,
2354 MachineInstr &I) const {
2355 assert(I.getNumOperands() == 3);
2356 assert(I.getOperand(2).isReg());
2357 MachineBasicBlock &BB = *I.getParent();
2358 Register InputRegister = I.getOperand(2).getReg();
2359 SPIRVType *InputType = GR.getSPIRVTypeForVReg(InputRegister);
2360 auto &DL = I.getDebugLoc();
2361
2362 if (!InputType)
2363 report_fatal_error("Input Type could not be determined.");
2364
2365 bool IsFloatTy = GR.isScalarOrVectorOfType(InputRegister, SPIRV::OpTypeFloat);
2366
2367 unsigned SignBitWidth = GR.getScalarOrVectorBitWidth(InputType);
2368 unsigned ResBitWidth = GR.getScalarOrVectorBitWidth(ResType);
2369
2370 bool NeedsConversion = IsFloatTy || SignBitWidth != ResBitWidth;
2371
2372 auto SignOpcode = IsFloatTy ? GL::FSign : GL::SSign;
2373 Register SignReg = NeedsConversion
2374 ? MRI->createVirtualRegister(&SPIRV::IDRegClass)
2375 : ResVReg;
2376
2377 bool Result =
2378 BuildMI(BB, I, DL, TII.get(SPIRV::OpExtInst))
2379 .addDef(SignReg)
2380 .addUse(GR.getSPIRVTypeID(InputType))
2381 .addImm(static_cast<uint32_t>(SPIRV::InstructionSet::GLSL_std_450))
2382 .addImm(SignOpcode)
2383 .addUse(InputRegister)
2384 .constrainAllUses(TII, TRI, RBI);
2385
2386 if (NeedsConversion) {
2387 auto ConvertOpcode = IsFloatTy ? SPIRV::OpConvertFToS : SPIRV::OpSConvert;
2388 Result &= BuildMI(*I.getParent(), I, DL, TII.get(ConvertOpcode))
2389 .addDef(ResVReg)
2390 .addUse(GR.getSPIRVTypeID(ResType))
2391 .addUse(SignReg)
2392 .constrainAllUses(TII, TRI, RBI);
2393 }
2394
2395 return Result;
2396}
2397
2398bool SPIRVInstructionSelector::selectWaveOpInst(Register ResVReg,
2399 const SPIRVType *ResType,
2400 MachineInstr &I,
2401 unsigned Opcode) const {
2402 MachineBasicBlock &BB = *I.getParent();
2403 SPIRVType *IntTy = GR.getOrCreateSPIRVIntegerType(32, I, TII);
2404
2405 auto BMI = BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
2406 .addDef(ResVReg)
2407 .addUse(GR.getSPIRVTypeID(ResType))
2408 .addUse(GR.getOrCreateConstInt(SPIRV::Scope::Subgroup, I,
2409 IntTy, TII, !STI.isShader()));
2410
2411 for (unsigned J = 2; J < I.getNumOperands(); J++) {
2412 BMI.addUse(I.getOperand(J).getReg());
2413 }
2414
2415 return BMI.constrainAllUses(TII, TRI, RBI);
2416}
2417
2418bool SPIRVInstructionSelector::selectWaveActiveCountBits(
2419 Register ResVReg, const SPIRVType *ResType, MachineInstr &I) const {
2420
2421 SPIRVType *IntTy = GR.getOrCreateSPIRVIntegerType(32, I, TII);
2422 SPIRVType *BallotType = GR.getOrCreateSPIRVVectorType(IntTy, 4, I, TII);
2423 Register BallotReg = MRI->createVirtualRegister(GR.getRegClass(BallotType));
2424 bool Result = selectWaveOpInst(BallotReg, BallotType, I,
2425 SPIRV::OpGroupNonUniformBallot);
2426
2427 MachineBasicBlock &BB = *I.getParent();
2428 Result &= BuildMI(BB, I, I.getDebugLoc(),
2429 TII.get(SPIRV::OpGroupNonUniformBallotBitCount))
2430 .addDef(ResVReg)
2431 .addUse(GR.getSPIRVTypeID(ResType))
2432 .addUse(GR.getOrCreateConstInt(SPIRV::Scope::Subgroup, I, IntTy,
2433 TII, !STI.isShader()))
2434 .addImm(SPIRV::GroupOperation::Reduce)
2435 .addUse(BallotReg)
2436 .constrainAllUses(TII, TRI, RBI);
2437
2438 return Result;
2439}
2440
2441bool SPIRVInstructionSelector::selectWaveReduceMax(Register ResVReg,
2442 const SPIRVType *ResType,
2443 MachineInstr &I,
2444 bool IsUnsigned) const {
2445 assert(I.getNumOperands() == 3);
2446 assert(I.getOperand(2).isReg());
2447 MachineBasicBlock &BB = *I.getParent();
2448 Register InputRegister = I.getOperand(2).getReg();
2449 SPIRVType *InputType = GR.getSPIRVTypeForVReg(InputRegister);
2450
2451 if (!InputType)
2452 report_fatal_error("Input Type could not be determined.");
2453
2454 SPIRVType *IntTy = GR.getOrCreateSPIRVIntegerType(32, I, TII);
2455 // Retreive the operation to use based on input type
2456 bool IsFloatTy = GR.isScalarOrVectorOfType(InputRegister, SPIRV::OpTypeFloat);
2457 auto IntegerOpcodeType =
2458 IsUnsigned ? SPIRV::OpGroupNonUniformUMax : SPIRV::OpGroupNonUniformSMax;
2459 auto Opcode = IsFloatTy ? SPIRV::OpGroupNonUniformFMax : IntegerOpcodeType;
2460 return BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
2461 .addDef(ResVReg)
2462 .addUse(GR.getSPIRVTypeID(ResType))
2463 .addUse(GR.getOrCreateConstInt(SPIRV::Scope::Subgroup, I, IntTy, TII,
2464 !STI.isShader()))
2465 .addImm(SPIRV::GroupOperation::Reduce)
2466 .addUse(I.getOperand(2).getReg())
2467 .constrainAllUses(TII, TRI, RBI);
2468}
2469
2470bool SPIRVInstructionSelector::selectWaveReduceMin(Register ResVReg,
2471 const SPIRVType *ResType,
2472 MachineInstr &I,
2473 bool IsUnsigned) const {
2474 assert(I.getNumOperands() == 3);
2475 assert(I.getOperand(2).isReg());
2476 MachineBasicBlock &BB = *I.getParent();
2477 Register InputRegister = I.getOperand(2).getReg();
2478 SPIRVType *InputType = GR.getSPIRVTypeForVReg(InputRegister);
2479
2480 if (!InputType)
2481 report_fatal_error("Input Type could not be determined.");
2482
2483 SPIRVType *IntTy = GR.getOrCreateSPIRVIntegerType(32, I, TII);
2484 // Retreive the operation to use based on input type
2485 bool IsFloatTy = GR.isScalarOrVectorOfType(InputRegister, SPIRV::OpTypeFloat);
2486 auto IntegerOpcodeType =
2487 IsUnsigned ? SPIRV::OpGroupNonUniformUMin : SPIRV::OpGroupNonUniformSMin;
2488 auto Opcode = IsFloatTy ? SPIRV::OpGroupNonUniformFMin : IntegerOpcodeType;
2489 return BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
2490 .addDef(ResVReg)
2491 .addUse(GR.getSPIRVTypeID(ResType))
2492 .addUse(GR.getOrCreateConstInt(SPIRV::Scope::Subgroup, I, IntTy, TII,
2493 !STI.isShader()))
2494 .addImm(SPIRV::GroupOperation::Reduce)
2495 .addUse(I.getOperand(2).getReg())
2496 .constrainAllUses(TII, TRI, RBI);
2497}
2498
2499bool SPIRVInstructionSelector::selectWaveReduceSum(Register ResVReg,
2500 const SPIRVType *ResType,
2501 MachineInstr &I) const {
2502 assert(I.getNumOperands() == 3);
2503 assert(I.getOperand(2).isReg());
2504 MachineBasicBlock &BB = *I.getParent();
2505 Register InputRegister = I.getOperand(2).getReg();
2506 SPIRVType *InputType = GR.getSPIRVTypeForVReg(InputRegister);
2507
2508 if (!InputType)
2509 report_fatal_error("Input Type could not be determined.");
2510
2511 SPIRVType *IntTy = GR.getOrCreateSPIRVIntegerType(32, I, TII);
2512 // Retreive the operation to use based on input type
2513 bool IsFloatTy = GR.isScalarOrVectorOfType(InputRegister, SPIRV::OpTypeFloat);
2514 auto Opcode =
2515 IsFloatTy ? SPIRV::OpGroupNonUniformFAdd : SPIRV::OpGroupNonUniformIAdd;
2516 return BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
2517 .addDef(ResVReg)
2518 .addUse(GR.getSPIRVTypeID(ResType))
2519 .addUse(GR.getOrCreateConstInt(SPIRV::Scope::Subgroup, I, IntTy, TII,
2520 !STI.isShader()))
2521 .addImm(SPIRV::GroupOperation::Reduce)
2522 .addUse(I.getOperand(2).getReg());
2523}
2524
2525bool SPIRVInstructionSelector::selectBitreverse(Register ResVReg,
2526 const SPIRVType *ResType,
2527 MachineInstr &I) const {
2528 MachineBasicBlock &BB = *I.getParent();
2529 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpBitReverse))
2530 .addDef(ResVReg)
2531 .addUse(GR.getSPIRVTypeID(ResType))
2532 .addUse(I.getOperand(1).getReg())
2533 .constrainAllUses(TII, TRI, RBI);
2534}
2535
2536bool SPIRVInstructionSelector::selectFreeze(Register ResVReg,
2537 const SPIRVType *ResType,
2538 MachineInstr &I) const {
2539 // There is no way to implement `freeze` correctly without support on SPIR-V
2540 // standard side, but we may at least address a simple (static) case when
2541 // undef/poison value presence is obvious. The main benefit of even
2542 // incomplete `freeze` support is preventing of translation from crashing due
2543 // to lack of support on legalization and instruction selection steps.
2544 if (!I.getOperand(0).isReg() || !I.getOperand(1).isReg())
2545 return false;
2546 Register OpReg = I.getOperand(1).getReg();
2547 if (MachineInstr *Def = MRI->getVRegDef(OpReg)) {
2548 if (Def->getOpcode() == TargetOpcode::COPY)
2549 Def = MRI->getVRegDef(Def->getOperand(1).getReg());
2550 Register Reg;
2551 switch (Def->getOpcode()) {
2552 case SPIRV::ASSIGN_TYPE:
2553 if (MachineInstr *AssignToDef =
2554 MRI->getVRegDef(Def->getOperand(1).getReg())) {
2555 if (AssignToDef->getOpcode() == TargetOpcode::G_IMPLICIT_DEF)
2556 Reg = Def->getOperand(2).getReg();
2557 }
2558 break;
2559 case SPIRV::OpUndef:
2560 Reg = Def->getOperand(1).getReg();
2561 break;
2562 }
2563 unsigned DestOpCode;
2564 if (Reg.isValid()) {
2565 DestOpCode = SPIRV::OpConstantNull;
2566 } else {
2567 DestOpCode = TargetOpcode::COPY;
2568 Reg = OpReg;
2569 }
2570 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(DestOpCode))
2571 .addDef(I.getOperand(0).getReg())
2572 .addUse(Reg)
2573 .constrainAllUses(TII, TRI, RBI);
2574 }
2575 return false;
2576}
2577
2578bool SPIRVInstructionSelector::selectBuildVector(Register ResVReg,
2579 const SPIRVType *ResType,
2580 MachineInstr &I) const {
2581 unsigned N = 0;
2582 if (ResType->getOpcode() == SPIRV::OpTypeVector)
2583 N = GR.getScalarOrVectorComponentCount(ResType);
2584 else if (ResType->getOpcode() == SPIRV::OpTypeArray)
2585 N = getArrayComponentCount(MRI, ResType);
2586 else
2587 report_fatal_error("Cannot select G_BUILD_VECTOR with a non-vector result");
2588 if (I.getNumExplicitOperands() - I.getNumExplicitDefs() != N)
2589 report_fatal_error("G_BUILD_VECTOR and the result type are inconsistent");
2590
2591 // check if we may construct a constant vector
2592 bool IsConst = true;
2593 for (unsigned i = I.getNumExplicitDefs();
2594 i < I.getNumExplicitOperands() && IsConst; ++i)
2595 if (!isConstReg(MRI, I.getOperand(i).getReg()))
2596 IsConst = false;
2597
2598 if (!IsConst && N < 2)
2600 "There must be at least two constituent operands in a vector");
2601
2602 MRI->setRegClass(ResVReg, GR.getRegClass(ResType));
2603 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(),
2604 TII.get(IsConst ? SPIRV::OpConstantComposite
2605 : SPIRV::OpCompositeConstruct))
2606 .addDef(ResVReg)
2607 .addUse(GR.getSPIRVTypeID(ResType));
2608 for (unsigned i = I.getNumExplicitDefs(); i < I.getNumExplicitOperands(); ++i)
2609 MIB.addUse(I.getOperand(i).getReg());
2610 return MIB.constrainAllUses(TII, TRI, RBI);
2611}
2612
2613bool SPIRVInstructionSelector::selectSplatVector(Register ResVReg,
2614 const SPIRVType *ResType,
2615 MachineInstr &I) const {
2616 unsigned N = 0;
2617 if (ResType->getOpcode() == SPIRV::OpTypeVector)
2618 N = GR.getScalarOrVectorComponentCount(ResType);
2619 else if (ResType->getOpcode() == SPIRV::OpTypeArray)
2620 N = getArrayComponentCount(MRI, ResType);
2621 else
2622 report_fatal_error("Cannot select G_SPLAT_VECTOR with a non-vector result");
2623
2624 unsigned OpIdx = I.getNumExplicitDefs();
2625 if (!I.getOperand(OpIdx).isReg())
2626 report_fatal_error("Unexpected argument in G_SPLAT_VECTOR");
2627
2628 // check if we may construct a constant vector
2629 Register OpReg = I.getOperand(OpIdx).getReg();
2630 bool IsConst = isConstReg(MRI, OpReg);
2631
2632 if (!IsConst && N < 2)
2634 "There must be at least two constituent operands in a vector");
2635
2636 MRI->setRegClass(ResVReg, GR.getRegClass(ResType));
2637 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(),
2638 TII.get(IsConst ? SPIRV::OpConstantComposite
2639 : SPIRV::OpCompositeConstruct))
2640 .addDef(ResVReg)
2641 .addUse(GR.getSPIRVTypeID(ResType));
2642 for (unsigned i = 0; i < N; ++i)
2643 MIB.addUse(OpReg);
2644 return MIB.constrainAllUses(TII, TRI, RBI);
2645}
2646
2647bool SPIRVInstructionSelector::selectDiscard(Register ResVReg,
2648 const SPIRVType *ResType,
2649 MachineInstr &I) const {
2650
2651 unsigned Opcode;
2652
2653 if (STI.canUseExtension(
2654 SPIRV::Extension::SPV_EXT_demote_to_helper_invocation) ||
2655 STI.isAtLeastSPIRVVer(llvm::VersionTuple(1, 6))) {
2656 Opcode = SPIRV::OpDemoteToHelperInvocation;
2657 } else {
2658 Opcode = SPIRV::OpKill;
2659 // OpKill must be the last operation of any basic block.
2660 if (MachineInstr *NextI = I.getNextNode()) {
2661 GR.invalidateMachineInstr(NextI);
2662 NextI->removeFromParent();
2663 }
2664 }
2665
2666 MachineBasicBlock &BB = *I.getParent();
2667 return BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
2668 .constrainAllUses(TII, TRI, RBI);
2669}
2670
2671bool SPIRVInstructionSelector::selectCmp(Register ResVReg,
2672 const SPIRVType *ResType,
2673 unsigned CmpOpc,
2674 MachineInstr &I) const {
2675 Register Cmp0 = I.getOperand(2).getReg();
2676 Register Cmp1 = I.getOperand(3).getReg();
2677 assert(GR.getSPIRVTypeForVReg(Cmp0)->getOpcode() ==
2678 GR.getSPIRVTypeForVReg(Cmp1)->getOpcode() &&
2679 "CMP operands should have the same type");
2680 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(CmpOpc))
2681 .addDef(ResVReg)
2682 .addUse(GR.getSPIRVTypeID(ResType))
2683 .addUse(Cmp0)
2684 .addUse(Cmp1)
2685 .setMIFlags(I.getFlags())
2686 .constrainAllUses(TII, TRI, RBI);
2687}
2688
2689bool SPIRVInstructionSelector::selectICmp(Register ResVReg,
2690 const SPIRVType *ResType,
2691 MachineInstr &I) const {
2692 auto Pred = I.getOperand(1).getPredicate();
2693 unsigned CmpOpc;
2694
2695 Register CmpOperand = I.getOperand(2).getReg();
2696 if (GR.isScalarOfType(CmpOperand, SPIRV::OpTypePointer))
2697 CmpOpc = getPtrCmpOpcode(Pred);
2698 else if (GR.isScalarOrVectorOfType(CmpOperand, SPIRV::OpTypeBool))
2699 CmpOpc = getBoolCmpOpcode(Pred);
2700 else
2701 CmpOpc = getICmpOpcode(Pred);
2702 return selectCmp(ResVReg, ResType, CmpOpc, I);
2703}
2704
2705std::pair<Register, bool>
2706SPIRVInstructionSelector::buildI32Constant(uint32_t Val, MachineInstr &I,
2707 const SPIRVType *ResType) const {
2708 Type *LLVMTy = IntegerType::get(GR.CurMF->getFunction().getContext(), 32);
2709 const SPIRVType *SpvI32Ty =
2710 ResType ? ResType : GR.getOrCreateSPIRVIntegerType(32, I, TII);
2711 // Find a constant in DT or build a new one.
2712 auto ConstInt = ConstantInt::get(LLVMTy, Val);
2713 Register NewReg = GR.find(ConstInt, GR.CurMF);
2714 bool Result = true;
2715 if (!NewReg.isValid()) {
2716 NewReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
2717 MachineBasicBlock &BB = *I.getParent();
2718 MachineInstr *MI =
2719 Val == 0
2720 ? BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpConstantNull))
2721 .addDef(NewReg)
2722 .addUse(GR.getSPIRVTypeID(SpvI32Ty))
2723 : BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpConstantI))
2724 .addDef(NewReg)
2725 .addUse(GR.getSPIRVTypeID(SpvI32Ty))
2726 .addImm(APInt(32, Val).getZExtValue());
2728 GR.add(ConstInt, MI);
2729 }
2730 return {NewReg, Result};
2731}
2732
2733bool SPIRVInstructionSelector::selectFCmp(Register ResVReg,
2734 const SPIRVType *ResType,
2735 MachineInstr &I) const {
2736 unsigned CmpOp = getFCmpOpcode(I.getOperand(1).getPredicate());
2737 return selectCmp(ResVReg, ResType, CmpOp, I);
2738}
2739
2740Register SPIRVInstructionSelector::buildZerosVal(const SPIRVType *ResType,
2741 MachineInstr &I) const {
2742 // OpenCL uses nulls for Zero. In HLSL we don't use null constants.
2743 bool ZeroAsNull = !STI.isShader();
2744 if (ResType->getOpcode() == SPIRV::OpTypeVector)
2745 return GR.getOrCreateConstVector(0UL, I, ResType, TII, ZeroAsNull);
2746 return GR.getOrCreateConstInt(0, I, ResType, TII, ZeroAsNull);
2747}
2748
2749Register SPIRVInstructionSelector::buildZerosValF(const SPIRVType *ResType,
2750 MachineInstr &I) const {
2751 // OpenCL uses nulls for Zero. In HLSL we don't use null constants.
2752 bool ZeroAsNull = !STI.isShader();
2753 APFloat VZero = getZeroFP(GR.getTypeForSPIRVType(ResType));
2754 if (ResType->getOpcode() == SPIRV::OpTypeVector)
2755 return GR.getOrCreateConstVector(VZero, I, ResType, TII, ZeroAsNull);
2756 return GR.getOrCreateConstFP(VZero, I, ResType, TII, ZeroAsNull);
2757}
2758
2759Register SPIRVInstructionSelector::buildOnesValF(const SPIRVType *ResType,
2760 MachineInstr &I) const {
2761 // OpenCL uses nulls for Zero. In HLSL we don't use null constants.
2762 bool ZeroAsNull = !STI.isShader();
2763 APFloat VOne = getOneFP(GR.getTypeForSPIRVType(ResType));
2764 if (ResType->getOpcode() == SPIRV::OpTypeVector)
2765 return GR.getOrCreateConstVector(VOne, I, ResType, TII, ZeroAsNull);
2766 return GR.getOrCreateConstFP(VOne, I, ResType, TII, ZeroAsNull);
2767}
2768
2769Register SPIRVInstructionSelector::buildOnesVal(bool AllOnes,
2770 const SPIRVType *ResType,
2771 MachineInstr &I) const {
2772 unsigned BitWidth = GR.getScalarOrVectorBitWidth(ResType);
2773 APInt One =
2774 AllOnes ? APInt::getAllOnes(BitWidth) : APInt::getOneBitSet(BitWidth, 0);
2775 if (ResType->getOpcode() == SPIRV::OpTypeVector)
2776 return GR.getOrCreateConstVector(One.getZExtValue(), I, ResType, TII);
2777 return GR.getOrCreateConstInt(One.getZExtValue(), I, ResType, TII);
2778}
2779
2780bool SPIRVInstructionSelector::selectSelect(Register ResVReg,
2781 const SPIRVType *ResType,
2782 MachineInstr &I) const {
2783 Register SelectFirstArg = I.getOperand(2).getReg();
2784 Register SelectSecondArg = I.getOperand(3).getReg();
2785 assert(ResType == GR.getSPIRVTypeForVReg(SelectFirstArg) &&
2786 ResType == GR.getSPIRVTypeForVReg(SelectSecondArg));
2787
2788 bool IsFloatTy =
2789 GR.isScalarOrVectorOfType(SelectFirstArg, SPIRV::OpTypeFloat);
2790 bool IsPtrTy =
2791 GR.isScalarOrVectorOfType(SelectFirstArg, SPIRV::OpTypePointer);
2792 bool IsVectorTy = GR.getSPIRVTypeForVReg(SelectFirstArg)->getOpcode() ==
2793 SPIRV::OpTypeVector;
2794
2795 bool IsScalarBool =
2796 GR.isScalarOfType(I.getOperand(1).getReg(), SPIRV::OpTypeBool);
2797 unsigned Opcode;
2798 if (IsVectorTy) {
2799 if (IsFloatTy) {
2800 Opcode = IsScalarBool ? SPIRV::OpSelectVFSCond : SPIRV::OpSelectVFVCond;
2801 } else if (IsPtrTy) {
2802 Opcode = IsScalarBool ? SPIRV::OpSelectVPSCond : SPIRV::OpSelectVPVCond;
2803 } else {
2804 Opcode = IsScalarBool ? SPIRV::OpSelectVISCond : SPIRV::OpSelectVIVCond;
2805 }
2806 } else {
2807 if (IsFloatTy) {
2808 Opcode = IsScalarBool ? SPIRV::OpSelectSFSCond : SPIRV::OpSelectVFVCond;
2809 } else if (IsPtrTy) {
2810 Opcode = IsScalarBool ? SPIRV::OpSelectSPSCond : SPIRV::OpSelectVPVCond;
2811 } else {
2812 Opcode = IsScalarBool ? SPIRV::OpSelectSISCond : SPIRV::OpSelectVIVCond;
2813 }
2814 }
2815 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(Opcode))
2816 .addDef(ResVReg)
2817 .addUse(GR.getSPIRVTypeID(ResType))
2818 .addUse(I.getOperand(1).getReg())
2819 .addUse(SelectFirstArg)
2820 .addUse(SelectSecondArg)
2821 .constrainAllUses(TII, TRI, RBI);
2822}
2823
2824bool SPIRVInstructionSelector::selectSelectDefaultArgs(Register ResVReg,
2825 const SPIRVType *ResType,
2826 MachineInstr &I,
2827 bool IsSigned) const {
2828 // To extend a bool, we need to use OpSelect between constants.
2829 Register ZeroReg = buildZerosVal(ResType, I);
2830 Register OneReg = buildOnesVal(IsSigned, ResType, I);
2831 bool IsScalarBool =
2832 GR.isScalarOfType(I.getOperand(1).getReg(), SPIRV::OpTypeBool);
2833 unsigned Opcode =
2834 IsScalarBool ? SPIRV::OpSelectSISCond : SPIRV::OpSelectVIVCond;
2835 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(Opcode))
2836 .addDef(ResVReg)
2837 .addUse(GR.getSPIRVTypeID(ResType))
2838 .addUse(I.getOperand(1).getReg())
2839 .addUse(OneReg)
2840 .addUse(ZeroReg)
2841 .constrainAllUses(TII, TRI, RBI);
2842}
2843
2844bool SPIRVInstructionSelector::selectIToF(Register ResVReg,
2845 const SPIRVType *ResType,
2846 MachineInstr &I, bool IsSigned,
2847 unsigned Opcode) const {
2848 Register SrcReg = I.getOperand(1).getReg();
2849 // We can convert bool value directly to float type without OpConvert*ToF,
2850 // however the translator generates OpSelect+OpConvert*ToF, so we do the same.
2851 if (GR.isScalarOrVectorOfType(I.getOperand(1).getReg(), SPIRV::OpTypeBool)) {
2852 unsigned BitWidth = GR.getScalarOrVectorBitWidth(ResType);
2854 if (ResType->getOpcode() == SPIRV::OpTypeVector) {
2855 const unsigned NumElts = ResType->getOperand(2).getImm();
2856 TmpType = GR.getOrCreateSPIRVVectorType(TmpType, NumElts, I, TII);
2857 }
2858 SrcReg = createVirtualRegister(TmpType, &GR, MRI, MRI->getMF());
2859 selectSelectDefaultArgs(SrcReg, TmpType, I, false);
2860 }
2861 return selectOpWithSrcs(ResVReg, ResType, I, {SrcReg}, Opcode);
2862}
2863
2864bool SPIRVInstructionSelector::selectExt(Register ResVReg,
2865 const SPIRVType *ResType,
2866 MachineInstr &I, bool IsSigned) const {
2867 Register SrcReg = I.getOperand(1).getReg();
2868 if (GR.isScalarOrVectorOfType(SrcReg, SPIRV::OpTypeBool))
2869 return selectSelectDefaultArgs(ResVReg, ResType, I, IsSigned);
2870
2871 SPIRVType *SrcType = GR.getSPIRVTypeForVReg(SrcReg);
2872 if (SrcType == ResType)
2873 return BuildCOPY(ResVReg, SrcReg, I);
2874
2875 unsigned Opcode = IsSigned ? SPIRV::OpSConvert : SPIRV::OpUConvert;
2876 return selectUnOp(ResVReg, ResType, I, Opcode);
2877}
2878
2879bool SPIRVInstructionSelector::selectSUCmp(Register ResVReg,
2880 const SPIRVType *ResType,
2881 MachineInstr &I,
2882 bool IsSigned) const {
2883 MachineIRBuilder MIRBuilder(I);
2884 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
2885 MachineBasicBlock &BB = *I.getParent();
2886 // Ensure we have bool.
2887 SPIRVType *BoolType = GR.getOrCreateSPIRVBoolType(I, TII);
2888 unsigned N = GR.getScalarOrVectorComponentCount(ResType);
2889 if (N > 1)
2890 BoolType = GR.getOrCreateSPIRVVectorType(BoolType, N, I, TII);
2891 Register BoolTypeReg = GR.getSPIRVTypeID(BoolType);
2892 // Build less-than-equal and less-than.
2893 // TODO: replace with one-liner createVirtualRegister() from
2894 // llvm/lib/Target/SPIRV/SPIRVUtils.cpp when PR #116609 is merged.
2895 Register IsLessEqReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
2896 MRI->setType(IsLessEqReg, LLT::scalar(64));
2897 GR.assignSPIRVTypeToVReg(ResType, IsLessEqReg, MIRBuilder.getMF());
2898 bool Result = BuildMI(BB, I, I.getDebugLoc(),
2899 TII.get(IsSigned ? SPIRV::OpSLessThanEqual
2900 : SPIRV::OpULessThanEqual))
2901 .addDef(IsLessEqReg)
2902 .addUse(BoolTypeReg)
2903 .addUse(I.getOperand(1).getReg())
2904 .addUse(I.getOperand(2).getReg())
2905 .constrainAllUses(TII, TRI, RBI);
2906 Register IsLessReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
2907 MRI->setType(IsLessReg, LLT::scalar(64));
2908 GR.assignSPIRVTypeToVReg(ResType, IsLessReg, MIRBuilder.getMF());
2909 Result &= BuildMI(BB, I, I.getDebugLoc(),
2910 TII.get(IsSigned ? SPIRV::OpSLessThan : SPIRV::OpULessThan))
2911 .addDef(IsLessReg)
2912 .addUse(BoolTypeReg)
2913 .addUse(I.getOperand(1).getReg())
2914 .addUse(I.getOperand(2).getReg())
2915 .constrainAllUses(TII, TRI, RBI);
2916 // Build selects.
2917 Register ResTypeReg = GR.getSPIRVTypeID(ResType);
2918 Register NegOneOrZeroReg =
2919 MRI->createVirtualRegister(GR.getRegClass(ResType));
2920 MRI->setType(NegOneOrZeroReg, LLT::scalar(64));
2921 GR.assignSPIRVTypeToVReg(ResType, NegOneOrZeroReg, MIRBuilder.getMF());
2922 unsigned SelectOpcode =
2923 N > 1 ? SPIRV::OpSelectVIVCond : SPIRV::OpSelectSISCond;
2924 Result &= BuildMI(BB, I, I.getDebugLoc(), TII.get(SelectOpcode))
2925 .addDef(NegOneOrZeroReg)
2926 .addUse(ResTypeReg)
2927 .addUse(IsLessReg)
2928 .addUse(buildOnesVal(true, ResType, I)) // -1
2929 .addUse(buildZerosVal(ResType, I))
2930 .constrainAllUses(TII, TRI, RBI);
2931 return Result & BuildMI(BB, I, I.getDebugLoc(), TII.get(SelectOpcode))
2932 .addDef(ResVReg)
2933 .addUse(ResTypeReg)
2934 .addUse(IsLessEqReg)
2935 .addUse(NegOneOrZeroReg) // -1 or 0
2936 .addUse(buildOnesVal(false, ResType, I))
2937 .constrainAllUses(TII, TRI, RBI);
2938}
2939
2940bool SPIRVInstructionSelector::selectIntToBool(Register IntReg,
2941 Register ResVReg,
2942 MachineInstr &I,
2943 const SPIRVType *IntTy,
2944 const SPIRVType *BoolTy) const {
2945 // To truncate to a bool, we use OpBitwiseAnd 1 and OpINotEqual to zero.
2946 Register BitIntReg = createVirtualRegister(IntTy, &GR, MRI, MRI->getMF());
2947 bool IsVectorTy = IntTy->getOpcode() == SPIRV::OpTypeVector;
2948 unsigned Opcode = IsVectorTy ? SPIRV::OpBitwiseAndV : SPIRV::OpBitwiseAndS;
2949 Register Zero = buildZerosVal(IntTy, I);
2950 Register One = buildOnesVal(false, IntTy, I);
2951 MachineBasicBlock &BB = *I.getParent();
2952 bool Result = BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
2953 .addDef(BitIntReg)
2954 .addUse(GR.getSPIRVTypeID(IntTy))
2955 .addUse(IntReg)
2956 .addUse(One)
2957 .constrainAllUses(TII, TRI, RBI);
2958 return Result && BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpINotEqual))
2959 .addDef(ResVReg)
2960 .addUse(GR.getSPIRVTypeID(BoolTy))
2961 .addUse(BitIntReg)
2962 .addUse(Zero)
2963 .constrainAllUses(TII, TRI, RBI);
2964}
2965
2966bool SPIRVInstructionSelector::selectTrunc(Register ResVReg,
2967 const SPIRVType *ResType,
2968 MachineInstr &I) const {
2969 Register IntReg = I.getOperand(1).getReg();
2970 const SPIRVType *ArgType = GR.getSPIRVTypeForVReg(IntReg);
2971 if (GR.isScalarOrVectorOfType(ResVReg, SPIRV::OpTypeBool))
2972 return selectIntToBool(IntReg, ResVReg, I, ArgType, ResType);
2973 if (ArgType == ResType)
2974 return BuildCOPY(ResVReg, IntReg, I);
2975 bool IsSigned = GR.isScalarOrVectorSigned(ResType);
2976 unsigned Opcode = IsSigned ? SPIRV::OpSConvert : SPIRV::OpUConvert;
2977 return selectUnOp(ResVReg, ResType, I, Opcode);
2978}
2979
2980bool SPIRVInstructionSelector::selectConst(Register ResVReg,
2981 const SPIRVType *ResType,
2982 MachineInstr &I) const {
2983 unsigned Opcode = I.getOpcode();
2984 unsigned TpOpcode = ResType->getOpcode();
2985 Register Reg;
2986 if (TpOpcode == SPIRV::OpTypePointer || TpOpcode == SPIRV::OpTypeEvent) {
2987 assert(Opcode == TargetOpcode::G_CONSTANT &&
2988 I.getOperand(1).getCImm()->isZero());
2989 MachineBasicBlock &DepMBB = I.getMF()->front();
2990 MachineIRBuilder MIRBuilder(DepMBB, DepMBB.getFirstNonPHI());
2991 Reg = GR.getOrCreateConstNullPtr(MIRBuilder, ResType);
2992 } else if (Opcode == TargetOpcode::G_FCONSTANT) {
2993 Reg = GR.getOrCreateConstFP(I.getOperand(1).getFPImm()->getValue(), I,
2994 ResType, TII, !STI.isShader());
2995 } else {
2996 Reg = GR.getOrCreateConstInt(I.getOperand(1).getCImm()->getZExtValue(), I,
2997 ResType, TII, !STI.isShader());
2998 }
2999 return Reg == ResVReg ? true : BuildCOPY(ResVReg, Reg, I);
3000}
3001
3002bool SPIRVInstructionSelector::selectOpUndef(Register ResVReg,
3003 const SPIRVType *ResType,
3004 MachineInstr &I) const {
3005 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpUndef))
3006 .addDef(ResVReg)
3007 .addUse(GR.getSPIRVTypeID(ResType))
3008 .constrainAllUses(TII, TRI, RBI);
3009}
3010
3011bool SPIRVInstructionSelector::selectInsertVal(Register ResVReg,
3012 const SPIRVType *ResType,
3013 MachineInstr &I) const {
3014 MachineBasicBlock &BB = *I.getParent();
3015 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeInsert))
3016 .addDef(ResVReg)
3017 .addUse(GR.getSPIRVTypeID(ResType))
3018 // object to insert
3019 .addUse(I.getOperand(3).getReg())
3020 // composite to insert into
3021 .addUse(I.getOperand(2).getReg());
3022 for (unsigned i = 4; i < I.getNumOperands(); i++)
3023 MIB.addImm(foldImm(I.getOperand(i), MRI));
3024 return MIB.constrainAllUses(TII, TRI, RBI);
3025}
3026
3027bool SPIRVInstructionSelector::selectExtractVal(Register ResVReg,
3028 const SPIRVType *ResType,
3029 MachineInstr &I) const {
3030 MachineBasicBlock &BB = *I.getParent();
3031 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeExtract))
3032 .addDef(ResVReg)
3033 .addUse(GR.getSPIRVTypeID(ResType))
3034 .addUse(I.getOperand(2).getReg());
3035 for (unsigned i = 3; i < I.getNumOperands(); i++)
3036 MIB.addImm(foldImm(I.getOperand(i), MRI));
3037 return MIB.constrainAllUses(TII, TRI, RBI);
3038}
3039
3040bool SPIRVInstructionSelector::selectInsertElt(Register ResVReg,
3041 const SPIRVType *ResType,
3042 MachineInstr &I) const {
3043 if (getImm(I.getOperand(4), MRI))
3044 return selectInsertVal(ResVReg, ResType, I);
3045 MachineBasicBlock &BB = *I.getParent();
3046 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpVectorInsertDynamic))
3047 .addDef(ResVReg)
3048 .addUse(GR.getSPIRVTypeID(ResType))
3049 .addUse(I.getOperand(2).getReg())
3050 .addUse(I.getOperand(3).getReg())
3051 .addUse(I.getOperand(4).getReg())
3052 .constrainAllUses(TII, TRI, RBI);
3053}
3054
3055bool SPIRVInstructionSelector::selectExtractElt(Register ResVReg,
3056 const SPIRVType *ResType,
3057 MachineInstr &I) const {
3058 if (getImm(I.getOperand(3), MRI))
3059 return selectExtractVal(ResVReg, ResType, I);
3060 MachineBasicBlock &BB = *I.getParent();
3061 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpVectorExtractDynamic))
3062 .addDef(ResVReg)
3063 .addUse(GR.getSPIRVTypeID(ResType))
3064 .addUse(I.getOperand(2).getReg())
3065 .addUse(I.getOperand(3).getReg())
3066 .constrainAllUses(TII, TRI, RBI);
3067}
3068
3069bool SPIRVInstructionSelector::selectGEP(Register ResVReg,
3070 const SPIRVType *ResType,
3071 MachineInstr &I) const {
3072 const bool IsGEPInBounds = I.getOperand(2).getImm();
3073
3074 // OpAccessChain could be used for OpenCL, but the SPIRV-LLVM Translator only
3075 // relies on PtrAccessChain, so we'll try not to deviate. For Vulkan however,
3076 // we have to use Op[InBounds]AccessChain.
3077 const unsigned Opcode = STI.isLogicalSPIRV()
3078 ? (IsGEPInBounds ? SPIRV::OpInBoundsAccessChain
3079 : SPIRV::OpAccessChain)
3080 : (IsGEPInBounds ? SPIRV::OpInBoundsPtrAccessChain
3081 : SPIRV::OpPtrAccessChain);
3082
3083 auto Res = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(Opcode))
3084 .addDef(ResVReg)
3085 .addUse(GR.getSPIRVTypeID(ResType))
3086 // Object to get a pointer to.
3087 .addUse(I.getOperand(3).getReg());
3088 // Adding indices.
3089 const unsigned StartingIndex =
3090 (Opcode == SPIRV::OpAccessChain || Opcode == SPIRV::OpInBoundsAccessChain)
3091 ? 5
3092 : 4;
3093 for (unsigned i = StartingIndex; i < I.getNumExplicitOperands(); ++i)
3094 Res.addUse(I.getOperand(i).getReg());
3095 return Res.constrainAllUses(TII, TRI, RBI);
3096}
3097
3098// Maybe wrap a value into OpSpecConstantOp
3099bool SPIRVInstructionSelector::wrapIntoSpecConstantOp(
3100 MachineInstr &I, SmallVector<Register> &CompositeArgs) const {
3101 bool Result = true;
3102 unsigned Lim = I.getNumExplicitOperands();
3103 for (unsigned i = I.getNumExplicitDefs() + 1; i < Lim; ++i) {
3104 Register OpReg = I.getOperand(i).getReg();
3105 MachineInstr *OpDefine = MRI->getVRegDef(OpReg);
3106 SPIRVType *OpType = GR.getSPIRVTypeForVReg(OpReg);
3107 SmallPtrSet<SPIRVType *, 4> Visited;
3108 if (!OpDefine || !OpType || isConstReg(MRI, OpDefine, Visited) ||
3109 OpDefine->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST ||
3110 OpDefine->getOpcode() == TargetOpcode::G_INTTOPTR ||
3111 GR.isAggregateType(OpType)) {
3112 // The case of G_ADDRSPACE_CAST inside spv_const_composite() is processed
3113 // by selectAddrSpaceCast(), and G_INTTOPTR is processed by selectUnOp()
3114 CompositeArgs.push_back(OpReg);
3115 continue;
3116 }
3117 MachineFunction *MF = I.getMF();
3118 Register WrapReg = GR.find(OpDefine, MF);
3119 if (WrapReg.isValid()) {
3120 CompositeArgs.push_back(WrapReg);
3121 continue;
3122 }
3123 // Create a new register for the wrapper
3124 WrapReg = MRI->createVirtualRegister(GR.getRegClass(OpType));
3125 CompositeArgs.push_back(WrapReg);
3126 // Decorate the wrapper register and generate a new instruction
3127 MRI->setType(WrapReg, LLT::pointer(0, 64));
3128 GR.assignSPIRVTypeToVReg(OpType, WrapReg, *MF);
3129 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(),
3130 TII.get(SPIRV::OpSpecConstantOp))
3131 .addDef(WrapReg)
3132 .addUse(GR.getSPIRVTypeID(OpType))
3133 .addImm(static_cast<uint32_t>(SPIRV::Opcode::Bitcast))
3134 .addUse(OpReg);
3135 GR.add(OpDefine, MIB);
3136 Result = MIB.constrainAllUses(TII, TRI, RBI);
3137 if (!Result)
3138 break;
3139 }
3140 return Result;
3141}
3142
3143bool SPIRVInstructionSelector::selectIntrinsic(Register ResVReg,
3144 const SPIRVType *ResType,
3145 MachineInstr &I) const {
3146 MachineBasicBlock &BB = *I.getParent();
3147 Intrinsic::ID IID = cast<GIntrinsic>(I).getIntrinsicID();
3148 switch (IID) {
3149 case Intrinsic::spv_load:
3150 return selectLoad(ResVReg, ResType, I);
3151 case Intrinsic::spv_store:
3152 return selectStore(I);
3153 case Intrinsic::spv_extractv:
3154 return selectExtractVal(ResVReg, ResType, I);
3155 case Intrinsic::spv_insertv:
3156 return selectInsertVal(ResVReg, ResType, I);
3157 case Intrinsic::spv_extractelt:
3158 return selectExtractElt(ResVReg, ResType, I);
3159 case Intrinsic::spv_insertelt:
3160 return selectInsertElt(ResVReg, ResType, I);
3161 case Intrinsic::spv_gep:
3162 return selectGEP(ResVReg, ResType, I);
3163 case Intrinsic::spv_bitcast: {
3164 Register OpReg = I.getOperand(2).getReg();
3165 SPIRVType *OpType =
3166 OpReg.isValid() ? GR.getSPIRVTypeForVReg(OpReg) : nullptr;
3167 if (!GR.isBitcastCompatible(ResType, OpType))
3168 report_fatal_error("incompatible result and operand types in a bitcast");
3169 return selectOpWithSrcs(ResVReg, ResType, I, {OpReg}, SPIRV::OpBitcast);
3170 }
3171 case Intrinsic::spv_unref_global:
3172 case Intrinsic::spv_init_global: {
3173 MachineInstr *MI = MRI->getVRegDef(I.getOperand(1).getReg());
3174 MachineInstr *Init = I.getNumExplicitOperands() > 2
3175 ? MRI->getVRegDef(I.getOperand(2).getReg())
3176 : nullptr;
3177 assert(MI);
3178 Register GVarVReg = MI->getOperand(0).getReg();
3179 bool Res = selectGlobalValue(GVarVReg, *MI, Init);
3180 // We violate SSA form by inserting OpVariable and still having a gMIR
3181 // instruction %vreg = G_GLOBAL_VALUE @gvar. We need to fix this by erasing
3182 // the duplicated definition.
3183 if (MI->getOpcode() == TargetOpcode::G_GLOBAL_VALUE) {
3185 MI->removeFromParent();
3186 }
3187 return Res;
3188 }
3189 case Intrinsic::spv_undef: {
3190 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpUndef))
3191 .addDef(ResVReg)
3192 .addUse(GR.getSPIRVTypeID(ResType));
3193 return MIB.constrainAllUses(TII, TRI, RBI);
3194 }
3195 case Intrinsic::spv_const_composite: {
3196 // If no values are attached, the composite is null constant.
3197 bool IsNull = I.getNumExplicitDefs() + 1 == I.getNumExplicitOperands();
3198 SmallVector<Register> CompositeArgs;
3199 MRI->setRegClass(ResVReg, GR.getRegClass(ResType));
3200
3201 // skip type MD node we already used when generated assign.type for this
3202 if (!IsNull) {
3203 if (!wrapIntoSpecConstantOp(I, CompositeArgs))
3204 return false;
3205 MachineIRBuilder MIR(I);
3206 SmallVector<MachineInstr *, 4> Instructions = createContinuedInstructions(
3207 MIR, SPIRV::OpConstantComposite, 3,
3208 SPIRV::OpConstantCompositeContinuedINTEL, CompositeArgs, ResVReg,
3209 GR.getSPIRVTypeID(ResType));
3210 for (auto *Instr : Instructions) {
3211 Instr->setDebugLoc(I.getDebugLoc());
3212 if (!constrainSelectedInstRegOperands(*Instr, TII, TRI, RBI))
3213 return false;
3214 }
3215 return true;
3216 } else {
3217 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpConstantNull))
3218 .addDef(ResVReg)
3219 .addUse(GR.getSPIRVTypeID(ResType));
3220 return MIB.constrainAllUses(TII, TRI, RBI);
3221 }
3222 }
3223 case Intrinsic::spv_assign_name: {
3224 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpName));
3225 MIB.addUse(I.getOperand(I.getNumExplicitDefs() + 1).getReg());
3226 for (unsigned i = I.getNumExplicitDefs() + 2;
3227 i < I.getNumExplicitOperands(); ++i) {
3228 MIB.addImm(I.getOperand(i).getImm());
3229 }
3230 return MIB.constrainAllUses(TII, TRI, RBI);
3231 }
3232 case Intrinsic::spv_switch: {
3233 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpSwitch));
3234 for (unsigned i = 1; i < I.getNumExplicitOperands(); ++i) {
3235 if (I.getOperand(i).isReg())
3236 MIB.addReg(I.getOperand(i).getReg());
3237 else if (I.getOperand(i).isCImm())
3238 addNumImm(I.getOperand(i).getCImm()->getValue(), MIB);
3239 else if (I.getOperand(i).isMBB())
3240 MIB.addMBB(I.getOperand(i).getMBB());
3241 else
3242 llvm_unreachable("Unexpected OpSwitch operand");
3243 }
3244 return MIB.constrainAllUses(TII, TRI, RBI);
3245 }
3246 case Intrinsic::spv_loop_merge: {
3247 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpLoopMerge));
3248 for (unsigned i = 1; i < I.getNumExplicitOperands(); ++i) {
3249 if (I.getOperand(i).isMBB())
3250 MIB.addMBB(I.getOperand(i).getMBB());
3251 else
3252 MIB.addImm(foldImm(I.getOperand(i), MRI));
3253 }
3254 return MIB.constrainAllUses(TII, TRI, RBI);
3255 }
3256 case Intrinsic::spv_selection_merge: {
3257 auto MIB =
3258 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpSelectionMerge));
3259 assert(I.getOperand(1).isMBB() &&
3260 "operand 1 to spv_selection_merge must be a basic block");
3261 MIB.addMBB(I.getOperand(1).getMBB());
3262 MIB.addImm(getSelectionOperandForImm(I.getOperand(2).getImm()));
3263 return MIB.constrainAllUses(TII, TRI, RBI);
3264 }
3265 case Intrinsic::spv_cmpxchg:
3266 return selectAtomicCmpXchg(ResVReg, ResType, I);
3267 case Intrinsic::spv_unreachable:
3268 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpUnreachable))
3269 .constrainAllUses(TII, TRI, RBI);
3270 case Intrinsic::spv_alloca:
3271 return selectFrameIndex(ResVReg, ResType, I);
3272 case Intrinsic::spv_alloca_array:
3273 return selectAllocaArray(ResVReg, ResType, I);
3274 case Intrinsic::spv_assume:
3275 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_expect_assume))
3276 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpAssumeTrueKHR))
3277 .addUse(I.getOperand(1).getReg())
3278 .constrainAllUses(TII, TRI, RBI);
3279 break;
3280 case Intrinsic::spv_expect:
3281 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_expect_assume))
3282 return BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpExpectKHR))
3283 .addDef(ResVReg)
3284 .addUse(GR.getSPIRVTypeID(ResType))
3285 .addUse(I.getOperand(2).getReg())
3286 .addUse(I.getOperand(3).getReg())
3287 .constrainAllUses(TII, TRI, RBI);
3288 break;
3289 case Intrinsic::arithmetic_fence:
3290 if (STI.canUseExtension(SPIRV::Extension::SPV_EXT_arithmetic_fence))
3291 return BuildMI(BB, I, I.getDebugLoc(),
3292 TII.get(SPIRV::OpArithmeticFenceEXT))
3293 .addDef(ResVReg)
3294 .addUse(GR.getSPIRVTypeID(ResType))
3295 .addUse(I.getOperand(2).getReg())
3296 .constrainAllUses(TII, TRI, RBI);
3297 else
3298 return BuildCOPY(ResVReg, I.getOperand(2).getReg(), I);
3299 break;
3300 case Intrinsic::spv_thread_id:
3301 // The HLSL SV_DispatchThreadID semantic is lowered to llvm.spv.thread.id
3302 // intrinsic in LLVM IR for SPIR-V backend.
3303 //
3304 // In SPIR-V backend, llvm.spv.thread.id is now correctly translated to a
3305 // `GlobalInvocationId` builtin variable
3306 return loadVec3BuiltinInputID(SPIRV::BuiltIn::GlobalInvocationId, ResVReg,
3307 ResType, I);
3308 case Intrinsic::spv_thread_id_in_group:
3309 // The HLSL SV_GroupThreadId semantic is lowered to
3310 // llvm.spv.thread.id.in.group intrinsic in LLVM IR for SPIR-V backend.
3311 //
3312 // In SPIR-V backend, llvm.spv.thread.id.in.group is now correctly
3313 // translated to a `LocalInvocationId` builtin variable
3314 return loadVec3BuiltinInputID(SPIRV::BuiltIn::LocalInvocationId, ResVReg,
3315 ResType, I);
3316 case Intrinsic::spv_group_id:
3317 // The HLSL SV_GroupId semantic is lowered to
3318 // llvm.spv.group.id intrinsic in LLVM IR for SPIR-V backend.
3319 //
3320 // In SPIR-V backend, llvm.spv.group.id is now translated to a `WorkgroupId`
3321 // builtin variable
3322 return loadVec3BuiltinInputID(SPIRV::BuiltIn::WorkgroupId, ResVReg, ResType,
3323 I);
3324 case Intrinsic::spv_flattened_thread_id_in_group:
3325 // The HLSL SV_GroupIndex semantic is lowered to
3326 // llvm.spv.flattened.thread.id.in.group() intrinsic in LLVM IR for SPIR-V
3327 // backend.
3328 //
3329 // In SPIR-V backend, llvm.spv.flattened.thread.id.in.group is translated to
3330 // a `LocalInvocationIndex` builtin variable
3331 return loadBuiltinInputID(SPIRV::BuiltIn::LocalInvocationIndex, ResVReg,
3332 ResType, I);
3333 case Intrinsic::spv_workgroup_size:
3334 return loadVec3BuiltinInputID(SPIRV::BuiltIn::WorkgroupSize, ResVReg,
3335 ResType, I);
3336 case Intrinsic::spv_global_size:
3337 return loadVec3BuiltinInputID(SPIRV::BuiltIn::GlobalSize, ResVReg, ResType,
3338 I);
3339 case Intrinsic::spv_global_offset:
3340 return loadVec3BuiltinInputID(SPIRV::BuiltIn::GlobalOffset, ResVReg,
3341 ResType, I);
3342 case Intrinsic::spv_num_workgroups:
3343 return loadVec3BuiltinInputID(SPIRV::BuiltIn::NumWorkgroups, ResVReg,
3344 ResType, I);
3345 case Intrinsic::spv_subgroup_size:
3346 return loadBuiltinInputID(SPIRV::BuiltIn::SubgroupSize, ResVReg, ResType,
3347 I);
3348 case Intrinsic::spv_num_subgroups:
3349 return loadBuiltinInputID(SPIRV::BuiltIn::NumSubgroups, ResVReg, ResType,
3350 I);
3351 case Intrinsic::spv_subgroup_id:
3352 return loadBuiltinInputID(SPIRV::BuiltIn::SubgroupId, ResVReg, ResType, I);
3353 case Intrinsic::spv_subgroup_local_invocation_id:
3354 return loadBuiltinInputID(SPIRV::BuiltIn::SubgroupLocalInvocationId,
3355 ResVReg, ResType, I);
3356 case Intrinsic::spv_subgroup_max_size:
3357 return loadBuiltinInputID(SPIRV::BuiltIn::SubgroupMaxSize, ResVReg, ResType,
3358 I);
3359 case Intrinsic::spv_fdot:
3360 return selectFloatDot(ResVReg, ResType, I);
3361 case Intrinsic::spv_udot:
3362 case Intrinsic::spv_sdot:
3363 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_integer_dot_product) ||
3364 STI.isAtLeastSPIRVVer(VersionTuple(1, 6)))
3365 return selectIntegerDot(ResVReg, ResType, I,
3366 /*Signed=*/IID == Intrinsic::spv_sdot);
3367 return selectIntegerDotExpansion(ResVReg, ResType, I);
3368 case Intrinsic::spv_dot4add_i8packed:
3369 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_integer_dot_product) ||
3370 STI.isAtLeastSPIRVVer(VersionTuple(1, 6)))
3371 return selectDot4AddPacked<true>(ResVReg, ResType, I);
3372 return selectDot4AddPackedExpansion<true>(ResVReg, ResType, I);
3373 case Intrinsic::spv_dot4add_u8packed:
3374 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_integer_dot_product) ||
3375 STI.isAtLeastSPIRVVer(VersionTuple(1, 6)))
3376 return selectDot4AddPacked<false>(ResVReg, ResType, I);
3377 return selectDot4AddPackedExpansion<false>(ResVReg, ResType, I);
3378 case Intrinsic::spv_all:
3379 return selectAll(ResVReg, ResType, I);
3380 case Intrinsic::spv_any:
3381 return selectAny(ResVReg, ResType, I);
3382 case Intrinsic::spv_cross:
3383 return selectExtInst(ResVReg, ResType, I, CL::cross, GL::Cross);
3384 case Intrinsic::spv_distance:
3385 return selectExtInst(ResVReg, ResType, I, CL::distance, GL::Distance);
3386 case Intrinsic::spv_lerp:
3387 return selectExtInst(ResVReg, ResType, I, CL::mix, GL::FMix);
3388 case Intrinsic::spv_length:
3389 return selectExtInst(ResVReg, ResType, I, CL::length, GL::Length);
3390 case Intrinsic::spv_degrees:
3391 return selectExtInst(ResVReg, ResType, I, CL::degrees, GL::Degrees);
3392 case Intrinsic::spv_faceforward:
3393 return selectExtInst(ResVReg, ResType, I, GL::FaceForward);
3394 case Intrinsic::spv_frac:
3395 return selectExtInst(ResVReg, ResType, I, CL::fract, GL::Fract);
3396 case Intrinsic::spv_isinf:
3397 return selectOpIsInf(ResVReg, ResType, I);
3398 case Intrinsic::spv_isnan:
3399 return selectOpIsNan(ResVReg, ResType, I);
3400 case Intrinsic::spv_normalize:
3401 return selectExtInst(ResVReg, ResType, I, CL::normalize, GL::Normalize);
3402 case Intrinsic::spv_refract:
3403 return selectExtInst(ResVReg, ResType, I, GL::Refract);
3404 case Intrinsic::spv_reflect:
3405 return selectExtInst(ResVReg, ResType, I, GL::Reflect);
3406 case Intrinsic::spv_rsqrt:
3407 return selectExtInst(ResVReg, ResType, I, CL::rsqrt, GL::InverseSqrt);
3408 case Intrinsic::spv_sign:
3409 return selectSign(ResVReg, ResType, I);
3410 case Intrinsic::spv_smoothstep:
3411 return selectExtInst(ResVReg, ResType, I, CL::smoothstep, GL::SmoothStep);
3412 case Intrinsic::spv_firstbituhigh: // There is no CL equivalent of FindUMsb
3413 return selectFirstBitHigh(ResVReg, ResType, I, /*IsSigned=*/false);
3414 case Intrinsic::spv_firstbitshigh: // There is no CL equivalent of FindSMsb
3415 return selectFirstBitHigh(ResVReg, ResType, I, /*IsSigned=*/true);
3416 case Intrinsic::spv_firstbitlow: // There is no CL equivlent of FindILsb
3417 return selectFirstBitLow(ResVReg, ResType, I);
3418 case Intrinsic::spv_group_memory_barrier_with_group_sync: {
3419 bool Result = true;
3420 auto MemSemConstant =
3421 buildI32Constant(SPIRV::MemorySemantics::SequentiallyConsistent, I);
3422 Register MemSemReg = MemSemConstant.first;
3423 Result &= MemSemConstant.second;
3424 auto ScopeConstant = buildI32Constant(SPIRV::Scope::Workgroup, I);
3425 Register ScopeReg = ScopeConstant.first;
3426 Result &= ScopeConstant.second;
3427 MachineBasicBlock &BB = *I.getParent();
3428 return Result &&
3429 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpControlBarrier))
3430 .addUse(ScopeReg)
3431 .addUse(ScopeReg)
3432 .addUse(MemSemReg)
3433 .constrainAllUses(TII, TRI, RBI);
3434 }
3435 case Intrinsic::spv_generic_cast_to_ptr_explicit: {
3436 Register PtrReg = I.getOperand(I.getNumExplicitDefs() + 1).getReg();
3437 SPIRV::StorageClass::StorageClass ResSC =
3438 GR.getPointerStorageClass(ResType);
3439 if (!isGenericCastablePtr(ResSC))
3440 report_fatal_error("The target storage class is not castable from the "
3441 "Generic storage class");
3442 return BuildMI(BB, I, I.getDebugLoc(),
3443 TII.get(SPIRV::OpGenericCastToPtrExplicit))
3444 .addDef(ResVReg)
3445 .addUse(GR.getSPIRVTypeID(ResType))
3446 .addUse(PtrReg)
3447 .addImm(ResSC)
3448 .constrainAllUses(TII, TRI, RBI);
3449 }
3450 case Intrinsic::spv_lifetime_start:
3451 case Intrinsic::spv_lifetime_end: {
3452 unsigned Op = IID == Intrinsic::spv_lifetime_start ? SPIRV::OpLifetimeStart
3453 : SPIRV::OpLifetimeStop;
3454 int64_t Size = I.getOperand(I.getNumExplicitDefs() + 1).getImm();
3455 Register PtrReg = I.getOperand(I.getNumExplicitDefs() + 2).getReg();
3456 if (Size == -1)
3457 Size = 0;
3458 return BuildMI(BB, I, I.getDebugLoc(), TII.get(Op))
3459 .addUse(PtrReg)
3460 .addImm(Size)
3461 .constrainAllUses(TII, TRI, RBI);
3462 }
3463 case Intrinsic::spv_saturate:
3464 return selectSaturate(ResVReg, ResType, I);
3465 case Intrinsic::spv_nclamp:
3466 return selectExtInst(ResVReg, ResType, I, CL::fclamp, GL::NClamp);
3467 case Intrinsic::spv_uclamp:
3468 return selectExtInst(ResVReg, ResType, I, CL::u_clamp, GL::UClamp);
3469 case Intrinsic::spv_sclamp:
3470 return selectExtInst(ResVReg, ResType, I, CL::s_clamp, GL::SClamp);
3471 case Intrinsic::spv_wave_active_countbits:
3472 return selectWaveActiveCountBits(ResVReg, ResType, I);
3473 case Intrinsic::spv_wave_all:
3474 return selectWaveOpInst(ResVReg, ResType, I, SPIRV::OpGroupNonUniformAll);
3475 case Intrinsic::spv_wave_any:
3476 return selectWaveOpInst(ResVReg, ResType, I, SPIRV::OpGroupNonUniformAny);
3477 case Intrinsic::spv_wave_is_first_lane:
3478 return selectWaveOpInst(ResVReg, ResType, I, SPIRV::OpGroupNonUniformElect);
3479 case Intrinsic::spv_wave_reduce_umax:
3480 return selectWaveReduceMax(ResVReg, ResType, I, /*IsUnsigned*/ true);
3481 case Intrinsic::spv_wave_reduce_max:
3482 return selectWaveReduceMax(ResVReg, ResType, I, /*IsUnsigned*/ false);
3483 case Intrinsic::spv_wave_reduce_umin:
3484 return selectWaveReduceMin(ResVReg, ResType, I, /*IsUnsigned*/ true);
3485 case Intrinsic::spv_wave_reduce_min:
3486 return selectWaveReduceMin(ResVReg, ResType, I, /*IsUnsigned*/ false);
3487 case Intrinsic::spv_wave_reduce_sum:
3488 return selectWaveReduceSum(ResVReg, ResType, I);
3489 case Intrinsic::spv_wave_readlane:
3490 return selectWaveOpInst(ResVReg, ResType, I,
3491 SPIRV::OpGroupNonUniformShuffle);
3492 case Intrinsic::spv_step:
3493 return selectExtInst(ResVReg, ResType, I, CL::step, GL::Step);
3494 case Intrinsic::spv_radians:
3495 return selectExtInst(ResVReg, ResType, I, CL::radians, GL::Radians);
3496 // Discard intrinsics which we do not expect to actually represent code after
3497 // lowering or intrinsics which are not implemented but should not crash when
3498 // found in a customer's LLVM IR input.
3499 case Intrinsic::instrprof_increment:
3500 case Intrinsic::instrprof_increment_step:
3501 case Intrinsic::instrprof_value_profile:
3502 break;
3503 // Discard internal intrinsics.
3504 case Intrinsic::spv_value_md:
3505 break;
3506 case Intrinsic::spv_resource_handlefrombinding: {
3507 return selectHandleFromBinding(ResVReg, ResType, I);
3508 }
3509 case Intrinsic::spv_resource_counterhandlefrombinding:
3510 return selectCounterHandleFromBinding(ResVReg, ResType, I);
3511 case Intrinsic::spv_resource_updatecounter:
3512 return selectUpdateCounter(ResVReg, ResType, I);
3513 case Intrinsic::spv_resource_store_typedbuffer: {
3514 return selectImageWriteIntrinsic(I);
3515 }
3516 case Intrinsic::spv_resource_load_typedbuffer: {
3517 return selectReadImageIntrinsic(ResVReg, ResType, I);
3518 }
3519 case Intrinsic::spv_resource_getpointer: {
3520 return selectResourceGetPointer(ResVReg, ResType, I);
3521 }
3522 case Intrinsic::spv_discard: {
3523 return selectDiscard(ResVReg, ResType, I);
3524 }
3525 case Intrinsic::spv_resource_nonuniformindex: {
3526 return selectResourceNonUniformIndex(ResVReg, ResType, I);
3527 }
3528 case Intrinsic::spv_unpackhalf2x16: {
3529 return selectExtInst(ResVReg, ResType, I, GL::UnpackHalf2x16);
3530 }
3531
3532 default: {
3533 std::string DiagMsg;
3534 raw_string_ostream OS(DiagMsg);
3535 I.print(OS);
3536 DiagMsg = "Intrinsic selection not implemented: " + DiagMsg;
3537 report_fatal_error(DiagMsg.c_str(), false);
3538 }
3539 }
3540 return true;
3541}
3542
3543bool SPIRVInstructionSelector::selectHandleFromBinding(Register &ResVReg,
3544 const SPIRVType *ResType,
3545 MachineInstr &I) const {
3546 // The images need to be loaded in the same basic block as their use. We defer
3547 // loading the image to the intrinsic that uses it.
3548 if (ResType->getOpcode() == SPIRV::OpTypeImage)
3549 return true;
3550
3551 return loadHandleBeforePosition(ResVReg, GR.getSPIRVTypeForVReg(ResVReg),
3552 *cast<GIntrinsic>(&I), I);
3553}
3554
3555bool SPIRVInstructionSelector::selectCounterHandleFromBinding(
3556 Register &ResVReg, const SPIRVType *ResType, MachineInstr &I) const {
3557 auto &Intr = cast<GIntrinsic>(I);
3558 assert(Intr.getIntrinsicID() ==
3559 Intrinsic::spv_resource_counterhandlefrombinding);
3560
3561 // Extract information from the intrinsic call.
3562 Register MainHandleReg = Intr.getOperand(2).getReg();
3563 auto *MainHandleDef = cast<GIntrinsic>(getVRegDef(*MRI, MainHandleReg));
3564 assert(MainHandleDef->getIntrinsicID() ==
3565 Intrinsic::spv_resource_handlefrombinding);
3566
3567 uint32_t Set = getIConstVal(Intr.getOperand(4).getReg(), MRI);
3568 uint32_t Binding = getIConstVal(Intr.getOperand(3).getReg(), MRI);
3569 uint32_t ArraySize = getIConstVal(MainHandleDef->getOperand(4).getReg(), MRI);
3570 Register IndexReg = MainHandleDef->getOperand(5).getReg();
3571 std::string CounterName =
3572 getStringValueFromReg(MainHandleDef->getOperand(6).getReg(), *MRI) +
3573 ".counter";
3574
3575 // Create the counter variable.
3576 MachineIRBuilder MIRBuilder(I);
3577 Register CounterVarReg = buildPointerToResource(
3578 GR.getPointeeType(ResType), GR.getPointerStorageClass(ResType), Set,
3579 Binding, ArraySize, IndexReg, CounterName, MIRBuilder);
3580
3581 return BuildCOPY(ResVReg, CounterVarReg, I);
3582}
3583
3584bool SPIRVInstructionSelector::selectUpdateCounter(Register &ResVReg,
3585 const SPIRVType *ResType,
3586 MachineInstr &I) const {
3587 auto &Intr = cast<GIntrinsic>(I);
3588 assert(Intr.getIntrinsicID() == Intrinsic::spv_resource_updatecounter);
3589
3590 Register CounterHandleReg = Intr.getOperand(2).getReg();
3591 Register IncrReg = Intr.getOperand(3).getReg();
3592
3593 // The counter handle is a pointer to the counter variable (which is a struct
3594 // containing an i32). We need to get a pointer to that i32 member to do the
3595 // atomic operation.
3596#ifndef NDEBUG
3597 SPIRVType *CounterVarType = GR.getSPIRVTypeForVReg(CounterHandleReg);
3598 SPIRVType *CounterVarPointeeType = GR.getPointeeType(CounterVarType);
3599 assert(CounterVarPointeeType &&
3600 CounterVarPointeeType->getOpcode() == SPIRV::OpTypeStruct &&
3601 "Counter variable must be a struct");
3602 assert(GR.getPointerStorageClass(CounterVarType) ==
3603 SPIRV::StorageClass::StorageBuffer &&
3604 "Counter variable must be in the storage buffer storage class");
3605 assert(CounterVarPointeeType->getNumOperands() == 2 &&
3606 "Counter variable must have exactly 1 member in the struct");
3607 const SPIRVType *MemberType =
3608 GR.getSPIRVTypeForVReg(CounterVarPointeeType->getOperand(1).getReg());
3609 assert(MemberType->getOpcode() == SPIRV::OpTypeInt &&
3610 "Counter variable struct must have a single i32 member");
3611#endif
3612
3613 // The struct has a single i32 member.
3614 MachineIRBuilder MIRBuilder(I);
3615 const Type *LLVMIntType =
3616 Type::getInt32Ty(I.getMF()->getFunction().getContext());
3617
3618 SPIRVType *IntPtrType = GR.getOrCreateSPIRVPointerType(
3619 LLVMIntType, MIRBuilder, SPIRV::StorageClass::StorageBuffer);
3620
3621 auto Zero = buildI32Constant(0, I);
3622 if (!Zero.second)
3623 return false;
3624
3625 Register PtrToCounter =
3626 MRI->createVirtualRegister(GR.getRegClass(IntPtrType));
3627 if (!BuildMI(*I.getParent(), I, I.getDebugLoc(),
3628 TII.get(SPIRV::OpAccessChain))
3629 .addDef(PtrToCounter)
3630 .addUse(GR.getSPIRVTypeID(IntPtrType))
3631 .addUse(CounterHandleReg)
3632 .addUse(Zero.first)
3633 .constrainAllUses(TII, TRI, RBI)) {
3634 return false;
3635 }
3636
3637 // For UAV/SSBO counters, the scope is Device. The counter variable is not
3638 // used as a flag. So the memory semantics can be None.
3639 auto Scope = buildI32Constant(SPIRV::Scope::Device, I);
3640 if (!Scope.second)
3641 return false;
3642 auto Semantics = buildI32Constant(SPIRV::MemorySemantics::None, I);
3643 if (!Semantics.second)
3644 return false;
3645
3646 int64_t IncrVal = getIConstValSext(IncrReg, MRI);
3647 auto Incr = buildI32Constant(static_cast<uint32_t>(IncrVal), I);
3648 if (!Incr.second)
3649 return false;
3650
3651 Register AtomicRes = MRI->createVirtualRegister(GR.getRegClass(ResType));
3652 if (!BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpAtomicIAdd))
3653 .addDef(AtomicRes)
3654 .addUse(GR.getSPIRVTypeID(ResType))
3655 .addUse(PtrToCounter)
3656 .addUse(Scope.first)
3657 .addUse(Semantics.first)
3658 .addUse(Incr.first)
3659 .constrainAllUses(TII, TRI, RBI)) {
3660 return false;
3661 }
3662 if (IncrVal >= 0) {
3663 return BuildCOPY(ResVReg, AtomicRes, I);
3664 }
3665
3666 // In HLSL, IncrementCounter returns the value *before* the increment, while
3667 // DecrementCounter returns the value *after* the decrement. Both are lowered
3668 // to the same atomic intrinsic which returns the value *before* the
3669 // operation. So for decrements (negative IncrVal), we must subtract the
3670 // increment value from the result to get the post-decrement value.
3671 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpIAddS))
3672 .addDef(ResVReg)
3673 .addUse(GR.getSPIRVTypeID(ResType))
3674 .addUse(AtomicRes)
3675 .addUse(Incr.first)
3676 .constrainAllUses(TII, TRI, RBI);
3677}
3678bool SPIRVInstructionSelector::selectReadImageIntrinsic(
3679 Register &ResVReg, const SPIRVType *ResType, MachineInstr &I) const {
3680
3681 // If the load of the image is in a different basic block, then
3682 // this will generate invalid code. A proper solution is to move
3683 // the OpLoad from selectHandleFromBinding here. However, to do
3684 // that we will need to change the return type of the intrinsic.
3685 // We will do that when we can, but for now trying to move forward with other
3686 // issues.
3687 Register ImageReg = I.getOperand(2).getReg();
3688 auto *ImageDef = cast<GIntrinsic>(getVRegDef(*MRI, ImageReg));
3689 Register NewImageReg = MRI->createVirtualRegister(MRI->getRegClass(ImageReg));
3690 if (!loadHandleBeforePosition(NewImageReg, GR.getSPIRVTypeForVReg(ImageReg),
3691 *ImageDef, I)) {
3692 return false;
3693 }
3694
3695 Register IdxReg = I.getOperand(3).getReg();
3696 DebugLoc Loc = I.getDebugLoc();
3697 MachineInstr &Pos = I;
3698
3699 return generateImageReadOrFetch(ResVReg, ResType, NewImageReg, IdxReg, Loc,
3700 Pos);
3701}
3702
3703bool SPIRVInstructionSelector::generateImageReadOrFetch(
3704 Register &ResVReg, const SPIRVType *ResType, Register ImageReg,
3705 Register IdxReg, DebugLoc Loc, MachineInstr &Pos) const {
3706 SPIRVType *ImageType = GR.getSPIRVTypeForVReg(ImageReg);
3707 assert(ImageType && ImageType->getOpcode() == SPIRV::OpTypeImage &&
3708 "ImageReg is not an image type.");
3709
3710 bool IsSignedInteger =
3711 sampledTypeIsSignedInteger(GR.getTypeForSPIRVType(ImageType));
3712 // Check if the "sampled" operand of the image type is 1.
3713 // https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpImageFetch
3714 auto SampledOp = ImageType->getOperand(6);
3715 bool IsFetch = (SampledOp.getImm() == 1);
3716
3717 uint64_t ResultSize = GR.getScalarOrVectorComponentCount(ResType);
3718 if (ResultSize == 4) {
3719 auto BMI =
3720 BuildMI(*Pos.getParent(), Pos, Loc,
3721 TII.get(IsFetch ? SPIRV::OpImageFetch : SPIRV::OpImageRead))
3722 .addDef(ResVReg)
3723 .addUse(GR.getSPIRVTypeID(ResType))
3724 .addUse(ImageReg)
3725 .addUse(IdxReg);
3726
3727 if (IsSignedInteger)
3728 BMI.addImm(0x1000); // SignExtend
3729 return BMI.constrainAllUses(TII, TRI, RBI);
3730 }
3731
3732 SPIRVType *ReadType = widenTypeToVec4(ResType, Pos);
3733 Register ReadReg = MRI->createVirtualRegister(GR.getRegClass(ReadType));
3734 auto BMI =
3735 BuildMI(*Pos.getParent(), Pos, Loc,
3736 TII.get(IsFetch ? SPIRV::OpImageFetch : SPIRV::OpImageRead))
3737 .addDef(ReadReg)
3738 .addUse(GR.getSPIRVTypeID(ReadType))
3739 .addUse(ImageReg)
3740 .addUse(IdxReg);
3741 if (IsSignedInteger)
3742 BMI.addImm(0x1000); // SignExtend
3743 bool Succeed = BMI.constrainAllUses(TII, TRI, RBI);
3744 if (!Succeed)
3745 return false;
3746
3747 if (ResultSize == 1) {
3748 return BuildMI(*Pos.getParent(), Pos, Loc,
3749 TII.get(SPIRV::OpCompositeExtract))
3750 .addDef(ResVReg)
3751 .addUse(GR.getSPIRVTypeID(ResType))
3752 .addUse(ReadReg)
3753 .addImm(0)
3754 .constrainAllUses(TII, TRI, RBI);
3755 }
3756 return extractSubvector(ResVReg, ResType, ReadReg, Pos);
3757}
3758
3759bool SPIRVInstructionSelector::selectResourceGetPointer(
3760 Register &ResVReg, const SPIRVType *ResType, MachineInstr &I) const {
3761 Register ResourcePtr = I.getOperand(2).getReg();
3762 SPIRVType *RegType = GR.getSPIRVTypeForVReg(ResourcePtr, I.getMF());
3763 if (RegType->getOpcode() == SPIRV::OpTypeImage) {
3764 // For texel buffers, the index into the image is part of the OpImageRead or
3765 // OpImageWrite instructions. So we will do nothing in this case. This
3766 // intrinsic will be combined with the load or store when selecting the load
3767 // or store.
3768 return true;
3769 }
3770
3771 assert(ResType->getOpcode() == SPIRV::OpTypePointer);
3772 MachineIRBuilder MIRBuilder(I);
3773
3774 Register IndexReg = I.getOperand(3).getReg();
3775 Register ZeroReg =
3776 buildZerosVal(GR.getOrCreateSPIRVIntegerType(32, I, TII), I);
3777 return BuildMI(*I.getParent(), I, I.getDebugLoc(),
3778 TII.get(SPIRV::OpAccessChain))
3779 .addDef(ResVReg)
3780 .addUse(GR.getSPIRVTypeID(ResType))
3781 .addUse(ResourcePtr)
3782 .addUse(ZeroReg)
3783 .addUse(IndexReg)
3784 .constrainAllUses(TII, TRI, RBI);
3785}
3786
3787bool SPIRVInstructionSelector::selectResourceNonUniformIndex(
3788 Register &ResVReg, const SPIRVType *ResType, MachineInstr &I) const {
3789 Register ObjReg = I.getOperand(2).getReg();
3790 if (!BuildCOPY(ResVReg, ObjReg, I))
3791 return false;
3792
3793 buildOpDecorate(ResVReg, I, TII, SPIRV::Decoration::NonUniformEXT, {});
3794 // Check for the registers that use the index marked as non-uniform
3795 // and recursively mark them as non-uniform.
3796 // Per the spec, it's necessary that the final argument used for
3797 // load/store/sample/atomic must be decorated, so we need to propagate the
3798 // decoration through access chains and copies.
3799 // https://docs.vulkan.org/samples/latest/samples/extensions/descriptor_indexing/README.html#_when_to_use_non_uniform_indexing_qualifier
3800 decorateUsesAsNonUniform(ResVReg);
3801 return true;
3802}
3803
3804void SPIRVInstructionSelector::decorateUsesAsNonUniform(
3805 Register &NonUniformReg) const {
3806 llvm::SmallVector<Register> WorkList = {NonUniformReg};
3807 while (WorkList.size() > 0) {
3808 Register CurrentReg = WorkList.back();
3809 WorkList.pop_back();
3810
3811 bool IsDecorated = false;
3812 for (MachineInstr &Use : MRI->use_instructions(CurrentReg)) {
3813 if (Use.getOpcode() == SPIRV::OpDecorate &&
3814 Use.getOperand(1).getImm() == SPIRV::Decoration::NonUniformEXT) {
3815 IsDecorated = true;
3816 continue;
3817 }
3818 // Check if the instruction has the result register and add it to the
3819 // worklist.
3820 if (Use.getOperand(0).isReg() && Use.getOperand(0).isDef()) {
3821 Register ResultReg = Use.getOperand(0).getReg();
3822 if (ResultReg == CurrentReg)
3823 continue;
3824 WorkList.push_back(ResultReg);
3825 }
3826 }
3827
3828 if (!IsDecorated) {
3829 buildOpDecorate(CurrentReg, *MRI->getVRegDef(CurrentReg), TII,
3830 SPIRV::Decoration::NonUniformEXT, {});
3831 }
3832 }
3833}
3834
3835bool SPIRVInstructionSelector::extractSubvector(
3836 Register &ResVReg, const SPIRVType *ResType, Register &ReadReg,
3837 MachineInstr &InsertionPoint) const {
3838 SPIRVType *InputType = GR.getResultType(ReadReg);
3839 [[maybe_unused]] uint64_t InputSize =
3840 GR.getScalarOrVectorComponentCount(InputType);
3841 uint64_t ResultSize = GR.getScalarOrVectorComponentCount(ResType);
3842 assert(InputSize > 1 && "The input must be a vector.");
3843 assert(ResultSize > 1 && "The result must be a vector.");
3844 assert(ResultSize < InputSize &&
3845 "Cannot extract more element than there are in the input.");
3846 SmallVector<Register> ComponentRegisters;
3847 SPIRVType *ScalarType = GR.getScalarOrVectorComponentType(ResType);
3848 const TargetRegisterClass *ScalarRegClass = GR.getRegClass(ScalarType);
3849 for (uint64_t I = 0; I < ResultSize; I++) {
3850 Register ComponentReg = MRI->createVirtualRegister(ScalarRegClass);
3851 bool Succeed = BuildMI(*InsertionPoint.getParent(), InsertionPoint,
3852 InsertionPoint.getDebugLoc(),
3853 TII.get(SPIRV::OpCompositeExtract))
3854 .addDef(ComponentReg)
3855 .addUse(ScalarType->getOperand(0).getReg())
3856 .addUse(ReadReg)
3857 .addImm(I)
3858 .constrainAllUses(TII, TRI, RBI);
3859 if (!Succeed)
3860 return false;
3861 ComponentRegisters.emplace_back(ComponentReg);
3862 }
3863
3864 MachineInstrBuilder MIB = BuildMI(*InsertionPoint.getParent(), InsertionPoint,
3865 InsertionPoint.getDebugLoc(),
3866 TII.get(SPIRV::OpCompositeConstruct))
3867 .addDef(ResVReg)
3868 .addUse(GR.getSPIRVTypeID(ResType));
3869
3870 for (Register ComponentReg : ComponentRegisters)
3871 MIB.addUse(ComponentReg);
3872 return MIB.constrainAllUses(TII, TRI, RBI);
3873}
3874
3875bool SPIRVInstructionSelector::selectImageWriteIntrinsic(
3876 MachineInstr &I) const {
3877 // If the load of the image is in a different basic block, then
3878 // this will generate invalid code. A proper solution is to move
3879 // the OpLoad from selectHandleFromBinding here. However, to do
3880 // that we will need to change the return type of the intrinsic.
3881 // We will do that when we can, but for now trying to move forward with other
3882 // issues.
3883 Register ImageReg = I.getOperand(1).getReg();
3884 auto *ImageDef = cast<GIntrinsic>(getVRegDef(*MRI, ImageReg));
3885 Register NewImageReg = MRI->createVirtualRegister(MRI->getRegClass(ImageReg));
3886 if (!loadHandleBeforePosition(NewImageReg, GR.getSPIRVTypeForVReg(ImageReg),
3887 *ImageDef, I)) {
3888 return false;
3889 }
3890
3891 Register CoordinateReg = I.getOperand(2).getReg();
3892 Register DataReg = I.getOperand(3).getReg();
3893 assert(GR.getResultType(DataReg)->getOpcode() == SPIRV::OpTypeVector);
3895 return BuildMI(*I.getParent(), I, I.getDebugLoc(),
3896 TII.get(SPIRV::OpImageWrite))
3897 .addUse(NewImageReg)
3898 .addUse(CoordinateReg)
3899 .addUse(DataReg)
3900 .constrainAllUses(TII, TRI, RBI);
3901}
3902
3903Register SPIRVInstructionSelector::buildPointerToResource(
3904 const SPIRVType *SpirvResType, SPIRV::StorageClass::StorageClass SC,
3905 uint32_t Set, uint32_t Binding, uint32_t ArraySize, Register IndexReg,
3906 StringRef Name, MachineIRBuilder MIRBuilder) const {
3907 const Type *ResType = GR.getTypeForSPIRVType(SpirvResType);
3908 if (ArraySize == 1) {
3909 SPIRVType *PtrType =
3910 GR.getOrCreateSPIRVPointerType(ResType, MIRBuilder, SC);
3911 assert(GR.getPointeeType(PtrType) == SpirvResType &&
3912 "SpirvResType did not have an explicit layout.");
3913 return GR.getOrCreateGlobalVariableWithBinding(PtrType, Set, Binding, Name,
3914 MIRBuilder);
3915 }
3916
3917 const Type *VarType = ArrayType::get(const_cast<Type *>(ResType), ArraySize);
3918 SPIRVType *VarPointerType =
3919 GR.getOrCreateSPIRVPointerType(VarType, MIRBuilder, SC);
3921 VarPointerType, Set, Binding, Name, MIRBuilder);
3922
3923 SPIRVType *ResPointerType =
3924 GR.getOrCreateSPIRVPointerType(ResType, MIRBuilder, SC);
3925 Register AcReg = MRI->createVirtualRegister(GR.getRegClass(ResPointerType));
3926
3927 MIRBuilder.buildInstr(SPIRV::OpAccessChain)
3928 .addDef(AcReg)
3929 .addUse(GR.getSPIRVTypeID(ResPointerType))
3930 .addUse(VarReg)
3931 .addUse(IndexReg);
3932
3933 return AcReg;
3934}
3935
3936bool SPIRVInstructionSelector::selectFirstBitSet16(
3937 Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
3938 unsigned ExtendOpcode, unsigned BitSetOpcode) const {
3939 Register ExtReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
3940 bool Result = selectOpWithSrcs(ExtReg, ResType, I, {I.getOperand(2).getReg()},
3941 ExtendOpcode);
3942
3943 return Result &&
3944 selectFirstBitSet32(ResVReg, ResType, I, ExtReg, BitSetOpcode);
3945}
3946
3947bool SPIRVInstructionSelector::selectFirstBitSet32(
3948 Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
3949 Register SrcReg, unsigned BitSetOpcode) const {
3950 return BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpExtInst))
3951 .addDef(ResVReg)
3952 .addUse(GR.getSPIRVTypeID(ResType))
3953 .addImm(static_cast<uint32_t>(SPIRV::InstructionSet::GLSL_std_450))
3954 .addImm(BitSetOpcode)
3955 .addUse(SrcReg)
3956 .constrainAllUses(TII, TRI, RBI);
3957}
3958
3959bool SPIRVInstructionSelector::selectFirstBitSet64Overflow(
3960 Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
3961 Register SrcReg, unsigned BitSetOpcode, bool SwapPrimarySide) const {
3962
3963 // SPIR-V allow vectors of size 2,3,4 only. Calling with a larger vectors
3964 // requires creating a param register and return register with an invalid
3965 // vector size. If that is resolved, then this function can be used for
3966 // vectors of any component size.
3967 unsigned ComponentCount = GR.getScalarOrVectorComponentCount(ResType);
3968 assert(ComponentCount < 5 && "Vec 5+ will generate invalid SPIR-V ops");
3969
3970 MachineIRBuilder MIRBuilder(I);
3972 SPIRVType *I64Type = GR.getOrCreateSPIRVIntegerType(64, MIRBuilder);
3973 SPIRVType *I64x2Type =
3974 GR.getOrCreateSPIRVVectorType(I64Type, 2, MIRBuilder, false);
3975 SPIRVType *Vec2ResType =
3976 GR.getOrCreateSPIRVVectorType(BaseType, 2, MIRBuilder, false);
3977
3978 std::vector<Register> PartialRegs;
3979
3980 // Loops 0, 2, 4, ... but stops one loop early when ComponentCount is odd
3981 unsigned CurrentComponent = 0;
3982 for (; CurrentComponent + 1 < ComponentCount; CurrentComponent += 2) {
3983 // This register holds the firstbitX result for each of the i64x2 vectors
3984 // extracted from SrcReg
3985 Register BitSetResult =
3986 MRI->createVirtualRegister(GR.getRegClass(I64x2Type));
3987
3988 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(),
3989 TII.get(SPIRV::OpVectorShuffle))
3990 .addDef(BitSetResult)
3991 .addUse(GR.getSPIRVTypeID(I64x2Type))
3992 .addUse(SrcReg)
3993 .addUse(SrcReg)
3994 .addImm(CurrentComponent)
3995 .addImm(CurrentComponent + 1);
3996
3997 if (!MIB.constrainAllUses(TII, TRI, RBI))
3998 return false;
3999
4000 Register SubVecBitSetReg =
4001 MRI->createVirtualRegister(GR.getRegClass(Vec2ResType));
4002
4003 if (!selectFirstBitSet64(SubVecBitSetReg, Vec2ResType, I, BitSetResult,
4004 BitSetOpcode, SwapPrimarySide))
4005 return false;
4006
4007 PartialRegs.push_back(SubVecBitSetReg);
4008 }
4009
4010 // On odd component counts we need to handle one more component
4011 if (CurrentComponent != ComponentCount) {
4012 bool ZeroAsNull = !STI.isShader();
4013 Register FinalElemReg = MRI->createVirtualRegister(GR.getRegClass(I64Type));
4014 Register ConstIntLastIdx = GR.getOrCreateConstInt(
4015 ComponentCount - 1, I, BaseType, TII, ZeroAsNull);
4016
4017 if (!selectOpWithSrcs(FinalElemReg, I64Type, I, {SrcReg, ConstIntLastIdx},
4018 SPIRV::OpVectorExtractDynamic))
4019 return false;
4020
4021 Register FinalElemBitSetReg =
4022 MRI->createVirtualRegister(GR.getRegClass(BaseType));
4023
4024 if (!selectFirstBitSet64(FinalElemBitSetReg, BaseType, I, FinalElemReg,
4025 BitSetOpcode, SwapPrimarySide))
4026 return false;
4027
4028 PartialRegs.push_back(FinalElemBitSetReg);
4029 }
4030
4031 // Join all the resulting registers back into the return type in order
4032 // (ie i32x2, i32x2, i32x1 -> i32x5)
4033 return selectOpWithSrcs(ResVReg, ResType, I, std::move(PartialRegs),
4034 SPIRV::OpCompositeConstruct);
4035}
4036
4037bool SPIRVInstructionSelector::selectFirstBitSet64(
4038 Register ResVReg, const SPIRVType *ResType, MachineInstr &I,
4039 Register SrcReg, unsigned BitSetOpcode, bool SwapPrimarySide) const {
4040 unsigned ComponentCount = GR.getScalarOrVectorComponentCount(ResType);
4042 bool ZeroAsNull = !STI.isShader();
4043 Register ConstIntZero =
4044 GR.getOrCreateConstInt(0, I, BaseType, TII, ZeroAsNull);
4045 Register ConstIntOne =
4046 GR.getOrCreateConstInt(1, I, BaseType, TII, ZeroAsNull);
4047
4048 // SPIRV doesn't support vectors with more than 4 components. Since the
4049 // algoritm below converts i64 -> i32x2 and i64x4 -> i32x8 it can only
4050 // operate on vectors with 2 or less components. When largers vectors are
4051 // seen. Split them, recurse, then recombine them.
4052 if (ComponentCount > 2) {
4053 return selectFirstBitSet64Overflow(ResVReg, ResType, I, SrcReg,
4054 BitSetOpcode, SwapPrimarySide);
4055 }
4056
4057 // 1. Split int64 into 2 pieces using a bitcast
4058 MachineIRBuilder MIRBuilder(I);
4059 SPIRVType *PostCastType = GR.getOrCreateSPIRVVectorType(
4060 BaseType, 2 * ComponentCount, MIRBuilder, false);
4061 Register BitcastReg =
4062 MRI->createVirtualRegister(GR.getRegClass(PostCastType));
4063
4064 if (!selectOpWithSrcs(BitcastReg, PostCastType, I, {SrcReg},
4065 SPIRV::OpBitcast))
4066 return false;
4067
4068 // 2. Find the first set bit from the primary side for all the pieces in #1
4069 Register FBSReg = MRI->createVirtualRegister(GR.getRegClass(PostCastType));
4070 if (!selectFirstBitSet32(FBSReg, PostCastType, I, BitcastReg, BitSetOpcode))
4071 return false;
4072
4073 // 3. Split result vector into high bits and low bits
4074 Register HighReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
4075 Register LowReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
4076
4077 bool IsScalarRes = ResType->getOpcode() != SPIRV::OpTypeVector;
4078 if (IsScalarRes) {
4079 // if scalar do a vector extract
4080 if (!selectOpWithSrcs(HighReg, ResType, I, {FBSReg, ConstIntZero},
4081 SPIRV::OpVectorExtractDynamic))
4082 return false;
4083 if (!selectOpWithSrcs(LowReg, ResType, I, {FBSReg, ConstIntOne},
4084 SPIRV::OpVectorExtractDynamic))
4085 return false;
4086 } else {
4087 // if vector do a shufflevector
4088 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(),
4089 TII.get(SPIRV::OpVectorShuffle))
4090 .addDef(HighReg)
4091 .addUse(GR.getSPIRVTypeID(ResType))
4092 .addUse(FBSReg)
4093 // Per the spec, repeat the vector if only one vec is needed
4094 .addUse(FBSReg);
4095
4096 // high bits are stored in even indexes. Extract them from FBSReg
4097 for (unsigned J = 0; J < ComponentCount * 2; J += 2) {
4098 MIB.addImm(J);
4099 }
4100
4101 if (!MIB.constrainAllUses(TII, TRI, RBI))
4102 return false;
4103
4104 MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(),
4105 TII.get(SPIRV::OpVectorShuffle))
4106 .addDef(LowReg)
4107 .addUse(GR.getSPIRVTypeID(ResType))
4108 .addUse(FBSReg)
4109 // Per the spec, repeat the vector if only one vec is needed
4110 .addUse(FBSReg);
4111
4112 // low bits are stored in odd indexes. Extract them from FBSReg
4113 for (unsigned J = 1; J < ComponentCount * 2; J += 2) {
4114 MIB.addImm(J);
4115 }
4116 if (!MIB.constrainAllUses(TII, TRI, RBI))
4117 return false;
4118 }
4119
4120 // 4. Check the result. When primary bits == -1 use secondary, otherwise use
4121 // primary
4122 SPIRVType *BoolType = GR.getOrCreateSPIRVBoolType(I, TII);
4123 Register NegOneReg;
4124 Register Reg0;
4125 Register Reg32;
4126 unsigned SelectOp;
4127 unsigned AddOp;
4128
4129 if (IsScalarRes) {
4130 NegOneReg =
4131 GR.getOrCreateConstInt((unsigned)-1, I, ResType, TII, ZeroAsNull);
4132 Reg0 = GR.getOrCreateConstInt(0, I, ResType, TII, ZeroAsNull);
4133 Reg32 = GR.getOrCreateConstInt(32, I, ResType, TII, ZeroAsNull);
4134 SelectOp = SPIRV::OpSelectSISCond;
4135 AddOp = SPIRV::OpIAddS;
4136 } else {
4137 BoolType = GR.getOrCreateSPIRVVectorType(BoolType, ComponentCount,
4138 MIRBuilder, false);
4139 NegOneReg =
4140 GR.getOrCreateConstVector((unsigned)-1, I, ResType, TII, ZeroAsNull);
4141 Reg0 = GR.getOrCreateConstVector(0, I, ResType, TII, ZeroAsNull);
4142 Reg32 = GR.getOrCreateConstVector(32, I, ResType, TII, ZeroAsNull);
4143 SelectOp = SPIRV::OpSelectVIVCond;
4144 AddOp = SPIRV::OpIAddV;
4145 }
4146
4147 Register PrimaryReg = HighReg;
4148 Register SecondaryReg = LowReg;
4149 Register PrimaryShiftReg = Reg32;
4150 Register SecondaryShiftReg = Reg0;
4151
4152 // By default the emitted opcodes check for the set bit from the MSB side.
4153 // Setting SwapPrimarySide checks the set bit from the LSB side
4154 if (SwapPrimarySide) {
4155 PrimaryReg = LowReg;
4156 SecondaryReg = HighReg;
4157 PrimaryShiftReg = Reg0;
4158 SecondaryShiftReg = Reg32;
4159 }
4160
4161 // Check if the primary bits are == -1
4162 Register BReg = MRI->createVirtualRegister(GR.getRegClass(BoolType));
4163 if (!selectOpWithSrcs(BReg, BoolType, I, {PrimaryReg, NegOneReg},
4164 SPIRV::OpIEqual))
4165 return false;
4166
4167 // Select secondary bits if true in BReg, otherwise primary bits
4168 Register TmpReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
4169 if (!selectOpWithSrcs(TmpReg, ResType, I, {BReg, SecondaryReg, PrimaryReg},
4170 SelectOp))
4171 return false;
4172
4173 // 5. Add 32 when high bits are used, otherwise 0 for low bits
4174 Register ValReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
4175 if (!selectOpWithSrcs(ValReg, ResType, I,
4176 {BReg, SecondaryShiftReg, PrimaryShiftReg}, SelectOp))
4177 return false;
4178
4179 return selectOpWithSrcs(ResVReg, ResType, I, {ValReg, TmpReg}, AddOp);
4180}
4181
4182bool SPIRVInstructionSelector::selectFirstBitHigh(Register ResVReg,
4183 const SPIRVType *ResType,
4184 MachineInstr &I,
4185 bool IsSigned) const {
4186 // FindUMsb and FindSMsb intrinsics only support 32 bit integers
4187 Register OpReg = I.getOperand(2).getReg();
4188 SPIRVType *OpType = GR.getSPIRVTypeForVReg(OpReg);
4189 // zero or sign extend
4190 unsigned ExtendOpcode = IsSigned ? SPIRV::OpSConvert : SPIRV::OpUConvert;
4191 unsigned BitSetOpcode = IsSigned ? GL::FindSMsb : GL::FindUMsb;
4192
4193 switch (GR.getScalarOrVectorBitWidth(OpType)) {
4194 case 16:
4195 return selectFirstBitSet16(ResVReg, ResType, I, ExtendOpcode, BitSetOpcode);
4196 case 32:
4197 return selectFirstBitSet32(ResVReg, ResType, I, OpReg, BitSetOpcode);
4198 case 64:
4199 return selectFirstBitSet64(ResVReg, ResType, I, OpReg, BitSetOpcode,
4200 /*SwapPrimarySide=*/false);
4201 default:
4203 "spv_firstbituhigh and spv_firstbitshigh only support 16,32,64 bits.");
4204 }
4205}
4206
4207bool SPIRVInstructionSelector::selectFirstBitLow(Register ResVReg,
4208 const SPIRVType *ResType,
4209 MachineInstr &I) const {
4210 // FindILsb intrinsic only supports 32 bit integers
4211 Register OpReg = I.getOperand(2).getReg();
4212 SPIRVType *OpType = GR.getSPIRVTypeForVReg(OpReg);
4213 // OpUConvert treats the operand bits as an unsigned i16 and zero extends it
4214 // to an unsigned i32. As this leaves all the least significant bits unchanged
4215 // so the first set bit from the LSB side doesn't change.
4216 unsigned ExtendOpcode = SPIRV::OpUConvert;
4217 unsigned BitSetOpcode = GL::FindILsb;
4218
4219 switch (GR.getScalarOrVectorBitWidth(OpType)) {
4220 case 16:
4221 return selectFirstBitSet16(ResVReg, ResType, I, ExtendOpcode, BitSetOpcode);
4222 case 32:
4223 return selectFirstBitSet32(ResVReg, ResType, I, OpReg, BitSetOpcode);
4224 case 64:
4225 return selectFirstBitSet64(ResVReg, ResType, I, OpReg, BitSetOpcode,
4226 /*SwapPrimarySide=*/true);
4227 default:
4228 report_fatal_error("spv_firstbitlow only supports 16,32,64 bits.");
4229 }
4230}
4231
4232bool SPIRVInstructionSelector::selectAllocaArray(Register ResVReg,
4233 const SPIRVType *ResType,
4234 MachineInstr &I) const {
4235 // there was an allocation size parameter to the allocation instruction
4236 // that is not 1
4237 MachineBasicBlock &BB = *I.getParent();
4238 bool Res = BuildMI(BB, I, I.getDebugLoc(),
4239 TII.get(SPIRV::OpVariableLengthArrayINTEL))
4240 .addDef(ResVReg)
4241 .addUse(GR.getSPIRVTypeID(ResType))
4242 .addUse(I.getOperand(2).getReg())
4243 .constrainAllUses(TII, TRI, RBI);
4244 if (!STI.isShader()) {
4245 unsigned Alignment = I.getOperand(3).getImm();
4246 buildOpDecorate(ResVReg, I, TII, SPIRV::Decoration::Alignment, {Alignment});
4247 }
4248 return Res;
4249}
4250
4251bool SPIRVInstructionSelector::selectFrameIndex(Register ResVReg,
4252 const SPIRVType *ResType,
4253 MachineInstr &I) const {
4254 // Change order of instructions if needed: all OpVariable instructions in a
4255 // function must be the first instructions in the first block
4256 auto It = getOpVariableMBBIt(I);
4257 bool Res = BuildMI(*It->getParent(), It, It->getDebugLoc(),
4258 TII.get(SPIRV::OpVariable))
4259 .addDef(ResVReg)
4260 .addUse(GR.getSPIRVTypeID(ResType))
4261 .addImm(static_cast<uint32_t>(SPIRV::StorageClass::Function))
4262 .constrainAllUses(TII, TRI, RBI);
4263 if (!STI.isShader()) {
4264 unsigned Alignment = I.getOperand(2).getImm();
4265 buildOpDecorate(ResVReg, *It, TII, SPIRV::Decoration::Alignment,
4266 {Alignment});
4267 }
4268 return Res;
4269}
4270
4271bool SPIRVInstructionSelector::selectBranch(MachineInstr &I) const {
4272 // InstructionSelector walks backwards through the instructions. We can use
4273 // both a G_BR and a G_BRCOND to create an OpBranchConditional. We hit G_BR
4274 // first, so can generate an OpBranchConditional here. If there is no
4275 // G_BRCOND, we just use OpBranch for a regular unconditional branch.
4276 const MachineInstr *PrevI = I.getPrevNode();
4277 MachineBasicBlock &MBB = *I.getParent();
4278 if (PrevI != nullptr && PrevI->getOpcode() == TargetOpcode::G_BRCOND) {
4279 return BuildMI(MBB, I, I.getDebugLoc(), TII.get(SPIRV::OpBranchConditional))
4280 .addUse(PrevI->getOperand(0).getReg())
4281 .addMBB(PrevI->getOperand(1).getMBB())
4282 .addMBB(I.getOperand(0).getMBB())
4283 .constrainAllUses(TII, TRI, RBI);
4284 }
4285 return BuildMI(MBB, I, I.getDebugLoc(), TII.get(SPIRV::OpBranch))
4286 .addMBB(I.getOperand(0).getMBB())
4287 .constrainAllUses(TII, TRI, RBI);
4288}
4289
4290bool SPIRVInstructionSelector::selectBranchCond(MachineInstr &I) const {
4291 // InstructionSelector walks backwards through the instructions. For an
4292 // explicit conditional branch with no fallthrough, we use both a G_BR and a
4293 // G_BRCOND to create an OpBranchConditional. We should hit G_BR first, and
4294 // generate the OpBranchConditional in selectBranch above.
4295 //
4296 // If an OpBranchConditional has been generated, we simply return, as the work
4297 // is alread done. If there is no OpBranchConditional, LLVM must be relying on
4298 // implicit fallthrough to the next basic block, so we need to create an
4299 // OpBranchConditional with an explicit "false" argument pointing to the next
4300 // basic block that LLVM would fall through to.
4301 const MachineInstr *NextI = I.getNextNode();
4302 // Check if this has already been successfully selected.
4303 if (NextI != nullptr && NextI->getOpcode() == SPIRV::OpBranchConditional)
4304 return true;
4305 // Must be relying on implicit block fallthrough, so generate an
4306 // OpBranchConditional with the "next" basic block as the "false" target.
4307 MachineBasicBlock &MBB = *I.getParent();
4308 unsigned NextMBBNum = MBB.getNextNode()->getNumber();
4309 MachineBasicBlock *NextMBB = I.getMF()->getBlockNumbered(NextMBBNum);
4310 return BuildMI(MBB, I, I.getDebugLoc(), TII.get(SPIRV::OpBranchConditional))
4311 .addUse(I.getOperand(0).getReg())
4312 .addMBB(I.getOperand(1).getMBB())
4313 .addMBB(NextMBB)
4314 .constrainAllUses(TII, TRI, RBI);
4315}
4316
4317bool SPIRVInstructionSelector::selectPhi(Register ResVReg,
4318 const SPIRVType *ResType,
4319 MachineInstr &I) const {
4320 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpPhi))
4321 .addDef(ResVReg)
4322 .addUse(GR.getSPIRVTypeID(ResType));
4323 const unsigned NumOps = I.getNumOperands();
4324 for (unsigned i = 1; i < NumOps; i += 2) {
4325 MIB.addUse(I.getOperand(i + 0).getReg());
4326 MIB.addMBB(I.getOperand(i + 1).getMBB());
4327 }
4328 bool Res = MIB.constrainAllUses(TII, TRI, RBI);
4329 MIB->setDesc(TII.get(TargetOpcode::PHI));
4330 MIB->removeOperand(1);
4331 return Res;
4332}
4333
4334bool SPIRVInstructionSelector::selectGlobalValue(
4335 Register ResVReg, MachineInstr &I, const MachineInstr *Init) const {
4336 // FIXME: don't use MachineIRBuilder here, replace it with BuildMI.
4337 MachineIRBuilder MIRBuilder(I);
4338 const GlobalValue *GV = I.getOperand(1).getGlobal();
4340
4341 std::string GlobalIdent;
4342 if (!GV->hasName()) {
4343 unsigned &ID = UnnamedGlobalIDs[GV];
4344 if (ID == 0)
4345 ID = UnnamedGlobalIDs.size();
4346 GlobalIdent = "__unnamed_" + Twine(ID).str();
4347 } else {
4348 GlobalIdent = GV->getName();
4349 }
4350
4351 // Behaviour of functions as operands depends on availability of the
4352 // corresponding extension (SPV_INTEL_function_pointers):
4353 // - If there is an extension to operate with functions as operands:
4354 // We create a proper constant operand and evaluate a correct type for a
4355 // function pointer.
4356 // - Without the required extension:
4357 // We have functions as operands in tests with blocks of instruction e.g. in
4358 // transcoding/global_block.ll. These operands are not used and should be
4359 // substituted by zero constants. Their type is expected to be always
4360 // OpTypePointer Function %uchar.
4361 if (isa<Function>(GV)) {
4362 const Constant *ConstVal = GV;
4363 MachineBasicBlock &BB = *I.getParent();
4364 Register NewReg = GR.find(ConstVal, GR.CurMF);
4365 if (!NewReg.isValid()) {
4366 Register NewReg = ResVReg;
4367 const Function *GVFun =
4368 STI.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)
4369 ? dyn_cast<Function>(GV)
4370 : nullptr;
4372 GVType, I,
4373 GVFun ? SPIRV::StorageClass::CodeSectionINTEL
4375 if (GVFun) {
4376 // References to a function via function pointers generate virtual
4377 // registers without a definition. We will resolve it later, during
4378 // module analysis stage.
4379 Register ResTypeReg = GR.getSPIRVTypeID(ResType);
4380 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
4381 Register FuncVReg =
4382 MRI->createGenericVirtualRegister(GR.getRegType(ResType));
4383 MRI->setRegClass(FuncVReg, &SPIRV::pIDRegClass);
4384 MachineInstrBuilder MIB1 =
4385 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpUndef))
4386 .addDef(FuncVReg)
4387 .addUse(ResTypeReg);
4388 MachineInstrBuilder MIB2 =
4389 BuildMI(BB, I, I.getDebugLoc(),
4390 TII.get(SPIRV::OpConstantFunctionPointerINTEL))
4391 .addDef(NewReg)
4392 .addUse(ResTypeReg)
4393 .addUse(FuncVReg);
4394 GR.add(ConstVal, MIB2);
4395 // mapping the function pointer to the used Function
4396 GR.recordFunctionPointer(&MIB2.getInstr()->getOperand(2), GVFun);
4397 return MIB1.constrainAllUses(TII, TRI, RBI) &&
4398 MIB2.constrainAllUses(TII, TRI, RBI);
4399 }
4400 MachineInstrBuilder MIB3 =
4401 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpConstantNull))
4402 .addDef(NewReg)
4403 .addUse(GR.getSPIRVTypeID(ResType));
4404 GR.add(ConstVal, MIB3);
4405 return MIB3.constrainAllUses(TII, TRI, RBI);
4406 }
4407 assert(NewReg != ResVReg);
4408 return BuildCOPY(ResVReg, NewReg, I);
4409 }
4411 assert(GlobalVar->getName() != "llvm.global.annotations");
4412
4413 // Skip empty declaration for GVs with initializers till we get the decl with
4414 // passed initializer.
4415 if (hasInitializer(GlobalVar) && !Init)
4416 return true;
4417
4418 const std::optional<SPIRV::LinkageType::LinkageType> LnkType =
4419 getSpirvLinkageTypeFor(STI, *GV);
4420
4421 const unsigned AddrSpace = GV->getAddressSpace();
4422 SPIRV::StorageClass::StorageClass StorageClass =
4423 addressSpaceToStorageClass(AddrSpace, STI);
4424 SPIRVType *ResType = GR.getOrCreateSPIRVPointerType(GVType, I, StorageClass);
4426 ResVReg, ResType, GlobalIdent, GV, StorageClass, Init,
4427 GlobalVar->isConstant(), LnkType, MIRBuilder, true);
4428 return Reg.isValid();
4429}
4430
4431bool SPIRVInstructionSelector::selectLog10(Register ResVReg,
4432 const SPIRVType *ResType,
4433 MachineInstr &I) const {
4434 if (STI.canUseExtInstSet(SPIRV::InstructionSet::OpenCL_std)) {
4435 return selectExtInst(ResVReg, ResType, I, CL::log10);
4436 }
4437
4438 // There is no log10 instruction in the GLSL Extended Instruction set, so it
4439 // is implemented as:
4440 // log10(x) = log2(x) * (1 / log2(10))
4441 // = log2(x) * 0.30103
4442
4443 MachineIRBuilder MIRBuilder(I);
4444 MachineBasicBlock &BB = *I.getParent();
4445
4446 // Build log2(x).
4447 Register VarReg = MRI->createVirtualRegister(GR.getRegClass(ResType));
4448 bool Result =
4449 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpExtInst))
4450 .addDef(VarReg)
4451 .addUse(GR.getSPIRVTypeID(ResType))
4452 .addImm(static_cast<uint32_t>(SPIRV::InstructionSet::GLSL_std_450))
4453 .addImm(GL::Log2)
4454 .add(I.getOperand(1))
4455 .constrainAllUses(TII, TRI, RBI);
4456
4457 // Build 0.30103.
4458 assert(ResType->getOpcode() == SPIRV::OpTypeVector ||
4459 ResType->getOpcode() == SPIRV::OpTypeFloat);
4460 // TODO: Add matrix implementation once supported by the HLSL frontend.
4461 const SPIRVType *SpirvScalarType =
4462 ResType->getOpcode() == SPIRV::OpTypeVector
4463 ? GR.getSPIRVTypeForVReg(ResType->getOperand(1).getReg())
4464 : ResType;
4465 Register ScaleReg =
4466 GR.buildConstantFP(APFloat(0.30103f), MIRBuilder, SpirvScalarType);
4467
4468 // Multiply log2(x) by 0.30103 to get log10(x) result.
4469 auto Opcode = ResType->getOpcode() == SPIRV::OpTypeVector
4470 ? SPIRV::OpVectorTimesScalar
4471 : SPIRV::OpFMulS;
4472 return Result && BuildMI(BB, I, I.getDebugLoc(), TII.get(Opcode))
4473 .addDef(ResVReg)
4474 .addUse(GR.getSPIRVTypeID(ResType))
4475 .addUse(VarReg)
4476 .addUse(ScaleReg)
4477 .constrainAllUses(TII, TRI, RBI);
4478}
4479
4480bool SPIRVInstructionSelector::selectModf(Register ResVReg,
4481 const SPIRVType *ResType,
4482 MachineInstr &I) const {
4483 // llvm.modf has a single arg --the number to be decomposed-- and returns a
4484 // struct { restype, restype }, while OpenCLLIB::modf has two args --the
4485 // number to be decomposed and a pointer--, returns the fractional part and
4486 // the integral part is stored in the pointer argument. Therefore, we can't
4487 // use directly the OpenCLLIB::modf intrinsic. However, we can do some
4488 // scaffolding to make it work. The idea is to create an alloca instruction
4489 // to get a ptr, pass this ptr to OpenCL::modf, and then load the value
4490 // from this ptr to place it in the struct. llvm.modf returns the fractional
4491 // part as the first element of the result, and the integral part as the
4492 // second element of the result.
4493
4494 // At this point, the return type is not a struct anymore, but rather two
4495 // independent elements of SPIRVResType. We can get each independent element
4496 // from I.getDefs() or I.getOperands().
4497 if (STI.canUseExtInstSet(SPIRV::InstructionSet::OpenCL_std)) {
4498 MachineIRBuilder MIRBuilder(I);
4499 // Get pointer type for alloca variable.
4500 const SPIRVType *PtrType = GR.getOrCreateSPIRVPointerType(
4501 ResType, MIRBuilder, SPIRV::StorageClass::Function);
4502 // Create new register for the pointer type of alloca variable.
4503 Register PtrTyReg =
4504 MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
4505 MIRBuilder.getMRI()->setType(
4506 PtrTyReg,
4507 LLT::pointer(storageClassToAddressSpace(SPIRV::StorageClass::Function),
4508 GR.getPointerSize()));
4509
4510 // Assign SPIR-V type of the pointer type of the alloca variable to the
4511 // new register.
4512 GR.assignSPIRVTypeToVReg(PtrType, PtrTyReg, MIRBuilder.getMF());
4513 MachineBasicBlock &EntryBB = I.getMF()->front();
4516 auto AllocaMIB =
4517 BuildMI(EntryBB, VarPos, I.getDebugLoc(), TII.get(SPIRV::OpVariable))
4518 .addDef(PtrTyReg)
4519 .addUse(GR.getSPIRVTypeID(PtrType))
4520 .addImm(static_cast<uint32_t>(SPIRV::StorageClass::Function));
4521 Register Variable = AllocaMIB->getOperand(0).getReg();
4522
4523 MachineBasicBlock &BB = *I.getParent();
4524 // Create the OpenCLLIB::modf instruction.
4525 auto MIB =
4526 BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpExtInst))
4527 .addDef(ResVReg)
4528 .addUse(GR.getSPIRVTypeID(ResType))
4529 .addImm(static_cast<uint32_t>(SPIRV::InstructionSet::OpenCL_std))
4530 .addImm(CL::modf)
4531 .setMIFlags(I.getFlags())
4532 .add(I.getOperand(I.getNumExplicitDefs())) // Floating point value.
4533 .addUse(Variable); // Pointer to integral part.
4534 // Assign the integral part stored in the ptr to the second element of the
4535 // result.
4536 Register IntegralPartReg = I.getOperand(1).getReg();
4537 if (IntegralPartReg.isValid()) {
4538 // Load the value from the pointer to integral part.
4539 auto LoadMIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpLoad))
4540 .addDef(IntegralPartReg)
4541 .addUse(GR.getSPIRVTypeID(ResType))
4542 .addUse(Variable);
4543 return LoadMIB.constrainAllUses(TII, TRI, RBI);
4544 }
4545
4546 return MIB.constrainAllUses(TII, TRI, RBI);
4547 } else if (STI.canUseExtInstSet(SPIRV::InstructionSet::GLSL_std_450)) {
4548 assert(false && "GLSL::Modf is deprecated.");
4549 // FIXME: GL::Modf is deprecated, use Modfstruct instead.
4550 return false;
4551 }
4552 return false;
4553}
4554
4555// Generate the instructions to load 3-element vector builtin input
4556// IDs/Indices.
4557// Like: GlobalInvocationId, LocalInvocationId, etc....
4558
4559bool SPIRVInstructionSelector::loadVec3BuiltinInputID(
4560 SPIRV::BuiltIn::BuiltIn BuiltInValue, Register ResVReg,
4561 const SPIRVType *ResType, MachineInstr &I) const {
4562 MachineIRBuilder MIRBuilder(I);
4563 const SPIRVType *Vec3Ty =
4564 GR.getOrCreateSPIRVVectorType(ResType, 3, MIRBuilder, false);
4565 const SPIRVType *PtrType = GR.getOrCreateSPIRVPointerType(
4566 Vec3Ty, MIRBuilder, SPIRV::StorageClass::Input);
4567
4568 // Create new register for the input ID builtin variable.
4569 Register NewRegister =
4570 MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
4571 MIRBuilder.getMRI()->setType(NewRegister, LLT::pointer(0, 64));
4572 GR.assignSPIRVTypeToVReg(PtrType, NewRegister, MIRBuilder.getMF());
4573
4574 // Build global variable with the necessary decorations for the input ID
4575 // builtin variable.
4577 NewRegister, PtrType, getLinkStringForBuiltIn(BuiltInValue), nullptr,
4578 SPIRV::StorageClass::Input, nullptr, true, std::nullopt, MIRBuilder,
4579 false);
4580
4581 // Create new register for loading value.
4582 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
4583 Register LoadedRegister = MRI->createVirtualRegister(&SPIRV::iIDRegClass);
4584 MIRBuilder.getMRI()->setType(LoadedRegister, LLT::pointer(0, 64));
4585 GR.assignSPIRVTypeToVReg(Vec3Ty, LoadedRegister, MIRBuilder.getMF());
4586
4587 // Load v3uint value from the global variable.
4588 bool Result =
4589 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpLoad))
4590 .addDef(LoadedRegister)
4591 .addUse(GR.getSPIRVTypeID(Vec3Ty))
4592 .addUse(Variable);
4593
4594 // Get the input ID index. Expecting operand is a constant immediate value,
4595 // wrapped in a type assignment.
4596 assert(I.getOperand(2).isReg());
4597 const uint32_t ThreadId = foldImm(I.getOperand(2), MRI);
4598
4599 // Extract the input ID from the loaded vector value.
4600 MachineBasicBlock &BB = *I.getParent();
4601 auto MIB = BuildMI(BB, I, I.getDebugLoc(), TII.get(SPIRV::OpCompositeExtract))
4602 .addDef(ResVReg)
4603 .addUse(GR.getSPIRVTypeID(ResType))
4604 .addUse(LoadedRegister)
4605 .addImm(ThreadId);
4606 return Result && MIB.constrainAllUses(TII, TRI, RBI);
4607}
4608
4609// Generate the instructions to load 32-bit integer builtin input IDs/Indices.
4610// Like LocalInvocationIndex
4611bool SPIRVInstructionSelector::loadBuiltinInputID(
4612 SPIRV::BuiltIn::BuiltIn BuiltInValue, Register ResVReg,
4613 const SPIRVType *ResType, MachineInstr &I) const {
4614 MachineIRBuilder MIRBuilder(I);
4615 const SPIRVType *PtrType = GR.getOrCreateSPIRVPointerType(
4616 ResType, MIRBuilder, SPIRV::StorageClass::Input);
4617
4618 // Create new register for the input ID builtin variable.
4619 Register NewRegister =
4620 MIRBuilder.getMRI()->createVirtualRegister(GR.getRegClass(PtrType));
4621 MIRBuilder.getMRI()->setType(
4622 NewRegister,
4623 LLT::pointer(storageClassToAddressSpace(SPIRV::StorageClass::Input),
4624 GR.getPointerSize()));
4625 GR.assignSPIRVTypeToVReg(PtrType, NewRegister, MIRBuilder.getMF());
4626
4627 // Build global variable with the necessary decorations for the input ID
4628 // builtin variable.
4630 NewRegister, PtrType, getLinkStringForBuiltIn(BuiltInValue), nullptr,
4631 SPIRV::StorageClass::Input, nullptr, true, std::nullopt, MIRBuilder,
4632 false);
4633
4634 // Load uint value from the global variable.
4635 auto MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(SPIRV::OpLoad))
4636 .addDef(ResVReg)
4637 .addUse(GR.getSPIRVTypeID(ResType))
4638 .addUse(Variable);
4639
4640 return MIB.constrainAllUses(TII, TRI, RBI);
4641}
4642
4643SPIRVType *SPIRVInstructionSelector::widenTypeToVec4(const SPIRVType *Type,
4644 MachineInstr &I) const {
4645 MachineIRBuilder MIRBuilder(I);
4646 if (Type->getOpcode() != SPIRV::OpTypeVector)
4647 return GR.getOrCreateSPIRVVectorType(Type, 4, MIRBuilder, false);
4648
4649 uint64_t VectorSize = Type->getOperand(2).getImm();
4650 if (VectorSize == 4)
4651 return Type;
4652
4653 Register ScalarTypeReg = Type->getOperand(1).getReg();
4654 const SPIRVType *ScalarType = GR.getSPIRVTypeForVReg(ScalarTypeReg);
4655 return GR.getOrCreateSPIRVVectorType(ScalarType, 4, MIRBuilder, false);
4656}
4657
4658bool SPIRVInstructionSelector::loadHandleBeforePosition(
4659 Register &HandleReg, const SPIRVType *ResType, GIntrinsic &HandleDef,
4660 MachineInstr &Pos) const {
4661
4662 assert(HandleDef.getIntrinsicID() ==
4663 Intrinsic::spv_resource_handlefrombinding);
4664 uint32_t Set = foldImm(HandleDef.getOperand(2), MRI);
4665 uint32_t Binding = foldImm(HandleDef.getOperand(3), MRI);
4666 uint32_t ArraySize = foldImm(HandleDef.getOperand(4), MRI);
4667 Register IndexReg = HandleDef.getOperand(5).getReg();
4668 std::string Name =
4669 getStringValueFromReg(HandleDef.getOperand(6).getReg(), *MRI);
4670
4671 bool IsStructuredBuffer = ResType->getOpcode() == SPIRV::OpTypePointer;
4672 MachineIRBuilder MIRBuilder(HandleDef);
4673 SPIRVType *VarType = ResType;
4674 SPIRV::StorageClass::StorageClass SC = SPIRV::StorageClass::UniformConstant;
4675
4676 if (IsStructuredBuffer) {
4677 VarType = GR.getPointeeType(ResType);
4678 SC = GR.getPointerStorageClass(ResType);
4679 }
4680
4681 Register VarReg = buildPointerToResource(VarType, SC, Set, Binding, ArraySize,
4682 IndexReg, Name, MIRBuilder);
4683
4684 // The handle for the buffer is the pointer to the resource. For an image, the
4685 // handle is the image object. So images get an extra load.
4686 uint32_t LoadOpcode =
4687 IsStructuredBuffer ? SPIRV::OpCopyObject : SPIRV::OpLoad;
4688 GR.assignSPIRVTypeToVReg(ResType, HandleReg, *Pos.getMF());
4689 return BuildMI(*Pos.getParent(), Pos, HandleDef.getDebugLoc(),
4690 TII.get(LoadOpcode))
4691 .addDef(HandleReg)
4692 .addUse(GR.getSPIRVTypeID(ResType))
4693 .addUse(VarReg)
4694 .constrainAllUses(TII, TRI, RBI);
4695}
4696
4697namespace llvm {
4698InstructionSelector *
4700 const SPIRVSubtarget &Subtarget,
4701 const RegisterBankInfo &RBI) {
4702 return new SPIRVInstructionSelector(TM, Subtarget, RBI);
4703}
4704} // namespace llvm
unsigned const MachineRegisterInfo * MRI
#define GET_GLOBALISEL_PREDICATES_INIT
#define GET_GLOBALISEL_TEMPORARIES_INIT
@ Generic
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a class to represent arbitrary precision floating point values and provide a varie...
static bool selectUnmergeValues(MachineInstrBuilder &MIB, const ARMBaseInstrInfo &TII, MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
basic Basic Alias true
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
DXIL Resource Implicit Binding
#define DEBUG_TYPE
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define I(x, y, z)
Definition MD5.cpp:58
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
static StringRef getName(Value *V)
static unsigned getFCmpOpcode(CmpInst::Predicate Pred, unsigned Size)
static APFloat getOneFP(const Type *LLVMFloatTy)
static bool isUSMStorageClass(SPIRV::StorageClass::StorageClass SC)
static bool isASCastInGVar(MachineRegisterInfo *MRI, Register ResVReg)
static bool mayApplyGenericSelection(unsigned Opcode)
static APFloat getZeroFP(const Type *LLVMFloatTy)
std::vector< std::pair< SPIRV::InstructionSet::InstructionSet, uint32_t > > ExtInstList
static unsigned getBoolCmpOpcode(unsigned PredNum)
static unsigned getICmpOpcode(unsigned PredNum)
static void addMemoryOperands(MachineMemOperand *MemOp, MachineInstrBuilder &MIB, MachineIRBuilder &MIRBuilder, SPIRVGlobalRegistry &GR)
static bool isConstReg(MachineRegisterInfo *MRI, MachineInstr *OpDef, SmallPtrSet< SPIRVType *, 4 > &Visited)
static unsigned getPtrCmpOpcode(unsigned Pred)
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
spirv structurize SPIRV
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
BinaryOperator * Mul
static const fltSemantics & IEEEsingle()
Definition APFloat.h:296
static const fltSemantics & IEEEdouble()
Definition APFloat.h:297
static const fltSemantics & IEEEhalf()
Definition APFloat.h:294
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1070
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1061
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1541
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A debug info location.
Definition DebugLoc.h:124
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:359
Represents a call to an intrinsic.
Intrinsic::ID getIntrinsicID() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:319
constexpr bool isScalar() const
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr bool isVector() const
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
constexpr bool isPointer() const
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Helper class to build MachineInstr.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineFunction & getMF()
Getter for the function we currently build.
MachineRegisterInfo * getMRI()
Getter for MRI.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
bool constrainAllUses(const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
LLVM_ABI unsigned getNumExplicitDefs() const
Returns the number of non-implicit definitions.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
@ MOVolatile
The memory access is volatile.
@ MONonTemporal
The memory access is non-temporal.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
defusechain_instr_iterator< true, false, false, true > use_instr_iterator
use_instr_iterator/use_instr_begin/use_instr_end - Walk all uses of the specified register,...
defusechain_instr_iterator< false, true, false, true > def_instr_iterator
def_instr_iterator/def_instr_begin/def_instr_end - Walk all defs of the specified register,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI void setType(Register VReg, LLT Ty)
Set the low-level type of VReg to Ty.
Analysis providing profile information.
Holds all the information related to register banks.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
SPIRVType * getSPIRVTypeForVReg(Register VReg, const MachineFunction *MF=nullptr) const
Register getOrCreateConstInt(uint64_t Val, MachineInstr &I, SPIRVType *SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull=true)
SPIRVType * getResultType(Register VReg, MachineFunction *MF=nullptr)
SPIRVType * getOrCreateSPIRVBoolType(MachineIRBuilder &MIRBuilder, bool EmitIR)
MachineInstr * getOrAddMemAliasingINTELInst(MachineIRBuilder &MIRBuilder, const MDNode *AliasingListMD)
void assignSPIRVTypeToVReg(SPIRVType *Type, Register VReg, const MachineFunction &MF)
Register getOrCreateUndef(MachineInstr &I, SPIRVType *SpvType, const SPIRVInstrInfo &TII)
Register buildGlobalVariable(Register Reg, SPIRVType *BaseType, StringRef Name, const GlobalValue *GV, SPIRV::StorageClass::StorageClass Storage, const MachineInstr *Init, bool IsConst, const std::optional< SPIRV::LinkageType::LinkageType > &LinkageType, MachineIRBuilder &MIRBuilder, bool IsInstSelector)
SPIRVType * changePointerStorageClass(SPIRVType *PtrType, SPIRV::StorageClass::StorageClass SC, MachineInstr &I)
const Type * getTypeForSPIRVType(const SPIRVType *Ty) const
bool isBitcastCompatible(const SPIRVType *Type1, const SPIRVType *Type2) const
unsigned getScalarOrVectorComponentCount(Register VReg) const
bool isScalarOrVectorSigned(const SPIRVType *Type) const
Register getOrCreateGlobalVariableWithBinding(const SPIRVType *VarType, uint32_t Set, uint32_t Binding, StringRef Name, MachineIRBuilder &MIRBuilder)
SPIRVType * getOrCreateSPIRVType(const Type *Type, MachineInstr &I, SPIRV::AccessQualifier::AccessQualifier AQ, bool EmitIR)
SPIRVType * getOrCreateSPIRVPointerType(const Type *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SC)
Register buildConstantFP(APFloat Val, MachineIRBuilder &MIRBuilder, SPIRVType *SpvType=nullptr)
SPIRVType * getPointeeType(SPIRVType *PtrType)
void invalidateMachineInstr(MachineInstr *MI)
Register getSPIRVTypeID(const SPIRVType *SpirvType) const
bool isScalarOfType(Register VReg, unsigned TypeOpcode) const
bool findValueAttrs(const MachineInstr *Key, Type *&Ty, StringRef &Name)
void addGlobalObject(const Value *V, const MachineFunction *MF, Register R)
SPIRVType * getScalarOrVectorComponentType(Register VReg) const
void recordFunctionPointer(const MachineOperand *MO, const Function *F)
bool isAggregateType(SPIRVType *Type) const
const TargetRegisterClass * getRegClass(SPIRVType *SpvType) const
SPIRVType * getOrCreateSPIRVVectorType(SPIRVType *BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder, bool EmitIR)
bool isScalarOrVectorOfType(Register VReg, unsigned TypeOpcode) const
Register getOrCreateConstIntArray(uint64_t Val, size_t Num, MachineInstr &I, SPIRVType *SpvType, const SPIRVInstrInfo &TII)
MachineFunction * setCurrentFunc(MachineFunction &MF)
Register getOrCreateConstVector(uint64_t Val, MachineInstr &I, SPIRVType *SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull=true)
SPIRVType * getOrCreateSPIRVIntegerType(unsigned BitWidth, MachineIRBuilder &MIRBuilder)
Type * getDeducedGlobalValueType(const GlobalValue *Global)
LLT getRegType(SPIRVType *SpvType) const
SPIRV::StorageClass::StorageClass getPointerStorageClass(Register VReg) const
Register getOrCreateConstFP(APFloat Val, MachineInstr &I, SPIRVType *SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull=true)
Register getOrCreateConstNullPtr(MachineIRBuilder &MIRBuilder, SPIRVType *SpvType)
unsigned getScalarOrVectorBitWidth(const SPIRVType *Type) const
const SPIRVType * retrieveScalarOrVectorIntType(const SPIRVType *Type) const
bool erase(const MachineInstr *MI)
bool add(SPIRV::IRHandle Handle, const MachineInstr *MI)
Register find(SPIRV::IRHandle Handle, const MachineFunction *MF)
bool isPhysicalSPIRV() const
bool isAtLeastSPIRVVer(VersionTuple VerToCompareTo) const
bool canUseExtInstSet(SPIRV::InstructionSet::InstructionSet E) const
bool isLogicalSPIRV() const
bool canUseExtension(SPIRV::Extension::Extension E) const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:146
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:414
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
@ HalfTyID
16-bit floating point type
Definition Type.h:56
@ FloatTyID
32-bit floating point type
Definition Type.h:58
@ DoubleTyID
64-bit floating point type
Definition Type.h:59
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:261
TypeID getTypeID() const
Return the type id for the type.
Definition Type.h:136
Value * getOperand(unsigned i) const
Definition User.h:232
bool hasName() const
Definition Value.h:262
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
LLVM_C_ABI LLVMTypeRef LLVMIntType(unsigned NumBits)
Definition Core.cpp:701
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsConst[]
Key for Kernel::Arg::Metadata::mIsConst.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
void buildOpName(Register Target, const StringRef &Name, MachineIRBuilder &MIRBuilder)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1725
int64_t getIConstValSext(Register ConstReg, const MachineRegisterInfo *MRI)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool isTypeFoldingSupported(unsigned Opcode)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void addNumImm(const APInt &Imm, MachineInstrBuilder &MIB)
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1724
LLVM_ABI bool constrainSelectedInstRegOperands(MachineInstr &I, const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI)
Mutate the newly-selected instruction I to constrain its (possibly generic) virtual register operands...
Definition Utils.cpp:155
bool isPreISelGenericOpcode(unsigned Opcode)
Check whether the given Opcode is a generic opcode that is not supposed to appear after ISel.
unsigned getArrayComponentCount(const MachineRegisterInfo *MRI, const MachineInstr *ResType)
uint64_t getIConstVal(Register ConstReg, const MachineRegisterInfo *MRI)
SmallVector< MachineInstr *, 4 > createContinuedInstructions(MachineIRBuilder &MIRBuilder, unsigned Opcode, unsigned MinWC, unsigned ContinuedOpcode, ArrayRef< Register > Args, Register ReturnRegister, Register TypeID)
SPIRV::MemorySemantics::MemorySemantics getMemSemanticsForStorageClass(SPIRV::StorageClass::StorageClass SC)
constexpr unsigned storageClassToAddressSpace(SPIRV::StorageClass::StorageClass SC)
Definition SPIRVUtils.h:239
MachineBasicBlock::iterator getFirstValidInstructionInsertPoint(MachineBasicBlock &BB)
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, const std::vector< uint32_t > &DecArgs, StringRef StrImm)
MachineBasicBlock::iterator getOpVariableMBBIt(MachineInstr &I)
Register createVirtualRegister(SPIRVType *SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF)
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
Type * toTypedPointer(Type *Ty)
Definition SPIRVUtils.h:436
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
const MachineInstr SPIRVType
constexpr bool isGenericCastablePtr(SPIRV::StorageClass::StorageClass SC)
Definition SPIRVUtils.h:224
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
MachineInstr * passCopy(MachineInstr *Def, const MachineRegisterInfo *MRI)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
std::optional< SPIRV::LinkageType::LinkageType > getSpirvLinkageTypeFor(const SPIRVSubtarget &ST, const GlobalValue &GV)
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
AtomicOrdering
Atomic ordering for LLVM's memory model.
SPIRV::Scope::Scope getMemScope(LLVMContext &Ctx, SyncScope::ID Id)
InstructionSelector * createSPIRVInstructionSelector(const SPIRVTargetMachine &TM, const SPIRVSubtarget &Subtarget, const RegisterBankInfo &RBI)
std::string getStringValueFromReg(Register Reg, MachineRegisterInfo &MRI)
int64_t foldImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
DWARFExpression::Operation Op
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool hasInitializer(const GlobalVariable *GV)
Definition SPIRVUtils.h:324
MachineInstr * getVRegDef(MachineRegisterInfo &MRI, Register Reg)
SPIRV::MemorySemantics::MemorySemantics getMemSemantics(AtomicOrdering Ord)
std::string getLinkStringForBuiltIn(SPIRV::BuiltIn::BuiltIn BuiltInValue)
LLVM_ABI bool isTriviallyDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Check whether an instruction MI is dead: it only defines dead virtual registers, and doesn't have oth...
Definition Utils.cpp:222
#define N