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"
23#include "llvm/IR/Constants.h"
25#include "llvm/IR/Function.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/IntrinsicsSPIRV.h"
29#include "llvm/IR/Type.h"
32#include <cassert>
33#include <functional>
34
35using namespace llvm;
36
37static bool allowEmitFakeUse(const Value *Arg) {
38 if (isSpvIntrinsic(Arg))
39 return false;
41 return false;
42 if (const auto *LI = dyn_cast<LoadInst>(Arg))
43 if (LI->getType()->isAggregateType())
44 return false;
45 return true;
46}
47
48static unsigned typeToAddressSpace(const Type *Ty) {
49 if (auto PType = dyn_cast<TypedPointerType>(Ty))
50 return PType->getAddressSpace();
51 if (auto PType = dyn_cast<PointerType>(Ty))
52 return PType->getAddressSpace();
53 if (auto *ExtTy = dyn_cast<TargetExtType>(Ty);
54 ExtTy && isTypedPointerWrapper(ExtTy))
55 return ExtTy->getIntParameter(0);
56 reportFatalInternalError("Unable to convert LLVM type to SPIRVType");
57}
58
59static bool
60storageClassRequiresExplictLayout(SPIRV::StorageClass::StorageClass SC) {
61 switch (SC) {
62 case SPIRV::StorageClass::Uniform:
63 case SPIRV::StorageClass::PushConstant:
64 case SPIRV::StorageClass::StorageBuffer:
65 case SPIRV::StorageClass::PhysicalStorageBufferEXT:
66 return true;
67 case SPIRV::StorageClass::UniformConstant:
68 case SPIRV::StorageClass::Input:
69 case SPIRV::StorageClass::Output:
70 case SPIRV::StorageClass::Workgroup:
71 case SPIRV::StorageClass::CrossWorkgroup:
72 case SPIRV::StorageClass::Private:
73 case SPIRV::StorageClass::Function:
74 case SPIRV::StorageClass::Generic:
75 case SPIRV::StorageClass::AtomicCounter:
76 case SPIRV::StorageClass::Image:
77 case SPIRV::StorageClass::CallableDataNV:
78 case SPIRV::StorageClass::IncomingCallableDataNV:
79 case SPIRV::StorageClass::RayPayloadNV:
80 case SPIRV::StorageClass::HitAttributeNV:
81 case SPIRV::StorageClass::IncomingRayPayloadNV:
82 case SPIRV::StorageClass::ShaderRecordBufferNV:
83 case SPIRV::StorageClass::CodeSectionINTEL:
84 case SPIRV::StorageClass::DeviceOnlyINTEL:
85 case SPIRV::StorageClass::HostOnlyINTEL:
86 return false;
87 }
88 llvm_unreachable("Unknown SPIRV::StorageClass enum");
89}
90
92 : DL(DL), Bound(0), CurMF(nullptr) {}
93
94void SPIRVGlobalRegistry::constrainSelectedInstRegOperands(
95 MachineInstrBuilder &MIB) const {
96 const auto &ST = CurMF->getSubtarget();
97 MIB.constrainAllUses(*ST.getInstrInfo(), *ST.getRegisterInfo(),
98 *ST.getRegBankInfo());
99}
100
104 const SPIRVInstrInfo &TII) {
106 assignSPIRVTypeToVReg(SpirvType, VReg, *CurMF);
107 return SpirvType;
108}
109
111 const Type *Type, Register VReg, MachineIRBuilder &MIRBuilder,
112 SPIRV::AccessQualifier::AccessQualifier AccessQual, bool EmitIR) {
113 SPIRVTypeInst SpirvType =
114 getOrCreateSPIRVType(Type, MIRBuilder, AccessQual, EmitIR);
115 assignSPIRVTypeToVReg(SpirvType, VReg, MIRBuilder.getMF());
116 return SpirvType;
117}
118
120 Register VReg,
121 const MachineFunction &MF) {
122 VRegToTypeMap[&MF][VReg] = SpirvType;
123}
124
126 auto Res = MRI.createGenericVirtualRegister(LLT::scalar(64));
127 MRI.setRegClass(Res, &SPIRV::TYPERegClass);
128 return Res;
129}
130
132 return createTypeVReg(MIRBuilder.getMF().getRegInfo());
133}
134
135SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeBool(MachineIRBuilder &MIRBuilder) {
136 return createConstOrTypeAtFunctionEntry(
137 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
138 return MIRBuilder.buildInstr(SPIRV::OpTypeBool)
139 .addDef(createTypeVReg(MIRBuilder));
140 });
141}
142
143unsigned SPIRVGlobalRegistry::adjustOpTypeIntWidth(unsigned Width) const {
144 const SPIRVSubtarget &ST = cast<SPIRVSubtarget>(CurMF->getSubtarget());
145 if (ST.canUseExtension(
146 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers) ||
147 (Width == 4 && ST.canUseExtension(SPIRV::Extension::SPV_INTEL_int4)))
148 return Width;
149 if (Width <= 8)
150 return 8;
151 else if (Width <= 16)
152 return 16;
153 else if (Width <= 32)
154 return 32;
155 else if (Width <= 64)
156 return 64;
157 else if (Width <= 128)
158 return 128;
159 reportFatalUsageError("Unsupported Integer width!");
160}
161
162SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeInt(unsigned Width,
163 MachineIRBuilder &MIRBuilder,
164 bool IsSigned) {
165 Width = adjustOpTypeIntWidth(Width);
166 const SPIRVSubtarget &ST =
168 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
169 &MIRBuilder) {
170 if (Width == 4 && ST.canUseExtension(SPIRV::Extension::SPV_INTEL_int4)) {
171 MIRBuilder.buildInstr(SPIRV::OpExtension)
172 .addImm(SPIRV::Extension::SPV_INTEL_int4);
173 MIRBuilder.buildInstr(SPIRV::OpCapability)
174 .addImm(SPIRV::Capability::Int4TypeINTEL);
175 } else if ((!isPowerOf2_32(Width) || Width < 8) &&
176 ST.canUseExtension(
177 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers)) {
178 MIRBuilder.buildInstr(SPIRV::OpExtension)
179 .addImm(SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers);
180 MIRBuilder.buildInstr(SPIRV::OpCapability)
181 .addImm(SPIRV::Capability::ArbitraryPrecisionIntegersALTERA);
182 }
183 return MIRBuilder.buildInstr(SPIRV::OpTypeInt)
184 .addDef(createTypeVReg(MIRBuilder))
185 .addImm(Width)
186 .addImm(IsSigned ? 1 : 0);
187 });
188}
189
191SPIRVGlobalRegistry::getOpTypeFloat(uint32_t Width,
192 MachineIRBuilder &MIRBuilder) {
193 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
194 &MIRBuilder) {
195 return MIRBuilder.buildInstr(SPIRV::OpTypeFloat)
196 .addDef(createTypeVReg(MIRBuilder))
197 .addImm(Width);
198 });
199}
200
202SPIRVGlobalRegistry::getOpTypeFloat(uint32_t Width,
203 MachineIRBuilder &MIRBuilder,
204 SPIRV::FPEncoding::FPEncoding FPEncode) {
205 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
206 &MIRBuilder) {
207 return MIRBuilder.buildInstr(SPIRV::OpTypeFloat)
208 .addDef(createTypeVReg(MIRBuilder))
209 .addImm(Width)
210 .addImm(FPEncode);
211 });
212}
213
215 return createConstOrTypeAtFunctionEntry(
216 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
217 return MIRBuilder.buildInstr(SPIRV::OpTypeVoid)
218 .addDef(createTypeVReg(MIRBuilder));
219 });
220}
221
223 // Other maps that may hold MachineInstr*:
224 // - VRegToTypeMap: We cannot remove the definitions of `MI` from
225 // VRegToTypeMap because some calls to invalidateMachineInstr are replacing MI
226 // with another instruction defining the same register. We expect that if MI
227 // is a type instruction, and it is still referenced in VRegToTypeMap, then
228 // those registers are dead or the VRegToTypeMap is out-of-date. We do not
229 // expect passes to ask for the SPIR-V type of a dead register. If the
230 // VRegToTypeMap is out-of-date already, then there was an error before. We
231 // cannot add an assert to verify this because the VRegToTypeMap can be
232 // out-of-date.
233 // - FunctionToInstr & FunctionToInstrRev: At this point, we should not be
234 // deleting functions. No need to update.
235 // - AliasInstMDMap: Would require a linear search, and the Intel Alias
236 // instruction are not instructions instruction selection will be able to
237 // remove.
238
239 const SPIRVSubtarget &ST = MI->getMF()->getSubtarget<SPIRVSubtarget>();
240 [[maybe_unused]] const SPIRVInstrInfo *TII = ST.getInstrInfo();
241 assert(!TII->isAliasingInstr(*MI) &&
242 "Cannot invalidate aliasing instructions.");
243 assert(MI->getOpcode() != SPIRV::OpFunction &&
244 "Cannot invalidate OpFunction.");
245
246 if (MI->getOpcode() == SPIRV::OpFunctionCall) {
247 if (const auto *F = dyn_cast<Function>(MI->getOperand(2).getGlobal())) {
248 auto It = ForwardCalls.find(F);
249 if (It != ForwardCalls.end()) {
250 It->second.erase(MI);
251 if (It->second.empty())
252 ForwardCalls.erase(It);
253 }
254 }
255 }
256
257 const MachineFunction *MF = MI->getMF();
258 auto It = LastInsertedTypeMap.find(MF);
259 if (It != LastInsertedTypeMap.end() && It->second == MI)
260 LastInsertedTypeMap.erase(MF);
261 // remove from the duplicate tracker to avoid incorrect reuse
262 erase(MI);
263}
264
265const MachineInstr *SPIRVGlobalRegistry::createConstOrTypeAtFunctionEntry(
266 MachineIRBuilder &MIRBuilder,
267 std::function<MachineInstr *(MachineIRBuilder &)> Op) {
268 auto oldInsertPoint = MIRBuilder.getInsertPt();
269 assert(oldInsertPoint.isValid() && "Builder must have insertion point set!");
270 MachineBasicBlock *OldMBB = &MIRBuilder.getMBB();
271 MachineBasicBlock *NewMBB = &*MIRBuilder.getMF().begin();
272
273 auto LastInsertedType = LastInsertedTypeMap.find(CurMF);
274 if (LastInsertedType != LastInsertedTypeMap.end()) {
275 auto It = LastInsertedType->second->getIterator();
276 // It might happen that this instruction was removed from the first MBB,
277 // hence the Parent's check.
279 if (It->getParent() != NewMBB)
280 InsertAt = oldInsertPoint->getParent() == NewMBB
281 ? oldInsertPoint
282 : getInsertPtValidEnd(NewMBB);
283 else if (It->getNextNode())
284 InsertAt = It->getNextNode()->getIterator();
285 else
286 InsertAt = getInsertPtValidEnd(NewMBB);
287 MIRBuilder.setInsertPt(*NewMBB, InsertAt);
288 } else {
289 MIRBuilder.setInsertPt(*NewMBB, NewMBB->begin());
290 auto Result = LastInsertedTypeMap.try_emplace(CurMF, nullptr);
291 assert(Result.second);
292 LastInsertedType = Result.first;
293 }
294
295 MachineInstr *ConstOrType = Op(MIRBuilder);
296 // We expect all users of this function to insert definitions at the insertion
297 // point set above that is always the first MBB.
298 assert(ConstOrType->getParent() == NewMBB);
299 LastInsertedType->second = ConstOrType;
300 // Advance past any continued instructions so that the next type/constant
301 // is inserted after the full group, preserving required adjacency.
302 while (auto *Next = LastInsertedType->second->getNextNode()) {
303 unsigned Opc = Next->getOpcode();
304 if (Opc == SPIRV::OpTypeStructContinuedINTEL ||
305 Opc == SPIRV::OpConstantCompositeContinuedINTEL ||
306 Opc == SPIRV::OpSpecConstantCompositeContinuedINTEL ||
307 Opc == SPIRV::OpCompositeConstructContinuedINTEL)
308 LastInsertedType->second = Next;
309 else
310 break;
311 }
312
313 MIRBuilder.setInsertPt(*OldMBB, oldInsertPoint);
314 return ConstOrType;
315}
316
317SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeVectorImpl(
318 uint32_t NumElems, SPIRVTypeInst ElemType, MachineIRBuilder &MIRBuilder,
319 bool IsLongVectorEXT) {
320 if (ElemType.isPointer()) {
321 if (!cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget())
322 .canUseExtension(
323 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
324 const Function &F = MIRBuilder.getMF().getFunction();
325 F.getContext().diagnose(DiagnosticInfoUnsupported(
326 F,
327 "Vector of pointers requires SPV_INTEL_masked_gather_scatter "
328 "extension",
329 DebugLoc(), DS_Error));
330 }
331 } else {
332 [[maybe_unused]] auto EleOpc = ElemType->getOpcode();
333 assert((EleOpc == SPIRV::OpTypeInt || EleOpc == SPIRV::OpTypeFloat ||
334 EleOpc == SPIRV::OpTypeBool) &&
335 "Invalid vector element type");
336 }
337
338 return createConstOrTypeAtFunctionEntry(
339 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
340 unsigned Op =
341 IsLongVectorEXT ? SPIRV::OpTypeVectorIdEXT : SPIRV::OpTypeVector;
342 Register VTy = createTypeVReg(MIRBuilder);
343 Register Ty = getSPIRVTypeID(ElemType);
344 auto MIB = MIRBuilder.buildInstr(Op).addDef(VTy).addUse(Ty);
345 if (!IsLongVectorEXT)
346 return MIB.addImm(NumElems);
347
348 const auto &ST = MIRBuilder.getMF().getSubtarget<SPIRVSubtarget>();
349 SPIRVTypeInst Int32Ty = getOrCreateSPIRVIntegerType(32, MIRBuilder);
350 return MIB.addUse(getOrCreateConstInt(NumElems, *MIB.getInstr(),
351 Int32Ty, *ST.getInstrInfo()));
352 });
353}
354
356SPIRVGlobalRegistry::getOpTypeVector(uint32_t NumElems, SPIRVTypeInst ElemType,
357 MachineIRBuilder &MIRBuilder) {
358 assert(NumElems >= 2 && "SPIR-V OpTypeVector requires at least 2 components");
359 return getOpTypeVectorImpl(NumElems, ElemType, MIRBuilder);
360}
361
362SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeVectorIdEXT(
363 uint32_t NumElems, SPIRVTypeInst ElemType, MachineIRBuilder &MIRBuilder) {
364 assert((NumElems < 2 || NumElems > 16 ||
365 (NumElems != 3 && NumElems != 4 && NumElems != 8)) &&
366 "SPIR-V OpTypeVectorIdExt should only be used for extended vectors");
367 return getOpTypeVectorImpl(NumElems, ElemType, MIRBuilder, true);
368}
369
371 SPIRVTypeInst SpvType,
372 const SPIRVInstrInfo &TII,
373 bool ZeroAsNull) {
374 LLVMContext &Ctx = CurMF->getFunction().getContext();
375 auto *const CF = ConstantFP::get(Ctx, Val);
376 const MachineInstr *MI = findMI(CF, CurMF);
377 if (MI && (MI->getOpcode() == SPIRV::OpConstantNull ||
378 MI->getOpcode() == SPIRV::OpConstantF))
379 return MI->getOperand(0).getReg();
380 return createConstFP(CF, I, SpvType, TII, ZeroAsNull);
381}
382
385 SPIRVTypeInst SpvType,
386 const SPIRVInstrInfo &TII,
387 bool ZeroAsNull) {
388 unsigned BitWidth = getScalarOrVectorBitWidth(SpvType);
389 LLT LLTy = LLT::scalar(BitWidth);
390 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
391 CurMF->getRegInfo().setRegClass(Res, &SPIRV::fIDRegClass);
392 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
393
394 MachineInstr *DepMI =
395 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
396 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
397 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
398 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
400 // In OpenCL OpConstantNull - Scalar floating point: +0.0 (all bits 0)
401 if (CF->getValue().isPosZero() && ZeroAsNull) {
402 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
403 .addDef(Res)
404 .addUse(getSPIRVTypeID(SpvType));
405 } else {
406 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantF)
407 .addDef(Res)
408 .addUse(getSPIRVTypeID(SpvType));
411 MIB);
412 }
413 constrainSelectedInstRegOperands(MIB);
414 return MIB;
415 });
416 add(CF, Const);
417 return Res;
418}
419
421 SPIRVTypeInst SpvType,
422 const SPIRVInstrInfo &TII,
423 bool ZeroAsNull) {
425 SpvType, TII, ZeroAsNull);
426}
427
430 SPIRVTypeInst SpvType,
431 const SPIRVInstrInfo &TII,
432 bool ZeroAsNull) {
433 auto *const CI = ConstantInt::get(
435 const MachineInstr *MI = findMI(CI, CurMF);
436 if (MI && (MI->getOpcode() == SPIRV::OpConstantNull ||
437 MI->getOpcode() == SPIRV::OpConstantI))
438 return MI->getOperand(0).getReg();
439 return createConstInt(CI, I, SpvType, TII, ZeroAsNull);
440}
441
444 SPIRVTypeInst SpvType,
445 const SPIRVInstrInfo &TII,
446 bool ZeroAsNull) {
447 unsigned BitWidth = getScalarOrVectorBitWidth(SpvType);
448 LLT LLTy = LLT::scalar(BitWidth);
449 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
450 CurMF->getRegInfo().setRegClass(Res, &SPIRV::iIDRegClass);
452
453 MachineInstr *DepMI =
454 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
455 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
456 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
457 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
459 if (BitWidth == 1) {
460 MIB = MIRBuilder
461 .buildInstr(CI->isZero() ? SPIRV::OpConstantFalse
462 : SPIRV::OpConstantTrue)
463 .addDef(Res)
464 .addUse(getSPIRVTypeID(SpvType));
465 } else if (!CI->isZero() || !ZeroAsNull) {
466 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantI)
467 .addDef(Res)
468 .addUse(getSPIRVTypeID(SpvType));
469 addNumImm(CI->getValue(), MIB);
470 } else {
471 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
472 .addDef(Res)
473 .addUse(getSPIRVTypeID(SpvType));
474 }
475 constrainSelectedInstRegOperands(MIB);
476 return MIB;
477 });
478 add(CI, Const);
479 return Res;
480}
481
483 MachineIRBuilder &MIRBuilder,
484 SPIRVTypeInst SpvType,
485 bool EmitIR, bool ZeroAsNull) {
486 assert(SpvType);
487 auto &MF = MIRBuilder.getMF();
489 // TODO: Avoid implicit trunc?
490 // See https://github.com/llvm/llvm-project/issues/112510.
491 auto *const CI = ConstantInt::get(const_cast<IntegerType *>(Ty), Val,
492 /*IsSigned=*/false, /*ImplicitTrunc=*/true);
493 Register Res = find(CI, &MF);
494 if (Res.isValid())
495 return Res;
496
497 unsigned BitWidth = getScalarOrVectorBitWidth(SpvType);
498 LLT LLTy = LLT::scalar(BitWidth);
499 MachineRegisterInfo &MRI = MF.getRegInfo();
500 Res = MRI.createGenericVirtualRegister(LLTy);
501 MRI.setRegClass(Res, &SPIRV::iIDRegClass);
502 assignTypeToVReg(Ty, Res, MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
503 EmitIR);
504
505 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
506 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
507 if (EmitIR)
508 return MIRBuilder.buildConstant(Res, *CI);
509 Register SpvTypeReg = getSPIRVTypeID(SpvType);
511 if (Val || !ZeroAsNull) {
512 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantI)
513 .addDef(Res)
514 .addUse(SpvTypeReg);
515 addNumImm(APInt(BitWidth, Val), MIB);
516 } else {
517 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
518 .addDef(Res)
519 .addUse(SpvTypeReg);
520 }
521 constrainSelectedInstRegOperands(MIB);
522 return MIB;
523 });
524 add(CI, Const);
525 return Res;
526}
527
529 MachineIRBuilder &MIRBuilder,
530 SPIRVTypeInst SpvType) {
531 auto &MF = MIRBuilder.getMF();
532 LLVMContext &Ctx = MF.getFunction().getContext();
533 if (!SpvType)
534 SpvType = getOrCreateSPIRVType(Type::getFloatTy(Ctx), MIRBuilder,
535 SPIRV::AccessQualifier::ReadWrite, true);
536 auto *const CF = ConstantFP::get(Ctx, Val);
537 Register Res = find(CF, &MF);
538 if (Res.isValid())
539 return Res;
540
542 Res = MF.getRegInfo().createGenericVirtualRegister(LLTy);
543 MF.getRegInfo().setRegClass(Res, &SPIRV::fIDRegClass);
544 assignSPIRVTypeToVReg(SpvType, Res, MF);
545
546 const MachineInstr *Const = createConstOrTypeAtFunctionEntry(
547 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
549 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantF)
550 .addDef(Res)
551 .addUse(getSPIRVTypeID(SpvType));
552 addNumImm(CF->getValueAPF().bitcastToAPInt(), MIB);
553 return MIB;
554 });
555 add(CF, Const);
556 return Res;
557}
558
559Register SPIRVGlobalRegistry::getOrCreateBaseRegister(
560 Constant *Val, MachineInstr &I, SPIRVTypeInst SpvType,
561 const SPIRVInstrInfo &TII, unsigned BitWidth, bool ZeroAsNull) {
562 SPIRVTypeInst Type = SpvType;
563 if (isVectorType(SpvType) || SpvType->getOpcode() == SPIRV::OpTypeArray) {
564 auto EleTypeReg = SpvType->getOperand(1).getReg();
565 Type = getSPIRVTypeForVReg(EleTypeReg);
566 }
567 if (Type->getOpcode() == SPIRV::OpTypeFloat) {
569 return getOrCreateConstFP(cast<ConstantFP>(Val)->getValue(), I, SpvBaseType,
570 TII, ZeroAsNull);
571 }
572 assert(Type->getOpcode() == SPIRV::OpTypeInt);
573 SPIRVTypeInst SpvBaseType = getOrCreateSPIRVIntegerType(BitWidth, I, TII);
574 return getOrCreateConstInt(Val->getUniqueInteger(), I, SpvBaseType, TII,
575 ZeroAsNull);
576}
577
578Register SPIRVGlobalRegistry::getOrCreateCompositeOrNull(
579 Constant *Val, MachineInstr &I, SPIRVTypeInst SpvType,
580 const SPIRVInstrInfo &TII, Constant *CA, unsigned BitWidth,
581 unsigned ElemCnt, bool ZeroAsNull) {
582 if (Register R = find(CA, CurMF); R.isValid())
583 return R;
584
585 bool IsNull = Val->isNullValue() && ZeroAsNull;
586 Register ElemReg;
587 if (!IsNull)
588 ElemReg =
589 getOrCreateBaseRegister(Val, I, SpvType, TII, BitWidth, ZeroAsNull);
590
591 LLT LLTy = LLT::scalar(64);
592 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
593 CurMF->getRegInfo().setRegClass(Res, getRegClass(SpvType));
594 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
595
596 MachineInstr *DepMI =
597 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
598 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
599 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
600 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
601 MachineInstrBuilder MIB;
602 if (!IsNull) {
603 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantComposite)
604 .addDef(Res)
605 .addUse(getSPIRVTypeID(SpvType));
606 for (unsigned i = 0; i < ElemCnt; ++i)
607 MIB.addUse(ElemReg);
608 } else {
609 MIB = MIRBuilder.buildInstr(SPIRV::OpConstantNull)
610 .addDef(Res)
611 .addUse(getSPIRVTypeID(SpvType));
612 }
613 constrainSelectedInstRegOperands(MIB);
614 return MIB;
615 });
616 add(CA, NewMI);
617 return Res;
618}
619
622 SPIRVTypeInst SpvType,
623 const SPIRVInstrInfo &TII,
624 bool ZeroAsNull) {
626 I, SpvType, TII, ZeroAsNull);
627}
628
631 SPIRVTypeInst SpvType,
632 const SPIRVInstrInfo &TII,
633 bool ZeroAsNull) {
634 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
635 assert(LLVMTy->isVectorTy() &&
636 "Expected vector type for constant vector creation");
637 const FixedVectorType *LLVMVecTy = cast<FixedVectorType>(LLVMTy);
638 Type *LLVMBaseTy = LLVMVecTy->getElementType();
639 [[maybe_unused]] const auto &ST = I.getMF()->getSubtarget<SPIRVSubtarget>();
640 assert((LLVMBaseTy->isIntegerTy() ||
641 (LLVMBaseTy->isPointerTy() &&
642 ST.canUseExtension(
643 SPIRV::Extension::SPV_INTEL_masked_gather_scatter))) &&
644 "Expected either integer element type for APInt constant vector or "
645 "pointer type if the SPV_INTEL_masked_gather_scatter extension is "
646 "enabled!");
647 Constant *ConstVal = nullptr;
648 if (LLVMBaseTy->isIntegerTy()) {
649 ConstVal = ConstantInt::get(LLVMBaseTy, Val);
650 } else {
651 if (Val.isZero())
652 ConstVal = ConstantPointerNull::get(LLVMBaseTy);
653 else
654 llvm_unreachable("Vectors of non-null constant pointers unimplemented!");
655 }
656 auto *ConstVec =
657 ConstantVector::getSplat(LLVMVecTy->getElementCount(), ConstVal);
658 unsigned BW = getScalarOrVectorBitWidth(SpvType);
659 return getOrCreateCompositeOrNull(ConstVal, I, SpvType, TII, ConstVec, BW,
661 ZeroAsNull);
662}
663
666 SPIRVTypeInst SpvType,
667 const SPIRVInstrInfo &TII,
668 bool ZeroAsNull) {
669 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
670 assert(LLVMTy->isVectorTy());
671 const FixedVectorType *LLVMVecTy = cast<FixedVectorType>(LLVMTy);
672 Type *LLVMBaseTy = LLVMVecTy->getElementType();
673 assert(LLVMBaseTy->isFloatingPointTy());
674 auto *ConstVal = ConstantFP::get(LLVMBaseTy, Val);
675 auto *ConstVec =
676 ConstantVector::getSplat(LLVMVecTy->getElementCount(), ConstVal);
677 unsigned BW = getScalarOrVectorBitWidth(SpvType);
678 return getOrCreateCompositeOrNull(ConstVal, I, SpvType, TII, ConstVec, BW,
680 ZeroAsNull);
681}
682
684 uint64_t Val, size_t Num, MachineInstr &I, SPIRVTypeInst SpvType,
685 const SPIRVInstrInfo &TII) {
686 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
687 assert(LLVMTy->isArrayTy());
688 const ArrayType *LLVMArrTy = cast<ArrayType>(LLVMTy);
689 Type *LLVMBaseTy = LLVMArrTy->getElementType();
690 Constant *CI = ConstantInt::get(LLVMBaseTy, Val);
691 SPIRVTypeInst SpvBaseTy =
693 unsigned BW = getScalarOrVectorBitWidth(SpvBaseTy);
694 // The following is reasonably unique key that is better that [Val]. The naive
695 // alternative would be something along the lines of:
696 // SmallVector<Constant *> NumCI(Num, CI);
697 // Constant *UniqueKey =
698 // ConstantArray::get(const_cast<ArrayType*>(LLVMArrTy), NumCI);
699 // that would be a truly unique but dangerous key, because it could lead to
700 // the creation of constants of arbitrary length (that is, the parameter of
701 // memset) which were missing in the original module.
702 Type *I64Ty = Type::getInt64Ty(LLVMBaseTy->getContext());
704 {PoisonValue::get(const_cast<ArrayType *>(LLVMArrTy)),
705 ConstantInt::get(LLVMBaseTy, Val), ConstantInt::get(I64Ty, Num)});
706 return getOrCreateCompositeOrNull(CI, I, SpvType, TII, UniqueKey, BW,
707 LLVMArrTy->getNumElements());
708}
709
710Register SPIRVGlobalRegistry::getOrCreateIntCompositeOrNull(
711 uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType,
712 bool EmitIR, Constant *CA, unsigned BitWidth, unsigned ElemCnt) {
713 if (Register R = find(CA, CurMF); R.isValid())
714 return R;
715
716 Register ElemReg;
717 if (Val || EmitIR) {
718 SPIRVTypeInst SpvBaseType =
720 ElemReg = buildConstantInt(Val, MIRBuilder, SpvBaseType, EmitIR);
721 }
722 LLT LLTy = EmitIR ? LLT::fixed_vector(ElemCnt, BitWidth) : LLT::scalar(64);
723 Register Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
724 CurMF->getRegInfo().setRegClass(Res, &SPIRV::iIDRegClass);
725 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
726
727 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
728 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
729 if (EmitIR)
730 return MIRBuilder.buildSplatBuildVector(Res, ElemReg);
731
732 if (Val) {
733 auto MIB = MIRBuilder.buildInstr(SPIRV::OpConstantComposite)
734 .addDef(Res)
735 .addUse(getSPIRVTypeID(SpvType));
736 for (unsigned i = 0; i < ElemCnt; ++i)
737 MIB.addUse(ElemReg);
738 return MIB;
739 }
740
741 return MIRBuilder.buildInstr(SPIRV::OpConstantNull)
742 .addDef(Res)
743 .addUse(getSPIRVTypeID(SpvType));
744 });
745 add(CA, NewMI);
746 return Res;
747}
748
750 uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType,
751 bool EmitIR) {
752 const Type *LLVMTy = getTypeForSPIRVType(SpvType);
753 assert(LLVMTy->isVectorTy());
754 const FixedVectorType *LLVMVecTy = cast<FixedVectorType>(LLVMTy);
755 Type *LLVMBaseTy = LLVMVecTy->getElementType();
756 const auto ConstInt = ConstantInt::get(LLVMBaseTy, Val);
757 auto ConstVec =
758 ConstantVector::getSplat(LLVMVecTy->getElementCount(), ConstInt);
759 unsigned BW = getScalarOrVectorBitWidth(SpvType);
760 return getOrCreateIntCompositeOrNull(
761 Val, MIRBuilder, SpvType, EmitIR, ConstVec, BW,
763}
764
767 SPIRVTypeInst SpvType) {
768 const Type *Ty = getTypeForSPIRVType(SpvType);
769 unsigned AddressSpace = typeToAddressSpace(Ty);
771 assert(ElemTy);
774 Register Res = find(CP, CurMF);
775 if (Res.isValid())
776 return Res;
777
779 Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
780 CurMF->getRegInfo().setRegClass(Res, &SPIRV::pIDRegClass);
781 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
782
783 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
784 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
785 return MIRBuilder.buildInstr(SPIRV::OpConstantNull)
786 .addDef(Res)
787 .addUse(getSPIRVTypeID(SpvType));
788 });
789 add(CP, NewMI);
790 return Res;
791}
792
795 unsigned Param, unsigned FilerMode,
796 MachineIRBuilder &MIRBuilder) {
797 auto Sampler =
798 ResReg.isValid()
799 ? ResReg
800 : MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
801 SPIRVTypeInst TypeSampler = getOrCreateOpTypeSampler(MIRBuilder);
802 Register TypeSamplerReg = getSPIRVTypeID(TypeSampler);
803 // We cannot use createOpType() logic here, because of the
804 // GlobalISel/IRTranslator.cpp check for a tail call that expects that
805 // MIRBuilder.getInsertPt() has a previous instruction. If this constant is
806 // inserted as a result of "__translate_sampler_initializer()" this would
807 // break this IRTranslator assumption.
808 MIRBuilder.buildInstr(SPIRV::OpConstantSampler)
810 .addUse(TypeSamplerReg)
812 .addImm(Param)
813 .addImm(FilerMode);
814 return Sampler;
815}
816
819 const GlobalValue *GV, SPIRV::StorageClass::StorageClass Storage,
820 const MachineInstr *Init, bool IsConst,
821 const std::optional<SPIRV::LinkageType::LinkageType> &LinkageType,
822 MachineIRBuilder &MIRBuilder, bool IsInstSelector) {
823 const GlobalVariable *GVar = nullptr;
824 if (GV) {
826 } else {
827 // If GV is not passed explicitly, use the name to find or construct
828 // the global variable.
829 Module *M = MIRBuilder.getMF().getFunction().getParent();
830 GVar = M->getGlobalVariable(Name);
831 if (GVar == nullptr) {
832 const Type *Ty = getTypeForSPIRVType(BaseType); // TODO: check type.
833 if (auto *TPTy = dyn_cast<TypedPointerType>(Ty))
834 Ty = PointerType::get(M->getContext(), TPTy->getAddressSpace());
835 // Module takes ownership of the global var.
836 GVar = new GlobalVariable(*M, const_cast<Type *>(Ty), false,
838 Twine(Name));
839 }
840 GV = GVar;
841 }
842
843 const MachineFunction *MF = &MIRBuilder.getMF();
844 Register Reg = find(GVar, MF);
845 if (Reg.isValid()) {
846 if (Reg != ResVReg)
847 MIRBuilder.buildCopy(ResVReg, Reg);
848 return ResVReg;
849 }
850
851 // Emit the OpVariable into the entry block to ensure the def dominates
852 // all uses across all MBBs.
853 MachineBasicBlock &EntryBB = MIRBuilder.getMF().front();
854 MachineIRBuilder GVBuilder(MIRBuilder.getState());
855 if (&GVBuilder.getMBB() != &EntryBB)
856 GVBuilder.setInsertPt(EntryBB, EntryBB.getFirstTerminator());
857
858 // Pointers to opaque types stay typed even with the extension on, so emit the
859 // untyped variant only when the result is actually an untyped pointer.
860 const bool UseUntypedPointers =
861 BaseType->getOpcode() == SPIRV::OpTypeUntypedPointerKHR;
862 const unsigned VariableOpcode =
863 UseUntypedPointers ? SPIRV::OpUntypedVariableKHR : SPIRV::OpVariable;
864
865 auto MIB = GVBuilder.buildInstr(VariableOpcode)
866 .addDef(ResVReg)
868 .addImm(static_cast<uint32_t>(Storage));
869
870 // OpUntypedVariableKHR takes an extra Data Type operand right after the
871 // storage class, holding the global's value type.
872 if (UseUntypedPointers) {
874 if (!DataType)
875 DataType = getOrCreateSPIRVType(GV->getValueType(), GVBuilder,
876 SPIRV::AccessQualifier::ReadWrite,
877 /*EmitIR=*/false);
878 if (!DataType) {
879 const Function &F = MIRBuilder.getMF().getFunction();
880 F.getContext().diagnose(DiagnosticInfoUnsupported(
881 F,
882 "Could not deduce the data type of untyped global variable '" +
883 GVar->getName() + "'",
884 DebugLoc(), DS_Error));
885 // Recover with i8 so that codegen can finish and report the error.
886 DataType =
887 getOrCreateSPIRVType(Type::getInt8Ty(F.getContext()), GVBuilder,
888 SPIRV::AccessQualifier::ReadWrite,
889 /*EmitIR=*/false);
890 }
891 MIB.addUse(getSPIRVTypeID(DataType));
892 }
893
894 if (Init)
895 MIB.addUse(Init->getOperand(0).getReg());
896 // ISel may introduce a new register on this step, so we need to add it to
897 // DT and correct its type avoiding fails on the next stage.
898 if (IsInstSelector) {
899 constrainSelectedInstRegOperands(MIB);
900 }
901 add(GVar, MIB);
902
903 Reg = MIB->getOperand(0).getReg();
904 addGlobalObject(GVar, MF, Reg);
905
906 // Set to Reg the same type as ResVReg has.
907 auto MRI = MIRBuilder.getMRI();
908 if (Reg != ResVReg) {
909 LLT RegLLTy =
910 LLT::pointer(MRI->getType(ResVReg).getAddressSpace(), getPointerSize());
911 MRI->setType(Reg, RegLLTy);
912 assignSPIRVTypeToVReg(BaseType, Reg, MIRBuilder.getMF());
913 } else {
914 // Our knowledge about the type may be updated.
915 // If that's the case, we need to update a type
916 // associated with the register.
917 SPIRVTypeInst DefType = getSPIRVTypeForVReg(ResVReg);
918 if (!DefType || DefType != SPIRVTypeInst(BaseType))
919 assignSPIRVTypeToVReg(BaseType, Reg, MIRBuilder.getMF());
920 }
921
922 // If it's a global variable with name, output OpName for it.
923 if (GVar && GVar->hasName())
924 buildOpName(Reg, GVar->getName(), MIRBuilder);
925
926 // Output decorations for the GV.
927 // TODO: maybe move to GenerateDecorations pass.
928 const SPIRVSubtarget &ST =
930 if (IsConst && !ST.isShader())
931 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::Constant, {});
932
933 if (GVar && GVar->getAlign().valueOrOne().value() != 1 && !ST.isShader()) {
934 unsigned Alignment = (unsigned)GVar->getAlign().valueOrOne().value();
935 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::Alignment, {Alignment});
936 }
937
938 if (LinkageType)
939 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::LinkageAttributes,
940 {static_cast<uint32_t>(*LinkageType)}, Name);
941
942 SPIRV::BuiltIn::BuiltIn BuiltInId;
943 if (getSpirvBuiltInIdByName(Name, BuiltInId))
944 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::BuiltIn,
945 {static_cast<uint32_t>(BuiltInId)});
946
947 // If it's a global variable with "spirv.Decorations" metadata node
948 // recognize it as a SPIR-V friendly LLVM IR and parse "spirv.Decorations"
949 // arguments.
950 MDNode *GVarMD = nullptr;
951 if (GVar && (GVarMD = GVar->getMetadata("spirv.Decorations")) != nullptr)
952 buildOpSpirvDecorations(Reg, MIRBuilder, GVarMD, ST);
953
954 return Reg;
955}
956
957// Returns a name based on the Type. Notes that this does not look at
958// decorations, and will return the same string for two types that are the same
959// except for decorations.
961 SPIRVTypeInst VarType, uint32_t Set, uint32_t Binding, StringRef Name,
962 MachineIRBuilder &MIRBuilder) {
963 Register VarReg =
964 MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
965
966 buildGlobalVariable(VarReg, VarType, Name, nullptr,
967 getPointerStorageClass(VarType), nullptr, false,
968 std::nullopt, MIRBuilder, false);
969
970 buildOpDecorate(VarReg, MIRBuilder, SPIRV::Decoration::DescriptorSet, {Set});
971 buildOpDecorate(VarReg, MIRBuilder, SPIRV::Decoration::Binding, {Binding});
972 return VarReg;
973}
974
975// TODO: Double check the calls to getOpTypeArray to make sure that `ElemType`
976// is explicitly laid out when required.
977SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeArray(uint32_t NumElems,
978 SPIRVTypeInst ElemType,
979 MachineIRBuilder &MIRBuilder,
980 bool ExplicitLayoutRequired,
981 bool EmitIR) {
982 assert((ElemType->getOpcode() != SPIRV::OpTypeVoid) &&
983 "Invalid array element type");
984 SPIRVTypeInst SpvTypeInt32 = getOrCreateSPIRVIntegerType(32, MIRBuilder);
985 SPIRVTypeInst ArrayType = nullptr;
986 const SPIRVSubtarget &ST =
988 if (NumElems != 0) {
989 Register NumElementsVReg =
990 buildConstantInt(NumElems, MIRBuilder, SpvTypeInt32, EmitIR);
991 ArrayType = createConstOrTypeAtFunctionEntry(
992 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
993 return MIRBuilder.buildInstr(SPIRV::OpTypeArray)
994 .addDef(createTypeVReg(MIRBuilder))
995 .addUse(getSPIRVTypeID(ElemType))
996 .addUse(NumElementsVReg);
997 });
998 } else if (ST.getTargetTriple().getVendor() == Triple::VendorType::AMD) {
999 // We set the array size to the token UINT64_MAX value, which is generally
1000 // illegal (the maximum legal size is 61-bits) for the foreseeable future.
1001 SPIRVTypeInst SpvTypeInt64 = getOrCreateSPIRVIntegerType(64, MIRBuilder);
1002 Register NumElementsVReg =
1003 buildConstantInt(UINT64_MAX, MIRBuilder, SpvTypeInt64, EmitIR);
1004 ArrayType = createConstOrTypeAtFunctionEntry(
1005 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1006 return MIRBuilder.buildInstr(SPIRV::OpTypeArray)
1007 .addDef(createTypeVReg(MIRBuilder))
1008 .addUse(getSPIRVTypeID(ElemType))
1009 .addUse(NumElementsVReg);
1010 });
1011 } else {
1012 if (!ST.isShader()) {
1014 "Runtime arrays are not allowed in non-shader "
1015 "SPIR-V modules");
1016 return nullptr;
1017 }
1018 ArrayType = createConstOrTypeAtFunctionEntry(
1019 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1020 return MIRBuilder.buildInstr(SPIRV::OpTypeRuntimeArray)
1021 .addDef(createTypeVReg(MIRBuilder))
1022 .addUse(getSPIRVTypeID(ElemType));
1023 });
1024 }
1025
1026 if (ExplicitLayoutRequired && !isResourceType(ElemType)) {
1027 Type *ET = const_cast<Type *>(getTypeForSPIRVType(ElemType));
1028 addArrayStrideDecorations(ArrayType->defs().begin()->getReg(), ET,
1029 MIRBuilder);
1030 }
1031
1032 return ArrayType;
1033}
1034
1036SPIRVGlobalRegistry::getOpTypeOpaque(const StructType *Ty,
1037 MachineIRBuilder &MIRBuilder) {
1038 assert(Ty->hasName());
1039 StringRef Name = Ty->hasName() ? Ty->getName() : "";
1040 Register ResVReg = createTypeVReg(MIRBuilder);
1041 return createConstOrTypeAtFunctionEntry(
1042 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1043 auto MIB = MIRBuilder.buildInstr(SPIRV::OpTypeOpaque).addDef(ResVReg);
1044 addStringImm(Name, MIB);
1045 buildOpName(ResVReg, Name, MIRBuilder);
1046 return MIB;
1047 });
1048}
1049
1050SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeStruct(
1051 const StructType *Ty, MachineIRBuilder &MIRBuilder,
1052 SPIRV::AccessQualifier::AccessQualifier AccQual,
1053 StructOffsetDecorator Decorator, bool EmitIR) {
1054 Type *OriginalElementType = nullptr;
1055 uint64_t TotalSize = 0;
1056 if (matchPeeledArrayPattern(Ty, OriginalElementType, TotalSize)) {
1057 SPIRVTypeInst ElementSPIRVType = findSPIRVType(
1058 OriginalElementType, MIRBuilder, AccQual,
1059 /* ExplicitLayoutRequired= */ Decorator != nullptr, EmitIR);
1060 return getOpTypeArray(TotalSize, ElementSPIRVType, MIRBuilder,
1061 /*ExplicitLayoutRequired=*/Decorator != nullptr,
1062 EmitIR);
1063 }
1064
1065 const SPIRVSubtarget &ST =
1066 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
1067 SmallVector<Register, 4> FieldTypes;
1068 constexpr unsigned MaxWordCount = UINT16_MAX;
1069 const size_t NumElements = Ty->getNumElements();
1070
1071 size_t MaxNumElements = MaxWordCount - 2;
1072 size_t SPIRVStructNumElements = NumElements;
1073 if (NumElements > MaxNumElements) {
1074 // Do adjustments for continued instructions.
1075 SPIRVStructNumElements = MaxNumElements;
1076 MaxNumElements = MaxWordCount - 1;
1077 }
1078
1079 for (const auto &Elem : Ty->elements()) {
1080 SPIRVTypeInst ElemTy = findSPIRVType(
1081 toTypedPointer(Elem), MIRBuilder, AccQual,
1082 /* ExplicitLayoutRequired= */ Decorator != nullptr, EmitIR);
1083 assert(ElemTy && ElemTy->getOpcode() != SPIRV::OpTypeVoid &&
1084 "Invalid struct element type");
1085 FieldTypes.push_back(getSPIRVTypeID(ElemTy));
1086 }
1087 Register ResVReg = createTypeVReg(MIRBuilder);
1088 if (Ty->hasName())
1089 buildOpName(ResVReg, Ty->getName(), MIRBuilder);
1090 if (Ty->isPacked() && !ST.isShader())
1091 buildOpDecorate(ResVReg, MIRBuilder, SPIRV::Decoration::CPacked, {});
1092
1093 SPIRVTypeInst SPVType = createConstOrTypeAtFunctionEntry(
1094 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1095 auto MIBStruct =
1096 MIRBuilder.buildInstr(SPIRV::OpTypeStruct).addDef(ResVReg);
1097 for (size_t I = 0; I < SPIRVStructNumElements; ++I)
1098 MIBStruct.addUse(FieldTypes[I]);
1099 for (size_t I = SPIRVStructNumElements; I < NumElements;
1100 I += MaxNumElements) {
1101 auto MIBCont =
1102 MIRBuilder.buildInstr(SPIRV::OpTypeStructContinuedINTEL);
1103 for (size_t J = I; J < std::min(I + MaxNumElements, NumElements); ++J)
1104 MIBCont.addUse(FieldTypes[J]);
1105 }
1106 return MIBStruct;
1107 });
1108
1109 if (Decorator)
1110 Decorator(SPVType->defs().begin()->getReg());
1111
1112 return SPVType;
1113}
1114
1115SPIRVTypeInst SPIRVGlobalRegistry::getOrCreateSpecialType(
1116 const Type *Ty, MachineIRBuilder &MIRBuilder,
1117 SPIRV::AccessQualifier::AccessQualifier AccQual) {
1118 assert(isSpecialOpaqueType(Ty) && "Not a special opaque builtin type");
1119 return SPIRV::lowerBuiltinType(Ty, AccQual, MIRBuilder, this);
1120}
1121
1122SPIRVTypeInst SPIRVGlobalRegistry::getOpTypePointer(
1123 SPIRV::StorageClass::StorageClass SC, SPIRVTypeInst ElemType,
1124 MachineIRBuilder &MIRBuilder, Register Reg) {
1125 // Check if we should use untyped pointers.
1126 const SPIRVSubtarget &ST =
1127 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
1128 if (shouldUseUntypedPointer(ElemType, ST))
1129 return getOrCreateSPIRVUntypedPointerType(SC, MIRBuilder);
1130
1131 if (!Reg.isValid())
1132 Reg = createTypeVReg(MIRBuilder);
1133
1134 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
1135 &MIRBuilder) {
1136 return MIRBuilder.buildInstr(SPIRV::OpTypePointer)
1137 .addDef(Reg)
1138 .addImm(static_cast<uint32_t>(SC))
1139 .addUse(getSPIRVTypeID(ElemType));
1140 });
1141}
1142
1143SPIRVTypeInst SPIRVGlobalRegistry::getOpTypeFunction(
1144 const FunctionType *Ty, SPIRVTypeInst RetType,
1145 const SmallVectorImpl<SPIRVTypeInst> &ArgTypes,
1146 MachineIRBuilder &MIRBuilder) {
1147 const SPIRVSubtarget *ST =
1148 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
1149 if (Ty->isVarArg() && ST->isShader()) {
1150 Function &Fn = MIRBuilder.getMF().getFunction();
1151 Ty->getContext().diagnose(DiagnosticInfoUnsupported(
1152 Fn, "SPIR-V shaders do not support variadic functions",
1153 MIRBuilder.getDebugLoc()));
1154 }
1155 return createConstOrTypeAtFunctionEntry(MIRBuilder, [&](MachineIRBuilder
1156 &MIRBuilder) {
1157 auto MIB = MIRBuilder.buildInstr(SPIRV::OpTypeFunction)
1158 .addDef(createTypeVReg(MIRBuilder))
1159 .addUse(getSPIRVTypeID(RetType));
1160 for (auto &ArgType : ArgTypes)
1161 MIB.addUse(getSPIRVTypeID(ArgType));
1162 return MIB;
1163 });
1164}
1165
1167 const Type *Ty, SPIRVTypeInst RetType,
1168 const SmallVectorImpl<SPIRVTypeInst> &ArgTypes,
1169 MachineIRBuilder &MIRBuilder) {
1170 if (const MachineInstr *MI = findMI(Ty, false, &MIRBuilder.getMF()))
1171 return MI;
1172 const MachineInstr *NewMI =
1173 getOpTypeFunction(cast<FunctionType>(Ty), RetType, ArgTypes, MIRBuilder);
1174 add(Ty, false, NewMI);
1175 return finishCreatingSPIRVType(Ty, NewMI);
1176}
1177
1178SPIRVTypeInst SPIRVGlobalRegistry::findSPIRVType(
1179 const Type *Ty, MachineIRBuilder &MIRBuilder,
1180 SPIRV::AccessQualifier::AccessQualifier AccQual,
1181 bool ExplicitLayoutRequired, bool EmitIR) {
1182 const auto &STI = MIRBuilder.getMF().getSubtarget<SPIRVSubtarget>();
1183 // Treat <1 x T> as T if the SPV_EXT_long_vector extension is not available.
1184 if (auto *FVT = dyn_cast<FixedVectorType>(Ty);
1185 FVT && FVT->getNumElements() == 1 &&
1186 !STI.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector))
1187 return findSPIRVType(FVT->getElementType(), MIRBuilder, AccQual,
1188 ExplicitLayoutRequired, EmitIR);
1189 Ty = adjustIntTypeByWidth(Ty);
1190 // TODO: findMI needs to know if a layout is required.
1191 if (const MachineInstr *MI =
1192 findMI(Ty, ExplicitLayoutRequired, &MIRBuilder.getMF()))
1193 return MI;
1194 if (auto It = ForwardPointerTypes.find(Ty); It != ForwardPointerTypes.end())
1195 return It->second;
1196 return restOfCreateSPIRVType(Ty, MIRBuilder, AccQual, ExplicitLayoutRequired,
1197 EmitIR);
1198}
1199
1201 assert(SpirvType && "Attempting to get type id for nullptr type.");
1202 if (SpirvType->getOpcode() == SPIRV::OpTypeForwardPointer ||
1203 SpirvType->getOpcode() == SPIRV::OpTypeStructContinuedINTEL)
1204 return SpirvType->uses().begin()->getReg();
1205 return SpirvType->defs().begin()->getReg();
1206}
1207
1208// We need to use a new LLVM integer type if there is a mismatch between
1209// number of bits in LLVM and SPIRV integer types to let DuplicateTracker
1210// ensure uniqueness of a SPIRV type by the corresponding LLVM type. Without
1211// such an adjustment SPIRVGlobalRegistry::getOpTypeInt() could create the
1212// same "OpTypeInt 8" type for a series of LLVM integer types with number of
1213// bits less than 8. This would lead to duplicate type definitions
1214// eventually due to the method that DuplicateTracker utilizes to reason
1215// about uniqueness of type records.
1216const Type *SPIRVGlobalRegistry::adjustIntTypeByWidth(const Type *Ty) const {
1217 if (auto IType = dyn_cast<IntegerType>(Ty)) {
1218 unsigned SrcBitWidth = IType->getBitWidth();
1219 if (SrcBitWidth > 1) {
1220 unsigned BitWidth = adjustOpTypeIntWidth(SrcBitWidth);
1221 // Maybe change source LLVM type to keep DuplicateTracker consistent.
1222 if (SrcBitWidth != BitWidth)
1223 Ty = IntegerType::get(Ty->getContext(), BitWidth);
1224 }
1225 }
1226 return Ty;
1227}
1228
1229SPIRVTypeInst SPIRVGlobalRegistry::createSPIRVType(
1230 const Type *Ty, MachineIRBuilder &MIRBuilder,
1231 SPIRV::AccessQualifier::AccessQualifier AccQual,
1232 bool ExplicitLayoutRequired, bool EmitIR) {
1233 if (isSpecialOpaqueType(Ty))
1234 return getOrCreateSpecialType(Ty, MIRBuilder, AccQual);
1235
1236 if (const MachineInstr *MI =
1237 findMI(Ty, ExplicitLayoutRequired, &MIRBuilder.getMF()))
1238 return MI;
1239
1240 if (auto IType = dyn_cast<IntegerType>(Ty)) {
1241 const unsigned Width = IType->getBitWidth();
1242 return Width == 1 ? getOpTypeBool(MIRBuilder)
1243 : getOpTypeInt(Width, MIRBuilder, false);
1244 }
1245 if (Ty->isFloatingPointTy()) {
1246 if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty())
1247 llvm::reportFatalUsageError("fp128 is not supported in SPIR-V");
1248 if (Ty->isBFloatTy()) {
1249 return getOpTypeFloat(Ty->getPrimitiveSizeInBits(), MIRBuilder,
1250 SPIRV::FPEncoding::BFloat16KHR);
1251 } else {
1252 return getOpTypeFloat(Ty->getPrimitiveSizeInBits(), MIRBuilder);
1253 }
1254 }
1255 if (Ty->isVoidTy())
1256 return getOpTypeVoid(MIRBuilder);
1257 if (Ty->isVectorTy()) {
1258 SPIRVTypeInst El =
1259 findSPIRVType(cast<FixedVectorType>(Ty)->getElementType(), MIRBuilder,
1260 AccQual, ExplicitLayoutRequired, EmitIR);
1261 unsigned NumElts = cast<FixedVectorType>(Ty)->getNumElements();
1262 const auto &STI = MIRBuilder.getMF().getSubtarget<SPIRVSubtarget>();
1263 if (isLongVectorEXT(Ty) &&
1264 STI.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector))
1265 return getOpTypeVectorIdEXT(NumElts, El, MIRBuilder);
1266 return getOpTypeVector(NumElts, El, MIRBuilder);
1267 }
1268 if (Ty->isArrayTy()) {
1269 SPIRVTypeInst El = findSPIRVType(Ty->getArrayElementType(), MIRBuilder,
1270 AccQual, ExplicitLayoutRequired, EmitIR);
1271 return getOpTypeArray(Ty->getArrayNumElements(), El, MIRBuilder,
1272 ExplicitLayoutRequired, EmitIR);
1273 }
1274 if (auto SType = dyn_cast<StructType>(Ty)) {
1275 if (SType->isOpaque())
1276 return getOpTypeOpaque(SType, MIRBuilder);
1277
1278 StructOffsetDecorator Decorator = nullptr;
1279 if (ExplicitLayoutRequired) {
1280 Decorator = [&MIRBuilder, SType, this](Register Reg) {
1281 addStructOffsetDecorations(Reg, const_cast<StructType *>(SType),
1282 MIRBuilder);
1283 };
1284 }
1285 return getOpTypeStruct(SType, MIRBuilder, AccQual, std::move(Decorator),
1286 EmitIR);
1287 }
1288 if (auto FType = dyn_cast<FunctionType>(Ty)) {
1289 SPIRVTypeInst RetTy =
1290 findSPIRVType(FType->getReturnType(), MIRBuilder, AccQual,
1291 ExplicitLayoutRequired, EmitIR);
1293 for (const auto &ParamTy : FType->params())
1294 ParamTypes.push_back(findSPIRVType(ParamTy, MIRBuilder, AccQual,
1295 ExplicitLayoutRequired, EmitIR));
1296 return getOpTypeFunction(FType, RetTy, ParamTypes, MIRBuilder);
1297 }
1298
1299 unsigned AddrSpace = typeToAddressSpace(Ty);
1300
1301 // Get access to information about available extensions
1302 const SPIRVSubtarget *ST =
1303 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
1304 auto SC = addressSpaceToStorageClass(AddrSpace, *ST);
1305
1306 SPIRVTypeInst SpvElementType = nullptr;
1307 Type *ElemTy = ::getPointeeType(Ty);
1308 if (ElemTy && isa<FunctionType>(ElemTy) &&
1309 !ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
1310 ElemTy = nullptr;
1311 if (ElemTy)
1312 SpvElementType = getOrCreateSPIRVType(ElemTy, MIRBuilder, AccQual, EmitIR);
1313 else
1314 SpvElementType = getOrCreateSPIRVIntegerType(8, MIRBuilder);
1315
1316 if (!ElemTy) {
1317 ElemTy = Type::getInt8Ty(MIRBuilder.getContext());
1318 }
1319
1320 // If we have forward pointer associated with this type, use its register
1321 // operand to create OpTypePointer.
1322 if (auto It = ForwardPointerTypes.find(Ty); It != ForwardPointerTypes.end()) {
1323 Register Reg = getSPIRVTypeID(It->second);
1324 // TODO: what does getOpTypePointer do?
1325 return getOpTypePointer(SC, SpvElementType, MIRBuilder, Reg);
1326 }
1327
1328 return getOrCreateSPIRVPointerType(ElemTy, MIRBuilder, SC);
1329}
1330
1331SPIRVTypeInst SPIRVGlobalRegistry::restOfCreateSPIRVType(
1332 const Type *Ty, MachineIRBuilder &MIRBuilder,
1333 SPIRV::AccessQualifier::AccessQualifier AccessQual,
1334 bool ExplicitLayoutRequired, bool EmitIR) {
1335 // TODO: Could this create a problem if one requires an explicit layout, and
1336 // the next time it does not?
1337 if (TypesInProcessing.count(Ty) && !isPointerTyOrWrapper(Ty))
1338 return nullptr;
1339 TypesInProcessing.insert(Ty);
1340 SPIRVTypeInst SpirvType = createSPIRVType(Ty, MIRBuilder, AccessQual,
1341 ExplicitLayoutRequired, EmitIR);
1342 TypesInProcessing.erase(Ty);
1343 VRegToTypeMap[&MIRBuilder.getMF()][getSPIRVTypeID(SpirvType)] = SpirvType;
1344
1345 // TODO: We could end up with two SPIR-V types pointing to the same llvm type.
1346 // Is that a problem?
1347 SPIRVToLLVMType[SpirvType] = unifyPtrType(Ty);
1348
1349 if (SpirvType->getOpcode() == SPIRV::OpTypeForwardPointer ||
1350 SpirvType->getOpcode() == SPIRV::OpTypeUntypedPointerKHR ||
1351 findMI(Ty, false, &MIRBuilder.getMF()) || isSpecialOpaqueType(Ty))
1352 return SpirvType;
1353
1354 if (auto *ExtTy = dyn_cast<TargetExtType>(Ty);
1355 ExtTy && isTypedPointerWrapper(ExtTy))
1356 add(ExtTy->getTypeParameter(0), ExtTy->getIntParameter(0), SpirvType);
1357 else if (!isPointerTy(Ty))
1358 add(Ty, ExplicitLayoutRequired, SpirvType);
1359 else if (isTypedPointerTy(Ty))
1360 add(cast<TypedPointerType>(Ty)->getElementType(),
1361 getPointerAddressSpace(Ty), SpirvType);
1362 else
1364 getPointerAddressSpace(Ty), SpirvType);
1365 return SpirvType;
1366}
1367
1370 const MachineFunction *MF) const {
1371 auto t = VRegToTypeMap.find(MF ? MF : CurMF);
1372 if (t != VRegToTypeMap.end()) {
1373 auto tt = t->second.find(VReg);
1374 if (tt != t->second.end())
1375 return tt->second;
1376 }
1377 return nullptr;
1378}
1379
1381 MachineFunction *MF) {
1382 if (!MF)
1383 MF = CurMF;
1384 MachineInstr *Instr = getVRegDef(MF->getRegInfo(), VReg);
1385 return getSPIRVTypeForVReg(Instr->getOperand(1).getReg(), MF);
1386}
1387
1389 const Type *Ty, MachineIRBuilder &MIRBuilder,
1390 SPIRV::AccessQualifier::AccessQualifier AccessQual,
1391 bool ExplicitLayoutRequired, bool EmitIR) {
1392 // SPIR-V doesn't support single-element vectors. Treat <1 x T> as T if the
1393 // SPV_EXT_long_vector extension is not available.
1394 const auto &STI = MIRBuilder.getMF().getSubtarget<SPIRVSubtarget>();
1395 if (auto *FVT = dyn_cast<FixedVectorType>(Ty);
1396 FVT && FVT->getNumElements() == 1 &&
1397 !STI.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector))
1398 return getOrCreateSPIRVType(FVT->getElementType(), MIRBuilder, AccessQual,
1399 ExplicitLayoutRequired, EmitIR);
1400 const MachineFunction *MF = &MIRBuilder.getMF();
1401 Register Reg;
1402 if (auto *ExtTy = dyn_cast<TargetExtType>(Ty);
1403 ExtTy && isTypedPointerWrapper(ExtTy))
1404 Reg = find(ExtTy->getTypeParameter(0), ExtTy->getIntParameter(0), MF);
1405 else if (!isPointerTy(Ty))
1406 Reg = find(Ty = adjustIntTypeByWidth(Ty), ExplicitLayoutRequired, MF);
1407 else if (isTypedPointerTy(Ty))
1408 Reg = find(cast<TypedPointerType>(Ty)->getElementType(),
1409 getPointerAddressSpace(Ty), MF);
1410 else
1411 Reg = find(Type::getInt8Ty(MIRBuilder.getMF().getFunction().getContext()),
1412 getPointerAddressSpace(Ty), MF);
1413 if (Reg.isValid() && !isSpecialOpaqueType(Ty))
1414 return getSPIRVTypeForVReg(Reg);
1415
1416 TypesInProcessing.clear();
1417 SPIRVTypeInst STy = restOfCreateSPIRVType(Ty, MIRBuilder, AccessQual,
1418 ExplicitLayoutRequired, EmitIR);
1419 // Create normal pointer types for the corresponding OpTypeForwardPointers.
1420 for (auto &CU : ForwardPointerTypes) {
1421 // Pointer type themselves do not require an explicit layout. The types
1422 // they pointer to might, but that is taken care of when creating the type.
1423 bool PtrNeedsLayout = false;
1424 const Type *Ty2 = CU.first;
1425 SPIRVTypeInst STy2 = CU.second;
1426 if ((Reg = find(Ty2, PtrNeedsLayout, MF)).isValid())
1427 STy2 = getSPIRVTypeForVReg(Reg);
1428 else
1429 STy2 = restOfCreateSPIRVType(Ty2, MIRBuilder, AccessQual, PtrNeedsLayout,
1430 EmitIR);
1431 if (Ty == Ty2)
1432 STy = STy2;
1433 }
1434 ForwardPointerTypes.clear();
1435 return STy;
1436}
1437
1439 unsigned TypeOpcode) const {
1441 assert(Type && "isScalarOfType VReg has no type assigned");
1442 return Type->getOpcode() == TypeOpcode;
1443}
1444
1446 unsigned TypeOpcode) const {
1448 assert(Type && "isScalarOrVectorOfType VReg has no type assigned");
1449 if (Type->getOpcode() == TypeOpcode)
1450 return true;
1451 if (!isVectorType(Type))
1452 return false;
1453 Register ScalarTypeVReg = Type->getOperand(1).getReg();
1454 SPIRVTypeInst ScalarType = getSPIRVTypeForVReg(ScalarTypeVReg);
1455 return ScalarType->getOpcode() == TypeOpcode;
1456}
1457
1459 switch (Type->getOpcode()) {
1460 case SPIRV::OpTypeImage:
1461 case SPIRV::OpTypeSampler:
1462 case SPIRV::OpTypeSampledImage:
1463 return true;
1464 case SPIRV::OpTypeStruct:
1465 return BlockDecoratedTypes.contains(Type);
1466 default:
1467 return false;
1468 }
1469 return false;
1470}
1471unsigned
1475
1476unsigned
1478 if (!Type)
1479 return 0;
1480 if (isVectorType(Type))
1481 return (Type->getOpcode() == SPIRV::OpTypeVector)
1482 ? static_cast<unsigned>(Type->getOperand(2).getImm())
1483 : foldImm(Type->getOperand(2), &CurMF->getRegInfo());
1484 return 1;
1485}
1486
1489 if (!Type)
1490 return nullptr;
1491 Register ScalarReg = (isVectorType(Type)) ? Type->getOperand(1).getReg()
1492 : Type->getOperand(0).getReg();
1493 SPIRVTypeInst ScalarType = getSPIRVTypeForVReg(ScalarReg);
1494 assert(isScalarOrVectorOfType(Type->getOperand(0).getReg(),
1495 ScalarType->getOpcode()));
1496 return ScalarType;
1497}
1498
1499unsigned
1501 assert(Type && "Invalid Type pointer");
1503 if (ScalarType->getOpcode() == SPIRV::OpTypeInt ||
1504 ScalarType->getOpcode() == SPIRV::OpTypeFloat)
1505 return ScalarType->getOperand(1).getImm();
1506 if (ScalarType->getOpcode() == SPIRV::OpTypeBool)
1507 return 1;
1508 if (ScalarType->getOpcode() == SPIRV::OpTypePointer)
1509 return getPointerSize(); // TODO: does not work for different per AS sizes.
1511 "Attempting to get bit width of non-integer/float/pointer type.");
1512}
1513
1515 SPIRVTypeInst Type) const {
1516 assert(Type && "Invalid Type pointer");
1517 unsigned NumElements = getScalarOrVectorComponentCount(Type);
1519 return ScalarType->getOpcode() == SPIRV::OpTypeInt ||
1520 ScalarType->getOpcode() == SPIRV::OpTypeFloat
1521 ? NumElements * ScalarType->getOperand(1).getImm()
1522 : 0;
1523}
1524
1526 // A function pointer has to keep its function type, which an untyped pointer
1527 // cannot express.
1528 if (ElemType && ElemType->getOpcode() == SPIRV::OpTypeFunction)
1529 return true;
1530 auto It = SPIRVToLLVMType.find(ElemType);
1531 return It != SPIRVToLLVMType.end() && It->second &&
1532 isSpecialOpaqueType(It->second);
1533}
1534
1536 SPIRVTypeInst ElemType, const SPIRVSubtarget &ST) const {
1537 // Shaders keep typed pointers, as this implementation targets compute.
1538 return ST.canUseExtension(SPIRV::Extension::SPV_KHR_untyped_pointers) &&
1539 !ST.isShader() && !shouldKeepTypedPtrType(ElemType);
1540}
1541
1545 return ScalarType && ScalarType->getOpcode() == SPIRV::OpTypeInt ? ScalarType
1546 : nullptr;
1547}
1548
1551 return IntType && IntType->getOperand(2).getImm() != 0;
1552}
1553
1555 return PtrType && PtrType->getOpcode() == SPIRV::OpTypePointer
1556 ? getSPIRVTypeForVReg(PtrType->getOperand(2).getReg())
1557 : nullptr;
1558}
1559
1561 SPIRVTypeInst Type2) const {
1562 if (!Type1 || !Type2)
1563 return false;
1564 // Ignore difference between <1.5 and >=1.5 protocol versions:
1565 // it's valid if either Result Type or Operand is a pointer, and the other
1566 // is a pointer, an integer scalar, or an integer vector.
1567 if (Type1.isPointer() &&
1568 (Type2.isPointer() || retrieveScalarOrVectorIntType(Type2)))
1569 return true;
1570 if (Type2.isPointer() &&
1571 (Type1.isPointer() || retrieveScalarOrVectorIntType(Type1)))
1572 return true;
1573 unsigned Bits1 = getNumScalarOrVectorTotalBitWidth(Type1),
1574 Bits2 = getNumScalarOrVectorTotalBitWidth(Type2);
1575 return Bits1 > 0 && Bits1 == Bits2;
1576}
1577
1578SPIRV::StorageClass::StorageClass
1581 assert(Type && Type.isPointer() && Type->getOperand(1).isImm() &&
1582 "Pointer type is expected");
1584}
1585
1586SPIRV::StorageClass::StorageClass
1588 return static_cast<SPIRV::StorageClass::StorageClass>(
1589 Type->getOperand(1).getImm());
1590}
1591
1593 MachineIRBuilder &MIRBuilder, Type *ElemType,
1594 SPIRV::StorageClass::StorageClass SC, bool IsWritable, bool EmitIr) {
1595 auto Key = SPIRV::irhandle_vkbuffer(ElemType, SC, IsWritable);
1596 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1597 return MI;
1598
1599 bool ExplicitLayoutRequired = storageClassRequiresExplictLayout(SC);
1600 // We need to get the SPIR-V type for the element here, so we can add the
1601 // decoration to it.
1602 auto *T = StructType::create(ElemType);
1603 SPIRVTypeInst BlockType =
1604 getOrCreateSPIRVType(T, MIRBuilder, SPIRV::AccessQualifier::None,
1605 ExplicitLayoutRequired, EmitIr);
1606
1607 buildOpDecorate(BlockType->defs().begin()->getReg(), MIRBuilder,
1608 SPIRV::Decoration::Block, {});
1609 BlockDecoratedTypes.insert(BlockType);
1610
1611 if (!IsWritable) {
1612 buildOpMemberDecorate(BlockType->defs().begin()->getReg(), MIRBuilder,
1613 SPIRV::Decoration::NonWritable, 0, {});
1614 }
1615
1616 SPIRVTypeInst R =
1617 getOrCreateSPIRVPointerTypeInternal(BlockType, MIRBuilder, SC);
1618 add(Key, R);
1619 return R;
1620}
1621
1625 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1626 return MI;
1627 auto *T = Type::getInt8Ty(MIRBuilder.getContext());
1628 SPIRVTypeInst R = getOrCreateSPIRVIntegerType(8, MIRBuilder);
1629 finishCreatingSPIRVType(T, R);
1630 add(Key, R);
1631 return R;
1632}
1633
1635 MachineIRBuilder &MIRBuilder, Type *T) {
1636 const auto SC = SPIRV::StorageClass::PushConstant;
1637
1638 auto Key = SPIRV::irhandle_vkbuffer(T, SC, /* IsWritable= */ false);
1639 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1640 return MI;
1641
1642 // We need to get the SPIR-V type for the element here, so we can add the
1643 // decoration to it.
1645 T, MIRBuilder, SPIRV::AccessQualifier::None,
1646 /* ExplicitLayoutRequired= */ true, /* EmitIr= */ false);
1647
1648 buildOpDecorate(BlockType->defs().begin()->getReg(), MIRBuilder,
1649 SPIRV::Decoration::Block, {});
1650 BlockDecoratedTypes.insert(BlockType);
1651 SPIRVTypeInst R = BlockType;
1652 add(Key, R);
1653 return R;
1654}
1655
1657 MachineIRBuilder &MIRBuilder, const TargetExtType *T, bool EmitIr) {
1658 auto Key = SPIRV::handle(T);
1659 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1660 return MI;
1661
1662 StructType *ST = cast<StructType>(T->getTypeParameter(0));
1663 ArrayRef<uint32_t> Offsets = T->int_params().slice(1);
1664 assert(ST->getNumElements() == Offsets.size());
1665
1666 StructOffsetDecorator Decorator = [&MIRBuilder, &Offsets](Register Reg) {
1667 for (uint32_t I = 0; I < Offsets.size(); ++I) {
1668 buildOpMemberDecorate(Reg, MIRBuilder, SPIRV::Decoration::Offset, I,
1669 {Offsets[I]});
1670 }
1671 };
1672
1673 // We need a new OpTypeStruct instruction because decorations will be
1674 // different from a struct with an explicit layout created from a different
1675 // entry point.
1676 SPIRVTypeInst SPIRVStructType =
1677 getOpTypeStruct(ST, MIRBuilder, SPIRV::AccessQualifier::None,
1678 std::move(Decorator), EmitIr);
1679 add(Key, SPIRVStructType);
1680 return SPIRVStructType;
1681}
1682
1684 const TargetExtType *ExtensionType,
1685 const SPIRV::AccessQualifier::AccessQualifier Qualifier,
1686 MachineIRBuilder &MIRBuilder) {
1687 assert(ExtensionType->getNumTypeParameters() == 1 &&
1688 "SPIR-V image builtin type must have sampled type parameter!");
1689 const SPIRVTypeInst SampledType =
1690 getOrCreateSPIRVType(ExtensionType->getTypeParameter(0), MIRBuilder,
1691 SPIRV::AccessQualifier::ReadWrite, true);
1692 assert((ExtensionType->getNumIntParameters() == 7 ||
1693 ExtensionType->getNumIntParameters() == 6) &&
1694 "Invalid number of parameters for SPIR-V image builtin!");
1695
1696 SPIRV::AccessQualifier::AccessQualifier accessQualifier =
1697 SPIRV::AccessQualifier::None;
1698 if (ExtensionType->getNumIntParameters() == 7) {
1699 accessQualifier = Qualifier == SPIRV::AccessQualifier::WriteOnly
1700 ? SPIRV::AccessQualifier::WriteOnly
1701 : SPIRV::AccessQualifier::AccessQualifier(
1702 ExtensionType->getIntParameter(6));
1703 }
1704
1705 // Create or get an existing type from GlobalRegistry.
1706 SPIRVTypeInst R = getOrCreateOpTypeImage(
1707 MIRBuilder, SampledType,
1708 SPIRV::Dim::Dim(ExtensionType->getIntParameter(0)),
1709 ExtensionType->getIntParameter(1), ExtensionType->getIntParameter(2),
1710 ExtensionType->getIntParameter(3), ExtensionType->getIntParameter(4),
1711 SPIRV::ImageFormat::ImageFormat(ExtensionType->getIntParameter(5)),
1712 accessQualifier);
1713 SPIRVToLLVMType[R] = ExtensionType;
1714 return R;
1715}
1716
1717SPIRVTypeInst SPIRVGlobalRegistry::getOrCreateOpTypeImage(
1718 MachineIRBuilder &MIRBuilder, SPIRVTypeInst SampledType,
1719 SPIRV::Dim::Dim Dim, uint32_t Depth, uint32_t Arrayed,
1720 uint32_t Multisampled, uint32_t Sampled,
1721 SPIRV::ImageFormat::ImageFormat ImageFormat,
1722 SPIRV::AccessQualifier::AccessQualifier AccessQual) {
1723 auto Key = SPIRV::irhandle_image(SPIRVToLLVMType.lookup(SampledType), Dim,
1724 Depth, Arrayed, Multisampled, Sampled,
1725 ImageFormat, AccessQual);
1726 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1727 return MI;
1728 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1729 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1730 auto MIB =
1731 MIRBuilder.buildInstr(SPIRV::OpTypeImage)
1732 .addDef(createTypeVReg(MIRBuilder))
1733 .addUse(getSPIRVTypeID(SampledType))
1734 .addImm(Dim)
1735 .addImm(Depth) // Depth (whether or not it is a Depth image).
1736 .addImm(Arrayed) // Arrayed.
1737 .addImm(Multisampled) // Multisampled (0 = only single-sample).
1738 .addImm(Sampled) // Sampled (0 = usage known at runtime).
1739 .addImm(ImageFormat);
1740 if (AccessQual != SPIRV::AccessQualifier::None)
1741 MIB.addImm(AccessQual);
1742 return MIB;
1743 });
1744 add(Key, NewMI);
1745 return NewMI;
1746}
1747
1751 const MachineFunction *MF = &MIRBuilder.getMF();
1752 if (const MachineInstr *MI = findMI(Key, MF))
1753 return MI;
1754 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1755 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1756 return MIRBuilder.buildInstr(SPIRV::OpTypeSampler)
1757 .addDef(createTypeVReg(MIRBuilder));
1758 });
1759 add(Key, NewMI);
1760 return NewMI;
1761}
1762
1764 MachineIRBuilder &MIRBuilder,
1765 SPIRV::AccessQualifier::AccessQualifier AccessQual) {
1766 auto Key = SPIRV::irhandle_pipe(AccessQual);
1767 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1768 return MI;
1769 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1770 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1771 return MIRBuilder.buildInstr(SPIRV::OpTypePipe)
1772 .addDef(createTypeVReg(MIRBuilder))
1773 .addImm(AccessQual);
1774 });
1775 add(Key, NewMI);
1776 return NewMI;
1777}
1778
1780 MachineIRBuilder &MIRBuilder) {
1781 auto Key = SPIRV::irhandle_event();
1782 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1783 return MI;
1784 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1785 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1786 return MIRBuilder.buildInstr(SPIRV::OpTypeDeviceEvent)
1787 .addDef(createTypeVReg(MIRBuilder));
1788 });
1789 add(Key, NewMI);
1790 return NewMI;
1791}
1792
1794 SPIRVTypeInst ImageType, MachineIRBuilder &MIRBuilder) {
1796 SPIRVToLLVMType.lookup(MIRBuilder.getMF().getRegInfo().getVRegDef(
1797 ImageType->getOperand(1).getReg())),
1798 ImageType);
1799 if (const MachineInstr *MI = findMI(Key, &MIRBuilder.getMF()))
1800 return MI;
1801 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1802 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1803 return MIRBuilder.buildInstr(SPIRV::OpTypeSampledImage)
1804 .addDef(createTypeVReg(MIRBuilder))
1805 .addUse(getSPIRVTypeID(ImageType));
1806 });
1807 add(Key, NewMI);
1808 return NewMI;
1809}
1810
1812 MachineIRBuilder &MIRBuilder, const TargetExtType *ExtensionType,
1813 SPIRVTypeInst ElemType, uint32_t Scope, uint32_t Rows, uint32_t Columns,
1814 uint32_t Use, bool EmitIR) {
1815 if (const MachineInstr *MI =
1816 findMI(ExtensionType, false, &MIRBuilder.getMF()))
1817 return MI;
1818 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1819 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1820 SPIRVTypeInst SpvTypeInt32 =
1821 getOrCreateSPIRVIntegerType(32, MIRBuilder);
1822 const Type *ET = getTypeForSPIRVType(ElemType);
1823 if (ET->isIntegerTy() && ET->getIntegerBitWidth() == 4 &&
1825 .canUseExtension(SPIRV::Extension::SPV_INTEL_int4)) {
1826 MIRBuilder.buildInstr(SPIRV::OpCapability)
1827 .addImm(SPIRV::Capability::Int4CooperativeMatrixINTEL);
1828 }
1829 return MIRBuilder.buildInstr(SPIRV::OpTypeCooperativeMatrixKHR)
1830 .addDef(createTypeVReg(MIRBuilder))
1831 .addUse(getSPIRVTypeID(ElemType))
1832 .addUse(buildConstantInt(Scope, MIRBuilder, SpvTypeInt32, EmitIR))
1833 .addUse(buildConstantInt(Rows, MIRBuilder, SpvTypeInt32, EmitIR))
1834 .addUse(buildConstantInt(Columns, MIRBuilder, SpvTypeInt32, EmitIR))
1835 .addUse(buildConstantInt(Use, MIRBuilder, SpvTypeInt32, EmitIR));
1836 });
1837 add(ExtensionType, false, NewMI);
1838 return NewMI;
1839}
1840
1842 const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode) {
1843 if (const MachineInstr *MI = findMI(Ty, false, &MIRBuilder.getMF()))
1844 return MI;
1845 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1846 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1847 return MIRBuilder.buildInstr(Opcode).addDef(createTypeVReg(MIRBuilder));
1848 });
1849 add(Ty, false, NewMI);
1850 return NewMI;
1851}
1852
1854 const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode,
1856 if (const MachineInstr *MI = findMI(Ty, false, &MIRBuilder.getMF()))
1857 return MI;
1858 Register ResVReg = createTypeVReg(MIRBuilder);
1859 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1860 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1861 MachineInstrBuilder MIB = MIRBuilder.buildInstr(SPIRV::UNKNOWN_type)
1862 .addDef(ResVReg)
1863 .addImm(Opcode);
1864 for (MCOperand Operand : Operands) {
1865 if (Operand.isReg()) {
1866 MIB.addUse(Operand.getReg());
1867 } else if (Operand.isImm()) {
1868 MIB.addImm(Operand.getImm());
1869 }
1870 }
1871 return MIB;
1872 });
1873 add(Ty, false, NewMI);
1874 return NewMI;
1875}
1876
1877// Returns nullptr if unable to recognize SPIRV type name
1879 StringRef TypeStr, MachineIRBuilder &MIRBuilder, bool EmitIR,
1880 SPIRV::StorageClass::StorageClass SC,
1881 SPIRV::AccessQualifier::AccessQualifier AQ) {
1882 unsigned VecElts = 0;
1883 auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
1884
1885 // Parse strings representing either a SPIR-V or OpenCL builtin type.
1886 if (hasBuiltinTypePrefix(TypeStr))
1888 TypeStr.str(), MIRBuilder.getContext()),
1889 MIRBuilder, AQ, false, true);
1890
1891 // Parse type name in either "typeN" or "type vector[N]" format, where
1892 // N is the number of elements of the vector.
1893 Type *Ty;
1894
1895 Ty = parseBasicTypeName(TypeStr, Ctx);
1896 if (!Ty)
1897 // Unable to recognize SPIRV type name
1898 return nullptr;
1899
1900 SPIRVTypeInst SpirvTy = getOrCreateSPIRVType(Ty, MIRBuilder, AQ, false, true);
1901
1902 // Handle "type*" or "type* vector[N]".
1903 if (TypeStr.consume_front("*"))
1904 SpirvTy = getOrCreateSPIRVPointerType(Ty, MIRBuilder, SC);
1905
1906 // Handle "typeN*" or "type vector[N]*".
1907 bool IsPtrToVec = TypeStr.consume_back("*");
1908
1909 if (TypeStr.consume_front(" vector[")) {
1910 TypeStr = TypeStr.substr(0, TypeStr.find(']'));
1911 }
1912 TypeStr.getAsInteger(10, VecElts);
1913 if (VecElts > 0)
1914 SpirvTy = getOrCreateSPIRVVectorType(SpirvTy, VecElts, MIRBuilder, EmitIR);
1915
1916 if (IsPtrToVec)
1917 SpirvTy = getOrCreateSPIRVPointerType(SpirvTy, MIRBuilder, SC);
1918
1919 return SpirvTy;
1920}
1921
1924 MachineIRBuilder &MIRBuilder) {
1925 return getOrCreateSPIRVType(
1927 MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false, true);
1928}
1929
1931SPIRVGlobalRegistry::finishCreatingSPIRVType(const Type *LLVMTy,
1932 SPIRVTypeInst SpirvType) {
1933 assert(CurMF == SpirvType->getMF());
1934 VRegToTypeMap[CurMF][getSPIRVTypeID(SpirvType)] = SpirvType;
1935 SPIRVToLLVMType[SpirvType] = unifyPtrType(LLVMTy);
1936 return SpirvType;
1937}
1938
1941 const SPIRVInstrInfo &TII,
1942 unsigned SPIRVOPcode, Type *Ty) {
1943 if (const MachineInstr *MI = findMI(Ty, false, CurMF))
1944 return MI;
1945 MachineBasicBlock &DepMBB = I.getMF()->front();
1946 MachineIRBuilder MIRBuilder(DepMBB, DepMBB.getFirstNonPHI());
1947 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
1948 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
1949 auto NewTypeMI = BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
1950 MIRBuilder.getDL(), TII.get(SPIRVOPcode))
1951 .addDef(createTypeVReg(CurMF->getRegInfo()))
1952 .addImm(BitWidth);
1953 // Don't add Encoding to FP type
1954 if (!Ty->isFloatTy()) {
1955 return NewTypeMI.addImm(0);
1956 } else {
1957 return NewTypeMI;
1958 }
1959 });
1960 add(Ty, false, NewMI);
1961 return finishCreatingSPIRVType(Ty, NewMI);
1962}
1963
1965 unsigned BitWidth, MachineInstr &I, const SPIRVInstrInfo &TII) {
1966 // Maybe adjust bit width to keep DuplicateTracker consistent. Without
1967 // such an adjustment SPIRVGlobalRegistry::getOpTypeInt() could create, for
1968 // example, the same "OpTypeInt 8" type for a series of LLVM integer types
1969 // with number of bits less than 8, causing duplicate type definitions.
1970 if (BitWidth > 1)
1971 BitWidth = adjustOpTypeIntWidth(BitWidth);
1972 Type *LLVMTy = IntegerType::get(CurMF->getFunction().getContext(), BitWidth);
1973 return getOrCreateSPIRVType(BitWidth, I, TII, SPIRV::OpTypeInt, LLVMTy);
1974}
1975
1977 unsigned BitWidth, MachineInstr &I, const SPIRVInstrInfo &TII) {
1978 LLVMContext &Ctx = CurMF->getFunction().getContext();
1979 Type *LLVMTy;
1980 switch (BitWidth) {
1981 case 16:
1982 LLVMTy = Type::getHalfTy(Ctx);
1983 break;
1984 case 32:
1985 LLVMTy = Type::getFloatTy(Ctx);
1986 break;
1987 case 64:
1988 LLVMTy = Type::getDoubleTy(Ctx);
1989 break;
1990 default:
1991 llvm_unreachable("Bit width is of unexpected size.");
1992 }
1993 return getOrCreateSPIRVType(BitWidth, I, TII, SPIRV::OpTypeFloat, LLVMTy);
1994}
1995
1998 bool EmitIR) {
1999 return getOrCreateSPIRVType(
2000 IntegerType::get(MIRBuilder.getMF().getFunction().getContext(), 1),
2001 MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false, EmitIR);
2002}
2003
2006 const SPIRVInstrInfo &TII) {
2007 Type *Ty = IntegerType::get(CurMF->getFunction().getContext(), 1);
2008 if (const MachineInstr *MI = findMI(Ty, false, CurMF))
2009 return MI;
2010 MachineBasicBlock &DepMBB = I.getMF()->front();
2011 MachineIRBuilder MIRBuilder(DepMBB, DepMBB.getFirstNonPHI());
2012 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2013 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2014 return BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
2015 MIRBuilder.getDL(), TII.get(SPIRV::OpTypeBool))
2016 .addDef(createTypeVReg(CurMF->getRegInfo()));
2017 });
2018 add(Ty, false, NewMI);
2019 return finishCreatingSPIRVType(Ty, NewMI);
2020}
2021
2023 SPIRVTypeInst BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder,
2024 bool EmitIR) {
2025 return getOrCreateSPIRVType(
2027 NumElements),
2028 MIRBuilder, SPIRV::AccessQualifier::ReadWrite, false, EmitIR);
2029}
2030
2032 SPIRVTypeInst BaseType, unsigned NumElements, MachineInstr &I,
2033 const SPIRVInstrInfo &TII) {
2034 const auto &STI = I.getMF()->getSubtarget<SPIRVSubtarget>();
2035 if (!STI.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector))
2036 // At this point of time all 1-element vectors are resolved. Add assertion
2037 // to fire if anything changes.
2038 assert(NumElements >= 2 &&
2039 "SPIR-V vectors must have at least 2 components");
2041 const_cast<Type *>(getTypeForSPIRVType(BaseType)), NumElements);
2042 if (const MachineInstr *MI = findMI(Ty, false, CurMF))
2043 return MI;
2044 MachineInstr *DepMI =
2045 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(BaseType));
2046 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
2047 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2048 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2049 // TODO: consider adding non-const accessors to SPIRVTypeInst, which
2050 // would remove the need for the gash casting here.
2051 return const_cast<MachineInstr *>(
2052 static_cast<const MachineInstr *>(getOpTypeVectorImpl(
2053 NumElements, BaseType, MIRBuilder, isLongVectorEXT(Ty))));
2054 });
2055 add(Ty, false, NewMI);
2056 return finishCreatingSPIRVType(Ty, NewMI);
2057}
2058
2060 const Type *BaseType, MachineInstr &I, SPIRV::StorageClass::StorageClass SC,
2061 bool ForceTyped) {
2062 MachineIRBuilder MIRBuilder(I);
2063 return getOrCreateSPIRVPointerType(BaseType, MIRBuilder, SC, ForceTyped);
2064}
2065
2067 const Type *BaseType, MachineIRBuilder &MIRBuilder,
2068 SPIRV::StorageClass::StorageClass SC, bool ForceTyped) {
2069 if (BaseType->isFunctionTy() &&
2070 !cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget())
2071 .canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)) {
2072 const Function &F = MIRBuilder.getMF().getFunction();
2073 F.getContext().diagnose(
2075 "Function used as a data pointer requires "
2076 "SPV_INTEL_function_pointers extension",
2077 DebugLoc(), DS_Error));
2078 }
2079 // TODO: Need to check if EmitIr should always be true.
2080 SPIRVTypeInst SpirvBaseType = getOrCreateSPIRVType(
2081 BaseType, MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
2083 assert(SpirvBaseType);
2084 return getOrCreateSPIRVPointerTypeInternal(SpirvBaseType, MIRBuilder, SC,
2085 ForceTyped);
2086}
2087
2089 SPIRVTypeInst PtrType, SPIRV::StorageClass::StorageClass SC,
2090 MachineInstr &I) {
2091 [[maybe_unused]] SPIRV::StorageClass::StorageClass OldSC =
2092 getPointerStorageClass(PtrType);
2095
2096 SPIRVTypeInst PointeeType = getPointeeType(PtrType);
2097 MachineIRBuilder MIRBuilder(I);
2098 return getOrCreateSPIRVPointerTypeInternal(PointeeType, MIRBuilder, SC);
2099}
2100
2103 SPIRV::StorageClass::StorageClass SC) {
2104 const Type *LLVMType = getTypeForSPIRVType(BaseType);
2106 SPIRVTypeInst R = getOrCreateSPIRVPointerType(LLVMType, MIRBuilder, SC);
2107 assert(
2108 (R->getOpcode() == SPIRV::OpTypeUntypedPointerKHR ||
2109 getPointeeType(R) == BaseType) &&
2110 "The base type was not correctly laid out for the given storage class.");
2111 return R;
2112}
2113
2114SPIRVTypeInst SPIRVGlobalRegistry::getOrCreateSPIRVPointerTypeInternal(
2116 SPIRV::StorageClass::StorageClass SC, bool ForceTyped) {
2117 // Check if we should use untyped pointers.
2118 const SPIRVSubtarget &ST =
2119 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
2120 if (!ForceTyped && shouldUseUntypedPointer(BaseType, ST))
2121 return getOrCreateSPIRVUntypedPointerType(SC, MIRBuilder);
2122
2123 const Type *PointerElementType = getTypeForSPIRVType(BaseType);
2125 if (const MachineInstr *MI = findMI(PointerElementType, AddressSpace, CurMF))
2126 return MI;
2127 Type *Ty = TypedPointerType::get(const_cast<Type *>(PointerElementType),
2128 AddressSpace);
2129 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2130 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2131 return BuildMI(MIRBuilder.getMBB(), MIRBuilder.getInsertPt(),
2132 MIRBuilder.getDebugLoc(),
2133 MIRBuilder.getTII().get(SPIRV::OpTypePointer))
2135 .addImm(static_cast<uint32_t>(SC))
2137 });
2138 add(PointerElementType, AddressSpace, NewMI);
2139 return finishCreatingSPIRVType(Ty, NewMI);
2140}
2141
2143 SPIRV::StorageClass::StorageClass SC, MachineIRBuilder &MIRBuilder) {
2144 [[maybe_unused]] const SPIRVSubtarget &ST =
2145 cast<SPIRVSubtarget>(MIRBuilder.getMF().getSubtarget());
2146 assert(ST.canUseExtension(SPIRV::Extension::SPV_KHR_untyped_pointers) &&
2147 !ST.isShader() && "Untyped pointers are not available");
2149 // Use STK_UntypedPointer handle keyed by address space only.
2151 if (const MachineInstr *MI = findMI(Handle, CurMF))
2152 return MI;
2153
2154 Type *Ty = PointerType::get(MIRBuilder.getMF().getFunction().getContext(),
2155 AddressSpace);
2156 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2157 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2158 return BuildMI(MIRBuilder.getMBB(), MIRBuilder.getInsertPt(),
2159 MIRBuilder.getDebugLoc(),
2160 MIRBuilder.getTII().get(SPIRV::OpTypeUntypedPointerKHR))
2161 .addDef(createTypeVReg(CurMF->getRegInfo()))
2162 .addImm(static_cast<uint32_t>(SC));
2163 });
2164 add(Handle, NewMI);
2165 return finishCreatingSPIRVType(Ty, NewMI);
2166}
2167
2169 SPIRVTypeInst SpvType,
2170 const SPIRVInstrInfo &TII) {
2171 UndefValue *UV =
2172 UndefValue::get(const_cast<Type *>(getTypeForSPIRVType(SpvType)));
2173 Register Res = find(UV, CurMF);
2174 if (Res.isValid())
2175 return Res;
2176
2177 LLT LLTy = LLT::scalar(64);
2178 Res = CurMF->getRegInfo().createGenericVirtualRegister(LLTy);
2179 CurMF->getRegInfo().setRegClass(Res, &SPIRV::iIDRegClass);
2180 assignSPIRVTypeToVReg(SpvType, Res, *CurMF);
2181
2182 MachineInstr *DepMI =
2183 const_cast<MachineInstr *>(static_cast<const MachineInstr *>(SpvType));
2184 MachineIRBuilder MIRBuilder(*DepMI->getParent(), DepMI->getIterator());
2185 const MachineInstr *NewMI = createConstOrTypeAtFunctionEntry(
2186 MIRBuilder, [&](MachineIRBuilder &MIRBuilder) {
2187 auto MIB = BuildMI(MIRBuilder.getMBB(), *MIRBuilder.getInsertPt(),
2188 MIRBuilder.getDL(), TII.get(SPIRV::OpUndef))
2189 .addDef(Res)
2190 .addUse(getSPIRVTypeID(SpvType));
2191 constrainSelectedInstRegOperands(MIB);
2192 return MIB;
2193 });
2194 add(UV, NewMI);
2195 return Res;
2196}
2197
2198const TargetRegisterClass *
2200 unsigned Opcode = SpvType->getOpcode();
2201 switch (Opcode) {
2202 case SPIRV::OpTypeFloat:
2203 return &SPIRV::fIDRegClass;
2204 case SPIRV::OpTypePointer:
2205 return &SPIRV::pIDRegClass;
2206 case SPIRV::OpTypeVector:
2207 case SPIRV::OpTypeVectorIdEXT: {
2209 unsigned ElemOpcode = ElemType ? ElemType->getOpcode() : 0;
2210 if (ElemOpcode == SPIRV::OpTypeFloat)
2211 return &SPIRV::vfIDRegClass;
2212 if (ElemOpcode == SPIRV::OpTypePointer)
2213 return &SPIRV::vpIDRegClass;
2214 return &SPIRV::viIDRegClass;
2215 }
2216 }
2217 return &SPIRV::iIDRegClass;
2218}
2219
2220inline unsigned getAS(SPIRVTypeInst SpvType) {
2222 static_cast<SPIRV::StorageClass::StorageClass>(
2223 SpvType->getOperand(1).getImm()));
2224}
2225
2227 unsigned Opcode = SpvType ? SpvType->getOpcode() : 0;
2228 switch (Opcode) {
2229 case SPIRV::OpTypeInt:
2230 case SPIRV::OpTypeFloat:
2231 case SPIRV::OpTypeBool:
2232 return LLT::scalar(getScalarOrVectorBitWidth(SpvType));
2233 case SPIRV::OpTypePointer:
2234 case SPIRV::OpTypeUntypedPointerKHR:
2235 return LLT::pointer(getAS(SpvType), getPointerSize());
2236 case SPIRV::OpTypeVector:
2237 case SPIRV::OpTypeVectorIdEXT: {
2239 LLT ET;
2240 switch (ElemType ? ElemType->getOpcode() : 0) {
2241 case SPIRV::OpTypePointer:
2242 case SPIRV::OpTypeUntypedPointerKHR:
2243 ET = LLT::pointer(getAS(ElemType), getPointerSize());
2244 break;
2245 case SPIRV::OpTypeInt:
2246 case SPIRV::OpTypeFloat:
2247 case SPIRV::OpTypeBool:
2248 ET = LLT::scalar(getScalarOrVectorBitWidth(ElemType));
2249 break;
2250 default:
2251 ET = LLT::scalar(64);
2252 }
2254 return LLT::scalarOrVector(EC, ET);
2255 }
2256 }
2257 return LLT::scalar(64);
2258}
2259
2260// Aliasing list MD contains several scope MD nodes whithin it. Each scope MD
2261// has a selfreference and an extra MD node for aliasing domain and also it
2262// can contain an optional string operand. Domain MD contains a self-reference
2263// with an optional string operand. Here we unfold the list, creating SPIR-V
2264// aliasing instructions.
2265// TODO: add support for an optional string operand.
2267 MachineIRBuilder &MIRBuilder, const MDNode *AliasingListMD) {
2268 if (AliasingListMD->getNumOperands() == 0)
2269 return nullptr;
2270 const MachineFunction *MF = &MIRBuilder.getMF();
2271 if (auto L = AliasInstMDMap.find({MF, AliasingListMD});
2272 L != AliasInstMDMap.end())
2273 return L->second;
2274
2276 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
2277 for (const MDOperand &MDListOp : AliasingListMD->operands()) {
2278 if (MDNode *ScopeMD = dyn_cast<MDNode>(MDListOp)) {
2279 if (ScopeMD->getNumOperands() < 2)
2280 return nullptr;
2281 MDNode *DomainMD = dyn_cast<MDNode>(ScopeMD->getOperand(1));
2282 if (!DomainMD)
2283 return nullptr;
2284 auto *Domain = [&] {
2285 auto D = AliasInstMDMap.find({MF, DomainMD});
2286 if (D != AliasInstMDMap.end())
2287 return D->second;
2288 const Register Ret = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2289 auto MIB =
2290 MIRBuilder.buildInstr(SPIRV::OpAliasDomainDeclINTEL).addDef(Ret);
2291 return MIB.getInstr();
2292 }();
2293 AliasInstMDMap.insert(
2294 std::make_pair(std::make_pair(MF, DomainMD), Domain));
2295 auto *Scope = [&] {
2296 auto S = AliasInstMDMap.find({MF, ScopeMD});
2297 if (S != AliasInstMDMap.end())
2298 return S->second;
2299 const Register Ret = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2300 auto MIB = MIRBuilder.buildInstr(SPIRV::OpAliasScopeDeclINTEL)
2301 .addDef(Ret)
2302 .addUse(Domain->getOperand(0).getReg());
2303 return MIB.getInstr();
2304 }();
2305 AliasInstMDMap.insert(std::make_pair(std::make_pair(MF, ScopeMD), Scope));
2306 ScopeList.push_back(Scope);
2307 }
2308 }
2309
2310 const Register Ret = MRI->createVirtualRegister(&SPIRV::IDRegClass);
2311 auto MIB =
2312 MIRBuilder.buildInstr(SPIRV::OpAliasScopeListDeclINTEL).addDef(Ret);
2313 for (auto *Scope : ScopeList)
2314 MIB.addUse(Scope->getOperand(0).getReg());
2315 auto List = MIB.getInstr();
2316 AliasInstMDMap.insert(
2317 std::make_pair(std::make_pair(MF, AliasingListMD), List));
2318 return List;
2319}
2320
2322 Register Reg, MachineIRBuilder &MIRBuilder, uint32_t Dec,
2323 const MDNode *AliasingListMD) {
2324 MachineInstr *AliasList =
2325 getOrAddMemAliasingINTELInst(MIRBuilder, AliasingListMD);
2326 if (!AliasList)
2327 return;
2328 MIRBuilder.buildInstr(SPIRV::OpDecorateId)
2329 .addUse(Reg)
2330 .addImm(Dec)
2331 .addUse(AliasList->getOperand(0).getReg());
2332}
2334 bool DeleteOld) {
2335 Old->replaceAllUsesWith(New);
2336 updateIfExistDeducedElementType(Old, New, DeleteOld);
2337 updateIfExistAssignPtrTypeInstr(Old, New, DeleteOld);
2338}
2339
2341 bool CanUseAnyVectorRank) {
2342 Value *OfType = getNormalizedPoisonValue(Ty, CanUseAnyVectorRank);
2343 CallInst *AssignCI = nullptr;
2344 if (Arg->getType()->isAggregateType() && Ty->isAggregateType() &&
2345 allowEmitFakeUse(Arg)) {
2346 LLVMContext &Ctx = Arg->getContext();
2349 MDString::get(Ctx, Arg->getName())};
2350 B.CreateIntrinsic(Intrinsic::spv_value_md,
2351 {MetadataAsValue::get(Ctx, MDTuple::get(Ctx, ArgMDs))});
2352 AssignCI = B.CreateIntrinsicWithoutFolding(Intrinsic::fake_use, {Arg});
2353 } else {
2354 AssignCI = buildIntrWithMD(Intrinsic::spv_assign_type, {Arg->getType()},
2355 OfType, Arg, {}, B);
2356 }
2357 addAssignPtrTypeInstr(Arg, AssignCI);
2358}
2359
2361 Value *Arg) {
2362 Value *OfType = PoisonValue::get(ElemTy);
2363 CallInst *AssignPtrTyCI = findAssignPtrTypeInstr(Arg);
2364 Function *CurrF =
2365 B.GetInsertBlock() ? B.GetInsertBlock()->getParent() : nullptr;
2366 if (AssignPtrTyCI == nullptr ||
2367 AssignPtrTyCI->getParent()->getParent() != CurrF) {
2368 AssignPtrTyCI = buildIntrWithMD(
2369 Intrinsic::spv_assign_ptr_type, {Arg->getType()}, OfType, Arg,
2370 {B.getInt32(getPointerAddressSpace(Arg->getType()))}, B);
2371 addDeducedElementType(AssignPtrTyCI, ElemTy);
2373 addAssignPtrTypeInstr(Arg, AssignPtrTyCI);
2374 } else {
2375 updateAssignType(AssignPtrTyCI, Arg, OfType);
2376 }
2377}
2378
2380 Value *OfType) {
2381 AssignCI->setArgOperand(1, buildMD(OfType));
2382 if (cast<IntrinsicInst>(AssignCI)->getIntrinsicID() !=
2383 Intrinsic::spv_assign_ptr_type)
2384 return;
2385
2386 // update association with the pointee type
2387 Type *ElemTy = OfType->getType();
2388 addDeducedElementType(AssignCI, ElemTy);
2390}
2391
2392void SPIRVGlobalRegistry::addStructOffsetDecorations(
2393 Register Reg, StructType *Ty, MachineIRBuilder &MIRBuilder) {
2394 ArrayRef<TypeSize> Offsets = DL.getStructLayout(Ty)->getMemberOffsets();
2395 for (uint32_t I = 0; I < Ty->getNumElements(); ++I) {
2396 buildOpMemberDecorate(Reg, MIRBuilder, SPIRV::Decoration::Offset, I,
2397 {static_cast<uint32_t>(Offsets[I])});
2398 }
2399}
2400
2401void SPIRVGlobalRegistry::addArrayStrideDecorations(
2402 Register Reg, Type *ElementType, MachineIRBuilder &MIRBuilder) {
2403 uint32_t SizeInBytes = DL.getTypeAllocSize(ElementType);
2404 buildOpDecorate(Reg, MIRBuilder, SPIRV::Decoration::ArrayStride,
2405 {SizeInBytes});
2406}
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 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...
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
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 bool allowEmitFakeUse(const Value *Arg)
static unsigned typeToAddressSpace(const Type *Ty)
unsigned getAS(SPIRVTypeInst SpvType)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
APInt bitcastToAPInt() const
Definition APFloat.h:1475
bool isPosZero() const
Definition APFloat.h:1594
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
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:64
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:843
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:2909
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:338
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 scalarOrVector(ElementCount EC, LLT ScalarTy)
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
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:40
Metadata node.
Definition Metadata.h:1081
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:597
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1525
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
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 & 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
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
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...
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:107
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:887
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:112
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
void assignSPIRVTypeToVReg(SPIRVTypeInst Type, Register VReg, const MachineFunction &MF)
SPIRVTypeInst getOrCreateOpTypeFunctionWithArgs(const Type *Ty, SPIRVTypeInst RetType, const SmallVectorImpl< SPIRVTypeInst > &ArgTypes, MachineIRBuilder &MIRBuilder)
SPIRVTypeInst getOrCreateSPIRVPointerType(const Type *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SC, bool ForceTyped=false)
void buildAssignPtr(IRBuilder<> &B, Type *ElemTy, Value *Arg)
const TargetRegisterClass * getRegClass(SPIRVTypeInst SpvType) const
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
SPIRVTypeInst getOrCreatePaddingType(MachineIRBuilder &MIRBuilder)
Register getOrCreateConstFP(APFloat Val, MachineInstr &I, SPIRVTypeInst SpvType, const SPIRVInstrInfo &TII, bool ZeroAsNull=true)
LLT getRegType(SPIRVTypeInst SpvType) const
SPIRVTypeInst getOpTypeVoid(MachineIRBuilder &MIRBuilder)
void invalidateMachineInstr(MachineInstr *MI)
bool isResourceType(SPIRVTypeInst Type) const
SPIRVTypeInst getOrCreateSPIRVBoolType(MachineIRBuilder &MIRBuilder, bool EmitIR)
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)
SPIRVTypeInst getOrCreateUnknownType(const Type *Ty, MachineIRBuilder &MIRBuilder, unsigned Opcode, const ArrayRef< MCOperand > Operands)
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)
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)
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)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
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:691
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
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:597
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:661
Class to represent struct types.
ArrayRef< Type * > elements() const
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:662
bool isPacked() const
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 StringRef getName() const
Return the name for this struct type if it has an identity.
Definition Type.cpp:736
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:300
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:420
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:297
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 Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:277
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:276
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
Definition Type.cpp:274
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
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:492
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:549
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:315
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Type * getElementType() const
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.
IRHandle handle(const Type *Ty)
IRHandle irhandle_sampled_image(const Type *SampledTy, const MachineInstr *ImageTy)
IRHandle irhandle_padding()
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)
This is an optimization pass for GlobalISel generic memory operations.
void addStringImm(StringRef Str, MCInst &Inst)
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.
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 isLongVectorEXT(const Type *Ty)
Definition SPIRVUtils.h:521
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:238
bool isVectorType(SPIRVTypeInst SPVTy)
bool getSpirvBuiltInIdByName(llvm::StringRef Name, SPIRV::BuiltIn::BuiltIn &BI)
MetadataAsValue * buildMD(Value *Arg)
Definition SPIRVUtils.h:548
bool isTypedPointerTy(const Type *T)
Definition SPIRVUtils.h:366
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
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)
Type * parseBasicTypeName(StringRef &TypeName, LLVMContext &Ctx)
DWARFExpression::Operation Op
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool 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
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID)
PoisonValue * getNormalizedPoisonValue(Type *Ty, bool CanUseAnyVectorRank)
Definition SPIRVUtils.h:543
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
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