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