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