LLVM 24.0.0git
SPIRVGlobalRegistry.cpp
Go to the documentation of this file.
1//===-- SPIRVGlobalRegistry.cpp - SPIR-V Global Registry --------*- 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 contains the implementation of the SPIRVGlobalRegistry class,
10// which is used to maintain rich type information required for SPIR-V even
11// after lowering from LLVM IR to GMIR. It can convert an llvm::Type into
12// an OpTypeXXX instruction, and map it to a virtual register. Also it builds
13// and supports consistency of constants and global variables.
14//
15//===----------------------------------------------------------------------===//
16
17#include "SPIRVGlobalRegistry.h"
18#include "SPIRV.h"
19#include "SPIRVBuiltins.h"
20#include "SPIRVSubtarget.h"
21#include "SPIRVUtils.h"
22#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/IR/Constants.h"
27#include "llvm/IR/Function.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/IntrinsicsSPIRV.h"
31#include "llvm/IR/Type.h"
34#include <cassert>
35#include <functional>
36
37using namespace llvm;
38
39static bool allowEmitFakeUse(const Value *Arg) {
40 if (isSpvIntrinsic(Arg))
41 return false;
43 return false;
44 if (const auto *LI = dyn_cast<LoadInst>(Arg))
45 if (LI->getType()->isAggregateType())
46 return false;
47 return true;
48}
49
50static unsigned typeToAddressSpace(const Type *Ty) {
51 if (auto PType = dyn_cast<TypedPointerType>(Ty))
52 return PType->getAddressSpace();
53 if (auto PType = dyn_cast<PointerType>(Ty))
54 return PType->getAddressSpace();
55 if (auto *ExtTy = dyn_cast<TargetExtType>(Ty);
56 ExtTy && isTypedPointerWrapper(ExtTy))
57 return ExtTy->getIntParameter(0);
58 reportFatalInternalError("Unable to convert LLVM type to SPIRVType");
59}
60
61static bool
62storageClassRequiresExplictLayout(SPIRV::StorageClass::StorageClass SC) {
63 switch (SC) {
64 case SPIRV::StorageClass::Uniform:
65 case SPIRV::StorageClass::PushConstant:
66 case SPIRV::StorageClass::StorageBuffer:
67 case SPIRV::StorageClass::PhysicalStorageBufferEXT:
68 return true;
69 case SPIRV::StorageClass::UniformConstant:
70 case SPIRV::StorageClass::Input:
71 case SPIRV::StorageClass::Output:
72 case SPIRV::StorageClass::Workgroup:
73 case SPIRV::StorageClass::CrossWorkgroup:
74 case SPIRV::StorageClass::Private:
75 case SPIRV::StorageClass::Function:
76 case SPIRV::StorageClass::Generic:
77 case SPIRV::StorageClass::AtomicCounter:
78 case SPIRV::StorageClass::Image:
79 case SPIRV::StorageClass::CallableDataNV:
80 case SPIRV::StorageClass::IncomingCallableDataNV:
81 case SPIRV::StorageClass::RayPayloadNV:
82 case SPIRV::StorageClass::HitAttributeNV:
83 case SPIRV::StorageClass::IncomingRayPayloadNV:
84 case SPIRV::StorageClass::ShaderRecordBufferNV:
85 case SPIRV::StorageClass::CodeSectionINTEL:
86 case SPIRV::StorageClass::DeviceOnlyINTEL:
87 case SPIRV::StorageClass::HostOnlyINTEL:
88 return false;
89 }
90 llvm_unreachable("Unknown SPIRV::StorageClass enum");
91}
92
94 : DL(DL), Bound(0), CurMF(nullptr) {}
95
96void SPIRVGlobalRegistry::constrainSelectedInstRegOperands(
97 MachineInstrBuilder &MIB) const {
98 const auto &ST = CurMF->getSubtarget();
99 MIB.constrainAllUses(*ST.getInstrInfo(), *ST.getRegisterInfo(),
100 *ST.getRegBankInfo());
101}
102
106 const SPIRVInstrInfo &TII) {
108 assignSPIRVTypeToVReg(SpirvType, VReg, *CurMF);
109 return SpirvType;
110}
111
113 const Type *Type, Register VReg, MachineIRBuilder &MIRBuilder,
114 SPIRV::AccessQualifier::AccessQualifier AccessQual, bool EmitIR) {
115 SPIRVTypeInst SpirvType =
116 getOrCreateSPIRVType(Type, MIRBuilder, AccessQual, EmitIR);
117 assignSPIRVTypeToVReg(SpirvType, VReg, MIRBuilder.getMF());
118 return SpirvType;
119}
120
122 Register VReg,
123 const MachineFunction &MF) {
124 VRegToTypeMap[&MF][VReg] = SpirvType;
125}
126
128 auto Res = MRI.createGenericVirtualRegister(LLT::scalar(64));
129 MRI.setRegClass(Res, &SPIRV::TYPERegClass);
130 return Res;
131}
132
134 return createTypeVReg(MIRBuilder.getMF().getRegInfo());
135}
136
137SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeBool(MachineIRBuilder &MIRBuilder) {
138 return createConstOrTypeAtFunctionEntry(
139 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
140 return MIRBuilder.buildInstr(SPIRV::OpTypeBool)
141 .addDef(createTypeVReg(MIRBuilder));
142 });
143}
144
145unsigned SPIRVGlobalRegistry::adjustOpTypeIntWidth(unsigned Width) const {
146 const SPIRVSubtarget &ST = cast<SPIRVSubtarget>(CurMF->getSubtarget());
147 if (ST.canUseExtension(
148 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers) ||
149 (Width == 4 && ST.canUseExtension(SPIRV::Extension::SPV_INTEL_int4)))
150 return Width;
151 if (Width <= 8)
152 return 8;
153 else if (Width <= 16)
154 return 16;
155 else if (Width <= 32)
156 return 32;
157 else if (Width <= 64)
158 return 64;
159 else if (Width <= 128)
160 return 128;
161 reportFatalUsageError("Unsupported Integer width!");
162}
163
164SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeInt(unsigned Width,
165 MachineIRBuilder &MIRBuilder,
166 bool IsSigned) {
167 Width = adjustOpTypeIntWidth(Width);
168 const SPIRVSubtarget &ST =
170 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
171 &MIRBuilder) {
172 if (Width == 4 && ST.canUseExtension(SPIRV::Extension::SPV_INTEL_int4)) {
173 MIRBuilder.buildInstr(SPIRV::OpExtension)
174 .addImm(SPIRV::Extension::SPV_INTEL_int4);
175 MIRBuilder.buildInstr(SPIRV::OpCapability)
176 .addImm(SPIRV::Capability::Int4TypeINTEL);
177 } else if ((!isPowerOf2_32(Width) || Width < 8) &&
178 ST.canUseExtension(
179 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers)) {
180 MIRBuilder.buildInstr(SPIRV::OpExtension)
181 .addImm(SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers);
182 MIRBuilder.buildInstr(SPIRV::OpCapability)
183 .addImm(SPIRV::Capability::ArbitraryPrecisionIntegersALTERA);
184 }
185 return MIRBuilder.buildInstr(SPIRV::OpTypeInt)
186 .addDef(createTypeVReg(MIRBuilder))
187 .addImm(Width)
188 .addImm(IsSigned ? 1 : 0);
189 });
190}
191
193SPIRVGlobalRegistry::getOpTypeFloat(uint32_t Width,
194 MachineIRBuilder &MIRBuilder) {
195 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
196 &MIRBuilder) {
197 return MIRBuilder.buildInstr(SPIRV::OpTypeFloat)
198 .addDef(createTypeVReg(MIRBuilder))
199 .addImm(Width);
200 });
201}
202
204SPIRVGlobalRegistry::getOpTypeFloat(uint32_t Width,
205 MachineIRBuilder &MIRBuilder,
206 SPIRV::FPEncoding::FPEncoding FPEncode) {
207 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
208 &MIRBuilder) {
209 return MIRBuilder.buildInstr(SPIRV::OpTypeFloat)
210 .addDef(createTypeVReg(MIRBuilder))
211 .addImm(Width)
212 .addImm(FPEncode);
213 });
214}
215
217 return createConstOrTypeAtFunctionEntry(
218 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
219 return MIRBuilder.buildInstr(SPIRV::OpTypeVoid)
220 .addDef(createTypeVReg(MIRBuilder));
221 });
222}
223
225 // Other maps that may hold MachineInstr*:
226 // - VRegToTypeMap: We cannot remove the definitions of `MI` from
227 // VRegToTypeMap because some calls to invalidateMachineInstr are replacing MI
228 // with another instruction defining the same register. We expect that if MI
229 // is a type instruction, and it is still referenced in VRegToTypeMap, then
230 // those registers are dead or the VRegToTypeMap is out-of-date. We do not
231 // expect passes to ask for the SPIR-V type of a dead register. If the
232 // VRegToTypeMap is out-of-date already, then there was an error before. We
233 // cannot add an assert to verify this because the VRegToTypeMap can be
234 // out-of-date.
235 // - FunctionToInstr & FunctionToInstrRev: At this point, we should not be
236 // deleting functions. No need to update.
237 // - AliasInstMDMap: Would require a linear search, and the Intel Alias
238 // instruction are not instructions instruction selection will be able to
239 // remove.
240
241 const SPIRVSubtarget &ST = MI->getMF()->getSubtarget<SPIRVSubtarget>();
242 [[maybe_unused]] const SPIRVInstrInfo *TII = ST.getInstrInfo();
243 assert(!TII->isAliasingInstr(*MI) &&
244 "Cannot invalidate aliasing instructions.");
245 assert(MI->getOpcode() != SPIRV::OpFunction &&
246 "Cannot invalidate OpFunction.");
247
248 if (MI->getOpcode() == SPIRV::OpFunctionCall) {
249 if (const auto *F = dyn_cast<Function>(MI->getOperand(2).getGlobal())) {
250 auto It = ForwardCalls.find(F);
251 if (It != ForwardCalls.end()) {
252 It->second.erase(MI);
253 if (It->second.empty())
254 ForwardCalls.erase(It);
255 }
256 }
257 }
258
259 const MachineFunction *MF = MI->getMF();
260 auto It = LastInsertedTypeMap.find(MF);
261 if (It != LastInsertedTypeMap.end() && It->second == MI)
262 LastInsertedTypeMap.erase(MF);
263 // remove from the duplicate tracker to avoid incorrect reuse
264 erase(MI);
265}
266
269 const SPIRVInstrInfo &TII = *MF.getSubtarget<SPIRVSubtarget>().getInstrInfo();
271 for (const MachineBasicBlock &MBB : MF)
272 for (const MachineInstr &MI : MBB)
273 if (MI.getNumDefs() && TII.isTypeDeclInstr(MI))
274 Res.push_back(&MI);
275 return Res;
276}
277
278inline unsigned getAS(SPIRVTypeInst SpvType) {
280 static_cast<SPIRV::StorageClass::StorageClass>(
281 SpvType->getOperand(1).getImm()));
282}
283
284// Inverse of addNumImm, 32-bit words, low word first.
286 unsigned NumWords = MI.getNumExplicitOperands() - 2;
287 APInt Val = APInt::getZero(NumWords * 32);
288 for (unsigned I = 0; I < NumWords; ++I)
289 Val.insertBits(static_cast<uint32_t>(MI.getOperand(I + 2).getImm()), I * 32,
290 32);
291 return Val;
292}
293
294namespace {
295// Derives the LLVM types the registry keys OpType* instructions by.
296struct LLVMTypeRestorer {
297 const MachineRegisterInfo &MRI;
298 const DataLayout &DL;
299 LLVMContext &Ctx;
300 DenseMap<const MachineInstr *, Type *> Types;
301 // Struct types handed out so far, paired with their layout flag.
302 DenseSet<PointerIntPair<Type *, 1, bool>> StructTypes;
303
304 LLVMTypeRestorer(const MachineFunction &MF)
305 : MRI(MF.getRegInfo()), DL(MF.getDataLayout()),
306 Ctx(MF.getFunction().getContext()) {}
307
308 bool hasDecoration(const MachineInstr &MI,
309 SPIRV::Decoration::Decoration Dec) const {
310 for (const MachineInstr &Use :
311 MRI.use_nodbg_instructions(MI.getOperand(0).getReg())) {
312 if ((Use.getOpcode() == SPIRV::OpDecorate &&
313 Use.getOperand(1).getImm() == Dec) ||
314 (Use.getOpcode() == SPIRV::OpMemberDecorate &&
315 Use.getOperand(2).getImm() == Dec))
316 return true;
317 }
318 return false;
319 }
320
321 // Matches the decorations ExplicitLayoutRequired makes the registry emit.
322 bool hasExplicitLayout(const MachineInstr &MI) const {
323 return hasDecoration(MI, SPIRV::Decoration::Offset) ||
324 hasDecoration(MI, SPIRV::Decoration::ArrayStride);
325 }
326
327 bool matchesOffsets(const MachineInstr &MI, StructType *STy) const {
328 if (!STy->isSized())
329 return true;
330 const StructLayout *SL = DL.getStructLayout(STy);
331 for (const MachineInstr &Use :
332 MRI.use_nodbg_instructions(MI.getOperand(0).getReg())) {
333 if (Use.getOpcode() != SPIRV::OpMemberDecorate ||
334 Use.getOperand(2).getImm() != SPIRV::Decoration::Offset)
335 continue;
336 uint64_t Idx = Use.getOperand(1).getImm();
337 if (Idx < STy->getNumElements() &&
338 SL->getElementOffset(Idx) != uint64_t(Use.getOperand(3).getImm()))
339 return false;
340 }
341 return true;
342 }
343
344 // Shaders get no CPacked, so the offsets pick the layout. Returns nullopt if
345 // neither layout matches them.
346 std::optional<bool> isPacked(const MachineInstr &MI,
347 ArrayRef<Type *> Elems) const {
348 if (hasDecoration(MI, SPIRV::Decoration::CPacked))
349 return true;
350 if (matchesOffsets(MI, StructType::get(Ctx, Elems, /*isPacked=*/false)))
351 return false;
352 if (matchesOffsets(MI, StructType::get(Ctx, Elems, /*isPacked=*/true)))
353 return true;
354 return std::nullopt;
355 }
356
357 // Named structs are keyed by their IR type, which the embedded module keeps.
358 // spirv.Layout structs reuse the name with their own offsets.
359 StructType *getNamedStruct(const MachineInstr &MI, size_t NumElems) const {
360 for (const MachineInstr &Use :
361 MRI.use_nodbg_instructions(MI.getOperand(0).getReg())) {
362 if (Use.getOpcode() != SPIRV::OpName)
363 continue;
364 StructType *STy = StructType::getTypeByName(Ctx, getStringImm(Use, 1));
365 return STy && !STy->isOpaque() && STy->getNumElements() == NumElems &&
366 matchesOffsets(MI, STy)
367 ? STy
368 : nullptr;
369 }
370 return nullptr;
371 }
372
373 Type *getOperandType(const MachineOperand &MO) {
374 const MachineInstr *Def = MRI.getVRegDef(MO.getReg());
375 return Def ? get(*Def) : nullptr;
376 }
377
378 // i8 pointees were opaque pointers, others typed pointer wrappers.
379 Type *getComponentType(const MachineOperand &MO) {
380 Type *Ty = getOperandType(MO);
381 auto *PtrTy = dyn_cast_or_null<TypedPointerType>(Ty);
382 if (!PtrTy)
383 return Ty;
384 Type *ElemTy = PtrTy->getElementType();
385 unsigned AS = PtrTy->getAddressSpace();
386 return ElemTy->isIntegerTy(8) ? PointerType::get(Ctx, AS)
387 : getTypedPointerWrapper(ElemTy, AS);
388 }
389
390 std::optional<uint64_t> getArrayLength(const MachineOperand &MO) {
391 const MachineInstr *Def = getImm(MO, &MRI);
392 if (!Def)
393 return std::nullopt;
394 APInt V = Def->getOpcode() == TargetOpcode::G_CONSTANT
395 ? Def->getOperand(1).getCImm()->getValue()
396 : decodeNumImm(*Def);
397 // getOpTypeArray encodes AMD runtime arrays as UINT64_MAX.
398 if (V.isMaxValue() && V.getBitWidth() == 64)
399 return 0;
400 if (V.getActiveBits() > 64)
401 return std::nullopt;
402 return V.getZExtValue();
403 }
404
405 Type *create(const MachineInstr &MI) {
406 switch (MI.getOpcode()) {
407 case SPIRV::OpTypeVoid:
408 return Type::getVoidTy(Ctx);
409 case SPIRV::OpTypeBool:
410 return Type::getInt1Ty(Ctx);
411 case SPIRV::OpTypeInt: {
412 // The registry only creates unsigned integer types.
413 int64_t Width = MI.getOperand(1).getImm();
414 if (MI.getOperand(2).getImm() || Width < IntegerType::MIN_INT_BITS ||
416 return nullptr;
417 return IntegerType::get(Ctx, Width);
418 }
419 case SPIRV::OpTypeFloat: {
420 int64_t Width = MI.getOperand(1).getImm();
421 if (MI.getNumOperands() > 2)
422 return Width == 16 && MI.getOperand(2).getImm() ==
423 SPIRV::FPEncoding::BFloat16KHR
424 ? Type::getBFloatTy(Ctx)
425 : nullptr;
426 if (Width == 16)
427 return Type::getHalfTy(Ctx);
428 if (Width == 32)
429 return Type::getFloatTy(Ctx);
430 if (Width == 64)
431 return Type::getDoubleTy(Ctx);
432 return nullptr;
433 }
434 case SPIRV::OpTypeVector:
435 case SPIRV::OpTypeVectorIdEXT: {
436 Type *ElemTy = getComponentType(MI.getOperand(1));
437 std::optional<uint64_t> N = MI.getOpcode() == SPIRV::OpTypeVector
438 ? MI.getOperand(2).getImm()
439 : getArrayLength(MI.getOperand(2));
440 if (!ElemTy || !VectorType::isValidElementType(ElemTy) || !N || !*N ||
441 *N > std::numeric_limits<unsigned>::max())
442 return nullptr;
443 return FixedVectorType::get(ElemTy, *N);
444 }
445 case SPIRV::OpTypeArray:
446 case SPIRV::OpTypeRuntimeArray: {
447 Type *ElemTy = getComponentType(MI.getOperand(1));
448 if (!ElemTy || !ArrayType::isValidElementType(ElemTy))
449 return nullptr;
450 if (MI.getOpcode() == SPIRV::OpTypeRuntimeArray)
451 return ArrayType::get(ElemTy, 0);
452 std::optional<uint64_t> N = getArrayLength(MI.getOperand(2));
453 return N ? ArrayType::get(ElemTy, *N) : nullptr;
454 }
455 case SPIRV::OpTypeStruct: {
457 for (const MachineInstr *I = &MI; I; I = I->getNextNode()) {
458 if (I != &MI && I->getOpcode() != SPIRV::OpTypeStructContinuedINTEL)
459 break;
460 for (const MachineOperand &MO : I->explicit_uses()) {
461 Elems.push_back(getComponentType(MO));
462 if (!Elems.back() || !StructType::isValidElementType(Elems.back()))
463 return nullptr;
464 }
465 }
466 std::optional<bool> Packed = isPacked(MI, Elems);
467 // Type lookups never reach Block structs: buffer blocks wrap their
468 // element in StructType::create and push constant blocks are rekeyed by
469 // their vkbuffer handle.
470 Type *STy = nullptr;
471 if (!hasDecoration(MI, SPIRV::Decoration::Block)) {
472 if (StructType *Named = getNamedStruct(MI, Elems.size()))
473 STy = Named;
474 else if (Packed)
475 STy = StructType::get(Ctx, Elems, *Packed);
476 }
477 // Distinct OpTypeStructs may share members, keep their keys apart.
478 if (!STy || !StructTypes.insert({STy, hasExplicitLayout(MI)}).second)
479 STy = StructType::create(Ctx, Elems, "", Packed.value_or(true));
480 return STy;
481 }
482 case SPIRV::OpTypeFunction: {
483 Type *RetTy = getOperandType(MI.getOperand(1));
484 if (!RetTy || !FunctionType::isValidReturnType(RetTy))
485 return nullptr;
486 SmallVector<Type *> Params;
487 for (const MachineOperand &MO : drop_begin(MI.explicit_uses())) {
488 Params.push_back(getOperandType(MO));
489 if (!Params.back() || !FunctionType::isValidArgumentType(Params.back()))
490 return nullptr;
491 }
492 return FunctionType::get(RetTy, Params, /*isVarArg=*/false);
493 }
494 case SPIRV::OpTypePointer: {
495 Type *ElemTy = getOperandType(MI.getOperand(2));
496 if (!ElemTy || !TypedPointerType::isValidElementType(ElemTy))
497 return nullptr;
498 return TypedPointerType::get(ElemTy, getAS(MI));
499 }
500 default:
501 return nullptr;
502 }
503 }
504
505 // A null entry marks MI in progress, breaking cycles.
506 Type *get(const MachineInstr &MI) {
507 if (auto [It, Inserted] = Types.try_emplace(&MI, nullptr); !Inserted)
508 return It->second;
509 Type *Ty = create(MI);
510 if (Ty)
511 Ty = const_cast<Type *>(unifyPtrType(Ty));
512 Types[&MI] = Ty;
513 return Ty;
514 }
515};
516} // namespace
517
519 LLVMTypeRestorer Restorer(MF);
520 for (const MachineInstr *MI : getTypeDecls(MF)) {
522 if (MI->getOpcode() == SPIRV::OpTypeStruct &&
523 Restorer.hasDecoration(*MI, SPIRV::Decoration::Block))
524 BlockDecoratedTypes.insert(MI);
525 const Type *Ty = Restorer.get(*MI);
526 if (!Ty)
527 continue;
528 SPIRVToLLVMType[MI] = Ty;
529 addTypeKey(Ty, Restorer.hasExplicitLayout(*MI), MI, MF);
530 }
531}
532
536 auto TypesIt = VRegToTypeMap.find(&MF);
537 if (TypesIt == VRegToTypeMap.end())
538 return Res;
539 // The map may hold erased instructions, so only compare pointers.
541 TypeInstrs.insert_range(getTypeDecls(MF));
542 const MachineRegisterInfo &MRI = MF.getRegInfo();
543 for (auto [Reg, Ty] : TypesIt->second) {
544 if (!TypeInstrs.contains(Ty))
545 continue;
546 Register TypeReg = getSPIRVTypeID(Ty);
547 if (TypeReg != Reg && !MRI.reg_empty(Reg))
548 Res.emplace_back(Reg, TypeReg);
549 }
550 llvm::sort(Res);
551 return Res;
552}
553
554static bool isContinuedInstr(const MachineInstr &MI) {
555 switch (MI.getOpcode()) {
556 case SPIRV::OpTypeStructContinuedINTEL:
557 case SPIRV::OpConstantCompositeContinuedINTEL:
558 case SPIRV::OpSpecConstantCompositeContinuedINTEL:
559 case SPIRV::OpCompositeConstructContinuedINTEL:
560 return true;
561 default:
562 return false;
563 }
564}
565
568 auto It = LastInsertedTypeMap.find(&MF);
569 if (It == LastInsertedTypeMap.end())
570 return Register();
571 // The map may hold an erased instruction, so only compare pointers.
572 for (const MachineBasicBlock &MBB : MF) {
573 for (const MachineInstr &MI : MBB) {
574 if (&MI != It->second)
575 continue;
576 const MachineInstr *Head = &MI;
577 while (isContinuedInstr(*Head) && Head->getPrevNode())
578 Head = Head->getPrevNode();
579 return Head->getNumDefs() ? Head->getOperand(0).getReg() : Register();
580 }
581 }
582 return Register();
583}
584
586 MachineInstr *MI) {
587 // Skip continued instructions to keep them adjacent to their head.
588 while (MI->getNextNode() && isContinuedInstr(*MI->getNextNode()))
589 MI = MI->getNextNode();
590 LastInsertedTypeMap[&MF] = MI;
591}
592
593const MachineInstr *SPIRVGlobalRegistry::createConstOrTypeAtFunctionEntry(
594 MachineIRBuilder &MIRBuilder,
595 std::function<MachineInstr *(MachineIRBuilder &)> Op) {
596 auto oldInsertPoint = MIRBuilder.getInsertPt();
597 assert(oldInsertPoint.isValid() && "Builder must have insertion point set!");
598 MachineBasicBlock *OldMBB = &MIRBuilder.getMBB();
599 MachineBasicBlock *NewMBB = &*MIRBuilder.getMF().begin();
600
601 auto LastInsertedType = LastInsertedTypeMap.find(CurMF);
602 if (LastInsertedType != LastInsertedTypeMap.end()) {
603 auto It = LastInsertedType->second->getIterator();
604 // It might happen that this instruction was removed from the first MBB,
605 // hence the Parent's check.
607 if (It->getParent() != NewMBB)
608 InsertAt = oldInsertPoint->getParent() == NewMBB
609 ? oldInsertPoint
610 : getInsertPtValidEnd(NewMBB);
611 else if (It->getNextNode())
612 InsertAt = It->getNextNode()->getIterator();
613 else
614 InsertAt = getInsertPtValidEnd(NewMBB);
615 MIRBuilder.setInsertPt(*NewMBB, InsertAt);
616 } else {
617 MIRBuilder.setInsertPt(*NewMBB, NewMBB->begin());
618 }
619
620 MachineInstr *ConstOrType = Op(MIRBuilder);
621 // We expect all users of this function to insert definitions at the insertion
622 // point set above that is always the first MBB.
623 assert(ConstOrType->getParent() == NewMBB);
624 setLastInsertedType(*CurMF, ConstOrType);
625
626 MIRBuilder.setInsertPt(*OldMBB, oldInsertPoint);
627 return ConstOrType;
628}
629
630SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeVectorImpl(
631 uint32_t NumElems, SPIRVTypeInst ElemType, MachineIRBuilder &MIRBuilder,
632 bool IsLongVectorEXT) {
633 if (ElemType.isPointer()) {
634 if (!cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget())
635 .canUseExtension(
636 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
637 const Function &F = MIRBuilder.getMF().getFunction();
638 F.getContext().diagnose(DiagnosticInfoUnsupported(
639 F,
640 "Vector of pointers requires SPV_INTEL_masked_gather_scatter "
641 "extension",
642 DebugLoc(), DS_Error));
643 }
644 } else {
645 [[maybe_unused]] auto EleOpc = ElemType->getOpcode();
646 assert((EleOpc == SPIRV::OpTypeInt || EleOpc == SPIRV::OpTypeFloat ||
647 EleOpc == SPIRV::OpTypeBool) &&
648 "Invalid vector element type");
649 }
650
651 return createConstOrTypeAtFunctionEntry(
652 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
653 unsigned Op =
654 IsLongVectorEXT ? SPIRV::OpTypeVectorIdEXT : SPIRV::OpTypeVector;
655 Register VTy = createTypeVReg(MIRBuilder);
656 Register Ty = getSPIRVTypeID(ElemType);
657 auto MIB = MIRBuilder.buildInstr(Op).addDef(VTy).addUse(Ty);
658 if (!IsLongVectorEXT)
659 return MIB.addImm(NumElems);
660
661 const auto &ST = MIRBuilder.getMF().getSubtarget<SPIRVSubtarget>();
662 SPIRVTypeInst Int32Ty = getOrCreateSPIRVIntegerType(32, MIRBuilder);
663 return MIB.addUse(getOrCreateConstInt(NumElems, *MIB.getInstr(),
664 Int32Ty, *ST.getInstrInfo()));
665 });
666}
667
669SPIRVGlobalRegistry::getOpTypeVector(uint32_t NumElems, SPIRVTypeInst ElemType,
670 MachineIRBuilder &MIRBuilder) {
671 assert(NumElems >= 2 && "SPIR-V OpTypeVector requires at least 2 components");
672 return getOpTypeVectorImpl(NumElems, ElemType, MIRBuilder);
673}
674
675SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeVectorIdEXT(
676 uint32_t NumElems, SPIRVTypeInst ElemType, MachineIRBuilder &MIRBuilder) {
677 assert(NumElems != 2 && NumElems != 3 && NumElems != 4 &&
678 (!MIRBuilder.getMF().getSubtarget<SPIRVSubtarget>().isKernel() ||
679 (NumElems != 8 && NumElems != 16)) &&
680 "SPIR-V OpTypeVectorIdExt should only be used for extended vectors");
681 return getOpTypeVectorImpl(NumElems, ElemType, MIRBuilder, true);
682}
683
685 SPIRVTypeInst SpvType,
686 const SPIRVInstrInfo &TII,
687 bool ZeroAsNull) {
688 LLVMContext &Ctx = CurMF->getFunction().getContext();
689 auto *const CF = ConstantFP::get(Ctx, Val);
690 const MachineInstr *MI = findMI(CF, CurMF);
691 if (MI && (MI->getOpcode() == SPIRV::OpConstantNull ||
692 MI->getOpcode() == SPIRV::OpConstantF))
693 return MI->getOperand(0).getReg();
694 return createConstFP(CF, I, SpvType, TII, ZeroAsNull);
695}
696
699 SPIRVTypeInst SpvType,
700 const SPIRVInstrInfo &TII,
701 bool ZeroAsNull) {
702 unsigned BitWidth = getScalarOrVectorBitWidth(SpvType);
703 Register Res =
704 CurMF->getRegInfo().createGenericVirtualRegister(getRegType(SpvType));
705 CurMF->getRegInfo().setRegClass(Res, &SPIRV::fIDRegClass);
706 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
707
708 MachineInstr *DepMI =
709 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
710 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
711 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
712 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
714 // In OpenCL OpConstantNull - Scalar floating point: +0.0 (all bits 0)
715 if (CF->getValue().isPosZero() && ZeroAsNull) {
716 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
717 .addDef(Res)
718 .addUse(getSPIRVTypeID(SpvType));
719 } else {
720 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantF)
721 .addDef(Res)
722 .addUse(getSPIRVTypeID(SpvType));
725 MIB);
726 }
727 constrainSelectedInstRegOperands(MIB);
728 return MIB;
729 });
730 add(CF, Const);
731 return Res;
732}
733
735 SPIRVTypeInst SpvType,
736 const SPIRVInstrInfo &TII,
737 bool ZeroAsNull) {
739 SpvType, TII, ZeroAsNull);
740}
741
744 SPIRVTypeInst SpvType,
745 const SPIRVInstrInfo &TII,
746 bool ZeroAsNull) {
747 auto *const CI = ConstantInt::get(
749 const MachineInstr *MI = findMI(CI, CurMF);
750 if (MI && (MI->getOpcode() == SPIRV::OpConstantNull ||
751 MI->getOpcode() == SPIRV::OpConstantI))
752 return MI->getOperand(0).getReg();
753 return createConstInt(CI, I, SpvType, TII, ZeroAsNull);
754}
755
758 SPIRVTypeInst SpvType,
759 const SPIRVInstrInfo &TII,
760 bool ZeroAsNull) {
761 unsigned BitWidth = getScalarOrVectorBitWidth(SpvType);
762 LLT LLTy = LLT::scalar(BitWidth);
763 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
764 CurMF->getRegInfo().setRegClass(Res, &SPIRV::iIDRegClass);
766
767 MachineInstr *DepMI =
768 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
769 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
770 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
771 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
773 if (BitWidth == 1) {
774 MIB = MIRBuilder
775 .buildInstr(CI->isZero() ? SPIRV::OpConstantFalse
776 : SPIRV::OpConstantTrue)
777 .addDef(Res)
778 .addUse(getSPIRVTypeID(SpvType));
779 } else if (!CI->isZero() || !ZeroAsNull) {
780 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantI)
781 .addDef(Res)
782 .addUse(getSPIRVTypeID(SpvType));
783 addNumImm(CI->getValue(), MIB);
784 } else {
785 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
786 .addDef(Res)
787 .addUse(getSPIRVTypeID(SpvType));
788 }
789 constrainSelectedInstRegOperands(MIB);
790 return MIB;
791 });
792 add(CI, Const);
793 return Res;
794}
795
797 MachineIRBuilder &MIRBuilder,
798 SPIRVTypeInst SpvType,
799 bool EmitIR, bool ZeroAsNull) {
800 assert(SpvType);
801 auto &MF = MIRBuilder.getMF();
803 // TODO: Avoid implicit trunc?
804 // See https://github.com/llvm/llvm-project/issues/112510.
805 auto *const CI = ConstantInt::get(const_cast<IntegerType *>(Ty), Val,
806 /*IsSigned=*/false, /*ImplicitTrunc=*/true);
807 Register Res = find(CI, &MF);
808 if (Res.isValid())
809 return Res;
810
811 unsigned BitWidth = getScalarOrVectorBitWidth(SpvType);
812 LLT LLTy = LLT::scalar(BitWidth);
813 MachineRegisterInfo &MRI = MF.getRegInfo();
814 Res = MRI.createGenericVirtualRegister(LLTy);
815 MRI.setRegClass(Res, &SPIRV::iIDRegClass);
816 assignTypeToVReg(Ty, Res, MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
817 EmitIR);
818
819 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
820 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
821 if (EmitIR)
822 return MIRBuilder.buildConstant(Res, *CI);
823 Register SpvTypeReg = getSPIRVTypeID(SpvType);
825 if (Val || !ZeroAsNull) {
826 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantI)
827 .addDef(Res)
828 .addUse(SpvTypeReg);
829 addNumImm(APInt(BitWidth, Val), MIB);
830 } else {
831 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
832 .addDef(Res)
833 .addUse(SpvTypeReg);
834 }
835 constrainSelectedInstRegOperands(MIB);
836 return MIB;
837 });
838 add(CI, Const);
839 return Res;
840}
841
843 MachineIRBuilder &MIRBuilder,
844 SPIRVTypeInst SpvType) {
845 auto &MF = MIRBuilder.getMF();
846 LLVMContext &Ctx = MF.getFunction().getContext();
847 if (!SpvType)
848 SpvType = getOrCreateSPIRVType(Type::getFloatTy(Ctx), MIRBuilder,
849 SPIRV::AccessQualifier::ReadWrite, true);
850 auto *const CF = ConstantFP::get(Ctx, Val);
851 Register Res = find(CF, &MF);
852 if (Res.isValid())
853 return Res;
854
855 Res = MF.getRegInfo().createGenericVirtualRegister(getRegType(SpvType));
856 MF.getRegInfo().setRegClass(Res, &SPIRV::fIDRegClass);
857 assignSPIRVTypeToVReg(SpvType, Res, MF);
858
859 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
860 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
862 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantF)
863 .addDef(Res)
864 .addUse(getSPIRVTypeID(SpvType));
865 addNumImm(CF->getValueAPF().bitcastToAPInt(), MIB);
866 return MIB;
867 });
868 add(CF, Const);
869 return Res;
870}
871
872Register SPIRVGlobalRegistry::getOrCreateBaseRegister(
873 Constant *Val, MachineInstr &I, SPIRVTypeInst SpvType,
874 const SPIRVInstrInfo &TII, unsigned BitWidth, bool ZeroAsNull) {
875 SPIRVTypeInst Type = SpvType;
876 if (isVectorType(SpvType) || SpvType->getOpcode() == SPIRV::OpTypeArray) {
877 auto EleTypeReg = SpvType->getOperand(1).getReg();
878 Type = getSPIRVTypeForVReg(EleTypeReg);
879 }
880 if (Type->getOpcode() == SPIRV::OpTypeFloat) {
882 return getOrCreateConstFP(cast<ConstantFP>(Val)->getValue(), I, SpvBaseType,
883 TII, ZeroAsNull);
884 }
885 assert(Type->getOpcode() == SPIRV::OpTypeInt);
886 SPIRVTypeInst SpvBaseType = getOrCreateSPIRVIntegerType(BitWidth, I, TII);
887 return getOrCreateConstInt(Val->getUniqueInteger(), I, SpvBaseType, TII,
888 ZeroAsNull);
889}
890
891Register SPIRVGlobalRegistry::getOrCreateCompositeOrNull(
892 Constant *Val, MachineInstr &I, SPIRVTypeInst SpvType,
893 const SPIRVInstrInfo &TII, Constant *CA, unsigned BitWidth,
894 unsigned ElemCnt, bool ZeroAsNull) {
895 if (Register R = find(CA, CurMF); R.isValid())
896 return R;
897
898 bool IsNull = Val->isNullValue() && ZeroAsNull;
899 Register ElemReg;
900 if (!IsNull)
901 ElemReg =
902 getOrCreateBaseRegister(Val, I, SpvType, TII, BitWidth, ZeroAsNull);
903
904 LLT LLTy = LLT::scalar(64);
905 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
906 CurMF->getRegInfo().setRegClass(Res, getRegClass(SpvType));
907 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
908
909 MachineInstr *DepMI =
910 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
911 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
912 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
913 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
914 MachineInstrBuilder MIB;
915 if (!IsNull) {
916 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantComposite)
917 .addDef(Res)
918 .addUse(getSPIRVTypeID(SpvType));
919 for (unsigned i = 0; i < ElemCnt; ++i)
920 MIB.addUse(ElemReg);
921 } else {
922 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
923 .addDef(Res)
924 .addUse(getSPIRVTypeID(SpvType));
925 }
926 constrainSelectedInstRegOperands(MIB);
927 return MIB;
928 });
929 add(CA, NewMI);
930 return Res;
931}
932
935 SPIRVTypeInst SpvType,
936 const SPIRVInstrInfo &TII,
937 bool ZeroAsNull) {
939 I, SpvType, TII, ZeroAsNull);
940}
941
944 SPIRVTypeInst SpvType,
945 const SPIRVInstrInfo &TII,
946 bool ZeroAsNull) {
947 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
948 assert(LLVMTy->isVectorTy() &&
949 "Expected vector type for constant vector creation");
950 const FixedVectorType *LLVMVecTy = cast<FixedVectorType>(LLVMTy);
951 Type *LLVMBaseTy = LLVMVecTy->getElementType();
952 [[maybe_unused]] const auto &ST = I.getMF()->getSubtarget<SPIRVSubtarget>();
953 assert((LLVMBaseTy->isIntegerTy() ||
954 (LLVMBaseTy->isPointerTy() &&
955 ST.canUseExtension(
956 SPIRV::Extension::SPV_INTEL_masked_gather_scatter))) &&
957 "Expected either integer element type for APInt constant vector or "
958 "pointer type if the SPV_INTEL_masked_gather_scatter extension is "
959 "enabled!");
960 Constant *ConstVal = nullptr;
961 if (LLVMBaseTy->isIntegerTy()) {
962 ConstVal = ConstantInt::get(LLVMBaseTy, Val);
963 } else {
964 if (Val.isZero())
965 ConstVal = ConstantPointerNull::get(LLVMBaseTy);
966 else
967 llvm_unreachable("Vectors of non-null constant pointers unimplemented!");
968 }
969 auto *ConstVec =
970 ConstantVector::getSplat(LLVMVecTy->getElementCount(), ConstVal);
971 unsigned BW = getScalarOrVectorBitWidth(SpvType);
972 return getOrCreateCompositeOrNull(ConstVal, I, SpvType, TII, ConstVec, BW,
974 ZeroAsNull);
975}
976
979 SPIRVTypeInst SpvType,
980 const SPIRVInstrInfo &TII,
981 bool ZeroAsNull) {
982 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
983 assert(LLVMTy->isVectorTy());
984 const FixedVectorType *LLVMVecTy = cast<FixedVectorType>(LLVMTy);
985 Type *LLVMBaseTy = LLVMVecTy->getElementType();
986 assert(LLVMBaseTy->isFloatingPointTy());
987 auto *ConstVal = ConstantFP::get(LLVMBaseTy, Val);
988 auto *ConstVec =
989 ConstantVector::getSplat(LLVMVecTy->getElementCount(), ConstVal);
990 unsigned BW = getScalarOrVectorBitWidth(SpvType);
991 return getOrCreateCompositeOrNull(ConstVal, I, SpvType, TII, ConstVec, BW,
993 ZeroAsNull);
994}
995
997 uint64_t Val, size_t Num, MachineInstr &I, SPIRVTypeInst SpvType,
998 const SPIRVInstrInfo &TII) {
999 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
1000 assert(LLVMTy->isArrayTy());
1001 const ArrayType *LLVMArrTy = cast<ArrayType>(LLVMTy);
1002 Type *LLVMBaseTy = LLVMArrTy->getElementType();
1003 Constant *CI = ConstantInt::get(LLVMBaseTy, Val);
1004 SPIRVTypeInst SpvBaseTy =
1005 getSPIRVTypeForVReg(SpvType->getOperand(1).getReg());
1006 unsigned BW = getScalarOrVectorBitWidth(SpvBaseTy);
1007 // The following is reasonably unique key that is better that [Val]. The naive
1008 // alternative would be something along the lines of:
1009 // SmallVector<Constant *> NumCI(Num, CI);
1010 // Constant *UniqueKey =
1011 // ConstantArray::get(const_cast<ArrayType*>(LLVMArrTy), NumCI);
1012 // that would be a truly unique but dangerous key, because it could lead to
1013 // the creation of constants of arbitrary length (that is, the parameter of
1014 // memset) which were missing in the original module.
1015 Type *I64Ty = Type::getInt64Ty(LLVMBaseTy->getContext());
1016 Constant *UniqueKey = ConstantStruct::getAnon(
1017 {PoisonValue::get(const_cast<ArrayType *>(LLVMArrTy)),
1018 ConstantInt::get(LLVMBaseTy, Val), ConstantInt::get(I64Ty, Num)});
1019 return getOrCreateCompositeOrNull(CI, I, SpvType, TII, UniqueKey, BW,
1020 LLVMArrTy->getNumElements());
1021}
1022
1023Register SPIRVGlobalRegistry::getOrCreateIntCompositeOrNull(
1024 uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType,
1025 bool EmitIR, Constant *CA, unsigned BitWidth, unsigned ElemCnt) {
1026 if (Register R = find(CA, CurMF); R.isValid())
1027 return R;
1028
1029 Register ElemReg;
1030 if (Val || EmitIR) {
1031 SPIRVTypeInst SpvBaseType =
1033 ElemReg = buildConstantInt(Val, MIRBuilder, SpvBaseType, EmitIR);
1034 }
1035 LLT LLTy = EmitIR ? LLT::fixed_vector(ElemCnt, BitWidth) : LLT::scalar(64);
1036 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
1037 CurMF->getRegInfo().setRegClass(Res, &SPIRV::iIDRegClass);
1038 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
1039
1040 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1041 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1042 if (EmitIR)
1043 return MIRBuilder.buildSplatBuildVector(Res, ElemReg);
1044
1045 if (Val) {
1046 auto MIB = MIRBuilder.buildInstr(SPIRV::OpConstantComposite)
1047 .addDef(Res)
1048 .addUse(getSPIRVTypeID(SpvType));
1049 for (unsigned i = 0; i < ElemCnt; ++i)
1050 MIB.addUse(ElemReg);
1051 return MIB;
1052 }
1053
1054 return MIRBuilder.buildInstr(SPIRV::OpConstantNull)
1055 .addDef(Res)
1056 .addUse(getSPIRVTypeID(SpvType));
1057 });
1058 add(CA, NewMI);
1059 return Res;
1060}
1061
1063 uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType,
1064 bool EmitIR) {
1065 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
1066 assert(LLVMTy->isVectorTy());
1067 const FixedVectorType *LLVMVecTy = cast<FixedVectorType>(LLVMTy);
1068 Type *LLVMBaseTy = LLVMVecTy->getElementType();
1069 const auto ConstInt = ConstantInt::get(LLVMBaseTy, Val);
1070 auto ConstVec =
1071 ConstantVector::getSplat(LLVMVecTy->getElementCount(), ConstInt);
1072 unsigned BW = getScalarOrVectorBitWidth(SpvType);
1073 return getOrCreateIntCompositeOrNull(
1074 Val, MIRBuilder, SpvType, EmitIR, ConstVec, BW,
1076}
1077
1080 SPIRVTypeInst SpvType) {
1081 const Type *Ty = getTypeForSPIRVType(SpvType);
1082 unsigned AddressSpace = typeToAddressSpace(Ty);
1084 assert(ElemTy);
1087 Register Res = find(CP, CurMF);
1088 if (Res.isValid())
1089 return Res;
1090
1092 Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
1093 CurMF->getRegInfo().setRegClass(Res, &SPIRV::pIDRegClass);
1094 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
1095
1096 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1097 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1098 return MIRBuilder.buildInstr(SPIRV::OpConstantNull)
1099 .addDef(Res)
1100 .addUse(getSPIRVTypeID(SpvType));
1101 });
1102 add(CP, NewMI);
1103 return Res;
1104}
1105
1108 unsigned Param, unsigned FilerMode,
1109 MachineIRBuilder &MIRBuilder) {
1110 auto Sampler =
1111 ResReg.isValid()
1112 ? ResReg
1113 : MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
1114 SPIRVTypeInst TypeSampler = getOrCreateOpTypeSampler(MIRBuilder);
1115 Register TypeSamplerReg = getSPIRVTypeID(TypeSampler);
1116 // We cannot use createOpType() logic here, because of the
1117 // GlobalISel/IRTranslator.cpp check for a tail call that expects that
1118 // MIRBuilder.getInsertPt() has a previous instruction. If this constant is
1119 // inserted as a result of "__translate_sampler_initializer()" this would
1120 // break this IRTranslator assumption.
1121 MIRBuilder.buildInstr(SPIRV::OpConstantSampler)
1122 .addDef(Sampler)
1123 .addUse(TypeSamplerReg)
1125 .addImm(Param)
1126 .addImm(FilerMode);
1127 return Sampler;
1128}
1129
1132 const GlobalValue *GV, SPIRV::StorageClass::StorageClass Storage,
1133 const MachineInstr *Init, bool IsConst,
1134 const std::optional<SPIRV::LinkageType::LinkageType> &LinkageType,
1135 MachineIRBuilder &MIRBuilder, bool IsInstSelector) {
1136 const GlobalVariable *GVar = nullptr;
1137 if (GV) {
1138 GVar = cast<const GlobalVariable>(GV);
1139 } else {
1140 // If GV is not passed explicitly, use the name to find or construct
1141 // the global variable.
1142 Module *M = MIRBuilder.getMF().getFunction().getParent();
1143 GVar = M->getGlobalVariable(Name);
1144 if (GVar == nullptr) {
1145 const Type *Ty = getTypeForSPIRVType(BaseType); // TODO: check type.
1146 if (auto *TPTy = dyn_cast<TypedPointerType>(Ty))
1147 Ty = PointerType::get(M->getContext(), TPTy->getAddressSpace());
1148 // Module takes ownership of the global var.
1149 GVar = new GlobalVariable(*M, const_cast<Type *>(Ty), false,
1151 Twine(Name));
1152 }
1153 GV = GVar;
1154 }
1155
1156 const MachineFunction *MF = &MIRBuilder.getMF();
1157 Register Reg = find(GVar, MF);
1158 if (Reg.isValid()) {
1159 if (Reg != ResVReg)
1160 MIRBuilder.buildCopy(ResVReg, Reg);
1161 return ResVReg;
1162 }
1163
1164 // Emit the OpVariable into the entry block to ensure the def dominates
1165 // all uses across all MBBs.
1166 MachineBasicBlock &EntryBB = MIRBuilder.getMF().front();
1167 MachineIRBuilder GVBuilder(MIRBuilder.getState());
1168 if (&GVBuilder.getMBB() != &EntryBB)
1169 GVBuilder.setInsertPt(EntryBB, getOpVariableMBBIt(MIRBuilder.getMF()));
1170
1171 // Pointers to opaque types stay typed even with the extension on, so emit the
1172 // untyped variant only when the result is actually an untyped pointer.
1173 const bool UseUntypedPointers =
1174 BaseType->getOpcode() == SPIRV::OpTypeUntypedPointerKHR;
1175 const unsigned VariableOpcode =
1176 UseUntypedPointers ? SPIRV::OpUntypedVariableKHR : SPIRV::OpVariable;
1177
1178 auto MIB = GVBuilder.buildInstr(VariableOpcode)
1179 .addDef(ResVReg)
1181 .addImm(static_cast<uint32_t>(Storage));
1182
1183 // OpUntypedVariableKHR takes an extra Data Type operand right after the
1184 // storage class, holding the global's value type.
1185 if (UseUntypedPointers) {
1187 if (!DataType)
1188 DataType = getOrCreateSPIRVType(GV->getValueType(), GVBuilder,
1189 SPIRV::AccessQualifier::ReadWrite,
1190 /*EmitIR=*/false);
1191 if (!DataType) {
1192 const Function &F = MIRBuilder.getMF().getFunction();
1193 F.getContext().diagnose(DiagnosticInfoUnsupported(
1194 F,
1195 "Could not deduce the data type of untyped global variable '" +
1196 GVar->getName() + "'",
1197 DebugLoc(), DS_Error));
1198 // Recover with i8 so that codegen can finish and report the error.
1199 DataType =
1200 getOrCreateSPIRVType(Type::getInt8Ty(F.getContext()), GVBuilder,
1201 SPIRV::AccessQualifier::ReadWrite,
1202 /*EmitIR=*/false);
1203 }
1204 MIB.addUse(getSPIRVTypeID(DataType));
1205 }
1206
1207 if (Init)
1208 MIB.addUse(Init->getOperand(0).getReg());
1209 // ISel may introduce a new register on this step, so we need to add it to
1210 // DT and correct its type avoiding fails on the next stage.
1211 if (IsInstSelector) {
1212 constrainSelectedInstRegOperands(MIB);
1213 }
1214 add(GVar, MIB);
1215
1216 Reg = MIB->getOperand(0).getReg();
1217 addGlobalObject(GVar, MF, Reg);
1218
1219 // Set to Reg the same type as ResVReg has.
1220 auto MRI = MIRBuilder.getMRI();
1221 if (Reg != ResVReg) {
1222 LLT RegLLTy =
1223 LLT::pointer(MRI->getType(ResVReg).getAddressSpace(), getPointerSize());
1224 MRI->setType(Reg, RegLLTy);
1225 assignSPIRVTypeToVReg(BaseType, Reg, MIRBuilder.getMF());
1226 } else {
1227 // Our knowledge about the type may be updated.
1228 // If that's the case, we need to update a type
1229 // associated with the register.
1230 SPIRVTypeInst DefType = getSPIRVTypeForVReg(ResVReg);
1231 if (!DefType || DefType != SPIRVTypeInst(BaseType))
1232 assignSPIRVTypeToVReg(BaseType, Reg, MIRBuilder.getMF());
1233 }
1234
1235 // If it's a global variable with name, output OpName for it.
1236 if (GVar && GVar->hasName())
1237 buildOpName(Reg, GVar->getName(), MIRBuilder);
1238
1239 // Output decorations for the GV.
1240 // TODO: maybe move to GenerateDecorations pass.
1241 const SPIRVSubtarget &ST =
1242 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
1243 if (IsConst && !ST.isShader())
1244 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::Constant, {});
1245
1246 if (GVar && GVar->getAlign().valueOrOne().value() != 1 && !ST.isShader()) {
1247 unsigned Alignment = (unsigned)GVar->getAlign().valueOrOne().value();
1248 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::Alignment, {Alignment});
1249 }
1250
1251 if (LinkageType)
1252 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::LinkageAttributes,
1253 {static_cast<uint32_t>(*LinkageType)}, Name);
1254
1255 SPIRV::BuiltIn::BuiltIn BuiltInId;
1256 if (getSpirvBuiltInIdByName(Name, BuiltInId))
1257 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::BuiltIn,
1258 {static_cast<uint32_t>(BuiltInId)});
1259
1260 // If it's a global variable with "spirv.Decorations" metadata node
1261 // recognize it as a SPIR-V friendly LLVM IR and parse "spirv.Decorations"
1262 // arguments.
1263 MDNode *GVarMD = nullptr;
1264 if (GVar && (GVarMD = GVar->getMetadata("spirv.Decorations")) != nullptr)
1265 buildOpSpirvDecorations(Reg, MIRBuilder, GVarMD, ST);
1266
1267 return Reg;
1268}
1269
1270// Returns a name based on the Type. Notes that this does not look at
1271// decorations, and will return the same string for two types that are the same
1272// except for decorations.
1274 SPIRVTypeInst VarType, uint32_t Set, uint32_t Binding, StringRef Name,
1275 MachineIRBuilder &MIRBuilder) {
1276 Register VarReg =
1277 MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
1278
1279 buildGlobalVariable(VarReg, VarType, Name, nullptr,
1280 getPointerStorageClass(VarType), nullptr, false,
1281 std::nullopt, MIRBuilder, false);
1282
1283 buildOpDecorate(VarReg, MIRBuilder, SPIRV::Decoration::DescriptorSet, {Set});
1284 buildOpDecorate(VarReg, MIRBuilder, SPIRV::Decoration::Binding, {Binding});
1285 return VarReg;
1286}
1287
1288// TODO: Double check the calls to getOpTypeArray to make sure that `ElemType`
1289// is explicitly laid out when required.
1290SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeArray(uint32_t NumElems,
1291 SPIRVTypeInst ElemType,
1292 MachineIRBuilder &MIRBuilder,
1293 bool ExplicitLayoutRequired,
1294 bool EmitIR) {
1295 assert((ElemType->getOpcode() != SPIRV::OpTypeVoid) &&
1296 "Invalid array element type");
1297 SPIRVTypeInst SpvTypeInt32 = getOrCreateSPIRVIntegerType(32, MIRBuilder);
1298 SPIRVTypeInst ArrayType = nullptr;
1299 const SPIRVSubtarget &ST =
1300 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
1301 if (NumElems != 0) {
1302 Register NumElementsVReg =
1303 buildConstantInt(NumElems, MIRBuilder, SpvTypeInt32, EmitIR);
1304 ArrayType = createConstOrTypeAtFunctionEntry(
1305 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1306 return MIRBuilder.buildInstr(SPIRV::OpTypeArray)
1307 .addDef(createTypeVReg(MIRBuilder))
1308 .addUse(getSPIRVTypeID(ElemType))
1309 .addUse(NumElementsVReg);
1310 });
1311 } else if (ST.getTargetTriple().getVendor() == Triple::VendorType::AMD) {
1312 // We set the array size to the token UINT64_MAX value, which is generally
1313 // illegal (the maximum legal size is 61-bits) for the foreseeable future.
1314 SPIRVTypeInst SpvTypeInt64 = getOrCreateSPIRVIntegerType(64, MIRBuilder);
1315 Register NumElementsVReg =
1316 buildConstantInt(UINT64_MAX, MIRBuilder, SpvTypeInt64, EmitIR);
1317 ArrayType = createConstOrTypeAtFunctionEntry(
1318 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1319 return MIRBuilder.buildInstr(SPIRV::OpTypeArray)
1320 .addDef(createTypeVReg(MIRBuilder))
1321 .addUse(getSPIRVTypeID(ElemType))
1322 .addUse(NumElementsVReg);
1323 });
1324 } else {
1325 if (!ST.isShader()) {
1327 "Runtime arrays are not allowed in non-shader "
1328 "SPIR-V modules");
1329 return nullptr;
1330 }
1331 ArrayType = createConstOrTypeAtFunctionEntry(
1332 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1333 return MIRBuilder.buildInstr(SPIRV::OpTypeRuntimeArray)
1334 .addDef(createTypeVReg(MIRBuilder))
1335 .addUse(getSPIRVTypeID(ElemType));
1336 });
1337 }
1338
1339 if (ExplicitLayoutRequired && !isResourceType(ElemType)) {
1340 Type *ET = const_cast<Type *>(getTypeForSPIRVType(ElemType));
1341 addArrayStrideDecorations(ArrayType->defs().begin()->getReg(), ET,
1342 MIRBuilder);
1343 }
1344
1345 return ArrayType;
1346}
1347
1349SPIRVGlobalRegistry::getOpTypeOpaque(const StructType *Ty,
1350 MachineIRBuilder &MIRBuilder) {
1351 assert(Ty->hasName());
1352 StringRef Name = Ty->hasName() ? Ty->getName() : "";
1353 Register ResVReg = createTypeVReg(MIRBuilder);
1354 return createConstOrTypeAtFunctionEntry(
1355 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1356 auto MIB = MIRBuilder.buildInstr(SPIRV::OpTypeOpaque).addDef(ResVReg);
1357 addStringImm(Name, MIB);
1358 buildOpName(ResVReg, Name, MIRBuilder);
1359 return MIB;
1360 });
1361}
1362
1363SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeStruct(
1364 const StructType *Ty, MachineIRBuilder &MIRBuilder,
1365 SPIRV::AccessQualifier::AccessQualifier AccQual,
1366 StructOffsetDecorator Decorator, bool EmitIR) {
1367 Type *OriginalElementType = nullptr;
1368 uint64_t TotalSize = 0;
1369 if (matchPeeledArrayPattern(Ty, OriginalElementType, TotalSize)) {
1370 SPIRVTypeInst ElementSPIRVType = findSPIRVType(
1371 OriginalElementType, MIRBuilder, AccQual,
1372 /* ExplicitLayoutRequired= */ Decorator != nullptr, EmitIR);
1373 return getOpTypeArray(TotalSize, ElementSPIRVType, MIRBuilder,
1374 /*ExplicitLayoutRequired=*/Decorator != nullptr,
1375 EmitIR);
1376 }
1377
1378 const SPIRVSubtarget &ST =
1379 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
1380 SmallVector<Register, 4> FieldTypes;
1381 constexpr unsigned MaxWordCount = UINT16_MAX;
1382 const size_t NumElements = Ty->getNumElements();
1383
1384 size_t MaxNumElements = MaxWordCount - 2;
1385 size_t SPIRVStructNumElements = NumElements;
1386 if (NumElements > MaxNumElements) {
1387 // Do adjustments for continued instructions.
1388 SPIRVStructNumElements = MaxNumElements;
1389 MaxNumElements = MaxWordCount - 1;
1390 }
1391
1392 for (const auto &[Idx, Elem] : enumerate(Ty->elements())) {
1393 SPIRVTypeInst ElemTy;
1394 auto *PadTy = dyn_cast<TargetExtType>(Elem);
1395 if (PadTy && PadTy->getName() == "spirv.Padding")
1396 ElemTy = getOrCreatePaddingType(
1397 MIRBuilder, PadTy->getIntParameter(0),
1398 DL.getStructLayout(const_cast<StructType *>(Ty))
1399 ->getElementOffset(Idx));
1400 else
1401 ElemTy = findSPIRVType(toTypedPointer(Elem), MIRBuilder, AccQual,
1402 /* ExplicitLayoutRequired= */ Decorator != nullptr,
1403 EmitIR);
1404 assert(ElemTy && ElemTy->getOpcode() != SPIRV::OpTypeVoid &&
1405 "Invalid struct element type");
1406 FieldTypes.push_back(getSPIRVTypeID(ElemTy));
1407 }
1408 Register ResVReg = createTypeVReg(MIRBuilder);
1409 if (Ty->hasName())
1410 buildOpName(ResVReg, Ty->getName(), MIRBuilder);
1411 if (Ty->isPacked() && !ST.isShader())
1412 buildOpDecorate(ResVReg, MIRBuilder, SPIRV::Decoration::CPacked, {});
1413
1414 SPIRVTypeInst SPVType = createConstOrTypeAtFunctionEntry(
1415 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1416 auto MIBStruct =
1417 MIRBuilder.buildInstr(SPIRV::OpTypeStruct).addDef(ResVReg);
1418 for (size_t I = 0; I < SPIRVStructNumElements; ++I)
1419 MIBStruct.addUse(FieldTypes[I]);
1420 for (size_t I = SPIRVStructNumElements; I < NumElements;
1421 I += MaxNumElements) {
1422 auto MIBCont =
1423 MIRBuilder.buildInstr(SPIRV::OpTypeStructContinuedINTEL);
1424 for (size_t J = I; J < std::min(I + MaxNumElements, NumElements); ++J)
1425 MIBCont.addUse(FieldTypes[J]);
1426 }
1427 return MIBStruct;
1428 });
1429
1430 if (Decorator)
1431 Decorator(SPVType->defs().begin()->getReg());
1432
1433 return SPVType;
1434}
1435
1436SPIRVTypeInst SPIRVGlobalRegistry::getOrCreateSpecialType(
1437 const Type *Ty, MachineIRBuilder &MIRBuilder,
1438 SPIRV::AccessQualifier::AccessQualifier AccQual) {
1439 assert(isSpecialOpaqueType(Ty) && "Not a special opaque builtin type");
1440 return SPIRV::lowerBuiltinType(Ty, AccQual, MIRBuilder, this);
1441}
1442
1443SPIRVTypeInst SPIRVGlobalRegistry::getOpTypePointer(
1444 SPIRV::StorageClass::StorageClass SC, SPIRVTypeInst ElemType,
1445 MachineIRBuilder &MIRBuilder, Register Reg) {
1446 // Check if we should use untyped pointers.
1447 const SPIRVSubtarget &ST =
1448 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
1449 if (shouldUseUntypedPointer(ElemType, ST))
1450 return getOrCreateSPIRVUntypedPointerType(SC, MIRBuilder);
1451
1452 if (!Reg.isValid())
1453 Reg = createTypeVReg(MIRBuilder);
1454
1455 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
1456 &MIRBuilder) {
1457 return MIRBuilder.buildInstr(SPIRV::OpTypePointer)
1458 .addDef(Reg)
1459 .addImm(static_cast<uint32_t>(SC))
1460 .addUse(getSPIRVTypeID(ElemType));
1461 });
1462}
1463
1464SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeFunction(
1465 const FunctionType *Ty, SPIRVTypeInst RetType,
1466 const SmallVectorImpl<SPIRVTypeInst> &ArgTypes,
1467 MachineIRBuilder &MIRBuilder) {
1468 const SPIRVSubtarget *ST =
1469 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
1470 if (Ty->isVarArg() && ST->isShader()) {
1471 Function &Fn = MIRBuilder.getMF().getFunction();
1472 Ty->getContext().diagnose(DiagnosticInfoUnsupported(
1473 Fn, "SPIR-V shaders do not support variadic functions",
1474 MIRBuilder.getDebugLoc()));
1475 }
1476 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
1477 &MIRBuilder) {
1478 auto MIB = MIRBuilder.buildInstr(SPIRV::OpTypeFunction)
1479 .addDef(createTypeVReg(MIRBuilder))
1480 .addUse(getSPIRVTypeID(RetType));
1481 for (auto &ArgType : ArgTypes)
1482 MIB.addUse(getSPIRVTypeID(ArgType));
1483 return MIB;
1484 });
1485}
1486
1488 const Type *Ty, SPIRVTypeInst RetType,
1489 const SmallVectorImpl<SPIRVTypeInst> &ArgTypes,
1490 MachineIRBuilder &MIRBuilder) {
1491 if (const MachineInstr *MI = findMI(Ty, false, &MIRBuilder.getMF()))
1492 return MI;
1493 const MachineInstr *NewMI =
1494 getOpTypeFunction(cast<FunctionType>(Ty), RetType, ArgTypes, MIRBuilder);
1495 add(Ty, false, NewMI);
1496 return finishCreatingSPIRVType(Ty, NewMI);
1497}
1498
1499SPIRVTypeInst SPIRVGlobalRegistry::findSPIRVType(
1500 const Type *Ty, MachineIRBuilder &MIRBuilder,
1501 SPIRV::AccessQualifier::AccessQualifier AccQual,
1502 bool ExplicitLayoutRequired, bool EmitIR) {
1503 const auto &STI = MIRBuilder.getMF().getSubtarget<SPIRVSubtarget>();
1504 // Treat <1 x T> as T if the SPV_EXT_long_vector extension is not available.
1505 if (auto *FVT = dyn_cast<FixedVectorType>(Ty);
1506 FVT && FVT->getNumElements() == 1 &&
1507 !STI.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector))
1508 return findSPIRVType(FVT->getElementType(), MIRBuilder, AccQual,
1509 ExplicitLayoutRequired, EmitIR);
1510 Ty = adjustIntTypeByWidth(Ty);
1511 // TODO: findMI needs to know if a layout is required.
1512 if (const MachineInstr *MI =
1513 findMI(Ty, ExplicitLayoutRequired, &MIRBuilder.getMF()))
1514 return MI;
1515 if (auto It = ForwardPointerTypes.find(Ty); It != ForwardPointerTypes.end())
1516 return It->second;
1517 return restOfCreateSPIRVType(Ty, MIRBuilder, AccQual, ExplicitLayoutRequired,
1518 EmitIR);
1519}
1520
1522 assert(SpirvType && "Attempting to get type id for nullptr type.");
1523 if (SpirvType->getOpcode() == SPIRV::OpTypeForwardPointer ||
1524 SpirvType->getOpcode() == SPIRV::OpTypeStructContinuedINTEL)
1525 return SpirvType->uses().begin()->getReg();
1526 return SpirvType->defs().begin()->getReg();
1527}
1528
1529// We need to use a new LLVM integer type if there is a mismatch between
1530// number of bits in LLVM and SPIRV integer types to let DuplicateTracker
1531// ensure uniqueness of a SPIRV type by the corresponding LLVM type. Without
1532// such an adjustment SPIRVGlobalRegistry::getOpTypeInt() could create the
1533// same "OpTypeInt 8" type for a series of LLVM integer types with number of
1534// bits less than 8. This would lead to duplicate type definitions
1535// eventually due to the method that DuplicateTracker utilizes to reason
1536// about uniqueness of type records.
1537const Type *SPIRVGlobalRegistry::adjustIntTypeByWidth(const Type *Ty) const {
1538 if (auto IType = dyn_cast<IntegerType>(Ty)) {
1539 unsigned SrcBitWidth = IType->getBitWidth();
1540 if (SrcBitWidth > 1) {
1541 unsigned BitWidth = adjustOpTypeIntWidth(SrcBitWidth);
1542 // Maybe change source LLVM type to keep DuplicateTracker consistent.
1543 if (SrcBitWidth != BitWidth)
1544 Ty = IntegerType::get(Ty->getContext(), BitWidth);
1545 }
1546 }
1547 return Ty;
1548}
1549
1550SPIRVTypeInst SPIRVGlobalRegistry::createSPIRVType(
1551 const Type *Ty, MachineIRBuilder &MIRBuilder,
1552 SPIRV::AccessQualifier::AccessQualifier AccQual,
1553 bool ExplicitLayoutRequired, bool EmitIR) {
1554 if (isSpecialOpaqueType(Ty))
1555 return getOrCreateSpecialType(Ty, MIRBuilder, AccQual);
1556
1557 if (const MachineInstr *MI =
1558 findMI(Ty, ExplicitLayoutRequired, &MIRBuilder.getMF()))
1559 return MI;
1560
1561 if (auto IType = dyn_cast<IntegerType>(Ty)) {
1562 const unsigned Width = IType->getBitWidth();
1563 return Width == 1 ? getOpTypeBool(MIRBuilder)
1564 : getOpTypeInt(Width, MIRBuilder, false);
1565 }
1566 if (Ty->isFloatingPointTy()) {
1567 if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty())
1568 llvm::reportFatalUsageError("fp128 is not supported in SPIR-V");
1569 if (Ty->isBFloatTy()) {
1570 return getOpTypeFloat(Ty->getPrimitiveSizeInBits(), MIRBuilder,
1571 SPIRV::FPEncoding::BFloat16KHR);
1572 } else {
1573 return getOpTypeFloat(Ty->getPrimitiveSizeInBits(), MIRBuilder);
1574 }
1575 }
1576 if (Ty->isVoidTy())
1577 return getOpTypeVoid(MIRBuilder);
1578 if (Ty->isVectorTy()) {
1579 SPIRVTypeInst El =
1580 findSPIRVType(cast<FixedVectorType>(Ty)->getElementType(), MIRBuilder,
1581 AccQual, ExplicitLayoutRequired, EmitIR);
1582 unsigned NumElts = cast<FixedVectorType>(Ty)->getNumElements();
1583 const auto &STI = MIRBuilder.getMF().getSubtarget<SPIRVSubtarget>();
1584 if (isLongVectorEXT(Ty, STI.isKernel()) &&
1585 STI.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector))
1586 return getOpTypeVectorIdEXT(NumElts, El, MIRBuilder);
1587 return getOpTypeVector(NumElts, El, MIRBuilder);
1588 }
1589 if (Ty->isArrayTy()) {
1590 SPIRVTypeInst El = findSPIRVType(Ty->getArrayElementType(), MIRBuilder,
1591 AccQual, ExplicitLayoutRequired, EmitIR);
1592 return getOpTypeArray(Ty->getArrayNumElements(), El, MIRBuilder,
1593 ExplicitLayoutRequired, EmitIR);
1594 }
1595 if (auto SType = dyn_cast<StructType>(Ty)) {
1596 if (SType->isOpaque())
1597 return getOpTypeOpaque(SType, MIRBuilder);
1598
1599 StructOffsetDecorator Decorator = nullptr;
1600 if (ExplicitLayoutRequired) {
1601 Decorator = [&MIRBuilder, SType, this](Register Reg) {
1602 addStructOffsetDecorations(Reg, const_cast<StructType *>(SType),
1603 MIRBuilder);
1604 };
1605 }
1606 return getOpTypeStruct(SType, MIRBuilder, AccQual, std::move(Decorator),
1607 EmitIR);
1608 }
1609 if (auto FType = dyn_cast<FunctionType>(Ty)) {
1610 SPIRVTypeInst RetTy =
1611 findSPIRVType(FType->getReturnType(), MIRBuilder, AccQual,
1612 ExplicitLayoutRequired, EmitIR);
1614 for (const auto &ParamTy : FType->params())
1615 ParamTypes.push_back(findSPIRVType(ParamTy, MIRBuilder, AccQual,
1616 ExplicitLayoutRequired, EmitIR));
1617 return getOpTypeFunction(FType, RetTy, ParamTypes, MIRBuilder);
1618 }
1619
1620 unsigned AddrSpace = typeToAddressSpace(Ty);
1621
1622 // Get access to information about available extensions
1623 const SPIRVSubtarget *ST =
1624 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
1625 auto SC = addressSpaceToStorageClass(AddrSpace, *ST);
1626
1627 SPIRVTypeInst SpvElementType = nullptr;
1628 Type *ElemTy = ::getPointeeType(Ty);
1629 if (ElemTy && isa<FunctionType>(ElemTy) &&
1630 !ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
1631 ElemTy = nullptr;
1632 if (ElemTy)
1633 SpvElementType = getOrCreateSPIRVType(ElemTy, MIRBuilder, AccQual, EmitIR);
1634 else
1635 SpvElementType = getOrCreateSPIRVIntegerType(8, MIRBuilder);
1636
1637 if (!ElemTy) {
1638 ElemTy = Type::getInt8Ty(MIRBuilder.getContext());
1639 }
1640
1641 // If we have forward pointer associated with this type, use its register
1642 // operand to create OpTypePointer.
1643 if (auto It = ForwardPointerTypes.find(Ty); It != ForwardPointerTypes.end()) {
1644 Register Reg = getSPIRVTypeID(It->second);
1645 // TODO: what does getOpTypePointer do?
1646 return getOpTypePointer(SC, SpvElementType, MIRBuilder, Reg);
1647 }
1648
1649 return getOrCreateSPIRVPointerType(ElemTy, MIRBuilder, SC);
1650}
1651
1652SPIRVTypeInst SPIRVGlobalRegistry::restOfCreateSPIRVType(
1653 const Type *Ty, MachineIRBuilder &MIRBuilder,
1654 SPIRV::AccessQualifier::AccessQualifier AccessQual,
1655 bool ExplicitLayoutRequired, bool EmitIR) {
1656 // TODO: Could this create a problem if one requires an explicit layout, and
1657 // the next time it does not?
1658 if (TypesInProcessing.count(Ty) && !isPointerTyOrWrapper(Ty))
1659 return nullptr;
1660 TypesInProcessing.insert(Ty);
1661 SPIRVTypeInst SpirvType = createSPIRVType(Ty, MIRBuilder, AccessQual,
1662 ExplicitLayoutRequired, EmitIR);
1663 TypesInProcessing.erase(Ty);
1664 VRegToTypeMap[&MIRBuilder.getMF()][getSPIRVTypeID(SpirvType)] = SpirvType;
1665
1666 // TODO: We could end up with two SPIR-V types pointing to the same llvm type.
1667 // Is that a problem?
1668 // spirv.Padding lowers to a plain integer type shared with real members;
1669 // keep that integer's IR type instead of remapping it to the target type.
1670 auto *PadTy = dyn_cast<TargetExtType>(Ty);
1671 if (!(PadTy && PadTy->getName() == "spirv.Padding"))
1672 SPIRVToLLVMType[SpirvType] = unifyPtrType(Ty);
1673
1674 if (SpirvType->getOpcode() != SPIRV::OpTypeForwardPointer &&
1675 SpirvType->getOpcode() != SPIRV::OpTypeUntypedPointerKHR &&
1677 addTypeKey(Ty, ExplicitLayoutRequired, SpirvType, MIRBuilder.getMF());
1678 return SpirvType;
1679}
1680
1681void SPIRVGlobalRegistry::addTypeKey(const Type *Ty,
1682 bool ExplicitLayoutRequired,
1683 SPIRVTypeInst SpirvType,
1684 const MachineFunction &MF) {
1685 if (findMI(Ty, false, &MF))
1686 return;
1687 if (auto *ExtTy = dyn_cast<TargetExtType>(Ty);
1688 ExtTy && isTypedPointerWrapper(ExtTy))
1689 add(ExtTy->getTypeParameter(0), ExtTy->getIntParameter(0), SpirvType);
1690 else if (!isPointerTy(Ty))
1691 add(Ty, ExplicitLayoutRequired, SpirvType);
1692 else if (isTypedPointerTy(Ty))
1693 add(cast<TypedPointerType>(Ty)->getElementType(),
1694 getPointerAddressSpace(Ty), SpirvType);
1695 else
1697 SpirvType);
1698}
1699
1702 const MachineFunction *MF) const {
1703 auto t = VRegToTypeMap.find(MF ? MF : CurMF);
1704 if (t != VRegToTypeMap.end()) {
1705 auto tt = t->second.find(VReg);
1706 if (tt != t->second.end())
1707 return tt->second;
1708 }
1709 return nullptr;
1710}
1711
1713 MachineFunction *MF) {
1714 if (!MF)
1715 MF = CurMF;
1716 MachineInstr *Instr = getVRegDef(MF->getRegInfo(), VReg);
1717 return getSPIRVTypeForVReg(Instr->getOperand(1).getReg(), MF);
1718}
1719
1721 const Type *Ty, MachineIRBuilder &MIRBuilder,
1722 SPIRV::AccessQualifier::AccessQualifier AccessQual,
1723 bool ExplicitLayoutRequired, bool EmitIR) {
1724 // SPIR-V doesn't support single-element vectors. Treat <1 x T> as T if the
1725 // SPV_EXT_long_vector extension is not available.
1726 const auto &STI = MIRBuilder.getMF().getSubtarget<SPIRVSubtarget>();
1727 if (auto *FVT = dyn_cast<FixedVectorType>(Ty);
1728 FVT && FVT->getNumElements() == 1 &&
1729 !STI.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector))
1730 return getOrCreateSPIRVType(FVT->getElementType(), MIRBuilder, AccessQual,
1731 ExplicitLayoutRequired, EmitIR);
1732 const MachineFunction *MF = &MIRBuilder.getMF();
1733 Register Reg;
1734 if (auto *ExtTy = dyn_cast<TargetExtType>(Ty);
1735 ExtTy && isTypedPointerWrapper(ExtTy))
1736 Reg = find(ExtTy->getTypeParameter(0), ExtTy->getIntParameter(0), MF);
1737 else if (!isPointerTy(Ty))
1738 Reg = find(Ty = adjustIntTypeByWidth(Ty), ExplicitLayoutRequired, MF);
1739 else if (isTypedPointerTy(Ty))
1740 Reg = find(cast<TypedPointerType>(Ty)->getElementType(),
1741 getPointerAddressSpace(Ty), MF);
1742 else
1743 Reg = find(Type::getInt8Ty(MIRBuilder.getMF().getFunction().getContext()),
1744 getPointerAddressSpace(Ty), MF);
1745 if (Reg.isValid() && !isSpecialOpaqueType(Ty))
1746 return getSPIRVTypeForVReg(Reg);
1747
1748 TypesInProcessing.clear();
1749 SPIRVTypeInst STy = restOfCreateSPIRVType(Ty, MIRBuilder, AccessQual,
1750 ExplicitLayoutRequired, EmitIR);
1751 // Create normal pointer types for the corresponding OpTypeForwardPointers.
1752 for (auto &CU : ForwardPointerTypes) {
1753 // Pointer type themselves do not require an explicit layout. The types
1754 // they pointer to might, but that is taken care of when creating the type.
1755 bool PtrNeedsLayout = false;
1756 const Type *Ty2 = CU.first;
1757 SPIRVTypeInst STy2 = CU.second;
1758 if ((Reg = find(Ty2, PtrNeedsLayout, MF)).isValid())
1759 STy2 = getSPIRVTypeForVReg(Reg);
1760 else
1761 STy2 = restOfCreateSPIRVType(Ty2, MIRBuilder, AccessQual, PtrNeedsLayout,
1762 EmitIR);
1763 if (Ty == Ty2)
1764 STy = STy2;
1765 }
1766 ForwardPointerTypes.clear();
1767 return STy;
1768}
1769
1771 unsigned TypeOpcode) const {
1773 assert(Type && "isScalarOfType VReg has no type assigned");
1774 return Type->getOpcode() == TypeOpcode;
1775}
1776
1778 unsigned TypeOpcode) const {
1780 assert(Type && "isScalarOrVectorOfType VReg has no type assigned");
1781 if (Type->getOpcode() == TypeOpcode)
1782 return true;
1783 if (!isVectorType(Type))
1784 return false;
1785 Register ScalarTypeVReg = Type->getOperand(1).getReg();
1786 SPIRVTypeInst ScalarType = getSPIRVTypeForVReg(ScalarTypeVReg);
1787 return ScalarType->getOpcode() == TypeOpcode;
1788}
1789
1791 switch (Type->getOpcode()) {
1792 case SPIRV::OpTypeImage:
1793 case SPIRV::OpTypeSampler:
1794 case SPIRV::OpTypeSampledImage:
1795 return true;
1796 case SPIRV::OpTypeStruct:
1797 return BlockDecoratedTypes.contains(Type);
1798 default:
1799 return false;
1800 }
1801 return false;
1802}
1803unsigned
1807
1808unsigned
1810 if (!Type)
1811 return 0;
1812 if (isVectorType(Type))
1813 return (Type->getOpcode() == SPIRV::OpTypeVector)
1814 ? static_cast<unsigned>(Type->getOperand(2).getImm())
1815 : foldImm(Type->getOperand(2), &CurMF->getRegInfo());
1816 return 1;
1817}
1818
1821 if (!Type)
1822 return nullptr;
1823 Register ScalarReg = (isVectorType(Type)) ? Type->getOperand(1).getReg()
1824 : Type->getOperand(0).getReg();
1825 SPIRVTypeInst ScalarType = getSPIRVTypeForVReg(ScalarReg);
1826 assert(isScalarOrVectorOfType(Type->getOperand(0).getReg(),
1827 ScalarType->getOpcode()));
1828 return ScalarType;
1829}
1830
1831unsigned
1833 assert(Type && "Invalid Type pointer");
1835 if (ScalarType->getOpcode() == SPIRV::OpTypeInt ||
1836 ScalarType->getOpcode() == SPIRV::OpTypeFloat)
1837 return ScalarType->getOperand(1).getImm();
1838 if (ScalarType->getOpcode() == SPIRV::OpTypeBool)
1839 return 1;
1840 if (ScalarType->getOpcode() == SPIRV::OpTypePointer)
1841 return getPointerSize(); // TODO: does not work for different per AS sizes.
1843 "Attempting to get bit width of non-integer/float/pointer type.");
1844}
1845
1847 SPIRVTypeInst Type) const {
1848 assert(Type && "Invalid Type pointer");
1849 unsigned NumElements = getScalarOrVectorComponentCount(Type);
1851 return ScalarType->getOpcode() == SPIRV::OpTypeInt ||
1852 ScalarType->getOpcode() == SPIRV::OpTypeFloat
1853 ? NumElements * ScalarType->getOperand(1).getImm()
1854 : 0;
1855}
1856
1858 // A function pointer has to keep its function type, which an untyped pointer
1859 // cannot express.
1860 if (ElemType && ElemType->getOpcode() == SPIRV::OpTypeFunction)
1861 return true;
1862 auto It = SPIRVToLLVMType.find(ElemType);
1863 return It != SPIRVToLLVMType.end() && It->second &&
1864 isSpecialOpaqueType(It->second);
1865}
1866
1868 SPIRVTypeInst ElemType, const SPIRVSubtarget &ST) const {
1869 // Shaders keep typed pointers, as this implementation targets compute.
1870 return ST.canUseExtension(SPIRV::Extension::SPV_KHR_untyped_pointers) &&
1871 !ST.isShader() && !shouldKeepTypedPtrType(ElemType);
1872}
1873
1877 return ScalarType && ScalarType->getOpcode() == SPIRV::OpTypeInt ? ScalarType
1878 : nullptr;
1879}
1880
1883 return IntType && IntType->getOperand(2).getImm() != 0;
1884}
1885
1887 return PtrType && PtrType->getOpcode() == SPIRV::OpTypePointer
1888 ? getSPIRVTypeForVReg(PtrType->getOperand(2).getReg())
1889 : nullptr;
1890}
1891
1893 SPIRVTypeInst Type2) const {
1894 if (!Type1 || !Type2)
1895 return false;
1896 // Ignore difference between <1.5 and >=1.5 protocol versions:
1897 // it's valid if either Result Type or Operand is a pointer, and the other
1898 // is a pointer, an integer scalar, or an integer vector.
1899 if (Type1.isPointer() &&
1900 (Type2.isPointer() || retrieveScalarOrVectorIntType(Type2)))
1901 return true;
1902 if (Type2.isPointer() &&
1903 (Type1.isPointer() || retrieveScalarOrVectorIntType(Type1)))
1904 return true;
1905 unsigned Bits1 = getNumScalarOrVectorTotalBitWidth(Type1),
1906 Bits2 = getNumScalarOrVectorTotalBitWidth(Type2);
1907 return Bits1 > 0 && Bits1 == Bits2;
1908}
1909
1910SPIRV::StorageClass::StorageClass
1913 assert(Type && Type.isPointer() && Type->getOperand(1).isImm() &&
1914 "Pointer type is expected");
1916}
1917
1918SPIRV::StorageClass::StorageClass
1920 return static_cast<SPIRV::StorageClass::StorageClass>(
1921 Type->getOperand(1).getImm());
1922}
1923
1925 MachineIRBuilder &MIRBuilder, Type *ElemType,
1926 SPIRV::StorageClass::StorageClass SC, bool IsWritable, bool EmitIr) {
1927 auto Key = SPIRV::irhandle_vkbuffer(ElemType, SC, IsWritable);
1928 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1929 return MI;
1930
1931 bool ExplicitLayoutRequired = storageClassRequiresExplictLayout(SC);
1932 // We need to get the SPIR-V type for the element here, so we can add the
1933 // decoration to it.
1934 auto *T = StructType::create(ElemType);
1935 SPIRVTypeInst BlockType =
1936 getOrCreateSPIRVType(T, MIRBuilder, SPIRV::AccessQualifier::None,
1937 ExplicitLayoutRequired, EmitIr);
1938
1939 buildOpDecorate(BlockType->defs().begin()->getReg(), MIRBuilder,
1940 SPIRV::Decoration::Block, {});
1941 BlockDecoratedTypes.insert(BlockType);
1942
1943 if (!IsWritable) {
1944 buildOpMemberDecorate(BlockType->defs().begin()->getReg(), MIRBuilder,
1945 SPIRV::Decoration::NonWritable, 0, {});
1946 }
1947
1948 SPIRVTypeInst R =
1949 getOrCreateSPIRVPointerTypeInternal(BlockType, MIRBuilder, SC);
1950 add(Key, R);
1951 return R;
1952}
1953
1956 uint64_t PaddingSizeInBytes,
1957 uint64_t OffsetInBytes) {
1958 // Member offsets are explicit, so the padding member only needs to be a
1959 // valid integer that fits the gap. Use the widest of i32/i16/i8 whose size
1960 // divides both the padding size and its offset (so the member is aligned):
1961 // i8 members require the Int8 capability and, in Vulkan,
1962 // uniformAndStorageBuffer8BitAccess.
1963 assert(PaddingSizeInBytes != 0 && "spirv.Padding must not be empty");
1964 uint64_t WidthInBytes =
1965 std::min<uint64_t>(4, MinAlign(OffsetInBytes, PaddingSizeInBytes));
1966 unsigned Width = WidthInBytes * 8;
1967 auto Key = SPIRV::irhandle_padding(Width);
1968 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1969 return MI;
1970 auto *T = Type::getIntNTy(MIRBuilder.getContext(), Width);
1971 SPIRVTypeInst R = getOrCreateSPIRVIntegerType(Width, MIRBuilder);
1972 finishCreatingSPIRVType(T, R);
1973 add(Key, R);
1974 return R;
1975}
1976
1978 MachineIRBuilder &MIRBuilder, Type *T) {
1979 const auto SC = SPIRV::StorageClass::PushConstant;
1980
1981 auto Key = SPIRV::irhandle_vkbuffer(T, SC, /* IsWritable= */ false);
1982 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1983 return MI;
1984
1985 // We need to get the SPIR-V type for the element here, so we can add the
1986 // decoration to it.
1988 T, MIRBuilder, SPIRV::AccessQualifier::None,
1989 /* ExplicitLayoutRequired= */ true, /* EmitIr= */ false);
1990
1991 buildOpDecorate(BlockType->defs().begin()->getReg(), MIRBuilder,
1992 SPIRV::Decoration::Block, {});
1993 BlockDecoratedTypes.insert(BlockType);
1994 SPIRVTypeInst R = BlockType;
1995 add(Key, R);
1996 return R;
1997}
1998
2000 MachineIRBuilder &MIRBuilder, const TargetExtType *T, bool EmitIr) {
2001 auto Key = SPIRV::handle(T);
2002 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
2003 return MI;
2004
2005 StructType *ST = cast<StructType>(T->getTypeParameter(0));
2006 ArrayRef<uint32_t> Offsets = T->int_params().slice(1);
2007 assert(ST->getNumElements() == Offsets.size());
2008
2009 StructOffsetDecorator Decorator = [&MIRBuilder, &Offsets](Register Reg) {
2010 for (uint32_t I = 0; I < Offsets.size(); ++I) {
2011 buildOpMemberDecorate(Reg, MIRBuilder, SPIRV::Decoration::Offset, I,
2012 {Offsets[I]});
2013 }
2014 };
2015
2016 // We need a new OpTypeStruct instruction because decorations will be
2017 // different from a struct with an explicit layout created from a different
2018 // entry point.
2019 SPIRVTypeInst SPIRVStructType =
2020 getOpTypeStruct(ST, MIRBuilder, SPIRV::AccessQualifier::None,
2021 std::move(Decorator), EmitIr);
2022 add(Key, SPIRVStructType);
2023 return SPIRVStructType;
2024}
2025
2027 const TargetExtType *ExtensionType,
2028 const SPIRV::AccessQualifier::AccessQualifier Qualifier,
2029 MachineIRBuilder &MIRBuilder) {
2030 assert(ExtensionType->getNumTypeParameters() == 1 &&
2031 "SPIR-V image builtin type must have sampled type parameter!");
2032 const SPIRVTypeInst SampledType =
2033 getOrCreateSPIRVType(ExtensionType->getTypeParameter(0), MIRBuilder,
2034 SPIRV::AccessQualifier::ReadWrite, true);
2035 assert((ExtensionType->getNumIntParameters() == 7 ||
2036 ExtensionType->getNumIntParameters() == 6) &&
2037 "Invalid number of parameters for SPIR-V image builtin!");
2038
2039 SPIRV::AccessQualifier::AccessQualifier accessQualifier =
2040 SPIRV::AccessQualifier::None;
2041 if (ExtensionType->getNumIntParameters() == 7) {
2042 accessQualifier = Qualifier == SPIRV::AccessQualifier::WriteOnly
2043 ? SPIRV::AccessQualifier::WriteOnly
2044 : SPIRV::AccessQualifier::AccessQualifier(
2045 ExtensionType->getIntParameter(6));
2046 }
2047
2048 // Create or get an existing type from GlobalRegistry.
2049 SPIRVTypeInst R = getOrCreateOpTypeImage(
2050 MIRBuilder, SampledType,
2051 SPIRV::Dim::Dim(ExtensionType->getIntParameter(0)),
2052 ExtensionType->getIntParameter(1), ExtensionType->getIntParameter(2),
2053 ExtensionType->getIntParameter(3), ExtensionType->getIntParameter(4),
2054 SPIRV::ImageFormat::ImageFormat(ExtensionType->getIntParameter(5)),
2055 accessQualifier);
2056 SPIRVToLLVMType[R] = ExtensionType;
2057 return R;
2058}
2059
2060SPIRVTypeInst SPIRVGlobalRegistry::getOrCreateOpTypeImage(
2061 MachineIRBuilder &MIRBuilder, SPIRVTypeInst SampledType,
2062 SPIRV::Dim::Dim Dim, uint32_t Depth, uint32_t Arrayed,
2063 uint32_t Multisampled, uint32_t Sampled,
2064 SPIRV::ImageFormat::ImageFormat ImageFormat,
2065 SPIRV::AccessQualifier::AccessQualifier AccessQual) {
2066 auto Key = SPIRV::irhandle_image(SPIRVToLLVMType.lookup(SampledType), Dim,
2067 Depth, Arrayed, Multisampled, Sampled,
2068 ImageFormat, AccessQual);
2069 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
2070 return MI;
2071
2072 // Vulkan restricts the Sampled Type of every image
2073 // (VUID-StandaloneSpirv-OpTypeImage-04656).
2074 const auto &ST = MIRBuilder.getMF().getSubtarget<SPIRVSubtarget>();
2075 if (ST.getTargetTriple().isVulkanOS()) {
2076 unsigned Opcode = SampledType->getOpcode();
2077 uint64_t Width = Opcode == SPIRV::OpTypeInt || Opcode == SPIRV::OpTypeFloat
2078 ? SampledType->getOperand(1).getImm()
2079 : 0;
2080 if (Width != 32 && !(Width == 64 && Opcode == SPIRV::OpTypeInt))
2082 "OpTypeImage Sampled Type must be a scalar 32-bit float, 32-bit "
2083 "integer or 64-bit integer for Vulkan "
2084 "(VUID-StandaloneSpirv-OpTypeImage-04656)");
2085 }
2086
2087 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2088 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2089 auto MIB =
2090 MIRBuilder.buildInstr(SPIRV::OpTypeImage)
2091 .addDef(createTypeVReg(MIRBuilder))
2092 .addUse(getSPIRVTypeID(SampledType))
2093 .addImm(Dim)
2094 .addImm(Depth) // Depth (whether or not it is a Depth image).
2095 .addImm(Arrayed) // Arrayed.
2096 .addImm(Multisampled) // Multisampled (0 = only single-sample).
2097 .addImm(Sampled) // Sampled (0 = usage known at runtime).
2098 .addImm(ImageFormat);
2099 if (AccessQual != SPIRV::AccessQualifier::None)
2100 MIB.addImm(AccessQual);
2101 return MIB;
2102 });
2103 add(Key, NewMI);
2104 return NewMI;
2105}
2106
2110 const MachineFunction *MF = &MIRBuilder.getMF();
2111 if (const MachineInstr *MI = findMI(Key, MF))
2112 return MI;
2113 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2114 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2115 return MIRBuilder.buildInstr(SPIRV::OpTypeSampler)
2116 .addDef(createTypeVReg(MIRBuilder));
2117 });
2118 add(Key, NewMI);
2119 return NewMI;
2120}
2121
2123 MachineIRBuilder &MIRBuilder,
2124 SPIRV::AccessQualifier::AccessQualifier AccessQual) {
2125 auto Key = SPIRV::irhandle_pipe(AccessQual);
2126 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
2127 return MI;
2128 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2129 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2130 return MIRBuilder.buildInstr(SPIRV::OpTypePipe)
2131 .addDef(createTypeVReg(MIRBuilder))
2132 .addImm(AccessQual);
2133 });
2134 add(Key, NewMI);
2135 return NewMI;
2136}
2137
2139 MachineIRBuilder &MIRBuilder) {
2140 auto Key = SPIRV::irhandle_event();
2141 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
2142 return MI;
2143 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2144 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2145 return MIRBuilder.buildInstr(SPIRV::OpTypeDeviceEvent)
2146 .addDef(createTypeVReg(MIRBuilder));
2147 });
2148 add(Key, NewMI);
2149 return NewMI;
2150}
2151
2153 SPIRVTypeInst ImageType, MachineIRBuilder &MIRBuilder) {
2155 SPIRVToLLVMType.lookup(MIRBuilder.getMF().getRegInfo().getVRegDef(
2156 ImageType->getOperand(1).getReg())),
2157 ImageType);
2158 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
2159 return MI;
2160 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2161 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2162 return MIRBuilder.buildInstr(SPIRV::OpTypeSampledImage)
2163 .addDef(createTypeVReg(MIRBuilder))
2164 .addUse(getSPIRVTypeID(ImageType));
2165 });
2166 add(Key, NewMI);
2167 return NewMI;
2168}
2169
2171 MachineIRBuilder &MIRBuilder, const TargetExtType *ExtensionType,
2172 SPIRVTypeInst ElemType, uint32_t Scope, uint32_t Rows, uint32_t Columns,
2173 uint32_t Use, bool EmitIR) {
2174 if (const MachineInstr *MI =
2175 findMI(ExtensionType, false, &MIRBuilder.getMF()))
2176 return MI;
2177 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2178 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2179 SPIRVTypeInst SpvTypeInt32 =
2180 getOrCreateSPIRVIntegerType(32, MIRBuilder);
2181 const Type *ET = getTypeForSPIRVType(ElemType);
2182 if (ET->isIntegerTy() && ET->getIntegerBitWidth() == 4 &&
2184 .canUseExtension(SPIRV::Extension::SPV_INTEL_int4)) {
2185 MIRBuilder.buildInstr(SPIRV::OpCapability)
2186 .addImm(SPIRV::Capability::Int4CooperativeMatrixINTEL);
2187 }
2188 return MIRBuilder.buildInstr(SPIRV::OpTypeCooperativeMatrixKHR)
2189 .addDef(createTypeVReg(MIRBuilder))
2190 .addUse(getSPIRVTypeID(ElemType))
2191 .addUse(buildConstantInt(Scope, MIRBuilder, SpvTypeInt32, EmitIR))
2192 .addUse(buildConstantInt(Rows, MIRBuilder, SpvTypeInt32, EmitIR))
2193 .addUse(buildConstantInt(Columns, MIRBuilder, SpvTypeInt32, EmitIR))
2194 .addUse(buildConstantInt(Use, MIRBuilder, SpvTypeInt32, EmitIR));
2195 });
2196 add(ExtensionType, false, NewMI);
2197 return NewMI;
2198}
2199
2201 const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode) {
2202 if (const MachineInstr *MI = findMI(Ty, false, &MIRBuilder.getMF()))
2203 return MI;
2204 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2205 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2206 return MIRBuilder.buildInstr(Opcode).addDef(createTypeVReg(MIRBuilder));
2207 });
2208 add(Ty, false, NewMI);
2209 return NewMI;
2210}
2211
2213 const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode,
2215 if (const MachineInstr *MI = findMI(Ty, false, &MIRBuilder.getMF()))
2216 return MI;
2217 Register ResVReg = createTypeVReg(MIRBuilder);
2218 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2219 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2220 MachineInstrBuilder MIB = MIRBuilder.buildInstr(SPIRV::UNKNOWN_type)
2221 .addDef(ResVReg)
2222 .addImm(Opcode);
2223 for (const MachineOperand &Operand : Operands) {
2224 assert((Operand.isReg() || Operand.isImm()) &&
2225 "Expected register or immediate operand");
2226 MIB.add(Operand);
2227 }
2228 return MIB;
2229 });
2230 add(Ty, false, NewMI);
2231 return NewMI;
2232}
2233
2234// Returns nullptr if unable to recognize SPIRV type name
2236 StringRef TypeStr, MachineIRBuilder &MIRBuilder, bool EmitIR,
2237 SPIRV::StorageClass::StorageClass SC,
2238 SPIRV::AccessQualifier::AccessQualifier AQ) {
2239 unsigned VecElts = 0;
2240 auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
2241
2242 // Parse strings representing either a SPIR-V or OpenCL builtin type.
2243 if (hasBuiltinTypePrefix(TypeStr))
2245 TypeStr.str(), MIRBuilder.getContext()),
2246 MIRBuilder, AQ, false, true);
2247
2248 // Parse type name in either "typeN" or "type vector[N]" format, where
2249 // N is the number of elements of the vector.
2250 Type *Ty;
2251
2252 Ty = parseBasicTypeName(TypeStr, Ctx);
2253 if (!Ty)
2254 // Unable to recognize SPIRV type name
2255 return nullptr;
2256
2257 SPIRVTypeInst SpirvTy = getOrCreateSPIRVType(Ty, MIRBuilder, AQ, false, true);
2258
2259 // Handle "type*" or "type* vector[N]".
2260 if (TypeStr.consume_front("*"))
2261 SpirvTy = getOrCreateSPIRVPointerType(Ty, MIRBuilder, SC);
2262
2263 // Handle "typeN*" or "type vector[N]*".
2264 bool IsPtrToVec = TypeStr.consume_back("*");
2265
2266 if (TypeStr.consume_front(" vector[")) {
2267 TypeStr = TypeStr.substr(0, TypeStr.find(']'));
2268 }
2269 TypeStr.getAsInteger(10, VecElts);
2270 if (VecElts > 0)
2271 SpirvTy = getOrCreateSPIRVVectorType(SpirvTy, VecElts, MIRBuilder, EmitIR);
2272
2273 if (IsPtrToVec)
2274 SpirvTy = getOrCreateSPIRVPointerType(SpirvTy, MIRBuilder, SC);
2275
2276 return SpirvTy;
2277}
2278
2281 MachineIRBuilder &MIRBuilder) {
2282 return getOrCreateSPIRVType(
2284 MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false, true);
2285}
2286
2288SPIRVGlobalRegistry::finishCreatingSPIRVType(const Type *LLVMTy,
2289 SPIRVTypeInst SpirvType) {
2290 assert(CurMF == SpirvType->getMF());
2291 VRegToTypeMap[CurMF][getSPIRVTypeID(SpirvType)] = SpirvType;
2292 SPIRVToLLVMType[SpirvType] = unifyPtrType(LLVMTy);
2293 return SpirvType;
2294}
2295
2298 const SPIRVInstrInfo &TII,
2299 unsigned SPIRVOPcode, Type *Ty) {
2300 if (const MachineInstr *MI = findMI(Ty, false, CurMF))
2301 return MI;
2302 MachineBasicBlock &DepMBB = I.getMF()->front();
2303 MachineIRBuilder MIRBuilder(DepMBB, DepMBB.getFirstNonPHI());
2304 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2305 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2306 auto NewTypeMI = BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
2307 MIRBuilder.getDL(), TII.get(SPIRVOPcode))
2308 .addDef(createTypeVReg(CurMF->getRegInfo()))
2309 .addImm(BitWidth);
2310 // Don't add Encoding to FP type
2311 if (!Ty->isFloatTy()) {
2312 return NewTypeMI.addImm(0);
2313 } else {
2314 return NewTypeMI;
2315 }
2316 });
2317 add(Ty, false, NewMI);
2318 return finishCreatingSPIRVType(Ty, NewMI);
2319}
2320
2322 unsigned BitWidth, MachineInstr &I, const SPIRVInstrInfo &TII) {
2323 // Maybe adjust bit width to keep DuplicateTracker consistent. Without
2324 // such an adjustment SPIRVGlobalRegistry::getOpTypeInt() could create, for
2325 // example, the same "OpTypeInt 8" type for a series of LLVM integer types
2326 // with number of bits less than 8, causing duplicate type definitions.
2327 if (BitWidth > 1)
2328 BitWidth = adjustOpTypeIntWidth(BitWidth);
2329 Type *LLVMTy = IntegerType::get(CurMF->getFunction().getContext(), BitWidth);
2330 return getOrCreateSPIRVType(BitWidth, I, TII, SPIRV::OpTypeInt, LLVMTy);
2331}
2332
2334 unsigned BitWidth, MachineInstr &I, const SPIRVInstrInfo &TII) {
2335 LLVMContext &Ctx = CurMF->getFunction().getContext();
2336 Type *LLVMTy;
2337 switch (BitWidth) {
2338 case 16:
2339 LLVMTy = Type::getHalfTy(Ctx);
2340 break;
2341 case 32:
2342 LLVMTy = Type::getFloatTy(Ctx);
2343 break;
2344 case 64:
2345 LLVMTy = Type::getDoubleTy(Ctx);
2346 break;
2347 default:
2348 llvm_unreachable("Bit width is of unexpected size.");
2349 }
2350 return getOrCreateSPIRVType(BitWidth, I, TII, SPIRV::OpTypeFloat, LLVMTy);
2351}
2352
2355 bool EmitIR) {
2356 return getOrCreateSPIRVType(
2357 IntegerType::get(MIRBuilder.getMF().getFunction().getContext(), 1),
2358 MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false, EmitIR);
2359}
2360
2363 const SPIRVInstrInfo &TII) {
2364 Type *Ty = IntegerType::get(CurMF->getFunction().getContext(), 1);
2365 if (const MachineInstr *MI = findMI(Ty, false, CurMF))
2366 return MI;
2367 MachineBasicBlock &DepMBB = I.getMF()->front();
2368 MachineIRBuilder MIRBuilder(DepMBB, DepMBB.getFirstNonPHI());
2369 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2370 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2371 return BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
2372 MIRBuilder.getDL(), TII.get(SPIRV::OpTypeBool))
2373 .addDef(createTypeVReg(CurMF->getRegInfo()));
2374 });
2375 add(Ty, false, NewMI);
2376 return finishCreatingSPIRVType(Ty, NewMI);
2377}
2378
2380 SPIRVTypeInst BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder,
2381 bool EmitIR) {
2382 return getOrCreateSPIRVType(
2384 NumElements),
2385 MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false, EmitIR);
2386}
2387
2389 SPIRVTypeInst BaseType, unsigned NumElements, MachineInstr &I,
2390 const SPIRVInstrInfo &TII) {
2391 const auto &STI = I.getMF()->getSubtarget<SPIRVSubtarget>();
2392 if (!STI.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector))
2393 // At this point of time all 1-element vectors are resolved. Add assertion
2394 // to fire if anything changes.
2395 assert(NumElements >= 2 &&
2396 "SPIR-V vectors must have at least 2 components");
2398 const_cast<Type *>(getTypeForSPIRVType(BaseType)), NumElements);
2399 if (const MachineInstr *MI = findMI(Ty, false, CurMF))
2400 return MI;
2401 MachineInstr *DepMI =
2402 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(BaseType));
2403 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
2404 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2405 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2406 // TODO: consider adding non-const accessors to SPIRVTypeInst, which
2407 // would remove the need for the gash casting here.
2408 return const_cast<MachineInstr *>(
2409 static_cast<const MachineInstr *>(getOpTypeVectorImpl(
2410 NumElements, BaseType, MIRBuilder, isLongVectorEXT(Ty))));
2411 });
2412 add(Ty, false, NewMI);
2413 return finishCreatingSPIRVType(Ty, NewMI);
2414}
2415
2417 const Type *BaseType, MachineInstr &I, SPIRV::StorageClass::StorageClass SC,
2418 bool ForceTyped) {
2419 MachineIRBuilder MIRBuilder(I);
2420 return getOrCreateSPIRVPointerType(BaseType, MIRBuilder, SC, ForceTyped);
2421}
2422
2424 const Type *BaseType, MachineIRBuilder &MIRBuilder,
2425 SPIRV::StorageClass::StorageClass SC, bool ForceTyped, bool EmitIR) {
2426 if (BaseType->isFunctionTy() &&
2427 !cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget())
2428 .canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)) {
2429 const Function &F = MIRBuilder.getMF().getFunction();
2430 F.getContext().diagnose(
2432 "Function used as a data pointer requires "
2433 "SPV_INTEL_function_pointers extension",
2434 DebugLoc(), DS_Error));
2435 }
2436 SPIRVTypeInst SpirvBaseType = getOrCreateSPIRVType(
2437 BaseType, MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
2439 assert(SpirvBaseType);
2440 return getOrCreateSPIRVPointerTypeInternal(SpirvBaseType, MIRBuilder, SC,
2441 ForceTyped);
2442}
2443
2445 SPIRVTypeInst PtrType, SPIRV::StorageClass::StorageClass SC,
2446 MachineInstr &I) {
2447 [[maybe_unused]] SPIRV::StorageClass::StorageClass OldSC =
2448 getPointerStorageClass(PtrType);
2451
2452 SPIRVTypeInst PointeeType = getPointeeType(PtrType);
2453 MachineIRBuilder MIRBuilder(I);
2454 return getOrCreateSPIRVPointerTypeInternal(PointeeType, MIRBuilder, SC);
2455}
2456
2459 SPIRV::StorageClass::StorageClass SC, bool EmitIR) {
2460 const Type *LLVMType = getTypeForSPIRVType(BaseType);
2462 SPIRVTypeInst R = getOrCreateSPIRVPointerType(LLVMType, MIRBuilder, SC,
2463 /*ForceTyped=*/false, EmitIR);
2464 assert(
2465 (R->getOpcode() == SPIRV::OpTypeUntypedPointerKHR ||
2466 getPointeeType(R) == BaseType) &&
2467 "The base type was not correctly laid out for the given storage class.");
2468 return R;
2469}
2470
2471SPIRVTypeInst SPIRVGlobalRegistry::getOrCreateSPIRVPointerTypeInternal(
2473 SPIRV::StorageClass::StorageClass SC, bool ForceTyped) {
2474 // Check if we should use untyped pointers.
2475 const SPIRVSubtarget &ST =
2476 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
2477 if (!ForceTyped && shouldUseUntypedPointer(BaseType, ST))
2478 return getOrCreateSPIRVUntypedPointerType(SC, MIRBuilder);
2479
2480 const Type *PointerElementType = getTypeForSPIRVType(BaseType);
2482 if (const MachineInstr *MI = findMI(PointerElementType, AddressSpace, CurMF))
2483 return MI;
2484 Type *Ty = TypedPointerType::get(const_cast<Type *>(PointerElementType),
2485 AddressSpace);
2486 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2487 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2488 return BuildMI(MIRBuilder.getMBB(), MIRBuilder.getInsertPt(),
2489 MIRBuilder.getDebugLoc(),
2490 MIRBuilder.getTII().get(SPIRV::OpTypePointer))
2492 .addImm(static_cast<uint32_t>(SC))
2494 });
2495 add(PointerElementType, AddressSpace, NewMI);
2496 return finishCreatingSPIRVType(Ty, NewMI);
2497}
2498
2500 SPIRV::StorageClass::StorageClass SC, MachineIRBuilder &MIRBuilder) {
2501 [[maybe_unused]] const SPIRVSubtarget &ST =
2502 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
2503 assert(ST.canUseExtension(SPIRV::Extension::SPV_KHR_untyped_pointers) &&
2504 !ST.isShader() && "Untyped pointers are not available");
2506 // Use STK_UntypedPointer handle keyed by address space only.
2508 if (const MachineInstr *MI = findMI(Handle, CurMF))
2509 return MI;
2510
2511 Type *Ty = PointerType::get(MIRBuilder.getMF().getFunction().getContext(),
2512 AddressSpace);
2513 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2514 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2515 return BuildMI(MIRBuilder.getMBB(), MIRBuilder.getInsertPt(),
2516 MIRBuilder.getDebugLoc(),
2517 MIRBuilder.getTII().get(SPIRV::OpTypeUntypedPointerKHR))
2518 .addDef(createTypeVReg(CurMF->getRegInfo()))
2519 .addImm(static_cast<uint32_t>(SC));
2520 });
2521 add(Handle, NewMI);
2522 return finishCreatingSPIRVType(Ty, NewMI);
2523}
2524
2526 SPIRVTypeInst SpvType,
2527 const SPIRVInstrInfo &TII) {
2528 UndefValue *UV =
2529 UndefValue::get(const_cast<Type *>(getTypeForSPIRVType(SpvType)));
2530 Register Res = find(UV, CurMF);
2531 if (Res.isValid())
2532 return Res;
2533
2534 LLT LLTy = LLT::scalar(64);
2535 Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
2536 CurMF->getRegInfo().setRegClass(Res, &SPIRV::iIDRegClass);
2537 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
2538
2539 MachineInstr *DepMI =
2540 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
2541 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
2542 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2543 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2544 auto MIB = BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
2545 MIRBuilder.getDL(), TII.get(SPIRV::OpUndef))
2546 .addDef(Res)
2547 .addUse(getSPIRVTypeID(SpvType));
2548 constrainSelectedInstRegOperands(MIB);
2549 return MIB;
2550 });
2551 add(UV, NewMI);
2552 return Res;
2553}
2554
2555const TargetRegisterClass *
2557 unsigned Opcode = SpvType->getOpcode();
2558 switch (Opcode) {
2559 case SPIRV::OpTypeFloat:
2560 return &SPIRV::fIDRegClass;
2561 case SPIRV::OpTypePointer:
2562 case SPIRV::OpTypeUntypedPointerKHR:
2563 return &SPIRV::pIDRegClass;
2564 case SPIRV::OpTypeVector:
2565 case SPIRV::OpTypeVectorIdEXT: {
2567 unsigned ElemOpcode = ElemType ? ElemType->getOpcode() : 0;
2568 if (ElemOpcode == SPIRV::OpTypeFloat)
2569 return &SPIRV::vfIDRegClass;
2570 if (ElemType && ElemType.isPointer())
2571 return &SPIRV::vpIDRegClass;
2572 return &SPIRV::viIDRegClass;
2573 }
2574 }
2575 return &SPIRV::iIDRegClass;
2576}
2577
2579 if (FloatType->getNumOperands() == 3 &&
2580 FloatType->getOperand(2).getImm() == SPIRV::FPEncoding::BFloat16KHR)
2581 return LLT::bfloat16();
2582 return LLT::floatIEEE(FloatType->getOperand(1).getImm());
2583}
2584
2586 unsigned Opcode = SpvType ? SpvType->getOpcode() : 0;
2587 switch (Opcode) {
2588 case SPIRV::OpTypeFloat:
2589 return getFloatRegType(SpvType);
2590 case SPIRV::OpTypeInt:
2591 case SPIRV::OpTypeBool:
2592 return LLT::scalar(getScalarOrVectorBitWidth(SpvType));
2593 case SPIRV::OpTypePointer:
2594 case SPIRV::OpTypeUntypedPointerKHR:
2595 return LLT::pointer(getAS(SpvType), getPointerSize());
2596 case SPIRV::OpTypeVector:
2597 case SPIRV::OpTypeVectorIdEXT: {
2599 LLT ET;
2600 switch (ElemType ? ElemType->getOpcode() : 0) {
2601 case SPIRV::OpTypePointer:
2602 case SPIRV::OpTypeUntypedPointerKHR:
2603 ET = LLT::pointer(getAS(ElemType), getPointerSize());
2604 break;
2605 case SPIRV::OpTypeFloat:
2606 ET = getFloatRegType(ElemType);
2607 break;
2608 case SPIRV::OpTypeInt:
2609 case SPIRV::OpTypeBool:
2610 ET = LLT::scalar(getScalarOrVectorBitWidth(ElemType));
2611 break;
2612 default:
2613 ET = LLT::scalar(64);
2614 }
2616 return LLT::scalarOrVector(EC, ET);
2617 }
2618 }
2619 return LLT::scalar(64);
2620}
2621
2622// Aliasing list MD contains several scope MD nodes whithin it. Each scope MD
2623// has a selfreference and an extra MD node for aliasing domain and also it
2624// can contain an optional string operand. Domain MD contains a self-reference
2625// with an optional string operand. Here we unfold the list, creating SPIR-V
2626// aliasing instructions.
2627// TODO: add support for an optional string operand.
2629 MachineIRBuilder &MIRBuilder, const MDNode *AliasingListMD) {
2630 if (AliasingListMD->getNumOperands() == 0)
2631 return nullptr;
2632 const MachineFunction *MF = &MIRBuilder.getMF();
2633 if (auto L = AliasInstMDMap.find({MF, AliasingListMD});
2634 L != AliasInstMDMap.end())
2635 return L->second;
2636
2638 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
2639 for (const MDOperand &MDListOp : AliasingListMD->operands()) {
2640 if (MDNode *ScopeMD = dyn_cast<MDNode>(MDListOp)) {
2641 if (ScopeMD->getNumOperands() < 2)
2642 return nullptr;
2643 MDNode *DomainMD = dyn_cast<MDNode>(ScopeMD->getOperand(1));
2644 if (!DomainMD)
2645 return nullptr;
2646 auto *Domain = [&] {
2647 auto D = AliasInstMDMap.find({MF, DomainMD});
2648 if (D != AliasInstMDMap.end())
2649 return D->second;
2650 const Register Ret = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2651 auto MIB =
2652 MIRBuilder.buildInstr(SPIRV::OpAliasDomainDeclINTEL).addDef(Ret);
2653 return MIB.getInstr();
2654 }();
2655 AliasInstMDMap.insert(
2656 std::make_pair(std::make_pair(MF, DomainMD), Domain));
2657 auto *Scope = [&] {
2658 auto S = AliasInstMDMap.find({MF, ScopeMD});
2659 if (S != AliasInstMDMap.end())
2660 return S->second;
2661 const Register Ret = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2662 auto MIB = MIRBuilder.buildInstr(SPIRV::OpAliasScopeDeclINTEL)
2663 .addDef(Ret)
2664 .addUse(Domain->getOperand(0).getReg());
2665 return MIB.getInstr();
2666 }();
2667 AliasInstMDMap.insert(std::make_pair(std::make_pair(MF, ScopeMD), Scope));
2668 ScopeList.push_back(Scope);
2669 }
2670 }
2671
2672 const Register Ret = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2673 auto MIB =
2674 MIRBuilder.buildInstr(SPIRV::OpAliasScopeListDeclINTEL).addDef(Ret);
2675 for (auto *Scope : ScopeList)
2676 MIB.addUse(Scope->getOperand(0).getReg());
2677 auto List = MIB.getInstr();
2678 AliasInstMDMap.insert(
2679 std::make_pair(std::make_pair(MF, AliasingListMD), List));
2680 return List;
2681}
2682
2684 Register Reg, MachineIRBuilder &MIRBuilder, uint32_t Dec,
2685 const MDNode *AliasingListMD) {
2686 MachineInstr *AliasList =
2687 getOrAddMemAliasingINTELInst(MIRBuilder, AliasingListMD);
2688 if (!AliasList)
2689 return;
2690 MIRBuilder.buildInstr(SPIRV::OpDecorateId)
2691 .addUse(Reg)
2692 .addImm(Dec)
2693 .addUse(AliasList->getOperand(0).getReg());
2694}
2696 bool DeleteOld) {
2697 Old->replaceAllUsesWith(New);
2698 updateIfExistDeducedElementType(Old, New, DeleteOld);
2699 updateIfExistAssignPtrTypeInstr(Old, New, DeleteOld);
2700}
2701
2703 bool CanUseAnyVectorRank) {
2704 Value *OfType = getNormalizedPoisonValue(Ty, CanUseAnyVectorRank);
2705 CallInst *AssignCI = nullptr;
2706 if (Arg->getType()->isAggregateType() && Ty->isAggregateType() &&
2707 allowEmitFakeUse(Arg)) {
2708 LLVMContext &Ctx = Arg->getContext();
2711 MDString::get(Ctx, Arg->getName())};
2712 B.CreateIntrinsic(Intrinsic::spv_value_md,
2713 {MetadataAsValue::get(Ctx, MDTuple::get(Ctx, ArgMDs))});
2714 AssignCI = B.CreateIntrinsicWithoutFolding(Intrinsic::fake_use, {Arg});
2715 } else {
2716 AssignCI = buildIntrWithMD(Intrinsic::spv_assign_type, {Arg->getType()},
2717 OfType, Arg, {}, B);
2718 }
2719 addAssignPtrTypeInstr(Arg, AssignCI);
2720}
2721
2723 Value *Arg) {
2724 Value *OfType = PoisonValue::get(ElemTy);
2725 CallInst *AssignPtrTyCI = findAssignPtrTypeInstr(Arg);
2726 Function *CurrF =
2727 B.GetInsertBlock() ? B.GetInsertBlock()->getParent() : nullptr;
2728 if (AssignPtrTyCI == nullptr ||
2729 AssignPtrTyCI->getParent()->getParent() != CurrF) {
2730 AssignPtrTyCI = buildIntrWithMD(
2731 Intrinsic::spv_assign_ptr_type, {Arg->getType()}, OfType, Arg,
2732 {B.getInt32(getPointerAddressSpace(Arg->getType()))}, B);
2733 addDeducedElementType(AssignPtrTyCI, ElemTy);
2735 addAssignPtrTypeInstr(Arg, AssignPtrTyCI);
2736 } else {
2737 updateAssignType(AssignPtrTyCI, Arg, OfType);
2738 }
2739}
2740
2742 Value *OfType) {
2743 AssignCI->setArgOperand(1, buildMD(OfType));
2744 if (cast<IntrinsicInst>(AssignCI)->getIntrinsicID() !=
2745 Intrinsic::spv_assign_ptr_type)
2746 return;
2747
2748 // update association with the pointee type
2749 Type *ElemTy = OfType->getType();
2750 addDeducedElementType(AssignCI, ElemTy);
2752}
2753
2754void SPIRVGlobalRegistry::addStructOffsetDecorations(
2755 Register Reg, StructType *Ty, MachineIRBuilder &MIRBuilder) {
2756 ArrayRef<TypeSize> Offsets = DL.getStructLayout(Ty)->getMemberOffsets();
2757 for (uint32_t I = 0; I < Ty->getNumElements(); ++I) {
2758 buildOpMemberDecorate(Reg, MIRBuilder, SPIRV::Decoration::Offset, I,
2759 {static_cast<uint32_t>(Offsets[I])});
2760 }
2761}
2762
2763void SPIRVGlobalRegistry::addArrayStrideDecorations(
2764 Register Reg, Type *ElementType, MachineIRBuilder &MIRBuilder) {
2765 uint32_t SizeInBytes = DL.getTypeAllocSize(ElementType);
2766 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::ArrayStride,
2767 {SizeInBytes});
2768}
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static dxbc::SigComponentType getComponentType(ElementType Type, bool Legacy)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static constexpr Value * getValue(Ty &ValueOrUse)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
This file defines the PointerIntPair class.
MachineRegisterInfo & MRI
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SI Fold Operands
static bool storageClassRequiresExplictLayout(SPIRV::StorageClass::StorageClass SC)
static Register createTypeVReg(MachineRegisterInfo &MRI)
static SmallVector< const MachineInstr * > getTypeDecls(const MachineFunction &MF)
static bool isContinuedInstr(const MachineInstr &MI)
static bool allowEmitFakeUse(const Value *Arg)
static APInt decodeNumImm(const MachineInstr &MI)
static unsigned typeToAddressSpace(const Type *Ty)
static LLT getFloatRegType(SPIRVTypeInst FloatType)
unsigned getAS(SPIRVTypeInst SpvType)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
APInt bitcastToAPInt() const
Definition APFloat.h:1508
bool isPosZero() const
Definition APFloat.h:1627
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Class to represent array types.
uint64_t getNumElements() const
Type * getElementType() const
void setArgOperand(unsigned i, Value *v)
This class represents a function call, abstracting a target machine's calling convention.
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValue() const
Definition Constants.h:464
const APFloat & getValueAPF() const
Definition Constants.h:463
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Definition Constants.h:643
static LLVM_ABI ConstantTargetNone * get(TargetExtType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
This is an important base class in LLVM.
Definition Constant.h:44
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
LLVM_ABI const APInt & getUniqueInteger() const
If C is a constant integer then return its value, otherwise C must be a vector of constant integers,...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
A debug info location.
Definition DebugLoc.h:126
Diagnostic information for unsupported feature in backend.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
Class to represent fixed width SIMD vectors.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
Class to represent function types.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
Module * getParent()
Get the module that this global value is contained inside of...
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
Type * getValueType() const
MaybeAlign getAlign() const
Returns the alignment of the given variable.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
@ MIN_INT_BITS
Minimum number of bits that can be specified.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
static constexpr LLT bfloat16()
static constexpr LLT scalarOrVector(ElementCount EC, LLT ScalarTy)
static LLT floatIEEE(unsigned SizeInBits)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:89
Metadata node.
Definition Metadata.h:1087
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1441
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
Tracking metadata reference owned by Metadata.
Definition Metadata.h:908
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1534
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
MachineInstrBundleIterator< MachineInstr > iterator
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & front() const
Helper class to build MachineInstr.
void setInsertPt(MachineBasicBlock &MBB, MachineBasicBlock::iterator II)
Set the insertion point before the specified position.
LLVMContext & getContext() const
const TargetInstrInfo & getTII()
MachineBasicBlock::iterator getInsertPt()
Current insertion point for new instructions.
MachineInstrBuilder buildSplatBuildVector(const DstOp &Res, const SrcOp &Src)
Build and insert Res = G_BUILD_VECTOR with Src replicated to fill the number of elements.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
const DebugLoc & getDL()
Getter for DebugLoc.
MachineFunction & getMF()
Getter for the function we currently build.
const MachineBasicBlock & getMBB() const
Getter for the basic block we currently build.
const DebugLoc & getDebugLoc()
Get the current instruction's debug location.
MachineRegisterInfo * getMRI()
Getter for MRI.
MachineIRBuilderState & getState()
Getter for the State.
MachineInstrBuilder buildCopy(const DstOp &Res, const SrcOp &Op)
Build and insert Res = COPY Op.
virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
void constrainAllUses(const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
mop_range defs()
Returns all explicit operands that are register definitions.
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 insert(mop_iterator InsertBefore, ArrayRef< MachineOperand > Ops)
Inserts Ops BEFORE It. Can untie/retie tied operands.
mop_range uses()
Returns all operands which may be register uses.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const MachineOperand & getOperand(unsigned i) const
unsigned getNumDefs() const
Returns the total number of definitions.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:105
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
void buildAssignType(IRBuilder<> &B, Type *Ty, Value *Arg, bool CanUseAnyVectorRank)
SPIRVTypeInst getImageType(const TargetExtType *ExtensionType, const SPIRV::AccessQualifier::AccessQualifier Qualifier, MachineIRBuilder &MIRBuilder)
bool isScalarOrVectorSigned(SPIRVTypeInst Type) const
void addAssignPtrTypeInstr(Value *Val, CallInst *AssignPtrTyCI)
SPIRVTypeInst getOrCreateOpTypeSampledImage(SPIRVTypeInst ImageType, MachineIRBuilder &MIRBuilder)
unsigned getNumScalarOrVectorTotalBitWidth(SPIRVTypeInst Type) const
SPIRVTypeInst getOrCreateUnknownType(const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode, const ArrayRef< MachineOperand > Operands)
void assignSPIRVTypeToVReg(SPIRVTypeInst Type, Register VReg, const MachineFunction &MF)
SPIRVTypeInst getOrCreateOpTypeFunctionWithArgs(const Type *Ty, SPIRVTypeInst RetType, const SmallVectorImpl< SPIRVTypeInst > &ArgTypes, MachineIRBuilder &MIRBuilder)
void buildAssignPtr(IRBuilder<> &B, Type *ElemTy, Value *Arg)
const TargetRegisterClass * getRegClass(SPIRVTypeInst SpvType) const
SPIRVTypeInst getOrCreateSPIRVPointerType(const Type *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SC, bool ForceTyped=false, bool EmitIR=true)
MachineInstr * getOrAddMemAliasingINTELInst(MachineIRBuilder &MIRBuilder, const MDNode *AliasingListMD)
unsigned getScalarOrVectorBitWidth(SPIRVTypeInst Type) const
SPIRVTypeInst getOrCreateSPIRVIntegerType(unsigned BitWidth, MachineIRBuilder &MIRBuilder)
SPIRVTypeInst getOrCreateSPIRVVectorType(SPIRVTypeInst BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder, bool EmitIR)
SPIRVTypeInst getOrCreateSPIRVTypeByName(StringRef TypeStr, MachineIRBuilder &MIRBuilder, bool EmitIR, SPIRV::StorageClass::StorageClass SC=SPIRV::StorageClass::Function, SPIRV::AccessQualifier::AccessQualifier AQ=SPIRV::AccessQualifier::ReadWrite)
Register buildGlobalVariable(Register Reg, SPIRVTypeInst 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)
SPIRVTypeInst assignIntTypeToVReg(unsigned BitWidth, Register VReg, MachineInstr &I, const SPIRVInstrInfo &TII)
SPIRVTypeInst getResultType(Register VReg, MachineFunction *MF=nullptr)
void replaceAllUsesWith(Value *Old, Value *New, bool DeleteOld=true)
SPIRVTypeInst getOrCreateOpTypeByOpcode(const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode)
unsigned getScalarOrVectorComponentCount(Register VReg) const
const Type * getTypeForSPIRVType(SPIRVTypeInst Ty) const
bool isBitcastCompatible(SPIRVTypeInst Type1, SPIRVTypeInst Type2) const
void addDeducedElementType(Value *Val, Type *Ty)
bool shouldKeepTypedPtrType(SPIRVTypeInst ElemType) const
Register getOrCreateConstFP(APFloat Val, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull=true)
LLT getRegType(SPIRVTypeInst SpvType) const
Register getLastInsertedTypeReg(const MachineFunction &MF) const
SPIRVTypeInst getOpTypeVoid(MachineIRBuilder &MIRBuilder)
void invalidateMachineInstr(MachineInstr *MI)
bool isResourceType(SPIRVTypeInst Type) const
SPIRVTypeInst getOrCreateSPIRVBoolType(MachineIRBuilder &MIRBuilder, bool EmitIR)
void setLastInsertedType(const MachineFunction &MF, MachineInstr *MI)
void updateIfExistDeducedElementType(Value *OldVal, Value *NewVal, bool DeleteOld)
bool isScalarOfType(Register VReg, unsigned TypeOpcode) const
Register getSPIRVTypeID(SPIRVTypeInst SpirvType) const
Register getOrCreateConstInt(uint64_t Val, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull=true)
Register getOrCreateConstIntArray(uint64_t Val, size_t Num, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII)
SPIRVTypeInst retrieveScalarOrVectorIntType(SPIRVTypeInst Type) const
Register getOrCreateGlobalVariableWithBinding(SPIRVTypeInst VarType, uint32_t Set, uint32_t Binding, StringRef Name, MachineIRBuilder &MIRBuilder)
SPIRVTypeInst getOrCreateOpTypeCoopMatr(MachineIRBuilder &MIRBuilder, const TargetExtType *ExtensionType, SPIRVTypeInst ElemType, uint32_t Scope, uint32_t Rows, uint32_t Columns, uint32_t Use, bool EmitIR)
SPIRVTypeInst changePointerStorageClass(SPIRVTypeInst PtrType, SPIRV::StorageClass::StorageClass SC, MachineInstr &I)
Register getOrCreateConstVector(uint64_t Val, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull=true)
Register buildConstantFP(APFloat Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType=nullptr)
SPIRVTypeInst getOrCreateOpTypePipe(MachineIRBuilder &MIRBuilder, SPIRV::AccessQualifier::AccessQualifier AccQual)
void addGlobalObject(const Value *V, const MachineFunction *MF, Register R)
SPIRVTypeInst getScalarOrVectorComponentType(SPIRVTypeInst Type) const
SPIRVTypeInst getOrCreateSPIRVFloatType(unsigned BitWidth, MachineInstr &I, const SPIRVInstrInfo &TII)
SPIRVTypeInst getOrCreateVulkanBufferType(MachineIRBuilder &MIRBuilder, Type *ElemType, SPIRV::StorageClass::StorageClass SC, bool IsWritable, bool EmitIr=false)
SPIRVTypeInst getPointeeType(SPIRVTypeInst PtrType)
SPIRVTypeInst getOrCreateSPIRVType(const Type *Type, MachineInstr &I, SPIRV::AccessQualifier::AccessQualifier AQ, bool EmitIR)
Register getOrCreateConsIntVector(uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType, bool EmitIR)
void updateIfExistAssignPtrTypeInstr(Value *OldVal, Value *NewVal, bool DeleteOld)
SPIRVTypeInst assignTypeToVReg(const Type *Type, Register VReg, MachineIRBuilder &MIRBuilder, SPIRV::AccessQualifier::AccessQualifier AQ, bool EmitIR)
bool isScalarOrVectorOfType(Register VReg, unsigned TypeOpcode) const
SPIRVTypeInst getOrCreateLayoutType(MachineIRBuilder &MIRBuilder, const TargetExtType *T, bool EmitIr=false)
void restoreFromMIR(const MachineFunction &MF)
SPIRVTypeInst getOrCreatePaddingType(MachineIRBuilder &MIRBuilder, uint64_t PaddingSizeInBytes, uint64_t OffsetInBytes=0)
Register createConstInt(const ConstantInt *CI, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull)
Register getOrCreateConstNullPtr(MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType)
SPIRVTypeInst getSPIRVTypeForVReg(Register VReg, const MachineFunction *MF=nullptr) const
SPIRVTypeInst getOrCreateSPIRVUntypedPointerType(SPIRV::StorageClass::StorageClass SC, MachineIRBuilder &MIRBuilder)
Register getOrCreateUndef(MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII)
SPIRVTypeInst getOrCreateOpTypeSampler(MachineIRBuilder &MIRBuilder)
void buildMemAliasingOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, uint32_t Dec, const MDNode *GVarMD)
SPIRV::StorageClass::StorageClass getPointerStorageClass(Register VReg) const
bool shouldUseUntypedPointer(SPIRVTypeInst ElemType, const SPIRVSubtarget &ST) const
Register buildConstantSampler(Register Res, unsigned AddrMode, unsigned Param, unsigned FilerMode, MachineIRBuilder &MIRBuilder)
SmallVector< std::pair< Register, Register > > getVRegTypeIDs(const MachineFunction &MF) const
void updateAssignType(CallInst *AssignCI, Value *Arg, Value *OfType)
CallInst * findAssignPtrTypeInstr(const Value *Val)
Register buildConstantInt(uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType, bool EmitIR, bool ZeroAsNull=true)
SPIRVTypeInst getOrCreateVulkanPushConstantType(MachineIRBuilder &MIRBuilder, Type *ElemType)
Register createConstFP(const ConstantFP *CF, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull)
SPIRVTypeInst getOrCreateOpTypeDeviceEvent(MachineIRBuilder &MIRBuilder)
const MachineInstr * findMI(SPIRV::IRHandle Handle, const MachineFunction *MF)
bool erase(const MachineInstr *MI)
bool add(SPIRV::IRHandle Handle, const MachineInstr *MI)
Register find(SPIRV::IRHandle Handle, const MachineFunction *MF)
void insert_range(Range &&R)
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
Definition StringRef.h:683
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:482
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:653
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:776
Class to represent struct types.
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:462
ArrayRef< Type * > elements() const
static LLVM_ABI StructType * getTypeByName(LLVMContext &C, StringRef Name)
Return the type with the specified name, or null if there is none by that name.
Definition Type.cpp:773
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:657
bool isPacked() const
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:738
unsigned getNumElements() const
Random access to the elements.
bool hasName() const
Return true if this is a named struct that has a non-empty name.
LLVM_ABI bool isSized() const
isSized - Return true if this is a sized type.
Definition Type.cpp:696
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
LLVM_ABI StringRef getName() const
Return the name for this struct type if it has an identity.
Definition Type.cpp:731
Class to represent target extensions types, which are generally unintrospectable from target-independ...
unsigned getNumIntParameters() const
Type * getTypeParameter(unsigned i) const
unsigned getNumTypeParameters() const
unsigned getIntParameter(unsigned i) const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:274
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
Type * getArrayElementType() const
Definition Type.h:427
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
LLVM_ABI uint64_t getArrayNumElements() const
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
bool isFP128Ty() const
Return true if this is 'fp128'.
Definition Type.h:164
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:314
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:272
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:271
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
Definition Type.cpp:269
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static LLVM_ABI TypedPointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
'undef' values are things that do not have specified contents.
Definition Constants.h:1657
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
static ConstantAsMetadata * getConstant(Value *C)
Definition Metadata.h:493
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Type * getElementType() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
IteratorT begin() const
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr bool isPacked(const T &...O)
Definition SIDefines.h:343
IRHandle handle(const Type *Ty)
IRHandle irhandle_padding(unsigned Width)
IRHandle irhandle_sampled_image(const Type *SampledTy, const MachineInstr *ImageTy)
IRHandle irhandle_vkbuffer(const Type *ElementType, StorageClass::StorageClass SC, bool IsWriteable)
IRHandle irhandle_untyped_pointer(unsigned AddressSpace)
IRHandle irhandle_sampler()
TargetExtType * parseBuiltinTypeNameToTargetExtType(std::string TypeName, LLVMContext &Context)
Translates a string representing a SPIR-V or OpenCL builtin type to a TargetExtType that can be furth...
IRHandle irhandle_event()
SPIRVTypeInst lowerBuiltinType(const Type *OpaqueType, SPIRV::AccessQualifier::AccessQualifier AccessQual, MachineIRBuilder &MIRBuilder, SPIRVGlobalRegistry *GR)
IRHandle irhandle_pipe(uint8_t AQ)
IRHandle irhandle_image(const Type *SampledTy, unsigned Dim, unsigned Depth, unsigned Arrayed, unsigned MS, unsigned Sampled, unsigned ImageFormat, unsigned AQ=0)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:118
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
std::string getStringImm(const MachineInstr &MI, unsigned StartIndex)
void addStringImm(StringRef Str, MCInst &Inst)
MachineBasicBlock::iterator getOpVariableMBBIt(MachineFunction &MF)
bool isTypedPointerWrapper(const TargetExtType *ExtTy)
Definition SPIRVUtils.h:417
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:388
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)
CallInst * buildIntrWithMD(Intrinsic::ID IntrID, ArrayRef< Type * > Types, Value *Arg, Value *Arg2, ArrayRef< Constant * > Imms, IRBuilder<> &B)
bool matchPeeledArrayPattern(const StructType *Ty, Type *&OriginalElementType, uint64_t &TotalSize)
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, ArrayRef< uint32_t > DecArgs, StringRef StrImm)
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
constexpr unsigned storageClassToAddressSpace(SPIRV::StorageClass::StorageClass SC)
Definition SPIRVUtils.h:234
bool isVectorType(SPIRVTypeInst SPVTy)
bool getSpirvBuiltInIdByName(llvm::StringRef Name, SPIRV::BuiltIn::BuiltIn &BI)
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition MathExtras.h:352
MetadataAsValue * buildMD(Value *Arg)
Definition SPIRVUtils.h:549
bool isTypedPointerTy(const Type *T)
Definition SPIRVUtils.h:366
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void buildOpName(Register Target, StringRef Name, MachineIRBuilder &MIRBuilder)
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
Type * getTypedPointerWrapper(Type *ElemTy, unsigned AS)
Definition SPIRVUtils.h:412
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
Type * toTypedPointer(Type *Ty)
Definition SPIRVUtils.h:472
bool isSpecialOpaqueType(const Type *Ty)
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:376
MachineBasicBlock::iterator getInsertPtValidEnd(MachineBasicBlock *MBB)
const Type * unifyPtrType(const Type *Ty)
Definition SPIRVUtils.h:499
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
std::function< void(Register)> StructOffsetDecorator
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
void buildOpSpirvDecorations(Register Reg, MachineIRBuilder &MIRBuilder, const MDNode *GVarMD, const SPIRVSubtarget &ST)
int64_t foldImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
bool isLongVectorEXT(const Type *Ty, bool CanUseVector16=true)
Definition SPIRVUtils.h:522
Type * parseBasicTypeName(StringRef &TypeName, LLVMContext &Ctx)
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
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 hasBuiltinTypePrefix(StringRef Name)
void buildOpMemberDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, uint32_t Member, ArrayRef< uint32_t > DecArgs, StringRef StrImm)
bool isPointerTyOrWrapper(const Type *Ty)
Definition SPIRVUtils.h:424
bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID)
PoisonValue * getNormalizedPoisonValue(Type *Ty, bool CanUseAnyVectorRank)
Definition SPIRVUtils.h:544
MachineInstr * getVRegDef(MachineRegisterInfo &MRI, Register Reg)
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:135