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