LLVM 24.0.0git
SPIRVUtils.cpp
Go to the documentation of this file.
1//===--- SPIRVUtils.cpp ---- SPIR-V Utility Functions -----------*- 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 miscellaneous utility functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SPIRVUtils.h"
15#include "SPIRV.h"
16#include "SPIRVBuiltins.h"
17#include "SPIRVGlobalRegistry.h"
18#include "SPIRVInstrInfo.h"
19#include "SPIRVSubtarget.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
28#include "llvm/IR/IntrinsicsSPIRV.h"
31#include <queue>
32#include <vector>
33
34namespace llvm {
35namespace SPIRV {
37 auto It = find_if(NMD->operands(), [Name](MDNode *N) {
38 if (auto *MDS = dyn_cast_or_null<MDString>(N->getOperand(0)))
39 return MDS->getString() == Name;
40 return false;
41 });
42 return It == NMD->op_end() ? nullptr : *It;
43}
44
45// This code restores function args/retvalue types for composite cases
46// because the final types should still be aggregate whereas they're i32
47// during the translation to cope with aggregate flattening etc.
48// TODO: should these just return nullptr when there's no metadata?
50 FunctionType *FTy,
51 StringRef Name) {
52 if (!NMD)
53 return FTy;
54
55 MDNode *Match = findNamedMDOperand(NMD, Name);
56 if (!Match)
57 return FTy;
58
59 Type *RetTy = FTy->getReturnType();
60 SmallVector<Type *, 4> PTys(FTy->params());
61
62 for (unsigned I = 1; I != Match->getNumOperands(); ++I) {
63 MDNode *MD = dyn_cast<MDNode>(Match->getOperand(I));
64 assert(MD && "MDNode operand is expected");
65
66 if (auto *Const = getMDOperandAsConstInt(MD, 0)) {
67 auto *CMeta = dyn_cast<ConstantAsMetadata>(MD->getOperand(1));
68 assert(CMeta && "ConstantAsMetadata operand is expected");
69 int64_t Idx = Const->getSExtValue();
70 // Currently -1 indicates return value, greater values mean
71 // argument numbers.
72 if (Idx == -1) {
73 RetTy = CMeta->getType();
74 continue;
75 }
76 if (Idx >= 0 && static_cast<uint64_t>(Idx) < PTys.size()) {
77 PTys[Idx] = CMeta->getType();
78 continue;
79 }
80 report_fatal_error("invalid argument index in function type metadata");
81 }
82 }
83
84 return FunctionType::get(RetTy, PTys, FTy->isVarArg());
85}
86
88 StringRef Constraints,
89 StringRef Name) {
90 if (!NMD)
91 return Constraints;
92
93 MDNode *Match = findNamedMDOperand(NMD, Name);
94 if (!Match)
95 return Constraints;
96
97 // By convention, the constraints string is stored in the final MD operand.
98 MDNode *MD = dyn_cast<MDNode>(Match->getOperand(Match->getNumOperands() - 1));
99 assert(MD && "MDNode operand is expected");
100
101 if (auto *MDS = dyn_cast<MDString>(MD->getOperand(0)))
102 Constraints = MDS->getString();
103
104 return Constraints;
105}
106
109 F.getParent()->getNamedMetadata("spv.cloned_funcs"), F.getFunctionType(),
110 F.getName());
111}
112
113// Keyed via instruction metadata, not a name.
114static std::optional<StringRef> getMutatedCallsiteKey(const CallBase &CB) {
115 if (MDNode *MD = CB.getMetadata("spv.mutated_callsite"))
116 if (MD->getNumOperands() > 0)
117 if (auto *MDS = dyn_cast<MDString>(MD->getOperand(0)))
118 return MDS->getString();
119 return std::nullopt;
120}
121
123 std::optional<StringRef> Key = getMutatedCallsiteKey(CB);
124 if (!Key)
125 return CB.getFunctionType();
127 CB.getModule()->getNamedMetadata("spv.mutated_callsites"),
128 CB.getFunctionType(), *Key);
129}
130
132 StringRef Constraints =
133 cast<InlineAsm>(CB.getCalledOperand())->getConstraintString();
134 std::optional<StringRef> Key = getMutatedCallsiteKey(CB);
135 if (!Key)
136 return Constraints;
138 CB.getModule()->getNamedMetadata("spv.mutated_callsites"), Constraints,
139 *Key);
140}
141} // Namespace SPIRV
142
143// The following functions are used to add these string literals as a series of
144// 32-bit integer operands with the correct format, and unpack them if necessary
145// when making string comparisons in compiler passes.
146// SPIR-V requires null-terminated UTF-8 strings padded to 32-bit alignment.
147static uint32_t convertCharsToWord(StringRef Str, unsigned i) {
148 uint32_t Word = 0u; // Build up this 32-bit word from 4 8-bit chars.
149 for (unsigned WordIndex = 0; WordIndex < 4; ++WordIndex) {
150 unsigned StrIndex = i + WordIndex;
151 uint8_t CharToAdd = 0; // Initilize char as padding/null.
152 if (StrIndex < Str.size()) { // If it's within the string, get a real char.
153 CharToAdd = Str[StrIndex];
154 }
155 Word |= (CharToAdd << (WordIndex * 8));
156 }
157 return Word;
158}
159
160// Get length including padding and null terminator.
161static size_t getPaddedLen(StringRef Str) { return alignTo(Str.size() + 1, 4); }
162
163void addStringImm(StringRef Str, MCInst &Inst) {
164 const size_t PaddedLen = getPaddedLen(Str);
165 for (unsigned i = 0; i < PaddedLen; i += 4) {
166 // Add an operand for the 32-bits of chars or padding.
168 }
169}
170
172 const size_t PaddedLen = getPaddedLen(Str);
173 for (unsigned i = 0; i < PaddedLen; i += 4) {
174 // Add an operand for the 32-bits of chars or padding.
175 MIB.addImm(convertCharsToWord(Str, i));
176 }
177}
178
179std::string getStringImm(const MachineInstr &MI, unsigned StartIndex) {
180 return getSPIRVStringOperand(MI, StartIndex);
181}
182
184 const auto Bitwidth = Imm.getBitWidth();
185 if (Bitwidth == 1)
186 return; // Already handled
187 else if (Bitwidth <= 32) {
188 MIB.addImm(Imm.getZExtValue());
189 // Asm Printer needs this info to print floating-type correctly
190 if (Bitwidth == 16)
192 return;
193 } else if (Bitwidth <= 64) {
194 uint64_t FullImm = Imm.getZExtValue();
195 MIB.addImm(Lo_32(FullImm)).addImm(Hi_32(FullImm));
196 // Asm Printer needs this info to print 64-bit operands correctly
198 return;
199 } else {
200 // Emit ceil(Bitwidth / 32) words to conform SPIR-V spec.
201 unsigned NumWords = divideCeil(Bitwidth, 32);
202 for (unsigned I = 0; I < NumWords; ++I) {
203 unsigned LimbIdx = I / 2;
204 unsigned LimbShift = (I % 2) * 32;
205 uint32_t Word = (Imm.getRawData()[LimbIdx] >> LimbShift) & 0xffffffff;
206 MIB.addImm(Word);
207 }
208 return;
209 }
210}
211
213 MachineIRBuilder &MIRBuilder) {
214 if (!Name.empty()) {
215 auto MIB = MIRBuilder.buildInstr(SPIRV::OpName).addUse(Target);
216 addStringImm(Name, MIB);
217 }
218}
219
221 ArrayRef<uint32_t> DecArgs,
222 StringRef StrImm) {
223 if (!StrImm.empty())
224 addStringImm(StrImm, MIB);
225 for (const auto &DecArg : DecArgs)
226 MIB.addImm(DecArg);
227}
228
230 SPIRV::Decoration::Decoration Dec,
231 ArrayRef<uint32_t> DecArgs, StringRef StrImm) {
232 auto MIB = MIRBuilder.buildInstr(SPIRV::OpDecorate)
233 .addUse(Reg)
234 .addImm(static_cast<uint32_t>(Dec));
235 finishBuildOpDecorate(MIB, DecArgs, StrImm);
236}
237
239 SPIRV::Decoration::Decoration Dec,
240 ArrayRef<uint32_t> DecArgs, StringRef StrImm) {
241 MachineBasicBlock &MBB = *I.getParent();
242 auto MIB = BuildMI(MBB, I, I.getDebugLoc(), TII.get(SPIRV::OpDecorate))
243 .addUse(Reg)
244 .addImm(static_cast<uint32_t>(Dec));
245 finishBuildOpDecorate(MIB, DecArgs, StrImm);
246}
247
249 SPIRV::Decoration::Decoration Dec, uint32_t Member,
250 ArrayRef<uint32_t> DecArgs, StringRef StrImm) {
251 auto MIB = MIRBuilder.buildInstr(SPIRV::OpMemberDecorate)
252 .addUse(Reg)
253 .addImm(Member)
254 .addImm(static_cast<uint32_t>(Dec));
255 finishBuildOpDecorate(MIB, DecArgs, StrImm);
256}
257
259 const MDNode *GVarMD, const SPIRVSubtarget &ST) {
260 for (unsigned I = 0, E = GVarMD->getNumOperands(); I != E; ++I) {
261 auto *OpMD = dyn_cast<MDNode>(GVarMD->getOperand(I));
262 if (!OpMD)
263 report_fatal_error("Invalid decoration");
264 if (OpMD->getNumOperands() == 0)
265 report_fatal_error("Expect operand(s) of the decoration");
266 ConstantInt *DecorationId =
267 mdconst::dyn_extract<ConstantInt>(OpMD->getOperand(0));
268 if (!DecorationId)
269 report_fatal_error("Expect SPIR-V <Decoration> operand to be the first "
270 "element of the decoration");
271
272 // The goal of `spirv.Decorations` metadata is to provide a way to
273 // represent SPIR-V entities that do not map to LLVM in an obvious way.
274 // FP flags do have obvious matches between LLVM IR and SPIR-V.
275 // Additionally, we have no guarantee at this point that the flags passed
276 // through the decoration are not violated already in the optimizer passes.
277 // Therefore, we simply ignore FP flags, including NoContraction, and
278 // FPFastMathMode.
279 if (DecorationId->getZExtValue() ==
280 static_cast<uint32_t>(SPIRV::Decoration::NoContraction) ||
281 DecorationId->getZExtValue() ==
282 static_cast<uint32_t>(SPIRV::Decoration::FPFastMathMode)) {
283 continue; // Ignored.
284 }
285 uint32_t Dec = static_cast<uint32_t>(DecorationId->getZExtValue());
286 if (Dec == static_cast<uint32_t>(SPIRV::Decoration::UniformId) ||
287 Dec == static_cast<uint32_t>(SPIRV::Decoration::AlignmentId) ||
288 Dec == static_cast<uint32_t>(SPIRV::Decoration::MaxByteOffsetId)) {
289 ConstantInt *IdV =
290 OpMD->getNumOperands() == 2
291 ? mdconst::dyn_extract<ConstantInt>(OpMD->getOperand(1))
292 : nullptr;
293 if (!IdV || !isUInt<32>(IdV->getZExtValue()))
294 report_fatal_error("Expect a single integer <id> operand of the "
295 "decoration");
296 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
297 SPIRVTypeInst SpvTypeInt32 =
298 GR->getOrCreateSPIRVIntegerType(32, MIRBuilder);
299 Register IdReg = GR->buildConstantInt(IdV->getZExtValue(), MIRBuilder,
300 SpvTypeInt32, /*EmitIR=*/false);
301 MIRBuilder.buildInstr(SPIRV::OpDecorateId)
302 .addUse(Reg)
303 .addImm(Dec)
304 .addUse(IdReg);
305 continue;
306 }
307 auto MIB = MIRBuilder.buildInstr(SPIRV::OpDecorate).addUse(Reg).addImm(Dec);
308 for (unsigned OpI = 1, OpE = OpMD->getNumOperands(); OpI != OpE; ++OpI) {
309 if (ConstantInt *OpV =
310 mdconst::dyn_extract<ConstantInt>(OpMD->getOperand(OpI)))
311 MIB.addImm(static_cast<uint32_t>(OpV->getZExtValue()));
312 else if (MDString *OpV = dyn_cast<MDString>(OpMD->getOperand(OpI)))
313 addStringImm(OpV->getString(), MIB);
314 else
315 report_fatal_error("Unexpected operand of the decoration");
316 }
317 }
318}
319
322 // Find the position to insert the OpVariable instruction.
323 // We will insert it after the last OpFunctionParameter, if any, or
324 // after OpFunction otherwise.
325 auto IsPreamble = [](const MachineInstr &MI) {
326 switch (MI.getOpcode()) {
327 case SPIRV::OpFunction:
328 case SPIRV::OpFunctionParameter:
329 case SPIRV::OpLabel:
330 case SPIRV::ASSIGN_TYPE:
331 return true;
332 default:
333 return false;
334 }
335 };
336 MachineBasicBlock::iterator VarPos = MBB.SkipPHIsAndLabels(MBB.begin());
337 while (VarPos != MBB.end() && VarPos->getOpcode() != SPIRV::OpFunction)
338 ++VarPos;
339 // Advance past the preamble.
340 while (VarPos != MBB.end() && IsPreamble(*VarPos))
341 ++VarPos;
342 return VarPos;
343}
344
347 if (I == MBB->begin())
348 return I;
349 --I;
350 while (I->isTerminator() || I->isDebugValue()) {
351 if (I == MBB->begin())
352 break;
353 --I;
354 }
355 return I;
356}
357
358SPIRV::StorageClass::StorageClass
359addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI) {
360 switch (AddrSpace) {
362 return SPIRV::StorageClass::Function;
364 return SPIRV::StorageClass::CrossWorkgroup;
366 return SPIRV::StorageClass::UniformConstant;
368 return SPIRV::StorageClass::Workgroup;
369 case SPIRVAS::Generic:
370 return SPIRV::StorageClass::Generic;
372 return STI.canUseExtension(SPIRV::Extension::SPV_INTEL_usm_storage_classes)
373 ? SPIRV::StorageClass::DeviceOnlyINTEL
374 : SPIRV::StorageClass::CrossWorkgroup;
376 return STI.canUseExtension(SPIRV::Extension::SPV_INTEL_usm_storage_classes)
377 ? SPIRV::StorageClass::HostOnlyINTEL
378 : SPIRV::StorageClass::CrossWorkgroup;
379 case SPIRVAS::Input:
380 return SPIRV::StorageClass::Input;
381 case SPIRVAS::Output:
382 return SPIRV::StorageClass::Output;
384 return SPIRV::StorageClass::CodeSectionINTEL;
385 case SPIRVAS::Private:
386 return SPIRV::StorageClass::Private;
388 return SPIRV::StorageClass::StorageBuffer;
389 case SPIRVAS::Uniform:
390 return SPIRV::StorageClass::Uniform;
392 return SPIRV::StorageClass::PushConstant;
393 default:
394 report_fatal_error("Unknown address space");
395 }
396}
397
398SPIRV::MemorySemantics::MemorySemantics
399getMemSemanticsForStorageClass(SPIRV::StorageClass::StorageClass SC) {
400 switch (SC) {
401 case SPIRV::StorageClass::StorageBuffer:
402 case SPIRV::StorageClass::Uniform:
403 return SPIRV::MemorySemantics::UniformMemory;
404 case SPIRV::StorageClass::Workgroup:
405 return SPIRV::MemorySemantics::WorkgroupMemory;
406 case SPIRV::StorageClass::CrossWorkgroup:
407 return SPIRV::MemorySemantics::CrossWorkgroupMemory;
408 case SPIRV::StorageClass::Generic:
409 return SPIRV::MemorySemantics::MemorySemantics(
410 SPIRV::MemorySemantics::WorkgroupMemory |
411 SPIRV::MemorySemantics::CrossWorkgroupMemory);
412 case SPIRV::StorageClass::AtomicCounter:
413 return SPIRV::MemorySemantics::AtomicCounterMemory;
414 case SPIRV::StorageClass::Image:
415 return SPIRV::MemorySemantics::ImageMemory;
416 default:
417 return SPIRV::MemorySemantics::None;
418 }
419}
420
421SPIRV::MemorySemantics::MemorySemantics getMemSemantics(AtomicOrdering Ord) {
422 switch (Ord) {
424 return SPIRV::MemorySemantics::Acquire;
426 return SPIRV::MemorySemantics::Release;
428 return SPIRV::MemorySemantics::AcquireRelease;
430 return SPIRV::MemorySemantics::SequentiallyConsistent;
434 return SPIRV::MemorySemantics::None;
435 }
436 llvm_unreachable(nullptr);
437}
438
440 uint32_t StorageClassSem) {
441 bool DropStorageClass =
442 TT.isVulkanOS() &&
443 OrderSem == static_cast<uint32_t>(SPIRV::MemorySemantics::None);
444 return OrderSem | (DropStorageClass ? 0 : StorageClassSem);
445}
446
447SPIRV::Scope::Scope getMemScope(const Triple &TT, LLVMContext &Ctx,
448 SyncScope::ID Id) {
449 // Named by
450 // https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#_scope_id.
451 // We don't need aliases for Invocation and CrossDevice, as we already have
452 // them covered by "singlethread" and "" strings respectively (see
453 // implementation of LLVMContext::LLVMContext()).
454 auto ScopeID = [&](AtomicScope Scope) {
455 return Ctx.getOrInsertSyncScopeID(*getAtomicScopeIRString(TT, Scope));
456 };
457 const llvm::SyncScope::ID SubGroup = ScopeID(AtomicScope::Wavefront);
458 const llvm::SyncScope::ID WorkGroup = ScopeID(AtomicScope::Workgroup);
460
462 return SPIRV::Scope::Invocation;
463 else if (Id == llvm::SyncScope::System)
464 return SPIRV::Scope::CrossDevice;
465 else if (Id == SubGroup)
466 return SPIRV::Scope::Subgroup;
467 else if (Id == WorkGroup)
468 return SPIRV::Scope::Workgroup;
469 else if (Id == Device)
470 return SPIRV::Scope::Device;
471 return SPIRV::Scope::CrossDevice;
472}
473
475 const MachineRegisterInfo *MRI) {
476 MachineInstr *MI = MRI->getVRegDef(ConstReg);
477 MachineInstr *ConstInstr =
478 MI->getOpcode() == SPIRV::G_TRUNC || MI->getOpcode() == SPIRV::G_ZEXT
479 ? MRI->getVRegDef(MI->getOperand(1).getReg())
480 : MI;
481 if (auto *GI = dyn_cast<GIntrinsic>(ConstInstr)) {
482 if (GI->is(Intrinsic::spv_track_constant)) {
483 ConstReg = ConstInstr->getOperand(2).getReg();
484 return MRI->getVRegDef(ConstReg);
485 }
486 } else if (ConstInstr->getOpcode() == SPIRV::ASSIGN_TYPE) {
487 ConstReg = ConstInstr->getOperand(1).getReg();
488 return MRI->getVRegDef(ConstReg);
489 } else if (ConstInstr->getOpcode() == TargetOpcode::G_CONSTANT ||
490 ConstInstr->getOpcode() == TargetOpcode::G_FCONSTANT) {
491 ConstReg = ConstInstr->getOperand(0).getReg();
492 return ConstInstr;
493 }
494 return MRI->getVRegDef(ConstReg);
495}
496
498 const MachineInstr *MI = getDefInstrMaybeConstant(ConstReg, MRI);
499 assert(MI && MI->getOpcode() == TargetOpcode::G_CONSTANT);
500 return MI->getOperand(1).getCImm()->getValue().getZExtValue();
501}
502
503bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID) {
504 if (const auto *GI = dyn_cast<GIntrinsic>(&MI))
505 return GI->is(IntrinsicID);
506 return false;
507}
508
509Type *getMDOperandAsType(const MDNode *N, unsigned I) {
510 Type *ElementTy = cast<ValueAsMetadata>(N->getOperand(I))->getType();
511 return toTypedPointer(ElementTy);
512}
513
515 if (N->getNumOperands() <= I)
516 return nullptr;
517 if (auto *CMeta = dyn_cast<ConstantAsMetadata>(N->getOperand(I)))
518 return dyn_cast<ConstantInt>(CMeta->getValue());
519 return nullptr;
520}
521
522static bool isEnqueueKernelBI(StringRef MangledName) {
523 return MangledName == "__enqueue_kernel_basic" ||
524 MangledName == "__enqueue_kernel_basic_events" ||
525 MangledName == "__enqueue_kernel_varargs" ||
526 MangledName == "__enqueue_kernel_events_varargs";
527}
528
529static bool isKernelQueryBI(StringRef MangledName) {
530 return MangledName == "__get_kernel_work_group_size_impl" ||
531 MangledName == "__get_kernel_sub_group_count_for_ndrange_impl" ||
532 MangledName == "__get_kernel_max_sub_group_size_for_ndrange_impl" ||
533 MangledName == "__get_kernel_preferred_work_group_size_multiple_impl";
534}
535
537 if (!Name.starts_with("__"))
538 return false;
539
540 return isEnqueueKernelBI(Name) || isKernelQueryBI(Name) ||
542 Name == "__translate_sampler_initializer";
543}
544
545// TODO: Add support for demangling cooperative matrix builtins.
547 bool IsNonMangledOCL = isNonMangledOCLBuiltin(Name);
548 bool IsNonMangledSPIRV = Name.starts_with("__spirv_");
549 bool IsNonMangledHLSL = Name.starts_with("__hlsl_");
550 bool IsMangled = Name.starts_with("_Z");
551
552 // Otherwise use simple demangling to return the function name.
553 if (IsNonMangledOCL || IsNonMangledSPIRV || IsNonMangledHLSL || !IsMangled)
554 return Name.str();
555
556 // Try to use the itanium demangler.
557 if (char *DemangledName = itaniumDemangle(Name.data())) {
558 std::string Result = DemangledName;
559 free(DemangledName);
560 return Result;
561 }
562
563 // Autocheck C++, maybe need to do explicit check of the source language.
564 // OpenCL C++ built-ins are declared in cl namespace.
565 // TODO: consider using 'St' abbriviation for cl namespace mangling.
566 // Similar to ::std:: in C++.
567 size_t Start, Len = 0;
568 size_t DemangledNameLenStart = 2;
569 if (Name.starts_with("_ZN")) {
570 // Skip CV and ref qualifiers.
571 size_t NameSpaceStart = Name.find_first_not_of("rVKRO", 3);
572 // All built-ins are in the ::cl:: namespace.
573 if (Name.substr(NameSpaceStart, 11) != "2cl7__spirv")
574 return std::string();
575 DemangledNameLenStart = NameSpaceStart + 11;
576 }
577 Start = Name.find_first_not_of("0123456789", DemangledNameLenStart);
578 bool Error = Name.substr(DemangledNameLenStart, Start - DemangledNameLenStart)
579 .getAsInteger(10, Len);
580 if (Error)
581 return std::string();
582 return Name.substr(Start, Len).str();
583}
584
586 if (Name.starts_with("opencl.") || Name.starts_with("ocl_") ||
587 Name.starts_with("spirv."))
588 return true;
589 return false;
590}
591
592bool isSpecialOpaqueType(const Type *Ty) {
593 if (const TargetExtType *ExtTy = dyn_cast<TargetExtType>(Ty))
594 return isTypedPointerWrapper(ExtTy)
595 ? false
596 : hasBuiltinTypePrefix(ExtTy->getName());
597
598 return false;
599}
600
601bool isEntryPoint(const Function &F) {
602 // OpenCL handling: any function with the SPIR_KERNEL
603 // calling convention will be a potential entry point.
604 if (F.getCallingConv() == CallingConv::SPIR_KERNEL)
605 return true;
606
607 // HLSL handling: special attribute are emitted from the
608 // front-end.
609 if (F.getFnAttribute("hlsl.shader").isValid())
610 return true;
611
612 return false;
613}
614
616 TypeName.consume_front("atomic_");
617 if (TypeName.consume_front("void"))
618 return Type::getVoidTy(Ctx);
619 else if (TypeName.consume_front("bool") || TypeName.consume_front("_Bool"))
620 return Type::getIntNTy(Ctx, 1);
621 else if (TypeName.consume_front("char") ||
622 TypeName.consume_front("signed char") ||
623 TypeName.consume_front("unsigned char") ||
624 TypeName.consume_front("uchar"))
625 return Type::getInt8Ty(Ctx);
626 else if (TypeName.consume_front("short") ||
627 TypeName.consume_front("signed short") ||
628 TypeName.consume_front("unsigned short") ||
629 TypeName.consume_front("ushort"))
630 return Type::getInt16Ty(Ctx);
631 else if (TypeName.consume_front("int") ||
632 TypeName.consume_front("signed int") ||
633 TypeName.consume_front("unsigned int") ||
634 TypeName.consume_front("uint"))
635 return Type::getInt32Ty(Ctx);
636 else if (TypeName.consume_front("long") ||
637 TypeName.consume_front("signed long") ||
638 TypeName.consume_front("unsigned long") ||
639 TypeName.consume_front("ulong"))
640 return Type::getInt64Ty(Ctx);
641 else if (TypeName.consume_front("half") ||
642 TypeName.consume_front("_Float16") ||
643 TypeName.consume_front("__fp16"))
644 return Type::getHalfTy(Ctx);
645 else if (TypeName.consume_front("float"))
646 return Type::getFloatTy(Ctx);
647 else if (TypeName.consume_front("double"))
648 return Type::getDoubleTy(Ctx);
649
650 // Unable to recognize SPIRV type name
651 return nullptr;
652}
653
654SmallPtrSet<BasicBlock *, 0>
655PartialOrderingVisitor::getReachableFrom(BasicBlock *Start) {
656 std::queue<BasicBlock *> ToVisit;
657 ToVisit.push(Start);
658
659 SmallPtrSet<BasicBlock *, 0> Output;
660 while (ToVisit.size() != 0) {
661 BasicBlock *BB = ToVisit.front();
662 ToVisit.pop();
663
664 if (Output.count(BB) != 0)
665 continue;
666 Output.insert(BB);
667
668 for (BasicBlock *Successor : successors(BB)) {
669 if (DT.dominates(Successor, BB))
670 continue;
671 ToVisit.push(Successor);
672 }
673 }
674
675 return Output;
676}
677
678bool PartialOrderingVisitor::CanBeVisited(BasicBlock *BB) const {
679 for (BasicBlock *P : predecessors(BB)) {
680 // Ignore back-edges.
681 if (DT.dominates(BB, P))
682 continue;
683
684 // One of the predecessor hasn't been visited. Not ready yet.
685 if (BlockToOrder.count(P) == 0)
686 return false;
687
688 // If the block is a loop exit, the loop must be finished before
689 // we can continue.
690 Loop *L = LI.getLoopFor(P);
691 if (L == nullptr || L->contains(BB))
692 continue;
693
694 // SPIR-V requires a single back-edge. And the backend first
695 // step transforms loops into the simplified format. If we have
696 // more than 1 back-edge, something is wrong.
697 assert(L->getNumBackEdges() <= 1);
698
699 // If the loop has no latch, loop's rank won't matter, so we can
700 // proceed.
701 BasicBlock *Latch = L->getLoopLatch();
702 assert(Latch);
703 if (Latch == nullptr)
704 continue;
705
706 // The latch is not ready yet, let's wait.
707 if (BlockToOrder.count(Latch) == 0)
708 return false;
709 }
710
711 return true;
712}
713
715 auto It = BlockToOrder.find(BB);
716 if (It != BlockToOrder.end())
717 return It->second.Rank;
718
719 size_t result = 0;
720 for (BasicBlock *P : predecessors(BB)) {
721 // Ignore back-edges.
722 if (DT.dominates(BB, P))
723 continue;
724
725 auto Iterator = BlockToOrder.end();
726 Loop *L = LI.getLoopFor(P);
727 BasicBlock *Latch = L ? L->getLoopLatch() : nullptr;
728
729 // If the predecessor is either outside a loop, or part of
730 // the same loop, simply take its rank + 1.
731 if (L == nullptr || L->contains(BB) || Latch == nullptr) {
732 Iterator = BlockToOrder.find(P);
733 } else {
734 // Otherwise, take the loop's rank (highest rank in the loop) as base.
735 // Since loops have a single latch, highest rank is easy to find.
736 // If the loop has no latch, then it doesn't matter.
737 Iterator = BlockToOrder.find(Latch);
738 }
739
740 assert(Iterator != BlockToOrder.end());
741 result = std::max(result, Iterator->second.Rank + 1);
742 }
743
744 return result;
745}
746
747size_t PartialOrderingVisitor::visit(BasicBlock *BB, size_t Unused) {
748 ToVisit.push(BB);
749 Queued.insert(BB);
750
751 size_t QueueIndex = 0;
752 while (ToVisit.size() != 0) {
753 BasicBlock *BB = ToVisit.front();
754 ToVisit.pop();
755
756 if (!CanBeVisited(BB)) {
757 ToVisit.push(BB);
758 if (QueueIndex >= ToVisit.size())
760 "No valid candidate in the queue. Is the graph reducible?");
761 QueueIndex++;
762 continue;
763 }
764
765 QueueIndex = 0;
766 size_t Rank = GetNodeRank(BB);
767 OrderInfo Info = {Rank, BlockToOrder.size()};
768 BlockToOrder.try_emplace(BB, Info);
769
770 for (BasicBlock *S : successors(BB)) {
771 if (Queued.count(S) != 0)
772 continue;
773 ToVisit.push(S);
774 Queued.insert(S);
775 }
776 }
777
778 return 0;
779}
780
782 DT.recalculate(F);
783 LI = LoopInfo(DT);
784
785 visit(&*F.begin(), 0);
786
787 Order.reserve(F.size());
788 for (auto &[BB, Info] : BlockToOrder)
789 Order.emplace_back(BB);
790
791 llvm::sort(Order, [&](const auto &LHS, const auto &RHS) {
792 return compare(LHS, RHS);
793 });
794}
795
797 const BasicBlock *RHS) const {
798 const OrderInfo &InfoLHS = BlockToOrder.at(const_cast<BasicBlock *>(LHS));
799 const OrderInfo &InfoRHS = BlockToOrder.at(const_cast<BasicBlock *>(RHS));
800 if (InfoLHS.Rank != InfoRHS.Rank)
801 return InfoLHS.Rank < InfoRHS.Rank;
802 return InfoLHS.TraversalIndex < InfoRHS.TraversalIndex;
803}
804
806 BasicBlock &Start, std::function<bool(BasicBlock *)> Op) {
807 SmallPtrSet<BasicBlock *, 0> Reachable = getReachableFrom(&Start);
808 assert(BlockToOrder.count(&Start) != 0);
809
810 // Skipping blocks with a rank inferior to |Start|'s rank.
811 auto It = Order.begin();
812 while (It != Order.end() && *It != &Start)
813 ++It;
814
815 // This is unexpected. Worst case |Start| is the last block,
816 // so It should point to the last block, not past-end.
817 assert(It != Order.end());
818
819 // By default, there is no rank limit. Setting it to the maximum value.
820 std::optional<size_t> EndRank = std::nullopt;
821 for (; It != Order.end(); ++It) {
822 if (EndRank.has_value() && BlockToOrder[*It].Rank > *EndRank)
823 break;
824
825 if (Reachable.count(*It) == 0) {
826 continue;
827 }
828
829 if (!Op(*It)) {
830 EndRank = BlockToOrder[*It].Rank;
831 }
832 }
833}
834
836 if (F.size() == 0)
837 return false;
838
839 bool Modified = false;
840 std::vector<BasicBlock *> Order;
841 Order.reserve(F.size());
842
844 llvm::append_range(Order, RPOT);
845
846 assert(&*F.begin() == Order[0]);
847 BasicBlock *LastBlock = &*F.begin();
848 for (BasicBlock *BB : Order) {
849 if (BB != LastBlock && &*LastBlock->getNextNode() != BB) {
850 Modified = true;
851 BB->moveAfter(LastBlock);
852 }
853 LastBlock = BB;
854 }
855
856 return Modified;
857}
858
860 const DataLayout &DL = F.getDataLayout();
861 return new AllocaInst(Type, DL.getAllocaAddrSpace(), nullptr, "reg",
862 F.begin()->getFirstInsertionPt());
863}
864
865Value *
867 const DenseMap<BasicBlock *, ConstantInt *> &TargetToValue) {
868 auto *T = BB->getTerminator();
869 if (isa<ReturnInst>(T))
870 return nullptr;
871 if (auto *BI = dyn_cast<UncondBrInst>(T))
872 return TargetToValue.lookup(BI->getSuccessor());
873
874 IRBuilder<> Builder(BB);
875 Builder.SetInsertPoint(T);
876
877 if (auto *BI = dyn_cast<CondBrInst>(T)) {
878 Value *LHS = TargetToValue.lookup(BI->getSuccessor(0));
879 Value *RHS = TargetToValue.lookup(BI->getSuccessor(1));
880
881 if (LHS == nullptr || RHS == nullptr)
882 return LHS == nullptr ? RHS : LHS;
883 return Builder.CreateSelect(BI->getCondition(), LHS, RHS);
884 }
885
886 if (auto *SI = dyn_cast<SwitchInst>(T)) {
887 Value *Condition = SI->getCondition();
888 // The default destination acts as the fallback value of the select chain.
889 Value *Result = TargetToValue.lookup(SI->getDefaultDest());
890 for (const auto &Case : SI->cases()) {
891 Value *CaseValue = TargetToValue.lookup(Case.getCaseSuccessor());
892 // Successors that are internal to the region have no exit value.
893 if (CaseValue == nullptr)
894 continue;
895 // The first known exit value becomes the base of the select chain.
896 if (Result == nullptr) {
897 Result = CaseValue;
898 continue;
899 }
900 Value *Cmp = Builder.CreateICmpEQ(Condition, Case.getCaseValue());
901 Result = Builder.CreateSelect(Cmp, CaseValue, Result);
902 }
903 return Result;
904 }
905
906 llvm_unreachable("Unhandled terminator type.");
907}
908
910 MachineInstr *MaybeDef = MRI.getVRegDef(Reg);
911 if (MaybeDef && MaybeDef->getOpcode() == SPIRV::ASSIGN_TYPE)
912 MaybeDef = MRI.getVRegDef(MaybeDef->getOperand(1).getReg());
913 return MaybeDef;
914}
915
916static bool getVacantFunctionName(Module &M, std::string &Name) {
917 // It's a bit of paranoia, but still we don't want to have even a chance that
918 // the loop will work for too long.
919 constexpr unsigned MaxIters = 1024;
920 for (unsigned I = 0; I < MaxIters; ++I) {
921 std::string OrdName = Name + Twine(I).str();
922 if (!M.getFunction(OrdName)) {
923 Name = std::move(OrdName);
924 return true;
925 }
926 }
927 return false;
928}
929
930// Assign SPIR-V type to the register. If the register has no valid assigned
931// class, set register LLT type and class according to the SPIR-V type.
934 const MachineFunction &MF, bool Force) {
935 GR->assignSPIRVTypeToVReg(SpvType, Reg, MF);
936 if (!MRI->getRegClassOrNull(Reg) || Force) {
937 MRI->setRegClass(Reg, GR->getRegClass(SpvType));
938 LLT RegType = GR->getRegType(SpvType);
939 if (Force || !MRI->getType(Reg).isValid())
940 MRI->setType(Reg, RegType);
941 }
942}
943
944// Create a SPIR-V type, assign SPIR-V type to the register. If the register has
945// no valid assigned class, set register LLT type and class according to the
946// SPIR-V type.
948 MachineIRBuilder &MIRBuilder,
949 SPIRV::AccessQualifier::AccessQualifier AccessQual,
950 bool EmitIR, bool Force) {
952 GR->getOrCreateSPIRVType(Ty, MIRBuilder, AccessQual, EmitIR),
953 GR, MIRBuilder.getMRI(), MIRBuilder.getMF(), Force);
954}
955
956// Create a virtual register and assign SPIR-V type to the register. Set
957// register LLT type and class according to the SPIR-V type.
960 const MachineFunction &MF) {
961 Register Reg = MRI->createVirtualRegister(GR->getRegClass(SpvType));
962 MRI->setType(Reg, GR->getRegType(SpvType));
963 GR->assignSPIRVTypeToVReg(SpvType, Reg, MF);
964 return Reg;
965}
966
967// Create a virtual register and assign SPIR-V type to the register. Set
968// register LLT type and class according to the SPIR-V type.
970 MachineIRBuilder &MIRBuilder) {
971 return createVirtualRegister(SpvType, GR, MIRBuilder.getMRI(),
972 MIRBuilder.getMF());
973}
974
975// Create a SPIR-V type, virtual register and assign SPIR-V type to the
976// register. Set register LLT type and class according to the SPIR-V type.
978 const Type *Ty, SPIRVGlobalRegistry *GR, MachineIRBuilder &MIRBuilder,
979 SPIRV::AccessQualifier::AccessQualifier AccessQual, bool EmitIR) {
981 GR->getOrCreateSPIRVType(Ty, MIRBuilder, AccessQual, EmitIR), GR,
982 MIRBuilder);
983}
984
986 return SPVTy->getOpcode() == SPIRV::OpTypeVector ||
987 SPVTy->getOpcode() == SPIRV::OpTypeVectorIdEXT;
988}
989
991 Value *Arg, Value *Arg2, ArrayRef<Constant *> Imms,
992 IRBuilder<> &B) {
994 Args.push_back(Arg2);
995 Args.push_back(buildMD(Arg));
996 llvm::append_range(Args, Imms);
997 return B.CreateIntrinsicWithoutFolding(IntrID, {Types}, Args);
998}
999
1000// Return true if there is an opaque pointer type nested in the argument.
1001bool isNestedPointer(const Type *Ty) {
1002 if (Ty->isPtrOrPtrVectorTy())
1003 return true;
1004 if (const FunctionType *RefTy = dyn_cast<FunctionType>(Ty)) {
1005 if (isNestedPointer(RefTy->getReturnType()))
1006 return true;
1007 for (const Type *ArgTy : RefTy->params())
1008 if (isNestedPointer(ArgTy))
1009 return true;
1010 return false;
1011 }
1012 if (const ArrayType *RefTy = dyn_cast<ArrayType>(Ty))
1013 return isNestedPointer(RefTy->getElementType());
1014 return false;
1015}
1016
1017bool isSpvIntrinsic(const Value *Arg) {
1018 if (const auto *II = dyn_cast<IntrinsicInst>(Arg))
1019 if (Function *F = II->getCalledFunction())
1020 if (F->getName().starts_with("llvm.spv."))
1021 return true;
1022 return false;
1023}
1024
1025// Function to create continued instructions for SPV_INTEL_long_composites
1026// extension
1027SmallVector<MachineInstr *, 4>
1029 unsigned MinWC, unsigned ContinuedOpcode,
1030 ArrayRef<Register> Args, Register ReturnRegister,
1031 Register TypeID) {
1032
1033 SmallVector<MachineInstr *, 4> Instructions;
1034 constexpr unsigned MaxWordCount = UINT16_MAX;
1035 const size_t NumElements = Args.size();
1036 size_t MaxNumElements = MaxWordCount - MinWC;
1037 size_t SPIRVStructNumElements = NumElements;
1038
1039 if (NumElements > MaxNumElements) {
1040 // Do adjustments for continued instructions which always had only one
1041 // minumum word count.
1042 SPIRVStructNumElements = MaxNumElements;
1043 MaxNumElements = MaxWordCount - 1;
1044 }
1045
1046 auto MIB =
1047 MIRBuilder.buildInstr(Opcode).addDef(ReturnRegister).addUse(TypeID);
1048
1049 for (size_t I = 0; I < SPIRVStructNumElements; ++I)
1050 MIB.addUse(Args[I]);
1051
1052 Instructions.push_back(MIB.getInstr());
1053
1054 for (size_t I = SPIRVStructNumElements; I < NumElements;
1055 I += MaxNumElements) {
1056 auto MIB = MIRBuilder.buildInstr(ContinuedOpcode);
1057 for (size_t J = I; J < std::min(I + MaxNumElements, NumElements); ++J)
1058 MIB.addUse(Args[J]);
1059 Instructions.push_back(MIB.getInstr());
1060 }
1061 return Instructions;
1062}
1063
1064SmallVector<unsigned, 1>
1066 unsigned LC = SPIRV::LoopControl::None;
1067 // Currently used only to store PartialCount value. Later when other
1068 // LoopControls are added - this map should be sorted before making
1069 // them loop_merge operands to satisfy 3.23. Loop Control requirements.
1070 std::vector<std::pair<unsigned, unsigned>> MaskToValueMap;
1071 if (findOptionMDForLoopID(LoopMD, "llvm.loop.unroll.disable")) {
1072 LC |= SPIRV::LoopControl::DontUnroll;
1073 } else {
1074 if (findOptionMDForLoopID(LoopMD, "llvm.loop.unroll.enable") ||
1075 findOptionMDForLoopID(LoopMD, "llvm.loop.unroll.full")) {
1076 LC |= SPIRV::LoopControl::Unroll;
1077 }
1078 if (MDNode *CountMD =
1079 findOptionMDForLoopID(LoopMD, "llvm.loop.unroll.count")) {
1080 if (auto *CI =
1081 mdconst::extract_or_null<ConstantInt>(CountMD->getOperand(1))) {
1082 unsigned Count = CI->getZExtValue();
1083 if (Count != 1) {
1084 LC |= SPIRV::LoopControl::PartialCount;
1085 MaskToValueMap.emplace_back(
1086 std::make_pair(SPIRV::LoopControl::PartialCount, Count));
1087 }
1088 }
1089 }
1090 }
1091 SmallVector<unsigned, 1> Result = {LC};
1092 for (auto &[Mask, Val] : MaskToValueMap)
1093 Result.push_back(Val);
1094 return Result;
1095}
1096
1100
1101const std::set<unsigned> &getTypeFoldingSupportedOpcodes() {
1102 // clang-format off
1103 static const std::set<unsigned> TypeFoldingSupportingOpcs = {
1104 TargetOpcode::G_ADD,
1105 TargetOpcode::G_FADD,
1106 TargetOpcode::G_STRICT_FADD,
1107 TargetOpcode::G_SUB,
1108 TargetOpcode::G_FSUB,
1109 TargetOpcode::G_STRICT_FSUB,
1110 TargetOpcode::G_MUL,
1111 TargetOpcode::G_FMUL,
1112 TargetOpcode::G_STRICT_FMUL,
1113 TargetOpcode::G_SDIV,
1114 TargetOpcode::G_UDIV,
1115 TargetOpcode::G_FDIV,
1116 TargetOpcode::G_STRICT_FDIV,
1117 TargetOpcode::G_SREM,
1118 TargetOpcode::G_UREM,
1119 TargetOpcode::G_FREM,
1120 TargetOpcode::G_STRICT_FREM,
1121 TargetOpcode::G_FNEG,
1122 TargetOpcode::G_CONSTANT,
1123 TargetOpcode::G_FCONSTANT,
1124 TargetOpcode::G_AND,
1125 TargetOpcode::G_OR,
1126 TargetOpcode::G_XOR,
1127 TargetOpcode::G_SHL,
1128 TargetOpcode::G_ASHR,
1129 TargetOpcode::G_LSHR,
1130 TargetOpcode::G_SELECT,
1131 TargetOpcode::G_EXTRACT_VECTOR_ELT,
1132 };
1133 // clang-format on
1134 return TypeFoldingSupportingOpcs;
1135}
1136
1137bool isTypeFoldingSupported(unsigned Opcode) {
1138 return getTypeFoldingSupportedOpcodes().count(Opcode) > 0;
1139}
1140
1141// Traversing [g]MIR accounting for pseudo-instructions.
1143 return (Def->getOpcode() == SPIRV::ASSIGN_TYPE ||
1144 Def->getOpcode() == TargetOpcode::COPY)
1145 ? MRI->getVRegDef(Def->getOperand(1).getReg())
1146 : Def;
1147}
1148
1150 if (MachineInstr *Def = MRI->getVRegDef(MO.getReg()))
1151 return passCopy(Def, MRI);
1152 return nullptr;
1153}
1154
1156 if (MachineInstr *Def = getDef(MO, MRI)) {
1157 if (Def->getOpcode() == TargetOpcode::G_CONSTANT ||
1158 Def->getOpcode() == SPIRV::OpConstantI)
1159 return Def;
1160 }
1161 return nullptr;
1162}
1163
1164int64_t foldImm(const MachineOperand &MO, const MachineRegisterInfo *MRI) {
1165 if (MachineInstr *Def = getImm(MO, MRI)) {
1166 if (Def->getOpcode() == SPIRV::OpConstantI)
1167 return Def->getOperand(2).getImm();
1168 if (Def->getOpcode() == TargetOpcode::G_CONSTANT)
1169 return Def->getOperand(1).getCImm()->getZExtValue();
1170 }
1171 llvm_unreachable("Unexpected integer constant pattern");
1172}
1173
1175 const MachineInstr *ResType) {
1176 return foldImm(ResType->getOperand(2), MRI);
1177}
1178
1179bool matchPeeledArrayPattern(const StructType *Ty, Type *&OriginalElementType,
1180 uint64_t &TotalSize) {
1181 // An array of N padded structs is represented as {[N-1 x <{T, pad}>], T}.
1182 if (Ty->getStructNumElements() != 2)
1183 return false;
1184
1185 Type *FirstElement = Ty->getStructElementType(0);
1186 Type *SecondElement = Ty->getStructElementType(1);
1187
1188 if (!FirstElement->isArrayTy())
1189 return false;
1190
1191 Type *ArrayElementType = FirstElement->getArrayElementType();
1192 if (!ArrayElementType->isStructTy() ||
1193 ArrayElementType->getStructNumElements() != 2)
1194 return false;
1195
1196 Type *T_in_struct = ArrayElementType->getStructElementType(0);
1197 if (T_in_struct != SecondElement)
1198 return false;
1199
1200 auto *Padding_in_struct =
1201 dyn_cast<TargetExtType>(ArrayElementType->getStructElementType(1));
1202 if (!Padding_in_struct || Padding_in_struct->getName() != "spirv.Padding")
1203 return false;
1204
1205 const uint64_t ArraySize = FirstElement->getArrayNumElements();
1206 TotalSize = ArraySize + 1;
1207 OriginalElementType = ArrayElementType;
1208 return true;
1209}
1210
1212 if (!Ty->isStructTy())
1213 return Ty;
1214
1215 auto *STy = cast<StructType>(Ty);
1216 Type *OriginalElementType = nullptr;
1217 uint64_t TotalSize = 0;
1218 if (matchPeeledArrayPattern(STy, OriginalElementType, TotalSize)) {
1219 Type *ResultTy = ArrayType::get(
1220 reconstitutePeeledArrayType(OriginalElementType), TotalSize);
1221 return ResultTy;
1222 }
1223
1224 SmallVector<Type *, 4> NewElementTypes;
1225 bool Changed = false;
1226 for (Type *ElementTy : STy->elements()) {
1227 Type *NewElementTy = reconstitutePeeledArrayType(ElementTy);
1228 if (NewElementTy != ElementTy)
1229 Changed = true;
1230 NewElementTypes.push_back(NewElementTy);
1231 }
1232
1233 if (!Changed)
1234 return Ty;
1235
1236 Type *ResultTy;
1237 if (STy->isLiteral()) {
1238 ResultTy =
1239 StructType::get(STy->getContext(), NewElementTypes, STy->isPacked());
1240 } else {
1241 ResultTy = StructType::create(STy->getContext(), NewElementTypes,
1242 STy->getName(), STy->isPacked());
1243 }
1244 return ResultTy;
1245}
1246
1247std::optional<SPIRV::LinkageType::LinkageType>
1249 if (GV.hasLocalLinkage())
1250 return std::nullopt;
1251
1252 if (GV.isDeclarationForLinker()) {
1253 if (const auto *GVar = dyn_cast<GlobalVariable>(&GV)) {
1254 auto SC = addressSpaceToStorageClass(GVar->getAddressSpace(), ST);
1255 // Interface variables must not get Import linkage.
1256 if (SC == SPIRV::StorageClass::Input ||
1257 SC == SPIRV::StorageClass::Output ||
1258 SC == SPIRV::StorageClass::PushConstant)
1259 return std::nullopt;
1260 // Shaders have no linker, so module-internal storage
1261 // (e.g. HLSL groupshared) can't be imported
1262 if (ST.isShader() && (SC == SPIRV::StorageClass::Workgroup ||
1263 SC == SPIRV::StorageClass::Private))
1264 return std::nullopt;
1265 }
1266 return SPIRV::LinkageType::Import;
1267 }
1268
1269 if (GV.hasHiddenVisibility())
1270 return std::nullopt;
1271
1272 if (GV.hasLinkOnceODRLinkage() &&
1273 ST.canUseExtension(SPIRV::Extension::SPV_KHR_linkonce_odr))
1274 return SPIRV::LinkageType::LinkOnceODR;
1275
1276 if (GV.hasWeakLinkage() &&
1277 ST.canUseExtension(SPIRV::Extension::SPV_AMD_weak_linkage))
1278 return SPIRV::LinkageType::WeakAMD;
1279
1280 return SPIRV::LinkageType::Export;
1281}
1282
1284 std::string ServiceFunName = SPIRV_BACKEND_SERVICE_FUN_NAME;
1285 if (!getVacantFunctionName(M, ServiceFunName))
1287 "cannot allocate a name for the internal service function");
1288 if (Function *SF = M.getFunction(ServiceFunName)) {
1289 if (SF->getInstructionCount() > 0)
1291 "Unexpected combination of global variables and function pointers");
1292 return SF;
1293 }
1295 FunctionType::get(Type::getVoidTy(M.getContext()), {}, false),
1296 GlobalValue::PrivateLinkage, ServiceFunName, M);
1298 return SF;
1299}
1300
1301} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
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
This file declares the MachineIRBuilder class.
Register Reg
Type::TypeID TypeID
#define T
uint64_t IntrinsicInst * II
#define P(N)
MachineRegisterInfo & MRI
#define SPIRV_BACKEND_SERVICE_FUN_NAME
Definition SPIRVUtils.h:561
This file contains some templates that are useful if you are working with the STL at all.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
const Instruction & front() const
Definition BasicBlock.h:462
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Value * getCalledOperand() const
FunctionType * getFunctionType() const
This class represents a function call, abstracting a target machine's calling convention.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
unsigned size() const
Definition DenseMap.h:717
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Class to represent function types.
ArrayRef< Type * > params() const
bool isVarArg() const
Type * getReturnType() const
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:641
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
const Function & getFunction() const
Definition Function.h:167
bool hasLocalLinkage() const
bool hasHiddenVisibility() const
bool isDeclarationForLinker() const
bool hasWeakLinkage() const
bool hasLinkOnceODRLinkage() const
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
void addOperand(const MCOperand Op)
Definition MCInst.h:214
static MCOperand createImm(int64_t Val)
Definition MCInst.h:144
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
A single uniqued string.
Definition Metadata.h:734
MachineInstrBundleIterator< MachineInstr > iterator
const MachineBasicBlock & front() const
Helper class to build MachineInstr.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineFunction & getMF()
Getter for the function we currently build.
MachineRegisterInfo * getMRI()
Getter for MRI.
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.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
void setAsmPrinterFlag(AsmPrinterFlagTy Flag)
Set a flag for the AsmPrinter.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
Definition Module.cpp:320
A tuple of MDNodes.
Definition Metadata.h:1806
op_iterator op_end()
Definition Metadata.h:1895
iterator_range< op_iterator > operands()
Definition Metadata.h:1902
size_t GetNodeRank(BasicBlock *BB) const
void partialOrderVisit(BasicBlock &Start, std::function< bool(BasicBlock *)> Op)
bool compare(const BasicBlock *LHS, const BasicBlock *RHS) const
Wrapper class representing virtual and physical registers.
Definition Register.h:20
void assignSPIRVTypeToVReg(SPIRVTypeInst Type, Register VReg, const MachineFunction &MF)
const TargetRegisterClass * getRegClass(SPIRVTypeInst SpvType) const
SPIRVTypeInst getOrCreateSPIRVIntegerType(unsigned BitWidth, MachineIRBuilder &MIRBuilder)
LLT getRegType(SPIRVTypeInst SpvType) const
SPIRVTypeInst getOrCreateSPIRVType(const Type *Type, MachineInstr &I, SPIRV::AccessQualifier::AccessQualifier AQ, bool EmitIR)
Register buildConstantInt(uint64_t Val, MachineIRBuilder &MIRBuilder, SPIRVTypeInst SpvType, bool EmitIR, bool ZeroAsNull=true)
bool canUseExtension(SPIRV::Extension::Extension E) const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:462
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:657
Class to represent target extensions types, which are generally unintrospectable from target-independ...
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:274
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
Type * getArrayElementType() const
Definition Type.h:427
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:293
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:272
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:271
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
Definition Type.cpp:269
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
static StringRef extractAsmConstraintsFromMetadata(NamedMDNode *NMD, StringRef Constraints, StringRef Name)
bool isPipeOrAddressSpaceCastBuiltin(StringRef Name)
Returns true if Name is a pipe or address-space-cast OpenCL builtin.
static MDNode * findNamedMDOperand(NamedMDNode *NMD, StringRef Name)
FunctionType * getOriginalFunctionType(const Function &F)
static std::optional< StringRef > getMutatedCallsiteKey(const CallBase &CB)
static FunctionType * extractFunctionTypeFromMetadata(NamedMDNode *NMD, FunctionType *FTy, StringRef Name)
StringRef getOriginalAsmConstraints(const CallBase &CB)
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition LLVMContext.h:63
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:66
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:695
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:708
This is an optimization pass for GlobalISel generic memory operations.
std::string getStringImm(const MachineInstr &MI, unsigned StartIndex)
void addStringImm(StringRef Str, MCInst &Inst)
MachineBasicBlock::iterator getOpVariableMBBIt(MachineFunction &MF)
bool isTypedPointerWrapper(const TargetExtType *ExtTy)
Definition SPIRVUtils.h:417
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AtomicScope
Target-neutral memory synchronization scopes.
Definition AtomicScope.h:23
bool isTypeFoldingSupported(unsigned Opcode)
uint32_t getMemSemanticsWithStorageClass(const Triple &TT, uint32_t OrderSem, uint32_t StorageClassSem)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
MachineInstr * getDef(const MachineOperand &MO, const MachineRegisterInfo *MRI)
void addNumImm(const APInt &Imm, MachineInstrBuilder &MIB)
auto successors(const MachineBasicBlock *BB)
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)
Register createVirtualRegister(SPIRVTypeInst SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
unsigned getArrayComponentCount(const MachineRegisterInfo *MRI, const MachineInstr *ResType)
bool sortBlocks(Function &F)
AllocaInst * createVariable(Function &F, Type *Type)
static bool getVacantFunctionName(Module &M, std::string &Name)
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, ArrayRef< uint32_t > DecArgs, StringRef StrImm)
SPIRV::Scope::Scope getMemScope(const Triple &TT, LLVMContext &Ctx, SyncScope::ID Id)
uint64_t getIConstVal(Register ConstReg, const MachineRegisterInfo *MRI)
SmallVector< MachineInstr *, 4 > createContinuedInstructions(MachineIRBuilder &MIRBuilder, unsigned Opcode, unsigned MinWC, unsigned ContinuedOpcode, ArrayRef< Register > Args, Register ReturnRegister, Register TypeID)
SPIRV::MemorySemantics::MemorySemantics getMemSemanticsForStorageClass(SPIRV::StorageClass::StorageClass SC)
bool isVectorType(SPIRVTypeInst SPVTy)
bool isNestedPointer(const Type *Ty)
Function * getOrCreateBackendServiceFunction(Module &M)
MetadataAsValue * buildMD(Value *Arg)
Definition SPIRVUtils.h:549
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
void buildOpName(Register Target, StringRef Name, MachineIRBuilder &MIRBuilder)
static void finishBuildOpDecorate(MachineInstrBuilder &MIB, ArrayRef< uint32_t > DecArgs, StringRef StrImm)
SmallVector< unsigned, 1 > getSpirvLoopControlOperandsFromLoopMetadata(MDNode *LoopMD)
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
static uint32_t convertCharsToWord(StringRef Str, unsigned i)
@ Force
Turn off window algorithm.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
std::string getSPIRVStringOperand(const InstType &MI, unsigned StartIndex)
Type * toTypedPointer(Type *Ty)
Definition SPIRVUtils.h:472
ConstantInt * getMDOperandAsConstInt(const MDNode *N, unsigned I)
DEMANGLE_ABI char * itaniumDemangle(std::string_view mangled_name, bool ParseParams=true)
Returns a non-NULL pointer to a NUL-terminated C style string that should be explicitly freed,...
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
bool isSpecialOpaqueType(const Type *Ty)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
void setRegClassType(Register Reg, SPIRVTypeInst SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF, bool Force)
MachineBasicBlock::iterator getInsertPtValidEnd(MachineBasicBlock *MBB)
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
static bool isNonMangledOCLBuiltin(StringRef Name)
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
MachineInstr * passCopy(MachineInstr *Def, const MachineRegisterInfo *MRI)
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
std::optional< SPIRV::LinkageType::LinkageType > getSpirvLinkageTypeFor(const SPIRVSubtarget &ST, const GlobalValue &GV)
bool isEntryPoint(const Function &F)
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
const std::set< unsigned > & getTypeFoldingSupportedOpcodes()
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
AtomicOrdering
Atomic ordering for LLVM's memory model.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
static bool isEnqueueKernelBI(StringRef MangledName)
static bool isKernelQueryBI(StringRef MangledName)
void buildOpSpirvDecorations(Register Reg, MachineIRBuilder &MIRBuilder, const MDNode *GVarMD, const SPIRVSubtarget &ST)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
int64_t foldImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
Type * parseBasicTypeName(StringRef &TypeName, LLVMContext &Ctx)
DWARFExpression::Operation Op
MachineInstr * getDefInstrMaybeConstant(Register &ConstReg, const MachineRegisterInfo *MRI)
Value * createExitVariable(BasicBlock *BB, const DenseMap< BasicBlock *, ConstantInt * > &TargetToValue)
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)
Type * getMDOperandAsType(const MDNode *N, unsigned I)
void buildOpMemberDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, uint32_t Member, ArrayRef< uint32_t > DecArgs, StringRef StrImm)
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
std::optional< StringRef > getAtomicScopeIRString(const Triple &T, AtomicScope S, bool IsSingleAddressSpace=false)
Returns the LLVM IR syncscope string that T uses to spell S.
Definition AtomicScope.h:34
auto predecessors(const MachineBasicBlock *BB)
static size_t getPaddedLen(StringRef Str)
bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID)
MachineInstr * getVRegDef(MachineRegisterInfo &MRI, Register Reg)
Type * reconstitutePeeledArrayType(Type *Ty)
SPIRV::MemorySemantics::MemorySemantics getMemSemantics(AtomicOrdering Ord)
LLVM_ABI MDNode * findOptionMDForLoopID(MDNode *LoopID, StringRef Name)
Find and return the loop attribute node for the attribute Name in LoopID.
#define N