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