LLVM 24.0.0git
SPIRVModuleAnalysis.cpp
Go to the documentation of this file.
1//===- SPIRVModuleAnalysis.cpp - analysis of global instrs & regs - 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// The analysis collects instructions that should be output at the module level
10// and performs the global register numbering.
11//
12// The results of this analysis are used in AsmPrinter to rename registers
13// globally and to output required instructions at the module level.
14//
15//===----------------------------------------------------------------------===//
16
17// TODO: Per LLVM best practices, the report_fatal_error (deprecated) /
18// ReportFatalUsageError calls in this file should be replaced with the
19// Diagnostic infrastructure (e.g. the reportUnsupported function below).
20
21#include "SPIRVModuleAnalysis.h"
24#include "SPIRV.h"
25#include "SPIRVSubtarget.h"
26#include "SPIRVTargetMachine.h"
27#include "SPIRVUtils.h"
28#include "llvm/ADT/STLExtras.h"
35
36using namespace llvm;
37
38#define DEBUG_TYPE "spirv-module-analysis"
39
41
43 "SPIRV module analysis", true, true)
44
46 const Function &Func = MI.getMF()->getFunction();
47 Func.getContext().diagnose(
48 DiagnosticInfoUnsupported(Func, Msg, MI.getDebugLoc()));
49}
50
51// Retrieve an unsigned from an MDNode with a list of them as operands.
52static unsigned getMetadataUInt(MDNode *MdNode, unsigned OpIndex,
53 unsigned DefaultVal = 0) {
54 if (MdNode && OpIndex < MdNode->getNumOperands()) {
55 const auto &Op = MdNode->getOperand(OpIndex);
56 return mdconst::extract<ConstantInt>(Op)->getZExtValue();
57 }
58 return DefaultVal;
59}
60
61// Return true if Cap should be avoided when another option enables the feature.
63 SPIRV::Capability::Capability Cap) {
64 return Cap == (ST.isShader() ? SPIRV::Capability::Kernel
65 : SPIRV::Capability::Shader) ||
66 is_contained(ST.getCLOpts().avoid_capabilities, Cap);
67}
68
70getSymbolicOperandRequirements(SPIRV::OperandCategory::OperandCategory Category,
71 unsigned i, const SPIRVSubtarget &ST,
73 VersionTuple ReqMinVer = getSymbolicOperandMinVersion(Category, i);
74 VersionTuple ReqMaxVer = getSymbolicOperandMaxVersion(Category, i);
75 VersionTuple SPIRVVersion = ST.getSPIRVVersion();
76 bool MinVerOK = SPIRVVersion.empty() || SPIRVVersion >= ReqMinVer;
77 bool MaxVerOK =
78 ReqMaxVer.empty() || SPIRVVersion.empty() || SPIRVVersion <= ReqMaxVer;
79 bool VerOK = MinVerOK && MaxVerOK;
81 ExtensionList ReqExts = getSymbolicOperandExtensions(Category, i);
82 // A met minimum version makes the extension unnecessary.
83 if (VerOK && !ReqMinVer.empty())
84 ReqExts.clear();
85 if (ReqCaps.empty()) {
86 if (ReqExts.empty()) {
87 if (VerOK)
88 return {true, {}, {}, ReqMinVer, ReqMaxVer};
89 return {false, {}, {}, VersionTuple(), VersionTuple()};
90 }
91 } else if (VerOK) {
92 if (ReqCaps.size() == 1) {
93 auto Cap = ReqCaps[0];
94 if (Reqs.isCapabilityAvailable(Cap)) {
96 SPIRV::OperandCategory::CapabilityOperand, Cap));
97 return {true, {Cap}, std::move(ReqExts), ReqMinVer, ReqMaxVer};
98 }
99 } else {
100 // By SPIR-V specification: "If an instruction, enumerant, or other
101 // feature specifies multiple enabling capabilities, only one such
102 // capability needs to be declared to use the feature." However, one
103 // capability may be preferred over another. We use command line
104 // argument(s) and AvoidCapabilities to avoid selection of certain
105 // capabilities if there are other options.
106 CapabilityList UseCaps;
107 for (auto Cap : ReqCaps)
108 if (Reqs.isCapabilityAvailable(Cap))
109 UseCaps.push_back(Cap);
110 for (size_t i = 0, Sz = UseCaps.size(); i < Sz; ++i) {
111 auto Cap = UseCaps[i];
112 if (i == Sz - 1 || !shouldAvoidCapability(ST, Cap)) {
114 SPIRV::OperandCategory::CapabilityOperand, Cap));
115 return {true, {Cap}, std::move(ReqExts), ReqMinVer, ReqMaxVer};
116 }
117 }
118 }
119 }
120 // If there are no capabilities, or we can't satisfy the version or
121 // capability requirements, use the list of extensions (if the subtarget
122 // can handle them all). Without an extension the version must hold. An
123 // extension stands in for an unmet version.
124 if ((!ReqExts.empty() || VerOK) &&
125 llvm::all_of(ReqExts, [&ST](const SPIRV::Extension::Extension &Ext) {
126 return ST.canUseExtension(Ext);
127 })) {
128 if (VerOK)
129 return {true, {}, std::move(ReqExts), ReqMinVer, ReqMaxVer};
130 return {true, {}, std::move(ReqExts), VersionTuple(), VersionTuple()};
131 }
132 return {false, {}, {}, VersionTuple(), VersionTuple()};
133}
134
135void SPIRVModuleAnalysisImpl::setBaseInfo(const Module &M) {
136 MAI.MaxID = 0;
137 for (int i = 0; i < SPIRV::NUM_MODULE_SECTIONS; i++)
138 MAI.MS[i].clear();
139 MAI.RegisterAliasTable.clear();
140 MAI.InstrsToDelete.clear();
141 MAI.MBBNames.clear();
142 MAI.GlobalObjMap.clear();
143 MAI.GlobalVarList.clear();
144 MAI.ExtInstSetMap.clear();
145 MAI.InstrAuxDataRecords.clear();
146 MAI.DebugValueMIs.clear();
147 MAI.Reqs.clear();
148 MAI.Reqs.initAvailableCapabilities(*ST);
149
150 // TODO: determine memory model and source language from the configuratoin.
151 if (auto MemModel = M.getNamedMetadata("spirv.MemoryModel")) {
152 auto MemMD = MemModel->getOperand(0);
153 MAI.Addr = static_cast<SPIRV::AddressingModel::AddressingModel>(
154 getMetadataUInt(MemMD, 0));
155 MAI.Mem =
156 static_cast<SPIRV::MemoryModel::MemoryModel>(getMetadataUInt(MemMD, 1));
157 } else {
158 // TODO: Add support for VulkanMemoryModel.
159 MAI.Mem = ST->isShader() ? SPIRV::MemoryModel::GLSL450
160 : SPIRV::MemoryModel::OpenCL;
161 if (MAI.Mem == SPIRV::MemoryModel::OpenCL) {
162 unsigned PtrSize = ST->getPointerSize();
163 MAI.Addr = PtrSize == 32 ? SPIRV::AddressingModel::Physical32
164 : PtrSize == 64 ? SPIRV::AddressingModel::Physical64
165 : SPIRV::AddressingModel::Logical;
166 } else {
167 // TODO: Add support for PhysicalStorageBufferAddress.
168 MAI.Addr = SPIRV::AddressingModel::Logical;
169 }
170 }
171 // Get the OpenCL version number from metadata.
172 // TODO: support other source languages.
173 if (auto VerNode = M.getNamedMetadata("opencl.ocl.version")) {
174 MAI.SrcLang = SPIRV::SourceLanguage::OpenCL_C;
175 // Construct version literal in accordance with SPIRV-LLVM-Translator.
176 // TODO: support multiple OCL version metadata.
177 assert(VerNode->getNumOperands() > 0 && "Invalid SPIR");
178 auto VersionMD = VerNode->getOperand(0);
179 unsigned MajorNum = getMetadataUInt(VersionMD, 0, 2);
180 unsigned MinorNum = getMetadataUInt(VersionMD, 1);
181 unsigned RevNum = getMetadataUInt(VersionMD, 2);
182 // Prevent Major part of OpenCL version to be 0
183 MAI.SrcLangVersion =
184 (std::max(1U, MajorNum) * 100 + MinorNum) * 1000 + RevNum;
185 // When opencl.cxx.version is also present, validate compatibility
186 // and use C++ for OpenCL as source language with the C++ version.
187 if (auto *CxxVerNode = M.getNamedMetadata("opencl.cxx.version")) {
188 assert(CxxVerNode->getNumOperands() > 0 && "Invalid SPIR");
189 auto *CxxMD = CxxVerNode->getOperand(0);
190 unsigned CxxVer =
191 (getMetadataUInt(CxxMD, 0) * 100 + getMetadataUInt(CxxMD, 1)) * 1000 +
192 getMetadataUInt(CxxMD, 2);
193 if ((MAI.SrcLangVersion == 200000 && CxxVer == 100000) ||
194 (MAI.SrcLangVersion == 300000 && CxxVer == 202100000)) {
195 MAI.SrcLang = SPIRV::SourceLanguage::CPP_for_OpenCL;
196 MAI.SrcLangVersion = CxxVer;
197 } else {
199 "opencl cxx version is not compatible with opencl c version!");
200 }
201 }
202 } else {
203 // If there is no information about OpenCL version we are forced to generate
204 // OpenCL 1.0 by default for the OpenCL environment to avoid puzzling
205 // run-times with Unknown/0.0 version output. For a reference, LLVM-SPIRV
206 // Translator avoids potential issues with run-times in a similar manner.
207 if (!ST->isShader()) {
208 MAI.SrcLang = SPIRV::SourceLanguage::OpenCL_CPP;
209 MAI.SrcLangVersion = 100000;
210 } else {
211 MAI.SrcLang = SPIRV::SourceLanguage::Unknown;
212 MAI.SrcLangVersion = 0;
213 }
214 }
215
216 if (auto ExtNode = M.getNamedMetadata("opencl.used.extensions")) {
217 for (unsigned I = 0, E = ExtNode->getNumOperands(); I != E; ++I) {
218 MDNode *MD = ExtNode->getOperand(I);
219 if (!MD || MD->getNumOperands() == 0)
220 continue;
221 for (unsigned J = 0, N = MD->getNumOperands(); J != N; ++J)
222 MAI.SrcExt.insert(cast<MDString>(MD->getOperand(J))->getString());
223 }
224 }
225
226 // Update required capabilities for this memory model, addressing model and
227 // source language.
228 MAI.Reqs.getAndAddRequirements(SPIRV::OperandCategory::MemoryModelOperand,
229 MAI.Mem, *ST);
230 MAI.Reqs.getAndAddRequirements(SPIRV::OperandCategory::SourceLanguageOperand,
231 MAI.SrcLang, *ST);
232 MAI.Reqs.getAndAddRequirements(SPIRV::OperandCategory::AddressingModelOperand,
233 MAI.Addr, *ST);
234
235 if (MAI.Mem == SPIRV::MemoryModel::VulkanKHR)
236 MAI.Reqs.addExtension(SPIRV::Extension::SPV_KHR_vulkan_memory_model);
237
238 if (!ST->isShader()) {
239 // TODO: check if it's required by default.
240 MAI.ExtInstSetMap[static_cast<unsigned>(
241 SPIRV::InstructionSet::OpenCL_std)] = MAI.getNextIDRegister();
242 }
243}
244
245// Appends the signature of the decoration instructions that decorate R to
246// Signature.
248 InstrSignature &Signature) {
249 for (MachineInstr &UseMI : MRI.use_instructions(R)) {
250 // We don't handle OpDecorateId because getting the register alias for the
251 // ID can cause problems, and we do not need it for now.
252 if (UseMI.getOpcode() != SPIRV::OpDecorate &&
253 UseMI.getOpcode() != SPIRV::OpMemberDecorate)
254 continue;
255
256 for (unsigned I = 0; I < UseMI.getNumOperands(); ++I) {
257 const MachineOperand &MO = UseMI.getOperand(I);
258 if (MO.isReg())
259 continue;
260 Signature.push_back(hash_value(MO));
261 }
262 }
263}
264
265// Returns a representation of an instruction as a vector of MachineOperand
266// hash values, see llvm::hash_value(const MachineOperand &MO) for details.
267// This creates a signature of the instruction with the same content
268// that MachineOperand::isIdenticalTo uses for comparison.
271 bool UseDefReg) {
272 Register DefReg;
273 InstrSignature Signature{MI.getOpcode()};
274 for (unsigned i = 0; i < MI.getNumOperands(); ++i) {
275 // The only decorations that can be applied more than once to a given <id>
276 // or structure member are FuncParamAttr (38), UserSemantic (5635),
277 // CacheControlLoadINTEL (6442), and CacheControlStoreINTEL (6443). For all
278 // the rest of decorations, we will only add to the signature the Opcode,
279 // the id to which it applies, and the decoration id, disregarding any
280 // decoration flags. This will ensure that any subsequent decoration with
281 // the same id will be deemed as a duplicate. Then, at the call site, we
282 // will be able to handle duplicates in the best way.
283 unsigned Opcode = MI.getOpcode();
284 if ((Opcode == SPIRV::OpDecorate) && i >= 2) {
285 unsigned DecorationID = MI.getOperand(1).getImm();
286 if (DecorationID != SPIRV::Decoration::FuncParamAttr &&
287 DecorationID != SPIRV::Decoration::UserSemantic &&
288 DecorationID != SPIRV::Decoration::CacheControlLoadINTEL &&
289 DecorationID != SPIRV::Decoration::CacheControlStoreINTEL)
290 continue;
291 }
292 const MachineOperand &MO = MI.getOperand(i);
293 size_t h;
294 if (MO.isReg()) {
295 if (!UseDefReg && MO.isDef()) {
296 assert(!DefReg.isValid() && "Multiple def registers.");
297 DefReg = MO.getReg();
298 continue;
299 }
300 Register RegAlias = MAI.getRegisterAlias(MI.getMF(), MO.getReg());
301 if (!RegAlias.isValid()) {
302 LLVM_DEBUG({
303 dbgs() << "Unexpectedly, no global id found for the operand ";
304 MO.print(dbgs());
305 dbgs() << "\nInstruction: ";
306 MI.print(dbgs());
307 dbgs() << "\n";
308 });
309 report_fatal_error("All v-regs must have been mapped to global id's");
310 }
311 // mimic llvm::hash_value(const MachineOperand &MO)
312 h = hash_combine(MO.getType(), (unsigned)RegAlias, MO.getSubReg(),
313 MO.isDef());
314 } else {
315 h = hash_value(MO);
316 }
317 Signature.push_back(h);
318 }
319
320 if (DefReg.isValid()) {
321 // Decorations change the semantics of the current instruction. So two
322 // identical instruction with different decorations cannot be merged. That
323 // is why we add the decorations to the signature.
324 appendDecorationsForReg(MI.getMF()->getRegInfo(), DefReg, Signature);
325 }
326 return Signature;
327}
328
329// Operand index of Invoke in device enqueue instructions, 0 if none.
330static unsigned getInvokeOperandIdx(unsigned Opcode) {
331 switch (Opcode) {
332 case SPIRV::OpEnqueueKernel:
333 return 8;
334 case SPIRV::OpGetKernelNDrangeSubGroupCount:
335 case SPIRV::OpGetKernelNDrangeMaxSubGroupSize:
336 return 3;
337 case SPIRV::OpGetKernelWorkGroupSize:
338 case SPIRV::OpGetKernelPreferredWorkGroupSizeMultiple:
339 return 2;
340 default:
341 return 0;
342 }
343}
344
345bool SPIRVModuleAnalysisImpl::isDeclSection(const MachineRegisterInfo &MRI,
346 const MachineInstr &MI) {
347 unsigned Opcode = MI.getOpcode();
348 switch (Opcode) {
349 case SPIRV::OpTypeForwardPointer:
350 // omit now, collect later
351 return false;
352 case SPIRV::OpVariable:
353 case SPIRV::OpUntypedVariableKHR:
354 return static_cast<SPIRV::StorageClass::StorageClass>(
355 MI.getOperand(2).getImm()) != SPIRV::StorageClass::Function;
356 case SPIRV::OpFunction:
357 case SPIRV::OpFunctionParameter:
358 return true;
359 }
360 if (GR->hasConstFunPtr() && Opcode == SPIRV::OpUndef) {
361 // The OpUndef may be a placeholder for a function reference recorded by
362 // selectGlobalValue. Skip emitting it if any user consumes it as a
363 // function-pointer-like operand (OpConstantFunctionPointerINTEL operand 2,
364 // or the Invoke operand of a device enqueue instruction). The rewrite
365 // happens in visitFunPtrUse, which aliases the OpUndef's vreg to the
366 // function's global <id>.
367 Register DefReg = MI.getOperand(0).getReg();
368 if (GR->getFunctionDefinitionByUse(&MI.getOperand(0))) {
369 for (MachineInstr &UseMI : MRI.use_instructions(DefReg)) {
370 unsigned UseOp = UseMI.getOpcode();
371 if (UseOp == SPIRV::OpConstantFunctionPointerINTEL ||
372 getInvokeOperandIdx(UseOp)) {
373 MAI.setSkipEmission(&MI);
374 return false;
375 }
376 }
377 }
378 for (MachineInstr &UseMI : MRI.use_instructions(DefReg)) {
379 if (UseMI.getOpcode() != SPIRV::OpConstantFunctionPointerINTEL)
380 continue;
381 // it's a dummy definition, FP constant refers to a function,
382 // and this is resolved in another way; let's skip this definition
383 assert(UseMI.getOperand(2).isReg() &&
384 UseMI.getOperand(2).getReg() == DefReg);
385 MAI.setSkipEmission(&MI);
386 return false;
387 }
388 }
389 return TII->isTypeDeclInstr(MI) || TII->isConstantInstr(MI) ||
390 TII->isInlineAsmDefInstr(MI);
391}
392
393// This is a special case of a function pointer referring to a possibly
394// forward function declaration. The operand is a dummy OpUndef that
395// requires a special treatment.
396// FunPtrOp is the MachineOperand previously recorded via
397// SPIRVGlobalRegistry::recordFunctionPointer, identifying which Function
398// this placeholder refers to.
399void SPIRVModuleAnalysisImpl::visitFunPtrUse(
400 Register OpReg, const MachineOperand *FunPtrOp,
401 InstrGRegsMap &SignatureToGReg,
402 std::map<const Value *, MCRegister> &GlobalToGReg,
403 const MachineFunction *MF) {
404 const MachineOperand *OpFunDef = GR->getFunctionDefinitionByUse(FunPtrOp);
405 assert(OpFunDef && OpFunDef->isReg());
406 // find the actual function definition and number it globally in advance
407 const MachineInstr *OpDefMI = OpFunDef->getParent();
408 assert(OpDefMI && OpDefMI->getOpcode() == SPIRV::OpFunction);
409 const MachineFunction *FunDefMF = OpDefMI->getParent()->getParent();
410 const MachineRegisterInfo &FunDefMRI = FunDefMF->getRegInfo();
411 do {
412 visitDecl(FunDefMRI, SignatureToGReg, GlobalToGReg, FunDefMF, *OpDefMI);
413 OpDefMI = OpDefMI->getNextNode();
414 } while (OpDefMI && (OpDefMI->getOpcode() == SPIRV::OpFunction ||
415 OpDefMI->getOpcode() == SPIRV::OpFunctionParameter));
416 // associate the function pointer with the newly assigned global number
417 MCRegister GlobalFunDefReg =
418 MAI.getRegisterAlias(FunDefMF, OpFunDef->getReg());
419 assert(GlobalFunDefReg.isValid() &&
420 "Function definition must refer to a global register");
421 MAI.setRegisterAlias(MF, OpReg, GlobalFunDefReg);
422}
423
424// Depth first recursive traversal of dependencies. Repeated visits are guarded
425// by MAI.hasRegisterAlias().
426void SPIRVModuleAnalysisImpl::visitDecl(
427 const MachineRegisterInfo &MRI, InstrGRegsMap &SignatureToGReg,
428 std::map<const Value *, MCRegister> &GlobalToGReg,
429 const MachineFunction *MF, const MachineInstr &MI) {
430 unsigned Opcode = MI.getOpcode();
431
432 // Process each operand of the instruction to resolve dependencies
433 for (const MachineOperand &MO : MI.operands()) {
434 if (!MO.isReg() || MO.isDef())
435 continue;
436 Register OpReg = MO.getReg();
437 // Handle function pointers special case
438 if (Opcode == SPIRV::OpConstantFunctionPointerINTEL &&
439 MRI.getRegClass(OpReg) == &SPIRV::pIDRegClass) {
440 visitFunPtrUse(OpReg, &MI.getOperand(2), SignatureToGReg, GlobalToGReg,
441 MF);
442 continue;
443 }
444 // Skip already processed instructions
445 if (MAI.hasRegisterAlias(MF, MO.getReg()))
446 continue;
447 // Recursively visit dependencies
448 if (const MachineInstr *OpDefMI = MRI.getUniqueVRegDef(OpReg)) {
449 if (isDeclSection(MRI, *OpDefMI))
450 visitDecl(MRI, SignatureToGReg, GlobalToGReg, MF, *OpDefMI);
451 continue;
452 }
453 // Handle the unexpected case of no unique definition for the SPIR-V
454 // instruction
455 LLVM_DEBUG({
456 dbgs() << "Unexpectedly, no unique definition for the operand ";
457 MO.print(dbgs());
458 dbgs() << "\nInstruction: ";
459 MI.print(dbgs());
460 dbgs() << "\n";
461 });
463 "No unique definition is found for the virtual register");
464 }
465
466 MCRegister GReg;
467 bool IsFunDef = false;
468 if (TII->isSpecConstantInstr(MI)) {
469 GReg = MAI.getNextIDRegister();
470 MAI.MS[SPIRV::MB_TypeConstVars].push_back(&MI);
471 } else if (Opcode == SPIRV::OpFunction ||
472 Opcode == SPIRV::OpFunctionParameter) {
473 GReg = handleFunctionOrParameter(MF, MI, GlobalToGReg, IsFunDef);
474 } else if (Opcode == SPIRV::OpTypeStruct ||
475 Opcode == SPIRV::OpConstantComposite) {
476 GReg = handleTypeDeclOrConstant(MI, SignatureToGReg);
477 const MachineInstr *NextInstr = MI.getNextNode();
478 while (NextInstr &&
479 ((Opcode == SPIRV::OpTypeStruct &&
480 NextInstr->getOpcode() == SPIRV::OpTypeStructContinuedINTEL) ||
481 (Opcode == SPIRV::OpConstantComposite &&
482 NextInstr->getOpcode() ==
483 SPIRV::OpConstantCompositeContinuedINTEL))) {
484 MCRegister Tmp = handleTypeDeclOrConstant(*NextInstr, SignatureToGReg);
485 MAI.setRegisterAlias(MF, NextInstr->getOperand(0).getReg(), Tmp);
486 MAI.setSkipEmission(NextInstr);
487 NextInstr = NextInstr->getNextNode();
488 }
489 } else if (TII->isTypeDeclInstr(MI) || TII->isConstantInstr(MI) ||
490 TII->isInlineAsmDefInstr(MI)) {
491 GReg = handleTypeDeclOrConstant(MI, SignatureToGReg);
492 } else if (Opcode == SPIRV::OpVariable ||
493 Opcode == SPIRV::OpUntypedVariableKHR) {
494 GReg = handleVariable(MF, MI, GlobalToGReg);
495 } else {
496 LLVM_DEBUG({
497 dbgs() << "\nInstruction: ";
498 MI.print(dbgs());
499 dbgs() << "\n";
500 });
501 llvm_unreachable("Unexpected instruction is visited");
502 }
503 MAI.setRegisterAlias(MF, MI.getOperand(0).getReg(), GReg);
504 if (!IsFunDef)
505 MAI.setSkipEmission(&MI);
506}
507
508MCRegister SPIRVModuleAnalysisImpl::handleFunctionOrParameter(
509 const MachineFunction *MF, const MachineInstr &MI,
510 std::map<const Value *, MCRegister> &GlobalToGReg, bool &IsFunDef) {
511 const Value *GObj = GR->getGlobalObject(MF, MI.getOperand(0).getReg());
512 assert(GObj && "Unregistered global definition");
513 const Function *F = dyn_cast<Function>(GObj);
514 if (!F)
515 F = dyn_cast<Argument>(GObj)->getParent();
516 assert(F && "Expected a reference to a function or an argument");
517 IsFunDef = !F->isDeclaration();
518 auto [It, Inserted] = GlobalToGReg.try_emplace(GObj);
519 if (!Inserted)
520 return It->second;
521 MCRegister GReg = MAI.getNextIDRegister();
522 It->second = GReg;
523 if (!IsFunDef)
524 MAI.MS[SPIRV::MB_ExtFuncDecls].push_back(&MI);
525 return GReg;
526}
527
528MCRegister SPIRVModuleAnalysisImpl::handleTypeDeclOrConstant(
529 const MachineInstr &MI, InstrGRegsMap &SignatureToGReg) {
530 InstrSignature MISign = instrToSignature(MI, MAI, false);
531 auto [It, Inserted] = SignatureToGReg.try_emplace(MISign);
532 if (!Inserted)
533 return It->second;
534 MCRegister GReg = MAI.getNextIDRegister();
535 It->second = GReg;
536 MAI.MS[SPIRV::MB_TypeConstVars].push_back(&MI);
537 return GReg;
538}
539
540MCRegister SPIRVModuleAnalysisImpl::handleVariable(
541 const MachineFunction *MF, const MachineInstr &MI,
542 std::map<const Value *, MCRegister> &GlobalToGReg) {
543 MAI.GlobalVarList.push_back(&MI);
544 const Value *GObj = GR->getGlobalObject(MF, MI.getOperand(0).getReg());
545 assert(GObj && "Unregistered global definition");
546 auto [It, Inserted] = GlobalToGReg.try_emplace(GObj);
547 if (!Inserted)
548 return It->second;
549 MCRegister GReg = MAI.getNextIDRegister();
550 It->second = GReg;
551 MAI.MS[SPIRV::MB_TypeConstVars].push_back(&MI);
552 if (const auto *GV = dyn_cast<GlobalVariable>(GObj))
553 MAI.GlobalObjMap[GV] = GReg;
554 return GReg;
555}
556
557void SPIRVModuleAnalysisImpl::collectDeclarations(const Module &M) {
558 InstrGRegsMap SignatureToGReg;
559 std::map<const Value *, MCRegister> GlobalToGReg;
560 for (const Function &F : M) {
561 MachineFunction *MF = GetMF(F);
562 if (!MF)
563 continue;
564 const MachineRegisterInfo &MRI = MF->getRegInfo();
565 unsigned PastHeader = 0;
566 for (MachineBasicBlock &MBB : *MF) {
567 for (MachineInstr &MI : MBB) {
568 if (MI.getNumOperands() == 0)
569 continue;
570 unsigned Opcode = MI.getOpcode();
571 if (Opcode == SPIRV::OpFunction) {
572 if (PastHeader == 0) {
573 PastHeader = 1;
574 continue;
575 }
576 } else if (Opcode == SPIRV::OpFunctionParameter) {
577 if (PastHeader < 2)
578 continue;
579 } else if (PastHeader > 0) {
580 PastHeader = 2;
581 }
582
583 const MachineOperand &DefMO = MI.getOperand(0);
584 switch (Opcode) {
585 case SPIRV::OpExtension:
586 MAI.Reqs.addExtension(SPIRV::Extension::Extension(DefMO.getImm()));
587 MAI.setSkipEmission(&MI);
588 break;
589 case SPIRV::OpCapability:
590 MAI.Reqs.addCapability(SPIRV::Capability::Capability(DefMO.getImm()));
591 MAI.setSkipEmission(&MI);
592 if (PastHeader > 0)
593 PastHeader = 2;
594 break;
595 default:
596 if (DefMO.isReg() && isDeclSection(MRI, MI) &&
597 !MAI.hasRegisterAlias(MF, DefMO.getReg()))
598 visitDecl(MRI, SignatureToGReg, GlobalToGReg, MF, MI);
599 // Device enqueue instructions are not decls, but their Invoke
600 // operand may be a function-pointer placeholder OpUndef. Resolve it
601 // to the OpFunction's global <id> via visitFunPtrUse.
602 if (unsigned InvokeIdx = getInvokeOperandIdx(Opcode)) {
603 const MachineOperand &InvokeMO = MI.getOperand(InvokeIdx);
604 if (InvokeMO.isReg()) {
605 Register InvokeReg = InvokeMO.getReg();
606 if (!MAI.hasRegisterAlias(MF, InvokeReg)) {
607 if (const MachineInstr *DefMI =
608 MRI.getUniqueVRegDef(InvokeReg)) {
609 if (DefMI->getOpcode() == SPIRV::OpUndef) {
610 const MachineOperand *FunPtrOp = &DefMI->getOperand(0);
611 if (GR->getFunctionDefinitionByUse(FunPtrOp))
612 visitFunPtrUse(InvokeReg, FunPtrOp, SignatureToGReg,
613 GlobalToGReg, MF);
614 }
615 }
616 }
617 }
618 }
619 }
620 }
621 }
622 }
623}
624
625// Look for IDs declared with Import linkage, and map the corresponding function
626// to the register defining that variable (which will usually be the result of
627// an OpFunction). This lets us call externally imported functions using
628// the correct ID registers.
629void SPIRVModuleAnalysisImpl::collectFuncNames(MachineInstr &MI,
630 const Function *F) {
631 if (MI.getOpcode() == SPIRV::OpDecorate) {
632 // If it's got Import linkage.
633 auto Dec = MI.getOperand(1).getImm();
634 if (Dec == SPIRV::Decoration::LinkageAttributes) {
635 auto Lnk = MI.getOperand(MI.getNumOperands() - 1).getImm();
636 if (Lnk == SPIRV::LinkageType::Import) {
637 // Map imported function name to function ID register.
638 const Function *ImportedFunc =
639 F->getParent()->getFunction(getStringImm(MI, 2));
640 Register Target = MI.getOperand(0).getReg();
641 MAI.GlobalObjMap[ImportedFunc] =
642 MAI.getRegisterAlias(MI.getMF(), Target);
643 }
644 }
645 } else if (MI.getOpcode() == SPIRV::OpFunction) {
646 // Record all internal OpFunction declarations.
647 Register Reg = MI.defs().begin()->getReg();
648 MCRegister GlobalReg = MAI.getRegisterAlias(MI.getMF(), Reg);
649 assert(GlobalReg.isValid());
650 MAI.GlobalObjMap[F] = GlobalReg;
651 }
652}
653
654// Collect the given instruction in the specified MS. We assume global register
655// numbering has already occurred by this point. We can directly compare reg
656// arguments when detecting duplicates.
659 bool Append = true) {
660 MAI.setSkipEmission(&MI);
661 InstrSignature MISign = instrToSignature(MI, MAI, true);
662 auto FoundMI = IS.insert(std::move(MISign));
663 if (!FoundMI.second) {
664 if (MI.getOpcode() == SPIRV::OpDecorate) {
665 assert(MI.getNumOperands() >= 2 &&
666 "Decoration instructions must have at least 2 operands");
667 assert(MSType == SPIRV::MB_Annotations &&
668 "Only OpDecorate instructions can be duplicates");
669 // For FPFastMathMode decoration, we need to merge the flags of the
670 // duplicate decoration with the original one, so we need to find the
671 // original instruction that has the same signature. For the rest of
672 // instructions, we will simply skip the duplicate.
673 if (MI.getOperand(1).getImm() != SPIRV::Decoration::FPFastMathMode)
674 return; // Skip duplicates of other decorations.
675
676 const SPIRV::InstrList &Decorations = MAI.MS[MSType];
677 for (const MachineInstr *OrigMI : Decorations) {
678 if (instrToSignature(*OrigMI, MAI, true) == MISign) {
679 assert(OrigMI->getNumOperands() == MI.getNumOperands() &&
680 "Original instruction must have the same number of operands");
681 assert(
682 OrigMI->getNumOperands() == 3 &&
683 "FPFastMathMode decoration must have 3 operands for OpDecorate");
684 unsigned OrigFlags = OrigMI->getOperand(2).getImm();
685 unsigned NewFlags = MI.getOperand(2).getImm();
686 if (OrigFlags == NewFlags)
687 return; // No need to merge, the flags are the same.
688
689 // Emit warning about possible conflict between flags.
690 unsigned FinalFlags = OrigFlags | NewFlags;
691 llvm::errs()
692 << "Warning: Conflicting FPFastMathMode decoration flags "
693 "in instruction: "
694 << *OrigMI << "Original flags: " << OrigFlags
695 << ", new flags: " << NewFlags
696 << ". They will be merged on a best effort basis, but not "
697 "validated. Final flags: "
698 << FinalFlags << "\n";
699 MachineInstr *OrigMINonConst = const_cast<MachineInstr *>(OrigMI);
700 MachineOperand &OrigFlagsOp = OrigMINonConst->getOperand(2);
701 OrigFlagsOp = MachineOperand::CreateImm(FinalFlags);
702 return; // Merge done, so we found a duplicate; don't add it to MAI.MS
703 }
704 }
705 assert(false && "No original instruction found for the duplicate "
706 "OpDecorate, but we found one in IS.");
707 }
708 return; // insert failed, so we found a duplicate; don't add it to MAI.MS
709 }
710 // No duplicates, so add it.
711 if (Append)
712 MAI.MS[MSType].push_back(&MI);
713 else
714 MAI.MS[MSType].insert(MAI.MS[MSType].begin(), &MI);
715}
716
717// Some global instructions make reference to function-local ID regs, so cannot
718// be correctly collected until these registers are globally numbered.
719void SPIRVModuleAnalysisImpl::processOtherInstrs(const Module &M) {
721 for (const Function &F : M) {
722 if (F.isDeclaration())
723 continue;
724 MachineFunction *MF = GetMF(F);
725 assert(MF);
726
727 for (MachineBasicBlock &MBB : *MF)
728 for (MachineInstr &MI : MBB) {
729 if (MI.isDebugValueLike()) {
730 MAI.DebugValueMIs.push_back(&MI);
731 continue;
732 }
733 if (MAI.getSkipEmission(&MI))
734 continue;
735 const unsigned OpCode = MI.getOpcode();
736 if (OpCode == SPIRV::OpString) {
738 } else if (OpCode == SPIRV::OpExtInst && MI.getOperand(2).isImm() &&
739 MI.getOperand(2).getImm() ==
740 SPIRV::InstructionSet::
741 NonSemantic_Shader_DebugInfo_100) {
742 // TODO: This branch is dead. SPIRVNonSemanticDebugHandler emits NSDI
743 // instructions directly as MCInsts at print time; no
744 // MachineInstructions with the NSDI ext set are created anymore.
745 // Remove this block and
746 // MB_NonSemanticGlobalDI once per-function NSDI emission is confirmed
747 // not to need MIR routing.
748 MachineOperand Ins = MI.getOperand(3);
749 namespace NS = SPIRV::NonSemanticExtInst;
750 static constexpr int64_t GlobalNonSemanticDITy[] = {
751 NS::DebugSource, NS::DebugCompilationUnit, NS::DebugInfoNone,
752 NS::DebugTypeBasic, NS::DebugTypePointer};
753 bool IsGlobalDI = false;
754 for (unsigned Idx = 0; Idx < std::size(GlobalNonSemanticDITy); ++Idx)
755 IsGlobalDI |= Ins.getImm() == GlobalNonSemanticDITy[Idx];
756 if (IsGlobalDI)
758 } else if (OpCode == SPIRV::OpName || OpCode == SPIRV::OpMemberName) {
760 } else if (OpCode == SPIRV::OpEntryPoint) {
762 } else if (TII->isAliasingInstr(MI)) {
764 } else if (TII->isDecorationInstr(MI)) {
765 if (MI.getOpcode() == SPIRV::OpDecorate &&
766 MI.getOperand(1).getImm() ==
767 static_cast<unsigned>(
768 SPIRV::Decoration::AuxDataInstructionMetadata)) {
769 MAI.setSkipEmission(&MI);
770 std::string Str = getStringImm(MI, 2);
772 auto MaybeKind =
773 StringSwitch<std::optional<AMDMD>>(Str)
774 .Case("amdgpu.no.fine.grained.memory",
775 AMDMD::NoFineGrainedMemory)
776 .Case("amdgpu.no.remote.memory", AMDMD::NoRemoteMemory)
777 .Case("atomic.ignore.denormal.mode",
778 AMDMD::IgnoreDenormalMode)
779 .Default(std::nullopt);
780 if (MaybeKind)
781 MAI.InstrAuxDataRecords.push_back(
782 {MF, MI.getOperand(0).getReg(), *MaybeKind});
783 continue;
784 }
786 collectFuncNames(MI, &F);
787 } else if (TII->isConstantInstr(MI)) {
788 // Now OpSpecConstant*s are not in DT,
789 // but they need to be collected anyway.
791 } else if (OpCode == SPIRV::OpFunction) {
792 collectFuncNames(MI, &F);
793 } else if (OpCode == SPIRV::OpTypeForwardPointer) {
795 }
796 }
797 }
798 // Selection order can place a scope/list ahead of a domain/scope it
799 // references. The dependency meanwhile is domain -> scope -> list, so sort
800 // the def before its uses.
801 auto AliasingTier = [](const MachineInstr *MI) {
802 switch (MI->getOpcode()) {
803 case SPIRV::OpAliasDomainDeclINTEL:
804 return 0;
805 case SPIRV::OpAliasScopeDeclINTEL:
806 return 1;
807 case SPIRV::OpAliasScopeListDeclINTEL:
808 return 2;
809 default:
810 llvm_unreachable("unexpected aliasing instruction");
811 }
812 };
814 [&](const MachineInstr *LHS, const MachineInstr *RHS) {
815 return AliasingTier(LHS) < AliasingTier(RHS);
816 });
817}
818
819// Number registers in all functions globally from 0 onwards and store
820// the result in global register alias table. Some registers are already
821// numbered.
822void SPIRVModuleAnalysisImpl::numberRegistersGlobally(const Module &M) {
823 for (const Function &F : M) {
824 if (F.isDeclaration())
825 continue;
826 MachineFunction *MF = GetMF(F);
827 assert(MF);
828 for (MachineBasicBlock &MBB : *MF) {
829 for (MachineInstr &MI : MBB) {
830 for (MachineOperand &Op : MI.operands()) {
831 if (!Op.isReg())
832 continue;
833 Register Reg = Op.getReg();
834 if (MAI.hasRegisterAlias(MF, Reg))
835 continue;
836 MCRegister NewReg = MAI.getNextIDRegister();
837 MAI.setRegisterAlias(MF, Reg, NewReg);
838 }
839 if (MI.getOpcode() != SPIRV::OpExtInst)
840 continue;
841 auto Set = MI.getOperand(2).getImm();
842 auto [It, Inserted] = MAI.ExtInstSetMap.try_emplace(Set);
843 if (Inserted)
844 It->second = MAI.getNextIDRegister();
845 }
846 }
847 }
848}
849
851 const SPIRVSubtarget &ST,
852 StringRef Feature) {
853 if (!ST.isAtLeastSPIRVVer(VersionTuple(1, 3)))
854 report_fatal_error(Twine(Feature) + " requires SPIR-V 1.3", false);
855 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_quad_control))
856 report_fatal_error(Twine(Feature) + " requires the following SPIR-V "
857 "extension: SPV_KHR_quad_control",
858 false);
859 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_maximal_reconvergence))
860 report_fatal_error("SPV_KHR_quad_control requires the following SPIR-V "
861 "extension: SPV_KHR_maximal_reconvergence",
862 false);
863 Reqs.addExtension(SPIRV::Extension::SPV_KHR_quad_control);
864 Reqs.addExtension(SPIRV::Extension::SPV_KHR_maximal_reconvergence);
865}
866
867// RequirementHandler implementations.
869 SPIRV::OperandCategory::OperandCategory Category, uint32_t i,
870 const SPIRVSubtarget &ST) {
871 if (Category == SPIRV::OperandCategory::ExecutionModeOperand &&
872 (i == SPIRV::ExecutionMode::QuadDerivativesKHR ||
873 i == SPIRV::ExecutionMode::RequireFullQuadsKHR))
875 getSymbolicOperandMnemonic(Category, i));
876 if (Category == SPIRV::OperandCategory::ExecutionModeOperand &&
877 (i == SPIRV::ExecutionMode::DerivativeGroupQuadsKHR ||
878 i == SPIRV::ExecutionMode::DerivativeGroupLinearKHR) &&
879 !ST.canUseExtension(SPIRV::Extension::SPV_KHR_compute_shader_derivatives))
881 " requires the following SPIR-V extension: "
882 "SPV_KHR_compute_shader_derivatives",
883 false);
884 addRequirements(getSymbolicOperandRequirements(Category, i, ST, *this));
885}
886
887void SPIRV::RequirementHandler::recursiveAddCapabilities(
888 const CapabilityList &ToPrune) {
889 for (const auto &Cap : ToPrune) {
890 AllCaps.insert(Cap);
891 CapabilityList ImplicitDecls =
892 getSymbolicOperandCapabilities(OperandCategory::CapabilityOperand, Cap);
893 recursiveAddCapabilities(ImplicitDecls);
894 }
895}
896
898 for (const auto &Cap : ToAdd) {
899 bool IsNewlyInserted = AllCaps.insert(Cap).second;
900 if (!IsNewlyInserted) // Don't re-add if it's already been declared.
901 continue;
902 CapabilityList ImplicitDecls =
903 getSymbolicOperandCapabilities(OperandCategory::CapabilityOperand, Cap);
904 recursiveAddCapabilities(ImplicitDecls);
905 MinimalCaps.push_back(Cap);
906 }
907}
908
910 const SPIRV::Requirements &Req) {
911 if (!Req.IsSatisfiable)
912 report_fatal_error("Adding SPIR-V requirements this target can't satisfy.");
913
914 if (Req.Cap.has_value())
915 addCapabilities({Req.Cap.value()});
916
917 addExtensions(Req.Exts);
918
919 if (!Req.MinVer.empty()) {
920 if (!MaxVersion.empty() && Req.MinVer > MaxVersion) {
921 LLVM_DEBUG(dbgs() << "Conflicting version requirements: >= " << Req.MinVer
922 << " and <= " << MaxVersion << "\n");
923 report_fatal_error("Adding SPIR-V requirements that can't be satisfied.");
924 }
925
926 if (MinVersion.empty() || Req.MinVer > MinVersion)
927 MinVersion = Req.MinVer;
928 }
929
930 if (!Req.MaxVer.empty()) {
931 if (!MinVersion.empty() && Req.MaxVer < MinVersion) {
932 LLVM_DEBUG(dbgs() << "Conflicting version requirements: <= " << Req.MaxVer
933 << " and >= " << MinVersion << "\n");
934 report_fatal_error("Adding SPIR-V requirements that can't be satisfied.");
935 }
936
937 if (MaxVersion.empty() || Req.MaxVer < MaxVersion)
938 MaxVersion = Req.MaxVer;
939 }
940}
941
943 const SPIRVSubtarget &ST) const {
944 // Report as many errors as possible before aborting the compilation.
945 bool IsSatisfiable = true;
946 auto TargetVer = ST.getSPIRVVersion();
947
948 if (!MaxVersion.empty() && !TargetVer.empty() && MaxVersion < TargetVer) {
950 dbgs() << "Target SPIR-V version too high for required features\n"
951 << "Required max version: " << MaxVersion << " target version "
952 << TargetVer << "\n");
953 IsSatisfiable = false;
954 }
955
956 if (!MinVersion.empty() && !TargetVer.empty() && MinVersion > TargetVer) {
957 LLVM_DEBUG(dbgs() << "Target SPIR-V version too low for required features\n"
958 << "Required min version: " << MinVersion
959 << " target version " << TargetVer << "\n");
960 IsSatisfiable = false;
961 }
962
963 if (!MinVersion.empty() && !MaxVersion.empty() && MinVersion > MaxVersion) {
965 dbgs()
966 << "Version is too low for some features and too high for others.\n"
967 << "Required SPIR-V min version: " << MinVersion
968 << " required SPIR-V max version " << MaxVersion << "\n");
969 IsSatisfiable = false;
970 }
971
972 for (auto Cap : MinimalCaps) {
973 if (AvailableCaps.contains(Cap) && !shouldAvoidCapability(ST, Cap))
974 continue;
975 LLVM_DEBUG(dbgs() << "Capability not supported: "
977 OperandCategory::CapabilityOperand, Cap)
978 << "\n");
979 IsSatisfiable = false;
980 }
981
982 for (auto Ext : AllExtensions) {
983 if (ST.canUseExtension(Ext))
984 continue;
985 LLVM_DEBUG(dbgs() << "Extension not supported: "
987 OperandCategory::ExtensionOperand, Ext)
988 << "\n");
989 IsSatisfiable = false;
990 }
991
992 if (!IsSatisfiable)
993 report_fatal_error("Unable to meet SPIR-V requirements for this target.");
994}
995
996// Add the given capabilities and all their implicitly defined capabilities too.
998 for (const auto Cap : ToAdd)
999 if (AvailableCaps.insert(Cap).second)
1001 SPIRV::OperandCategory::CapabilityOperand, Cap));
1002}
1003
1005 const Capability::Capability ToRemove,
1006 const Capability::Capability IfPresent) {
1007 if (AllCaps.contains(IfPresent)) {
1008 AllCaps.erase(ToRemove);
1009 llvm::erase(MinimalCaps, ToRemove);
1010 }
1011}
1012
1013namespace llvm {
1014namespace SPIRV {
1016 // Provided by both all supported Vulkan versions and OpenCl.
1017 addAvailableCaps({Capability::Shader, Capability::Linkage, Capability::Int8,
1018 Capability::Int16});
1019
1020 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 3)))
1021 addAvailableCaps({Capability::GroupNonUniform,
1022 Capability::GroupNonUniformVote,
1023 Capability::GroupNonUniformArithmetic,
1024 Capability::GroupNonUniformBallot,
1025 Capability::GroupNonUniformClustered,
1026 Capability::GroupNonUniformShuffle,
1027 Capability::GroupNonUniformShuffleRelative,
1028 Capability::GroupNonUniformQuad});
1029
1030 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 6)))
1031 addAvailableCaps({Capability::DotProduct, Capability::DotProductInputAll,
1032 Capability::DotProductInput4x8Bit,
1033 Capability::DotProductInput4x8BitPacked,
1034 Capability::DemoteToHelperInvocation});
1035
1036 // Add capabilities enabled by extensions.
1037 for (auto Extension : ST.getAllAvailableExtensions()) {
1038 CapabilityList EnabledCapabilities =
1040 addAvailableCaps(EnabledCapabilities);
1041 }
1042
1043 // EXT and NV use the same capability.
1044 if (ST.canUseExtension(Extension::SPV_EXT_shader_subgroup_partitioned))
1045 addAvailableCaps({Capability::GroupNonUniformPartitionedNV});
1046
1047 if (!ST.isShader()) {
1048 initAvailableCapabilitiesForOpenCL(ST);
1049 return;
1050 }
1051
1052 if (ST.isShader()) {
1053 initAvailableCapabilitiesForVulkan(ST);
1054 return;
1055 }
1056
1057 report_fatal_error("Unimplemented environment for SPIR-V generation.");
1058}
1059
1060void RequirementHandler::initAvailableCapabilitiesForOpenCL(
1061 const SPIRVSubtarget &ST) {
1062 // Add the min requirements for different OpenCL and SPIR-V versions.
1063 addAvailableCaps({Capability::Addresses, Capability::Float16Buffer,
1064 Capability::Kernel, Capability::Vector16,
1065 Capability::Groups, Capability::GenericPointer,
1066 Capability::StorageImageWriteWithoutFormat,
1067 Capability::StorageImageReadWithoutFormat});
1068 if (ST.hasOpenCLFullProfile())
1069 addAvailableCaps({Capability::Int64, Capability::Int64Atomics});
1070 if (ST.hasOpenCLImageSupport()) {
1071 addAvailableCaps({Capability::ImageBasic, Capability::LiteralSampler,
1072 Capability::Image1D, Capability::SampledBuffer,
1073 Capability::ImageBuffer});
1074 if (ST.isAtLeastOpenCLVer(VersionTuple(2, 0)))
1075 addAvailableCaps({Capability::ImageReadWrite});
1076 }
1077 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 1)) &&
1078 ST.isAtLeastOpenCLVer(VersionTuple(2, 2)))
1079 addAvailableCaps({Capability::SubgroupDispatch, Capability::PipeStorage});
1080 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 4)))
1081 addAvailableCaps({Capability::DenormPreserve, Capability::DenormFlushToZero,
1082 Capability::SignedZeroInfNanPreserve,
1083 Capability::RoundingModeRTE,
1084 Capability::RoundingModeRTZ});
1085 // TODO: verify if this needs some checks.
1086 addAvailableCaps({Capability::Float16, Capability::Float64});
1087
1088 // TODO: add OpenCL extensions.
1089}
1090
1091void RequirementHandler::initAvailableCapabilitiesForVulkan(
1092 const SPIRVSubtarget &ST) {
1093
1094 // Core in Vulkan 1.1 and earlier.
1095 addAvailableCaps({Capability::Int64,
1096 Capability::Geometry,
1097 Capability::MultiViewport,
1098 Capability::CullDistance,
1099 Capability::Float16,
1100 Capability::Float64,
1101 Capability::GroupNonUniform,
1102 Capability::Image1D,
1103 Capability::SampledBuffer,
1104 Capability::ImageBuffer,
1105 Capability::UniformBufferArrayDynamicIndexing,
1106 Capability::SampledImageArrayDynamicIndexing,
1107 Capability::StorageBufferArrayDynamicIndexing,
1108 Capability::StorageImageArrayDynamicIndexing,
1109 Capability::DerivativeControl,
1110 Capability::SampleRateShading,
1111 Capability::MinLod,
1112 Capability::ImageQuery,
1113 Capability::ImageGatherExtended,
1114 Capability::Addresses,
1115 Capability::VulkanMemoryModelKHR,
1116 Capability::StorageImageExtendedFormats,
1117 Capability::StorageImageMultisample,
1118 Capability::ImageMSArray});
1119
1120 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 3)) ||
1121 ST.canUseExtension(Extension::SPV_KHR_variable_pointers))
1122 addAvailableCaps({Capability::VariablePointersStorageBuffer,
1123 Capability::VariablePointers});
1124
1125 // Became core in Vulkan 1.1.
1126 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 3)))
1127 addAvailableCaps({Capability::DrawParameters, Capability::MultiView});
1128
1129 // Became core in Vulkan 1.2
1130 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 5))) {
1132 {Capability::Int64Atomics, Capability::ShaderLayer,
1133 Capability::ShaderNonUniformEXT, Capability::RuntimeDescriptorArrayEXT,
1134 Capability::InputAttachmentArrayDynamicIndexingEXT,
1135 Capability::UniformTexelBufferArrayDynamicIndexingEXT,
1136 Capability::StorageTexelBufferArrayDynamicIndexingEXT,
1137 Capability::UniformBufferArrayNonUniformIndexingEXT,
1138 Capability::SampledImageArrayNonUniformIndexingEXT,
1139 Capability::StorageBufferArrayNonUniformIndexingEXT,
1140 Capability::StorageImageArrayNonUniformIndexingEXT,
1141 Capability::InputAttachmentArrayNonUniformIndexingEXT,
1142 Capability::UniformTexelBufferArrayNonUniformIndexingEXT,
1143 Capability::StorageTexelBufferArrayNonUniformIndexingEXT});
1144 }
1145
1146 // Became core in Vulkan 1.3
1147 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 6)))
1148 addAvailableCaps({Capability::StorageImageWriteWithoutFormat,
1149 Capability::StorageImageReadWithoutFormat});
1150}
1151
1152} // namespace SPIRV
1153} // namespace llvm
1154
1155// Add a capability that became core in SPIR-V 1.3. Earlier versions require
1156// the extension that introduced it.
1158 const SPIRVSubtarget &ST,
1159 SPIRV::Capability::Capability Cap,
1160 SPIRV::Extension::Extension Ext) {
1161 Reqs.addCapability(Cap);
1162 if (ST.isAtLeastSPIRVVer(VersionTuple(1, 3)))
1163 return;
1164 if (!ST.canUseExtension(Ext))
1166 Twine("capability ") +
1168 SPIRV::OperandCategory::CapabilityOperand, Cap) +
1169 " requires SPIR-V 1.3 or the following SPIR-V extension: " +
1170 getSymbolicOperandMnemonic(SPIRV::OperandCategory::ExtensionOperand,
1171 Ext),
1172 false);
1173 Reqs.addExtension(Ext);
1174}
1175
1176// Returns true if the target of an OpDecorate is an OpFDiv or an OpenCL.std
1177// sqrt extended instruction, i.e. an instruction whose FPRoundingMode
1178// decoration requires SPV_INTEL_rounded_divide_sqrt.
1180 const MachineInstr *Def =
1181 MI.getMF()->getRegInfo().getVRegDef(MI.getOperand(0).getReg());
1182 if (!Def)
1183 return false;
1184 switch (Def->getOpcode()) {
1185 case SPIRV::OpFDivS:
1186 case SPIRV::OpFDivV:
1187 case SPIRV::OpStrictFDivS:
1188 case SPIRV::OpStrictFDivV:
1189 return true;
1190 case SPIRV::OpExtInst:
1191 return Def->getOperand(2).getImm() == SPIRV::InstructionSet::OpenCL_std &&
1192 Def->getOperand(3).getImm() == SPIRV::OpenCLExtInst::sqrt;
1193 default:
1194 return false;
1195 }
1196}
1197
1198// Returns true if the decorated target of \p MI is an Output variable.
1200 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1201 const MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
1202 return Def && Def->getOpcode() == SPIRV::OpVariable &&
1203 static_cast<SPIRV::StorageClass::StorageClass>(
1204 Def->getOperand(2).getImm()) == SPIRV::StorageClass::Output;
1205}
1206
1207// Returns true if the module containing MI has an HLSL vertex, hull or
1208// domain shader entry point. Outputs of these stages need
1209// ShaderViewportIndexLayerEXT (or ShaderLayer for Layer from SPIR-V 1.5) to
1210// write ViewportIndex or Layer, while a geometry shader writes them with the
1211// base MultiViewport or Geometry capability.
1213 return llvm::any_of(
1214 *MI.getMF()->getFunction().getParent(), [](const Function &F) {
1215 Attribute Stage = F.getFnAttribute("hlsl.shader");
1216 if (!Stage.isValid())
1217 return false;
1218 StringRef Name = Stage.getValueAsString();
1219 return Name == "vertex" || Name == "hull" || Name == "domain";
1220 });
1221}
1222
1223// Add the required capabilities from a decoration instruction (including
1224// BuiltIns).
1225static void addOpDecorateReqs(const MachineInstr &MI, unsigned DecIndex,
1227 const SPIRVSubtarget &ST) {
1228 int64_t DecOp = MI.getOperand(DecIndex).getImm();
1229 auto Dec = static_cast<SPIRV::Decoration::Decoration>(DecOp);
1231 SPIRV::OperandCategory::DecorationOperand, Dec, ST, Reqs));
1232
1233 if (Dec == SPIRV::Decoration::BuiltIn) {
1234 int64_t BuiltInOp = MI.getOperand(DecIndex + 1).getImm();
1235 auto BuiltIn = static_cast<SPIRV::BuiltIn::BuiltIn>(BuiltInOp);
1236 if ((BuiltIn == SPIRV::BuiltIn::BaryCoordKHR ||
1237 BuiltIn == SPIRV::BuiltIn::BaryCoordNoPerspKHR) &&
1238 !ST.canUseExtension(
1239 SPIRV::Extension::SPV_KHR_fragment_shader_barycentric))
1241 "Barycentric built-ins require the following SPIR-V extension: "
1242 "SPV_KHR_fragment_shader_barycentric",
1243 false);
1244 if (BuiltIn == SPIRV::BuiltIn::FragStencilRefEXT &&
1245 !ST.canUseExtension(SPIRV::Extension::SPV_EXT_shader_stencil_export))
1247 "FragStencilRefEXT requires the following SPIR-V extension: "
1248 "SPV_EXT_shader_stencil_export",
1249 false);
1250 if (BuiltIn == SPIRV::BuiltIn::DeviceBarrierExecutionValidINTEL &&
1251 !ST.canUseExtension(SPIRV::Extension::SPV_INTEL_device_barrier))
1253 "DeviceBarrierExecutionValidINTEL built-in requires the following "
1254 "SPIR-V extension: SPV_INTEL_device_barrier",
1255 false);
1256 if (BuiltIn == SPIRV::BuiltIn::FullyCoveredEXT &&
1257 !ST.canUseExtension(SPIRV::Extension::SPV_EXT_fragment_fully_covered))
1259 "FullyCoveredEXT requires the following SPIR-V extension: "
1260 "SPV_EXT_fragment_fully_covered",
1261 false);
1262 switch (BuiltIn) {
1263 case SPIRV::BuiltIn::BaseVertex:
1264 case SPIRV::BuiltIn::BaseInstance:
1266 Reqs, ST, SPIRV::Capability::DrawParameters,
1267 SPIRV::Extension::SPV_KHR_shader_draw_parameters);
1268 break;
1269 case SPIRV::BuiltIn::ViewIndex:
1270 addCoreInSPIRV13Capability(Reqs, ST, SPIRV::Capability::MultiView,
1271 SPIRV::Extension::SPV_KHR_multiview);
1272 break;
1273 case SPIRV::BuiltIn::ViewportIndex:
1274 case SPIRV::BuiltIn::Layer:
1275 // Only vertex and tessellation outputs need the extension. Geometry
1276 // outputs and fragment inputs use the base MultiViewport (ViewportIndex)
1277 // or Geometry (Layer) capability.
1280 // SPIR-V 1.5 promoted writing Layer from these stages to the core
1281 // ShaderLayer capability, which does not need the extension.
1282 if (BuiltIn == SPIRV::BuiltIn::Layer &&
1283 ST.isAtLeastSPIRVVer(VersionTuple(1, 5))) {
1284 Reqs.addCapability(SPIRV::Capability::ShaderLayer);
1285 break;
1286 }
1287 if (!ST.canUseExtension(
1288 SPIRV::Extension::SPV_EXT_shader_viewport_index_layer))
1290 "Writing ViewportIndex or Layer requires the following SPIR-V "
1291 "extension: SPV_EXT_shader_viewport_index_layer",
1292 false);
1293 Reqs.addCapability(SPIRV::Capability::ShaderViewportIndexLayerEXT);
1294 Reqs.addExtension(
1295 SPIRV::Extension::SPV_EXT_shader_viewport_index_layer);
1296 break;
1297 }
1299 SPIRV::OperandCategory::BuiltInOperand, BuiltIn, ST, Reqs));
1300 break;
1301 default:
1303 SPIRV::OperandCategory::BuiltInOperand, BuiltIn, ST, Reqs));
1304 break;
1305 }
1306 } else if (Dec == SPIRV::Decoration::LinkageAttributes) {
1307 int64_t LinkageOp = MI.getOperand(MI.getNumOperands() - 1).getImm();
1308 SPIRV::LinkageType::LinkageType LnkType =
1309 static_cast<SPIRV::LinkageType::LinkageType>(LinkageOp);
1310 if (LnkType == SPIRV::LinkageType::LinkOnceODR)
1311 Reqs.addExtension(SPIRV::Extension::SPV_KHR_linkonce_odr);
1312 else if (LnkType == SPIRV::LinkageType::WeakAMD) {
1313 Reqs.addExtension(SPIRV::Extension::SPV_AMD_weak_linkage);
1314 Reqs.addCapability(SPIRV::Capability::WeakLinkageAMD);
1315 }
1316 } else if (Dec == SPIRV::Decoration::CacheControlLoadINTEL ||
1317 Dec == SPIRV::Decoration::CacheControlStoreINTEL) {
1318 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_cache_controls);
1319 } else if (Dec == SPIRV::Decoration::HostAccessINTEL) {
1320 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_global_variable_host_access);
1321 } else if (Dec == SPIRV::Decoration::InitModeINTEL ||
1322 Dec == SPIRV::Decoration::ImplementInRegisterMapINTEL) {
1323 Reqs.addExtension(
1324 SPIRV::Extension::SPV_INTEL_global_variable_fpga_decorations);
1325 } else if (Dec == SPIRV::Decoration::NonUniformEXT) {
1326 Reqs.addRequirements(SPIRV::Capability::ShaderNonUniformEXT);
1327 } else if (Dec == SPIRV::Decoration::FPMaxErrorDecorationINTEL) {
1328 Reqs.addRequirements(SPIRV::Capability::FPMaxErrorINTEL);
1329 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_fp_max_error);
1330 } else if (Dec == SPIRV::Decoration::FPFastMathMode) {
1331 if (ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2)) {
1332 Reqs.addRequirements(SPIRV::Capability::FloatControls2);
1333 Reqs.addExtension(SPIRV::Extension::SPV_KHR_float_controls2);
1334 }
1335 } else if (Dec == SPIRV::Decoration::FPRoundingMode) {
1336 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_rounded_divide_sqrt) &&
1338 Reqs.addRequirements(SPIRV::Capability::RoundedDivideSqrtINTEL);
1339 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_rounded_divide_sqrt);
1340 }
1341 }
1342}
1343
1344// Add requirements for image handling.
1347 const SPIRVSubtarget &ST) {
1348 assert(MI.getNumOperands() >= 8 && "Insufficient operands for OpTypeImage");
1349 // The operand indices used here are based on the OpTypeImage layout, which
1350 // the MachineInstr follows as well.
1351 int64_t ImgFormatOp = MI.getOperand(7).getImm();
1352 auto ImgFormat = static_cast<SPIRV::ImageFormat::ImageFormat>(ImgFormatOp);
1353 Reqs.getAndAddRequirements(SPIRV::OperandCategory::ImageFormatOperand,
1354 ImgFormat, ST);
1355
1356 bool IsArrayed = MI.getOperand(4).getImm() == 1;
1357 bool IsMultisampled = MI.getOperand(5).getImm() == 1;
1358 bool NoSampler = MI.getOperand(6).getImm() == 2;
1359 // Add dimension requirements.
1360 assert(MI.getOperand(2).isImm());
1361 switch (MI.getOperand(2).getImm()) {
1362 case SPIRV::Dim::DIM_1D:
1363 Reqs.addRequirements(NoSampler ? SPIRV::Capability::Image1D
1364 : SPIRV::Capability::Sampled1D);
1365 break;
1366 case SPIRV::Dim::DIM_2D:
1367 if (IsMultisampled && NoSampler)
1368 Reqs.addRequirements(SPIRV::Capability::StorageImageMultisample);
1369 if (IsMultisampled && IsArrayed)
1370 Reqs.addRequirements(SPIRV::Capability::ImageMSArray);
1371 break;
1372 case SPIRV::Dim::DIM_3D:
1373 break;
1374 case SPIRV::Dim::DIM_Cube:
1375 Reqs.addRequirements(SPIRV::Capability::Shader);
1376 if (IsArrayed)
1377 Reqs.addRequirements(NoSampler ? SPIRV::Capability::ImageCubeArray
1378 : SPIRV::Capability::SampledCubeArray);
1379 break;
1380 case SPIRV::Dim::DIM_Rect:
1381 Reqs.addRequirements(NoSampler ? SPIRV::Capability::ImageRect
1382 : SPIRV::Capability::SampledRect);
1383 break;
1384 case SPIRV::Dim::DIM_Buffer:
1385 Reqs.addRequirements(NoSampler ? SPIRV::Capability::ImageBuffer
1386 : SPIRV::Capability::SampledBuffer);
1387 break;
1388 case SPIRV::Dim::DIM_SubpassData:
1389 Reqs.addRequirements(SPIRV::Capability::InputAttachment);
1390 break;
1391 }
1392
1393 // Has optional access qualifier.
1394 if (!ST.isShader()) {
1395 if (MI.getNumOperands() > 8 &&
1396 MI.getOperand(8).getImm() == SPIRV::AccessQualifier::ReadWrite)
1397 Reqs.addRequirements(SPIRV::Capability::ImageReadWrite);
1398 else
1399 Reqs.addRequirements(SPIRV::Capability::ImageBasic);
1400 }
1401}
1402
1403static bool isBFloat16Type(SPIRVTypeInst TypeDef) {
1404 return TypeDef && TypeDef->getNumOperands() == 3 &&
1405 TypeDef->getOpcode() == SPIRV::OpTypeFloat &&
1406 TypeDef->getOperand(1).getImm() == 16 &&
1407 TypeDef->getOperand(2).getImm() == SPIRV::FPEncoding::BFloat16KHR;
1408}
1409
1410// Adds the requirements for bfloat16 arithmetic. Prefers
1411// SPV_EXT_bfloat16_arithmetic and falls back to the legacy
1412// SPV_INTEL_bfloat16_arithmetic which enables the same capability.
1414 const SPIRVSubtarget &ST) {
1415 if (ST.canUseExtension(SPIRV::Extension::SPV_EXT_bfloat16_arithmetic)) {
1416 Reqs.addExtension(SPIRV::Extension::SPV_EXT_bfloat16_arithmetic);
1417 Reqs.addCapability(SPIRV::Capability::BFloat16ArithmeticEXT);
1418 return true;
1419 }
1420 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_bfloat16_arithmetic)) {
1421 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_bfloat16_arithmetic);
1422 Reqs.addCapability(SPIRV::Capability::BFloat16ArithmeticINTEL);
1423 return true;
1424 }
1425 return false;
1426}
1427
1428// Registers created after isel (e.g. by MachineCSE) may lack registry entries.
1429// Fall back to the defining instruction's result type.
1431 const SPIRVGlobalRegistry *GR) {
1432 if (SPIRVTypeInst Ty = GR->getSPIRVTypeForVReg(Reg, &MF))
1433 return Ty;
1434 const MachineRegisterInfo &MRI = MF.getRegInfo();
1435 return MRI.getVRegDef(MRI.getVRegDef(Reg)->getOperand(1).getReg());
1436}
1437
1438// Add requirements for handling atomic float instructions
1439#define ATOM_FLT_REQ_EXT_MSG(ExtName) \
1440 "The atomic float instruction requires the following SPIR-V " \
1441 "extension: SPV_EXT_shader_atomic_float" ExtName
1444 const SPIRVSubtarget &ST) {
1445 SPIRVTypeInst VecTypeDef =
1446 MI.getMF()->getRegInfo().getVRegDef(MI.getOperand(1).getReg());
1447
1448 const unsigned Rank = VecTypeDef->getOperand(2).getImm();
1449 if (Rank != 2 && Rank != 4)
1450 reportFatalUsageError("Result type of an atomic vector float instruction "
1451 "must be a 2-component or 4 component vector");
1452
1453 SPIRVTypeInst EltTypeDef =
1454 MI.getMF()->getRegInfo().getVRegDef(VecTypeDef->getOperand(1).getReg());
1455
1456 if (EltTypeDef->getOpcode() != SPIRV::OpTypeFloat ||
1457 EltTypeDef->getOperand(1).getImm() != 16)
1459 "The element type for the result type of an atomic vector float "
1460 "instruction must be a 16-bit floating-point scalar");
1461
1462 // The extension is defined for fp16, but the AMD target lets a bf16 vector
1463 // use the same instruction so it can lower to a packed bf16 atomic.
1464 if (isBFloat16Type(EltTypeDef) &&
1465 ST.getTargetTriple().getVendor() != Triple::AMD)
1467 "The element type for the result type of an atomic vector float "
1468 "instruction cannot be a bfloat16 scalar");
1469 if (!ST.canUseExtension(SPIRV::Extension::SPV_NV_shader_atomic_fp16_vector))
1471 "The atomic float16 vector instruction requires the following SPIR-V "
1472 "extension: SPV_NV_shader_atomic_fp16_vector");
1473
1474 Reqs.addExtension(SPIRV::Extension::SPV_NV_shader_atomic_fp16_vector);
1475 Reqs.addCapability(SPIRV::Capability::AtomicFloat16VectorNV);
1476}
1477
1480 const SPIRVSubtarget &ST) {
1481 assert(MI.getOperand(1).isReg() &&
1482 "Expect register operand in atomic float instruction");
1483 Register TypeReg = MI.getOperand(1).getReg();
1484 SPIRVTypeInst TypeDef = MI.getMF()->getRegInfo().getVRegDef(TypeReg);
1485
1486 if (isVectorType(TypeDef))
1487 return AddAtomicVectorFloatRequirements(MI, Reqs, ST);
1488
1489 if (TypeDef->getOpcode() != SPIRV::OpTypeFloat)
1490 report_fatal_error("Result type of an atomic float instruction must be a "
1491 "floating-point type scalar");
1492
1493 unsigned BitWidth = TypeDef->getOperand(1).getImm();
1494 unsigned Op = MI.getOpcode();
1495 if (Op == SPIRV::OpAtomicFAddEXT) {
1496 if (!ST.canUseExtension(SPIRV::Extension::SPV_EXT_shader_atomic_float_add))
1498 Reqs.addExtension(SPIRV::Extension::SPV_EXT_shader_atomic_float_add);
1499 switch (BitWidth) {
1500 case 16:
1501 if (isBFloat16Type(TypeDef)) {
1502 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics))
1504 "The atomic bfloat16 instruction requires the following SPIR-V "
1505 "extension: SPV_INTEL_16bit_atomics",
1506 false);
1507 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics);
1508 Reqs.addCapability(SPIRV::Capability::AtomicBFloat16AddINTEL);
1509 } else {
1510 if (!ST.canUseExtension(
1511 SPIRV::Extension::SPV_EXT_shader_atomic_float16_add))
1512 report_fatal_error(ATOM_FLT_REQ_EXT_MSG("16_add"), false);
1513 Reqs.addExtension(SPIRV::Extension::SPV_EXT_shader_atomic_float16_add);
1514 Reqs.addCapability(SPIRV::Capability::AtomicFloat16AddEXT);
1515 }
1516 break;
1517 case 32:
1518 Reqs.addCapability(SPIRV::Capability::AtomicFloat32AddEXT);
1519 break;
1520 case 64:
1521 Reqs.addCapability(SPIRV::Capability::AtomicFloat64AddEXT);
1522 break;
1523 default:
1525 "Unexpected floating-point type width in atomic float instruction");
1526 }
1527 } else {
1528 if (!ST.canUseExtension(
1529 SPIRV::Extension::SPV_EXT_shader_atomic_float_min_max))
1530 report_fatal_error(ATOM_FLT_REQ_EXT_MSG("_min_max"), false);
1531 Reqs.addExtension(SPIRV::Extension::SPV_EXT_shader_atomic_float_min_max);
1532 switch (BitWidth) {
1533 case 16:
1534 if (isBFloat16Type(TypeDef)) {
1535 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics))
1537 "The atomic bfloat16 instruction requires the following SPIR-V "
1538 "extension: SPV_INTEL_16bit_atomics",
1539 false);
1540 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics);
1541 Reqs.addCapability(SPIRV::Capability::AtomicBFloat16MinMaxINTEL);
1542 } else {
1543 Reqs.addCapability(SPIRV::Capability::AtomicFloat16MinMaxEXT);
1544 }
1545 break;
1546 case 32:
1547 Reqs.addCapability(SPIRV::Capability::AtomicFloat32MinMaxEXT);
1548 break;
1549 case 64:
1550 Reqs.addCapability(SPIRV::Capability::AtomicFloat64MinMaxEXT);
1551 break;
1552 default:
1554 "Unexpected floating-point type width in atomic float instruction");
1555 }
1556 }
1557}
1558
1560 if (ImageInst->getOpcode() != SPIRV::OpTypeImage)
1561 return false;
1562 uint32_t Dim = ImageInst->getOperand(2).getImm();
1563 uint32_t Sampled = ImageInst->getOperand(6).getImm();
1564 return Dim == SPIRV::Dim::DIM_Buffer && Sampled == 1;
1565}
1566
1568 if (ImageInst->getOpcode() != SPIRV::OpTypeImage)
1569 return false;
1570 uint32_t Dim = ImageInst->getOperand(2).getImm();
1571 uint32_t Sampled = ImageInst->getOperand(6).getImm();
1572 return Dim == SPIRV::Dim::DIM_Buffer && Sampled == 2;
1573}
1574
1576 if (ImageInst->getOpcode() != SPIRV::OpTypeImage)
1577 return false;
1578 uint32_t Dim = ImageInst->getOperand(2).getImm();
1579 uint32_t Sampled = ImageInst->getOperand(6).getImm();
1580 return Dim != SPIRV::Dim::DIM_Buffer && Sampled == 1;
1581}
1582
1584 if (ImageInst->getOpcode() != SPIRV::OpTypeImage)
1585 return false;
1586 uint32_t Dim = ImageInst->getOperand(2).getImm();
1587 uint32_t Sampled = ImageInst->getOperand(6).getImm();
1588 return Dim == SPIRV::Dim::DIM_SubpassData && Sampled == 2;
1589}
1590
1592 if (ImageInst->getOpcode() != SPIRV::OpTypeImage)
1593 return false;
1594 uint32_t Dim = ImageInst->getOperand(2).getImm();
1595 uint32_t Sampled = ImageInst->getOperand(6).getImm();
1596 return Dim != SPIRV::Dim::DIM_Buffer && Sampled == 2;
1597}
1598
1599bool isCombinedImageSampler(MachineInstr *SampledImageInst) {
1600 if (SampledImageInst->getOpcode() != SPIRV::OpTypeSampledImage)
1601 return false;
1602
1603 const MachineRegisterInfo &MRI = SampledImageInst->getMF()->getRegInfo();
1604 Register ImageReg = SampledImageInst->getOperand(1).getReg();
1605 auto *ImageInst = MRI.getUniqueVRegDef(ImageReg);
1606 return isSampledImage(ImageInst);
1607}
1608
1610 for (const auto &MI : MRI.reg_instructions(Reg)) {
1611 if (MI.getOpcode() != SPIRV::OpDecorate)
1612 continue;
1613
1614 uint32_t Dec = MI.getOperand(1).getImm();
1615 if (Dec == SPIRV::Decoration::NonUniformEXT)
1616 return true;
1617 }
1618 return false;
1619}
1620
1623 const SPIRVSubtarget &Subtarget) {
1624 const MachineRegisterInfo &MRI = Instr.getMF()->getRegInfo();
1625 // Get the result type. If it is an image type, then the shader uses
1626 // descriptor indexing. The appropriate capabilities will be added based
1627 // on the specifics of the image.
1628 Register ResTypeReg = Instr.getOperand(1).getReg();
1629 MachineInstr *ResTypeInst = MRI.getUniqueVRegDef(ResTypeReg);
1630
1631 assert(ResTypeInst->getOpcode() == SPIRV::OpTypePointer);
1632 uint32_t StorageClass = ResTypeInst->getOperand(1).getImm();
1633 if (StorageClass != SPIRV::StorageClass::StorageClass::UniformConstant &&
1634 StorageClass != SPIRV::StorageClass::StorageClass::Uniform &&
1635 StorageClass != SPIRV::StorageClass::StorageClass::StorageBuffer) {
1636 return;
1637 }
1638
1639 bool IsNonUniform =
1640 hasNonUniformDecoration(Instr.getOperand(0).getReg(), MRI);
1641
1642 auto FirstIndexReg = Instr.getOperand(3).getReg();
1643 bool FirstIndexIsConstant =
1644 Subtarget.getInstrInfo()->isConstantInstr(*MRI.getVRegDef(FirstIndexReg));
1645
1646 if (StorageClass == SPIRV::StorageClass::StorageClass::StorageBuffer) {
1647 if (IsNonUniform)
1648 Handler.addRequirements(
1649 SPIRV::Capability::StorageBufferArrayNonUniformIndexingEXT);
1650 else if (!FirstIndexIsConstant)
1651 Handler.addRequirements(
1652 SPIRV::Capability::StorageBufferArrayDynamicIndexing);
1653 return;
1654 }
1655
1656 Register PointeeTypeReg = ResTypeInst->getOperand(2).getReg();
1657 MachineInstr *PointeeType = MRI.getUniqueVRegDef(PointeeTypeReg);
1658 if (PointeeType->getOpcode() != SPIRV::OpTypeImage &&
1659 PointeeType->getOpcode() != SPIRV::OpTypeSampledImage &&
1660 PointeeType->getOpcode() != SPIRV::OpTypeSampler) {
1661 return;
1662 }
1663
1664 if (isUniformTexelBuffer(PointeeType)) {
1665 if (IsNonUniform)
1666 Handler.addRequirements(
1667 SPIRV::Capability::UniformTexelBufferArrayNonUniformIndexingEXT);
1668 else if (!FirstIndexIsConstant)
1669 Handler.addRequirements(
1670 SPIRV::Capability::UniformTexelBufferArrayDynamicIndexingEXT);
1671 } else if (isInputAttachment(PointeeType)) {
1672 if (IsNonUniform)
1673 Handler.addRequirements(
1674 SPIRV::Capability::InputAttachmentArrayNonUniformIndexingEXT);
1675 else if (!FirstIndexIsConstant)
1676 Handler.addRequirements(
1677 SPIRV::Capability::InputAttachmentArrayDynamicIndexingEXT);
1678 } else if (isStorageTexelBuffer(PointeeType)) {
1679 if (IsNonUniform)
1680 Handler.addRequirements(
1681 SPIRV::Capability::StorageTexelBufferArrayNonUniformIndexingEXT);
1682 else if (!FirstIndexIsConstant)
1683 Handler.addRequirements(
1684 SPIRV::Capability::StorageTexelBufferArrayDynamicIndexingEXT);
1685 } else if (isSampledImage(PointeeType) ||
1686 isCombinedImageSampler(PointeeType) ||
1687 PointeeType->getOpcode() == SPIRV::OpTypeSampler) {
1688 if (IsNonUniform)
1689 Handler.addRequirements(
1690 SPIRV::Capability::SampledImageArrayNonUniformIndexingEXT);
1691 else if (!FirstIndexIsConstant)
1692 Handler.addRequirements(
1693 SPIRV::Capability::SampledImageArrayDynamicIndexing);
1694 } else if (isStorageImage(PointeeType)) {
1695 if (IsNonUniform)
1696 Handler.addRequirements(
1697 SPIRV::Capability::StorageImageArrayNonUniformIndexingEXT);
1698 else if (!FirstIndexIsConstant)
1699 Handler.addRequirements(
1700 SPIRV::Capability::StorageImageArrayDynamicIndexing);
1701 }
1702}
1703
1705 if (TypeInst->getOpcode() != SPIRV::OpTypeImage)
1706 return false;
1707 assert(TypeInst->getOperand(7).isImm() && "The image format must be an imm.");
1708 return TypeInst->getOperand(7).getImm() == 0;
1709}
1710
1713 const SPIRVSubtarget &ST) {
1714 if (ST.canUseExtension(SPIRV::Extension::SPV_KHR_integer_dot_product))
1715 Reqs.addExtension(SPIRV::Extension::SPV_KHR_integer_dot_product);
1716 Reqs.addCapability(SPIRV::Capability::DotProduct);
1717
1718 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1719 assert(MI.getOperand(2).isReg() && "Unexpected operand in dot");
1720 SPIRVTypeInst TypeDef = getRegType(MI.getOperand(2).getReg(), *MI.getMF(),
1721 ST.getSPIRVGlobalRegistry());
1722 assert(TypeDef && "Unexpected type instruction for dot input");
1723 if (TypeDef->getOpcode() == SPIRV::OpTypeInt) {
1724 assert(TypeDef->getOperand(1).getImm() == 32);
1725 Reqs.addCapability(SPIRV::Capability::DotProductInput4x8BitPacked);
1726 } else if (isVectorType(TypeDef)) {
1727 SPIRVTypeInst ScalarTypeDef =
1728 MRI.getVRegDef(TypeDef->getOperand(1).getReg());
1729 assert(ScalarTypeDef->getOpcode() == SPIRV::OpTypeInt);
1730 if (ScalarTypeDef->getOperand(1).getImm() == 8) {
1731 assert(TypeDef->getOperand(2).getImm() == 4 &&
1732 "Dot operand of 8-bit integer type requires 4 components");
1733 Reqs.addCapability(SPIRV::Capability::DotProductInput4x8Bit);
1734 } else {
1735 Reqs.addCapability(SPIRV::Capability::DotProductInputAll);
1736 }
1737 }
1738}
1739
1742 const SPIRVSubtarget &ST) {
1743 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
1744 SPIRVTypeInst PtrType =
1745 GR->getSPIRVTypeForVReg(MI.getOperand(4).getReg(), MI.getMF());
1746 if (PtrType) {
1747 MachineOperand ASOp = PtrType->getOperand(1);
1748 if (ASOp.isImm()) {
1749 unsigned AddrSpace = ASOp.getImm();
1750 if (AddrSpace != SPIRV::StorageClass::UniformConstant) {
1751 if (!ST.canUseExtension(
1753 SPV_EXT_relaxed_printf_string_address_space)) {
1754 report_fatal_error("SPV_EXT_relaxed_printf_string_address_space is "
1755 "required because printf uses a format string not "
1756 "in constant address space.",
1757 false);
1758 }
1759 Reqs.addExtension(
1760 SPIRV::Extension::SPV_EXT_relaxed_printf_string_address_space);
1761 }
1762 }
1763 }
1764}
1765
1768 const SPIRVSubtarget &ST, unsigned OpIdx) {
1769 if (MI.getNumOperands() <= OpIdx)
1770 return;
1771 uint32_t Mask = MI.getOperand(OpIdx).getImm();
1772 for (uint32_t I = 0; I < 32; ++I)
1773 if (Mask & (1U << I))
1774 Reqs.getAndAddRequirements(SPIRV::OperandCategory::ImageOperandOperand,
1775 1U << I, ST);
1776}
1777
1778static inline void maybeAddScatterGatherReq(const MachineInstr &MI,
1780 const SPIRVSubtarget &ST) {
1781 assert(MI.getOperand(1).isReg());
1782 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1783 SPIRVTypeInst ElemTypeDef = MRI.getVRegDef(MI.getOperand(1).getReg());
1784 if (ElemTypeDef->getOpcode() == SPIRV::OpTypePointer &&
1785 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
1786 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_masked_gather_scatter);
1787 Reqs.addCapability(SPIRV::Capability::MaskedGatherScatterINTEL);
1788 }
1789}
1790
1793 const SPIRVSubtarget &ST) {
1794 SPIRV::RequirementHandler &Reqs = MAI.Reqs;
1795 unsigned Op = MI.getOpcode();
1796 switch (Op) {
1797 case SPIRV::OpMemoryModel: {
1798 int64_t Addr = MI.getOperand(0).getImm();
1799 Reqs.getAndAddRequirements(SPIRV::OperandCategory::AddressingModelOperand,
1800 Addr, ST);
1801 int64_t Mem = MI.getOperand(1).getImm();
1802 Reqs.getAndAddRequirements(SPIRV::OperandCategory::MemoryModelOperand, Mem,
1803 ST);
1804 break;
1805 }
1806 case SPIRV::OpEntryPoint: {
1807 int64_t Exe = MI.getOperand(0).getImm();
1808 Reqs.getAndAddRequirements(SPIRV::OperandCategory::ExecutionModelOperand,
1809 Exe, ST);
1810 break;
1811 }
1812 case SPIRV::OpExecutionMode:
1813 case SPIRV::OpExecutionModeId: {
1814 int64_t Exe = MI.getOperand(1).getImm();
1815 Reqs.getAndAddRequirements(SPIRV::OperandCategory::ExecutionModeOperand,
1816 Exe, ST);
1817 break;
1818 }
1819 case SPIRV::OpTypeMatrix:
1820 Reqs.addCapability(SPIRV::Capability::Matrix);
1821 break;
1822 case SPIRV::OpTypeInt: {
1823 unsigned BitWidth = MI.getOperand(1).getImm();
1824 if (BitWidth == 64)
1825 Reqs.addCapability(SPIRV::Capability::Int64);
1826 else if (BitWidth == 16)
1827 Reqs.addCapability(SPIRV::Capability::Int16);
1828 else if (BitWidth == 8)
1829 Reqs.addCapability(SPIRV::Capability::Int8);
1830 else if (BitWidth == 4 &&
1831 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_int4)) {
1832 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_int4);
1833 Reqs.addCapability(SPIRV::Capability::Int4TypeINTEL);
1834 } else if (BitWidth != 32) {
1835 if (!ST.canUseExtension(
1836 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers))
1838 "OpTypeInt type with a width other than 8, 16, 32 or 64 bits "
1839 "requires the following SPIR-V extension: "
1840 "SPV_ALTERA_arbitrary_precision_integers");
1841 Reqs.addExtension(
1842 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers);
1843 Reqs.addCapability(SPIRV::Capability::ArbitraryPrecisionIntegersALTERA);
1844 }
1845 break;
1846 }
1847 case SPIRV::OpDot: {
1848 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1849 SPIRVTypeInst TypeDef = MRI.getVRegDef(MI.getOperand(1).getReg());
1850 if (isBFloat16Type(TypeDef))
1851 Reqs.addCapability(SPIRV::Capability::BFloat16DotProductKHR);
1852 break;
1853 }
1854 case SPIRV::OpTypeFloat: {
1855 unsigned BitWidth = MI.getOperand(1).getImm();
1856 if (BitWidth == 64)
1857 Reqs.addCapability(SPIRV::Capability::Float64);
1858 else if (BitWidth == 16) {
1859 if (isBFloat16Type(&MI)) {
1860 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_bfloat16))
1861 report_fatal_error("OpTypeFloat type with bfloat requires the "
1862 "following SPIR-V extension: SPV_KHR_bfloat16",
1863 false);
1864 Reqs.addExtension(SPIRV::Extension::SPV_KHR_bfloat16);
1865 Reqs.addCapability(SPIRV::Capability::BFloat16TypeKHR);
1866 } else {
1867 Reqs.addCapability(SPIRV::Capability::Float16);
1868 }
1869 }
1870 break;
1871 }
1872 case SPIRV::OpTypeVector: {
1873 unsigned NumComponents = MI.getOperand(2).getImm();
1874 if (NumComponents == 8 || NumComponents == 16)
1875 Reqs.addCapability(SPIRV::Capability::Vector16);
1876 else if (requiresLongVectorEXT(NumComponents))
1877 // Such widths are only expressible as OpTypeVectorIdEXT.
1879 "OpTypeVector with " + Twine(NumComponents) +
1880 " components requires the following SPIR-V extension: "
1881 "SPV_EXT_long_vector");
1882
1883 maybeAddScatterGatherReq(MI, Reqs, ST);
1884 break;
1885 }
1886 case SPIRV::OpTypeVectorIdEXT: {
1887 if (!ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector))
1888 reportFatalUsageError("OpTypeVectorIdEXT requires the following SPIR-V "
1889 "extension: SPV_EXT_long_vector extension");
1890 Reqs.addExtension(SPIRV::Extension::SPV_EXT_long_vector);
1891 Reqs.addCapability(SPIRV::Capability::LongVectorEXT);
1892 maybeAddScatterGatherReq(MI, Reqs, ST);
1893 break;
1894 }
1895 case SPIRV::OpTypePointer: {
1896 auto SC = MI.getOperand(1).getImm();
1897 Reqs.getAndAddRequirements(SPIRV::OperandCategory::StorageClassOperand, SC,
1898 ST);
1899 // If it's a type of pointer to float16 targeting OpenCL, add Float16Buffer
1900 // capability.
1901 if (ST.isShader())
1902 break;
1903 assert(MI.getOperand(2).isReg());
1904 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1905 SPIRVTypeInst TypeDef = MRI.getVRegDef(MI.getOperand(2).getReg());
1906 if ((TypeDef->getNumOperands() == 2) &&
1907 (TypeDef->getOpcode() == SPIRV::OpTypeFloat) &&
1908 (TypeDef->getOperand(1).getImm() == 16))
1909 Reqs.addCapability(SPIRV::Capability::Float16Buffer);
1910 break;
1911 }
1912 case SPIRV::OpExtInst: {
1913 if (MI.getOperand(2).getImm() ==
1914 static_cast<int64_t>(
1915 SPIRV::InstructionSet::NonSemantic_Shader_DebugInfo_100)) {
1916 Reqs.addExtension(SPIRV::Extension::SPV_KHR_non_semantic_info);
1917 break;
1918 }
1919 if (MI.getOperand(2).getImm() ==
1920 static_cast<int64_t>(SPIRV::InstructionSet::NonSemantic_DebugBreak)) {
1921 // Non-semantic instruction sets no longer require
1922 // SPV_KHR_non_semantic_info as of SPIR-V 1.6
1923 if (!ST.isAtLeastSPIRVVer(VersionTuple(1, 6)))
1924 Reqs.addExtension(SPIRV::Extension::SPV_KHR_non_semantic_info);
1925 break;
1926 }
1927 if (MI.getOperand(3).getImm() ==
1928 static_cast<int64_t>(SPIRV::OpenCLExtInst::printf)) {
1929 addPrintfRequirements(MI, Reqs, ST);
1930 break;
1931 }
1932 if (MI.getOperand(2).getImm() ==
1933 static_cast<int64_t>(SPIRV::InstructionSet::OpenCL_std)) {
1934 const MachineFunction *MF = MI.getMF();
1935 const MachineRegisterInfo &MRI = MF->getRegInfo();
1936 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
1937
1938 auto IsBFloat16 = [&](SPIRVTypeInst TypeDef) {
1939 if (TypeDef && TypeDef->getOpcode() == SPIRV::OpTypeVector)
1940 TypeDef = MRI.getVRegDef(TypeDef->getOperand(1).getReg());
1941 return isBFloat16Type(TypeDef);
1942 };
1943
1944 // Result type is operand 1; arguments start at operand 4.
1945 bool UsesBFloat16 = IsBFloat16(MRI.getVRegDef(MI.getOperand(1).getReg()));
1946 for (unsigned I = 4, E = MI.getNumOperands(); I < E && !UsesBFloat16;
1947 ++I) {
1948 const MachineOperand &MO = MI.getOperand(I);
1949 if (MO.isReg())
1950 UsesBFloat16 = IsBFloat16(GR->getResultType(
1951 MO.getReg(), const_cast<MachineFunction *>(MF)));
1952 }
1953
1954 if (UsesBFloat16 && !addBFloat16ArithmeticRequirements(Reqs, ST))
1956 MI, "OpenCL Extended instructions with bfloat16 require the "
1957 "following SPIR-V extension: SPV_EXT_bfloat16_arithmetic");
1958 }
1959 break;
1960 }
1961 case SPIRV::OpAliasDomainDeclINTEL:
1962 case SPIRV::OpAliasScopeDeclINTEL:
1963 case SPIRV::OpAliasScopeListDeclINTEL: {
1964 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing);
1965 Reqs.addCapability(SPIRV::Capability::MemoryAccessAliasingINTEL);
1966 break;
1967 }
1968 case SPIRV::OpBitReverse:
1969 case SPIRV::OpBitFieldInsert:
1970 case SPIRV::OpBitFieldSExtract:
1971 case SPIRV::OpBitFieldUExtract:
1972 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_bit_instructions)) {
1973 Reqs.addCapability(SPIRV::Capability::Shader);
1974 break;
1975 }
1976 Reqs.addExtension(SPIRV::Extension::SPV_KHR_bit_instructions);
1977 Reqs.addCapability(SPIRV::Capability::BitInstructions);
1978 break;
1979 case SPIRV::OpTypeRuntimeArray:
1980 Reqs.addCapability(SPIRV::Capability::Shader);
1981 break;
1982 case SPIRV::OpTypeOpaque:
1983 case SPIRV::OpTypeEvent:
1984 Reqs.addCapability(SPIRV::Capability::Kernel);
1985 break;
1986 case SPIRV::OpTypePipe:
1987 case SPIRV::OpTypeReserveId:
1988 Reqs.addCapability(SPIRV::Capability::Pipes);
1989 break;
1990 case SPIRV::OpTypePipeStorage:
1991 Reqs.addCapability(SPIRV::Capability::PipeStorage);
1992 break;
1993 case SPIRV::OpTypeDeviceEvent:
1994 case SPIRV::OpTypeQueue:
1995 case SPIRV::OpBuildNDRange:
1996 case SPIRV::OpEnqueueKernel:
1997 case SPIRV::OpGetKernelNDrangeSubGroupCount:
1998 case SPIRV::OpGetKernelNDrangeMaxSubGroupSize:
1999 case SPIRV::OpGetKernelWorkGroupSize:
2000 case SPIRV::OpGetKernelPreferredWorkGroupSizeMultiple:
2001 Reqs.addCapability(SPIRV::Capability::DeviceEnqueue);
2002 break;
2003 case SPIRV::OpDecorate:
2004 case SPIRV::OpDecorateId:
2005 case SPIRV::OpDecorateString:
2006 addOpDecorateReqs(MI, 1, Reqs, ST);
2007 break;
2008 case SPIRV::OpMemberDecorate:
2009 case SPIRV::OpMemberDecorateString:
2010 addOpDecorateReqs(MI, 2, Reqs, ST);
2011 break;
2012 case SPIRV::OpInBoundsPtrAccessChain:
2013 Reqs.addCapability(SPIRV::Capability::Addresses);
2014 break;
2015 case SPIRV::OpConstantSampler:
2016 Reqs.addCapability(SPIRV::Capability::LiteralSampler);
2017 break;
2018 case SPIRV::OpInBoundsAccessChain:
2019 case SPIRV::OpAccessChain:
2020 addOpAccessChainReqs(MI, Reqs, ST);
2021 break;
2022 case SPIRV::OpTypeImage:
2023 addOpTypeImageReqs(MI, Reqs, ST);
2024 break;
2025 case SPIRV::OpTypeSampler:
2026 if (!ST.isShader()) {
2027 Reqs.addCapability(SPIRV::Capability::ImageBasic);
2028 }
2029 break;
2030 case SPIRV::OpTypeForwardPointer:
2031 // TODO: check if it's OpenCL's kernel.
2032 Reqs.addCapability(SPIRV::Capability::Addresses);
2033 break;
2034 case SPIRV::OpAtomicFlagTestAndSet:
2035 case SPIRV::OpAtomicLoad:
2036 case SPIRV::OpAtomicStore:
2037 case SPIRV::OpAtomicExchange:
2038 case SPIRV::OpAtomicCompareExchange:
2039 case SPIRV::OpAtomicCompareExchangeWeak:
2040 case SPIRV::OpAtomicIIncrement:
2041 case SPIRV::OpAtomicIDecrement:
2042 case SPIRV::OpAtomicIAdd:
2043 case SPIRV::OpAtomicISub:
2044 case SPIRV::OpAtomicUMin:
2045 case SPIRV::OpAtomicUMax:
2046 case SPIRV::OpAtomicSMin:
2047 case SPIRV::OpAtomicSMax:
2048 case SPIRV::OpAtomicAnd:
2049 case SPIRV::OpAtomicOr:
2050 case SPIRV::OpAtomicXor: {
2051 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2052 SPIRVTypeInst TypeDef;
2053 if (Op == SPIRV::OpAtomicStore) {
2054 assert(MI.getOperand(3).isReg());
2055 TypeDef = getRegType(MI.getOperand(3).getReg(), *MI.getMF(),
2056 ST.getSPIRVGlobalRegistry());
2057 assert(TypeDef && "Unexpected type instruction for OpAtomicStore");
2058 } else {
2059 assert(MI.getOperand(1).isReg() && "Unexpected operand in atomic");
2060 TypeDef = MRI.getVRegDef(MI.getOperand(1).getReg());
2061 }
2062
2063 if (TypeDef->getOpcode() == SPIRV::OpTypeInt) {
2064 unsigned BitWidth = TypeDef->getOperand(1).getImm();
2065 if (BitWidth == 64)
2066 Reqs.addCapability(SPIRV::Capability::Int64Atomics);
2067 else if (BitWidth == 16) {
2068 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics))
2070 "16-bit integer atomic operations require the following SPIR-V "
2071 "extension: SPV_INTEL_16bit_atomics",
2072 false);
2073 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics);
2074 switch (Op) {
2075 case SPIRV::OpAtomicLoad:
2076 case SPIRV::OpAtomicStore:
2077 case SPIRV::OpAtomicExchange:
2078 case SPIRV::OpAtomicCompareExchange:
2079 case SPIRV::OpAtomicCompareExchangeWeak:
2080 Reqs.addCapability(
2081 SPIRV::Capability::AtomicInt16CompareExchangeINTEL);
2082 break;
2083 default:
2084 Reqs.addCapability(SPIRV::Capability::Int16AtomicsINTEL);
2085 break;
2086 }
2087 }
2088 } else if (isBFloat16Type(TypeDef)) {
2089 if (is_contained({SPIRV::OpAtomicLoad, SPIRV::OpAtomicStore,
2090 SPIRV::OpAtomicExchange},
2091 Op)) {
2092 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics))
2094 "The atomic bfloat16 instruction requires the following SPIR-V "
2095 "extension: SPV_INTEL_16bit_atomics",
2096 false);
2097 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_16bit_atomics);
2098 Reqs.addCapability(SPIRV::Capability::AtomicBFloat16LoadStoreINTEL);
2099 }
2100 }
2101 break;
2102 }
2103 case SPIRV::OpGroupNonUniformIAdd:
2104 case SPIRV::OpGroupNonUniformFAdd:
2105 case SPIRV::OpGroupNonUniformIMul:
2106 case SPIRV::OpGroupNonUniformFMul:
2107 case SPIRV::OpGroupNonUniformSMin:
2108 case SPIRV::OpGroupNonUniformUMin:
2109 case SPIRV::OpGroupNonUniformFMin:
2110 case SPIRV::OpGroupNonUniformSMax:
2111 case SPIRV::OpGroupNonUniformUMax:
2112 case SPIRV::OpGroupNonUniformFMax:
2113 case SPIRV::OpGroupNonUniformBitwiseAnd:
2114 case SPIRV::OpGroupNonUniformBitwiseOr:
2115 case SPIRV::OpGroupNonUniformBitwiseXor:
2116 case SPIRV::OpGroupNonUniformLogicalAnd:
2117 case SPIRV::OpGroupNonUniformLogicalOr:
2118 case SPIRV::OpGroupNonUniformLogicalXor: {
2119 assert(MI.getOperand(3).isImm());
2120 int64_t GroupOp = MI.getOperand(3).getImm();
2121 switch (GroupOp) {
2122 case SPIRV::GroupOperation::Reduce:
2123 case SPIRV::GroupOperation::InclusiveScan:
2124 case SPIRV::GroupOperation::ExclusiveScan:
2125 Reqs.addCapability(SPIRV::Capability::GroupNonUniformArithmetic);
2126 break;
2127 case SPIRV::GroupOperation::ClusteredReduce:
2128 Reqs.addCapability(SPIRV::Capability::GroupNonUniformClustered);
2129 break;
2130 case SPIRV::GroupOperation::PartitionedReduceNV:
2131 case SPIRV::GroupOperation::PartitionedInclusiveScanNV:
2132 case SPIRV::GroupOperation::PartitionedExclusiveScanNV:
2133 if (ST.canUseExtension(
2134 SPIRV::Extension::SPV_EXT_shader_subgroup_partitioned))
2135 Reqs.addExtension(
2136 SPIRV::Extension::SPV_EXT_shader_subgroup_partitioned);
2137 else
2138 Reqs.addExtension(SPIRV::Extension::SPV_NV_shader_subgroup_partitioned);
2139 Reqs.addCapability(SPIRV::Capability::GroupNonUniformPartitionedNV);
2140 break;
2141 }
2142 break;
2143 }
2144 case SPIRV::OpGroupNonUniformQuadSwap:
2145 Reqs.addCapability(SPIRV::Capability::GroupNonUniformQuad);
2146 break;
2147 case SPIRV::OpImageQueryLod:
2148 Reqs.addCapability(SPIRV::Capability::ImageQuery);
2149 break;
2150 case SPIRV::OpImageQuerySize:
2151 case SPIRV::OpImageQuerySizeLod:
2152 case SPIRV::OpImageQueryLevels:
2153 case SPIRV::OpImageQuerySamples:
2154 if (ST.isShader())
2155 Reqs.addCapability(SPIRV::Capability::ImageQuery);
2156 break;
2157 case SPIRV::OpImageQueryFormat: {
2158 Register ResultReg = MI.getOperand(0).getReg();
2159 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2160 static const unsigned CompareOps[] = {
2161 SPIRV::OpIEqual, SPIRV::OpINotEqual,
2162 SPIRV::OpUGreaterThan, SPIRV::OpUGreaterThanEqual,
2163 SPIRV::OpULessThan, SPIRV::OpULessThanEqual,
2164 SPIRV::OpSGreaterThan, SPIRV::OpSGreaterThanEqual,
2165 SPIRV::OpSLessThan, SPIRV::OpSLessThanEqual};
2166
2167 auto CheckAndAddExtension = [&](int64_t ImmVal) {
2168 if (ImmVal == 4323 || ImmVal == 4324) {
2169 if (ST.canUseExtension(SPIRV::Extension::SPV_EXT_image_raw10_raw12))
2170 Reqs.addExtension(SPIRV::Extension::SPV_EXT_image_raw10_raw12);
2171 else
2172 report_fatal_error("This requires the "
2173 "SPV_EXT_image_raw10_raw12 extension");
2174 }
2175 };
2176
2177 for (MachineInstr &UseInst : MRI.use_instructions(ResultReg)) {
2178 unsigned Opc = UseInst.getOpcode();
2179
2180 if (Opc == SPIRV::OpSwitch) {
2181 for (const MachineOperand &Op : UseInst.operands())
2182 if (Op.isImm())
2183 CheckAndAddExtension(Op.getImm());
2184 } else if (llvm::is_contained(CompareOps, Opc)) {
2185 for (unsigned i = 1; i < UseInst.getNumOperands(); ++i) {
2186 Register UseReg = UseInst.getOperand(i).getReg();
2187 MachineInstr *ConstInst = MRI.getVRegDef(UseReg);
2188 if (ConstInst && ConstInst->getOpcode() == SPIRV::OpConstantI) {
2189 int64_t ImmVal = ConstInst->getOperand(2).getImm();
2190 if (ImmVal)
2191 CheckAndAddExtension(ImmVal);
2192 }
2193 }
2194 }
2195 }
2196 break;
2197 }
2198
2199 case SPIRV::OpGroupNonUniformShuffle:
2200 case SPIRV::OpGroupNonUniformShuffleXor:
2201 Reqs.addCapability(SPIRV::Capability::GroupNonUniformShuffle);
2202 break;
2203 case SPIRV::OpGroupNonUniformShuffleUp:
2204 case SPIRV::OpGroupNonUniformShuffleDown:
2205 Reqs.addCapability(SPIRV::Capability::GroupNonUniformShuffleRelative);
2206 break;
2207 case SPIRV::OpGroupAll:
2208 case SPIRV::OpGroupAny:
2209 case SPIRV::OpGroupBroadcast:
2210 case SPIRV::OpGroupIAdd:
2211 case SPIRV::OpGroupFAdd:
2212 case SPIRV::OpGroupFMin:
2213 case SPIRV::OpGroupUMin:
2214 case SPIRV::OpGroupSMin:
2215 case SPIRV::OpGroupFMax:
2216 case SPIRV::OpGroupUMax:
2217 case SPIRV::OpGroupSMax:
2218 Reqs.addCapability(SPIRV::Capability::Groups);
2219 break;
2220 case SPIRV::OpGroupNonUniformElect:
2221 Reqs.addCapability(SPIRV::Capability::GroupNonUniform);
2222 break;
2223 case SPIRV::OpGroupNonUniformAll:
2224 case SPIRV::OpGroupNonUniformAny:
2225 case SPIRV::OpGroupNonUniformAllEqual:
2226 Reqs.addCapability(SPIRV::Capability::GroupNonUniformVote);
2227 break;
2228 case SPIRV::OpGroupNonUniformBroadcast:
2229 case SPIRV::OpGroupNonUniformBroadcastFirst:
2230 case SPIRV::OpGroupNonUniformBallot:
2231 case SPIRV::OpGroupNonUniformInverseBallot:
2232 case SPIRV::OpGroupNonUniformBallotBitExtract:
2233 case SPIRV::OpGroupNonUniformBallotBitCount:
2234 case SPIRV::OpGroupNonUniformBallotFindLSB:
2235 case SPIRV::OpGroupNonUniformBallotFindMSB:
2236 Reqs.addCapability(SPIRV::Capability::GroupNonUniformBallot);
2237 break;
2238 case SPIRV::OpSubgroupShuffleINTEL:
2239 case SPIRV::OpSubgroupShuffleDownINTEL:
2240 case SPIRV::OpSubgroupShuffleUpINTEL:
2241 case SPIRV::OpSubgroupShuffleXorINTEL:
2242 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_subgroups)) {
2243 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_subgroups);
2244 Reqs.addCapability(SPIRV::Capability::SubgroupShuffleINTEL);
2245 }
2246 break;
2247 case SPIRV::OpSubgroupBlockReadINTEL:
2248 case SPIRV::OpSubgroupBlockWriteINTEL:
2249 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_subgroups)) {
2250 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_subgroups);
2251 Reqs.addCapability(SPIRV::Capability::SubgroupBufferBlockIOINTEL);
2252 }
2253 break;
2254 case SPIRV::OpSubgroupImageBlockReadINTEL:
2255 case SPIRV::OpSubgroupImageBlockWriteINTEL:
2256 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_subgroups)) {
2257 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_subgroups);
2258 Reqs.addCapability(SPIRV::Capability::SubgroupImageBlockIOINTEL);
2259 }
2260 break;
2261 case SPIRV::OpSubgroupImageMediaBlockReadINTEL:
2262 case SPIRV::OpSubgroupImageMediaBlockWriteINTEL:
2263 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_media_block_io)) {
2264 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_media_block_io);
2265 Reqs.addCapability(SPIRV::Capability::SubgroupImageMediaBlockIOINTEL);
2266 }
2267 break;
2268 case SPIRV::OpAssumeTrueKHR:
2269 case SPIRV::OpExpectKHR:
2270 if (ST.canUseExtension(SPIRV::Extension::SPV_KHR_expect_assume)) {
2271 Reqs.addExtension(SPIRV::Extension::SPV_KHR_expect_assume);
2272 Reqs.addCapability(SPIRV::Capability::ExpectAssumeKHR);
2273 }
2274 break;
2275 case SPIRV::OpFmaKHR:
2276 if (ST.canUseExtension(SPIRV::Extension::SPV_KHR_fma)) {
2277 Reqs.addExtension(SPIRV::Extension::SPV_KHR_fma);
2278 Reqs.addCapability(SPIRV::Capability::FmaKHR);
2279 }
2280 break;
2281 case SPIRV::OpPtrCastToCrossWorkgroupINTEL:
2282 case SPIRV::OpCrossWorkgroupCastToPtrINTEL:
2283 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_usm_storage_classes)) {
2284 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_usm_storage_classes);
2285 Reqs.addCapability(SPIRV::Capability::USMStorageClassesINTEL);
2286 }
2287 break;
2288 case SPIRV::OpConstantFunctionPointerINTEL:
2289 case SPIRV::OpFunctionPointerCallINTEL:
2290 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)) {
2291 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
2292 Reqs.addCapability(SPIRV::Capability::FunctionPointersINTEL);
2293 }
2294 break;
2295 case SPIRV::OpGroupNonUniformQuadAllKHR:
2296 addQuadControlRequirements(Reqs, ST, "OpGroupNonUniformQuadAllKHR");
2297 Reqs.addCapability(SPIRV::Capability::QuadControlKHR);
2298 break;
2299 case SPIRV::OpGroupNonUniformRotateKHR:
2300 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_subgroup_rotate))
2301 report_fatal_error("OpGroupNonUniformRotateKHR instruction requires the "
2302 "following SPIR-V extension: SPV_KHR_subgroup_rotate",
2303 false);
2304 Reqs.addExtension(SPIRV::Extension::SPV_KHR_subgroup_rotate);
2305 Reqs.addCapability(SPIRV::Capability::GroupNonUniformRotateKHR);
2306 Reqs.addCapability(SPIRV::Capability::GroupNonUniform);
2307 break;
2308 case SPIRV::OpFixedCosALTERA:
2309 case SPIRV::OpFixedSinALTERA:
2310 case SPIRV::OpFixedCosPiALTERA:
2311 case SPIRV::OpFixedSinPiALTERA:
2312 case SPIRV::OpFixedExpALTERA:
2313 case SPIRV::OpFixedLogALTERA:
2314 case SPIRV::OpFixedRecipALTERA:
2315 case SPIRV::OpFixedSqrtALTERA:
2316 case SPIRV::OpFixedSinCosALTERA:
2317 case SPIRV::OpFixedSinCosPiALTERA:
2318 case SPIRV::OpFixedRsqrtALTERA:
2319 if (!ST.canUseExtension(
2320 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_fixed_point))
2321 report_fatal_error("This instruction requires the "
2322 "following SPIR-V extension: "
2323 "SPV_ALTERA_arbitrary_precision_fixed_point",
2324 false);
2325 Reqs.addExtension(
2326 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_fixed_point);
2327 Reqs.addCapability(SPIRV::Capability::ArbitraryPrecisionFixedPointALTERA);
2328 break;
2329 case SPIRV::OpGroupIMulKHR:
2330 case SPIRV::OpGroupFMulKHR:
2331 case SPIRV::OpGroupBitwiseAndKHR:
2332 case SPIRV::OpGroupBitwiseOrKHR:
2333 case SPIRV::OpGroupBitwiseXorKHR:
2334 case SPIRV::OpGroupLogicalAndKHR:
2335 case SPIRV::OpGroupLogicalOrKHR:
2336 case SPIRV::OpGroupLogicalXorKHR:
2337 if (ST.canUseExtension(
2338 SPIRV::Extension::SPV_KHR_uniform_group_instructions)) {
2339 Reqs.addExtension(SPIRV::Extension::SPV_KHR_uniform_group_instructions);
2340 Reqs.addCapability(SPIRV::Capability::GroupUniformArithmeticKHR);
2341 }
2342 break;
2343 case SPIRV::OpReadClockKHR:
2344 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_shader_clock))
2345 report_fatal_error("OpReadClockKHR instruction requires the "
2346 "following SPIR-V extension: SPV_KHR_shader_clock",
2347 false);
2348 Reqs.addExtension(SPIRV::Extension::SPV_KHR_shader_clock);
2349 Reqs.addCapability(SPIRV::Capability::ShaderClockKHR);
2350 break;
2351 case SPIRV::OpAbortKHR:
2352 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_abort))
2353 report_fatal_error("OpAbortKHR instruction requires the "
2354 "following SPIR-V extension: SPV_KHR_abort",
2355 false);
2356 Reqs.addExtension(SPIRV::Extension::SPV_KHR_abort);
2357 Reqs.addCapability(SPIRV::Capability::AbortKHR);
2358 break;
2359 case SPIRV::OpPoisonKHR:
2360 case SPIRV::OpFreezeKHR:
2361 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze))
2362 report_fatal_error("OpPoisonKHR/OpFreezeKHR instruction requires the "
2363 "following SPIR-V extension: SPV_KHR_poison_freeze",
2364 false);
2365 Reqs.addExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
2366 Reqs.addCapability(SPIRV::Capability::PoisonFreezeKHR);
2367 break;
2368 case SPIRV::OpAtomicFAddEXT:
2369 case SPIRV::OpAtomicFMinEXT:
2370 case SPIRV::OpAtomicFMaxEXT:
2371 AddAtomicFloatRequirements(MI, Reqs, ST);
2372 break;
2373 case SPIRV::OpConvertBF16ToFINTEL:
2374 case SPIRV::OpConvertFToBF16INTEL:
2375 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_bfloat16_conversion)) {
2376 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_bfloat16_conversion);
2377 Reqs.addCapability(SPIRV::Capability::BFloat16ConversionINTEL);
2378 }
2379 break;
2380 case SPIRV::OpRoundFToTF32INTEL:
2381 if (ST.canUseExtension(
2382 SPIRV::Extension::SPV_INTEL_tensor_float32_conversion)) {
2383 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_tensor_float32_conversion);
2384 Reqs.addCapability(SPIRV::Capability::TensorFloat32RoundingINTEL);
2385 }
2386 break;
2387 case SPIRV::OpVariableLengthArrayINTEL:
2388 case SPIRV::OpSaveMemoryINTEL:
2389 case SPIRV::OpRestoreMemoryINTEL:
2390 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_variable_length_array)) {
2391 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_variable_length_array);
2392 Reqs.addCapability(SPIRV::Capability::VariableLengthArrayINTEL);
2393 }
2394 break;
2395 case SPIRV::OpUntypedVariableLengthArrayINTEL:
2396 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_variable_length_array)) {
2397 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_variable_length_array);
2398 Reqs.addCapability(SPIRV::Capability::UntypedVariableLengthArrayINTEL);
2399 }
2400 break;
2401 case SPIRV::OpAsmTargetINTEL:
2402 case SPIRV::OpAsmINTEL:
2403 case SPIRV::OpAsmCallINTEL:
2404 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_inline_assembly)) {
2405 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_inline_assembly);
2406 Reqs.addCapability(SPIRV::Capability::AsmINTEL);
2407 }
2408 break;
2409 case SPIRV::OpTypeCooperativeMatrixKHR: {
2410 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_cooperative_matrix))
2412 "OpTypeCooperativeMatrixKHR type requires the "
2413 "following SPIR-V extension: SPV_KHR_cooperative_matrix",
2414 false);
2415 Reqs.addExtension(SPIRV::Extension::SPV_KHR_cooperative_matrix);
2416 Reqs.addCapability(SPIRV::Capability::CooperativeMatrixKHR);
2417 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2418 SPIRVTypeInst TypeDef = MRI.getVRegDef(MI.getOperand(1).getReg());
2419 if (isBFloat16Type(TypeDef))
2420 Reqs.addCapability(SPIRV::Capability::BFloat16CooperativeMatrixKHR);
2421 break;
2422 }
2423 case SPIRV::OpArithmeticFenceEXT:
2424 if (!ST.canUseExtension(SPIRV::Extension::SPV_EXT_arithmetic_fence))
2425 report_fatal_error("OpArithmeticFenceEXT requires the "
2426 "following SPIR-V extension: SPV_EXT_arithmetic_fence",
2427 false);
2428 Reqs.addExtension(SPIRV::Extension::SPV_EXT_arithmetic_fence);
2429 Reqs.addCapability(SPIRV::Capability::ArithmeticFenceEXT);
2430 break;
2431 case SPIRV::OpControlBarrierArriveINTEL:
2432 case SPIRV::OpControlBarrierWaitINTEL:
2433 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_split_barrier)) {
2434 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_split_barrier);
2435 Reqs.addCapability(SPIRV::Capability::SplitBarrierINTEL);
2436 }
2437 break;
2438 case SPIRV::OpControlBarrier: {
2439 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_device_barrier))
2440 break;
2441 // DeviceBarrierINTEL allows Device as the Execution scope. Require it
2442 // unless the scope is known to be an integer OpConstant other than Device.
2443 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2444 const MachineInstr *ExecScopeDef =
2445 MRI.getVRegDef(MI.getOperand(0).getReg());
2446 if (ExecScopeDef->getOpcode() != SPIRV::OpConstantI ||
2447 ExecScopeDef->getOperand(2).getImm() == SPIRV::Scope::Device) {
2448 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_device_barrier);
2449 Reqs.addCapability(SPIRV::Capability::DeviceBarrierINTEL);
2450 }
2451 break;
2452 }
2453 case SPIRV::OpCooperativeMatrixMulAddKHR: {
2454 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_cooperative_matrix))
2455 report_fatal_error("Cooperative matrix instructions require the "
2456 "following SPIR-V extension: "
2457 "SPV_KHR_cooperative_matrix",
2458 false);
2459 Reqs.addExtension(SPIRV::Extension::SPV_KHR_cooperative_matrix);
2460 Reqs.addCapability(SPIRV::Capability::CooperativeMatrixKHR);
2461 constexpr unsigned MulAddMaxSize = 6;
2462 if (MI.getNumOperands() != MulAddMaxSize)
2463 break;
2464 const int64_t CoopOperands = MI.getOperand(MulAddMaxSize - 1).getImm();
2465 if (CoopOperands & SPIRV::CooperativeMatrixOperands::
2466 MatrixAAndBBFloat16ComponentsINTEL ||
2467 CoopOperands &
2468 SPIRV::CooperativeMatrixOperands::MatrixCBFloat16ComponentsINTEL ||
2469 CoopOperands & SPIRV::CooperativeMatrixOperands::
2470 MatrixResultBFloat16ComponentsINTEL) {
2471 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_joint_matrix))
2472 report_fatal_error("***BF16ComponentsINTEL type interpretations "
2473 "require the following SPIR-V extension: "
2474 "SPV_INTEL_joint_matrix",
2475 false);
2476 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_joint_matrix);
2477 Reqs.addCapability(
2478 SPIRV::Capability::CooperativeMatrixBFloat16ComponentTypeINTEL);
2479 }
2480 break;
2481 }
2482 case SPIRV::OpCooperativeMatrixLoadKHR:
2483 case SPIRV::OpCooperativeMatrixStoreKHR:
2484 case SPIRV::OpCooperativeMatrixLoadCheckedINTEL:
2485 case SPIRV::OpCooperativeMatrixStoreCheckedINTEL:
2486 case SPIRV::OpCooperativeMatrixPrefetchINTEL: {
2487 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_cooperative_matrix))
2488 report_fatal_error("Cooperative matrix instructions require the "
2489 "following SPIR-V extension: "
2490 "SPV_KHR_cooperative_matrix",
2491 false);
2492 Reqs.addExtension(SPIRV::Extension::SPV_KHR_cooperative_matrix);
2493 Reqs.addCapability(SPIRV::Capability::CooperativeMatrixKHR);
2494
2495 // Check Layout operand in case if it's not a standard one and add the
2496 // appropriate capability.
2497 unsigned LayoutNum;
2498 switch (Op) {
2499 case SPIRV::OpCooperativeMatrixLoadKHR:
2500 LayoutNum = 3;
2501 break;
2502 case SPIRV::OpCooperativeMatrixStoreKHR:
2503 LayoutNum = 2;
2504 break;
2505 case SPIRV::OpCooperativeMatrixLoadCheckedINTEL:
2506 LayoutNum = 5;
2507 break;
2508 case SPIRV::OpCooperativeMatrixStoreCheckedINTEL:
2509 case SPIRV::OpCooperativeMatrixPrefetchINTEL:
2510 LayoutNum = 4;
2511 break;
2512 default:
2513 llvm_unreachable("unexpected cooperative matrix opcode");
2514 }
2515 Register RegLayout = MI.getOperand(LayoutNum).getReg();
2516 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2517 MachineInstr *MILayout = MRI.getUniqueVRegDef(RegLayout);
2518 if (MILayout->getOpcode() == SPIRV::OpConstantI) {
2519 const unsigned LayoutVal = MILayout->getOperand(2).getImm();
2520 if (LayoutVal ==
2521 static_cast<unsigned>(SPIRV::CooperativeMatrixLayout::PackedINTEL)) {
2522 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_joint_matrix))
2523 report_fatal_error("PackedINTEL layout require the following SPIR-V "
2524 "extension: SPV_INTEL_joint_matrix",
2525 false);
2526 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_joint_matrix);
2527 Reqs.addCapability(SPIRV::Capability::PackedCooperativeMatrixINTEL);
2528 }
2529 }
2530
2531 // Nothing to do.
2532 if (Op == SPIRV::OpCooperativeMatrixLoadKHR ||
2533 Op == SPIRV::OpCooperativeMatrixStoreKHR)
2534 break;
2535
2536 std::string InstName;
2537 switch (Op) {
2538 case SPIRV::OpCooperativeMatrixPrefetchINTEL:
2539 InstName = "OpCooperativeMatrixPrefetchINTEL";
2540 break;
2541 case SPIRV::OpCooperativeMatrixLoadCheckedINTEL:
2542 InstName = "OpCooperativeMatrixLoadCheckedINTEL";
2543 break;
2544 case SPIRV::OpCooperativeMatrixStoreCheckedINTEL:
2545 InstName = "OpCooperativeMatrixStoreCheckedINTEL";
2546 break;
2547 }
2548
2549 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_joint_matrix)) {
2550 const std::string ErrorMsg =
2551 InstName + " instruction requires the "
2552 "following SPIR-V extension: SPV_INTEL_joint_matrix";
2553 report_fatal_error(ErrorMsg.c_str(), false);
2554 }
2555 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_joint_matrix);
2556 if (Op == SPIRV::OpCooperativeMatrixPrefetchINTEL) {
2557 Reqs.addCapability(SPIRV::Capability::CooperativeMatrixPrefetchINTEL);
2558 break;
2559 }
2560 Reqs.addCapability(
2561 SPIRV::Capability::CooperativeMatrixCheckedInstructionsINTEL);
2562 break;
2563 }
2564 case SPIRV::OpCooperativeMatrixConstructCheckedINTEL:
2565 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_joint_matrix))
2566 report_fatal_error("OpCooperativeMatrixConstructCheckedINTEL "
2567 "instructions require the following SPIR-V extension: "
2568 "SPV_INTEL_joint_matrix",
2569 false);
2570 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_joint_matrix);
2571 Reqs.addCapability(
2572 SPIRV::Capability::CooperativeMatrixCheckedInstructionsINTEL);
2573 break;
2574 case SPIRV::OpReadPipeBlockingALTERA:
2575 case SPIRV::OpWritePipeBlockingALTERA:
2576 if (ST.canUseExtension(SPIRV::Extension::SPV_ALTERA_blocking_pipes)) {
2577 Reqs.addExtension(SPIRV::Extension::SPV_ALTERA_blocking_pipes);
2578 Reqs.addCapability(SPIRV::Capability::BlockingPipesALTERA);
2579 }
2580 break;
2581 case SPIRV::OpCooperativeMatrixGetElementCoordINTEL:
2582 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_joint_matrix))
2583 report_fatal_error("OpCooperativeMatrixGetElementCoordINTEL requires the "
2584 "following SPIR-V extension: SPV_INTEL_joint_matrix",
2585 false);
2586 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_joint_matrix);
2587 Reqs.addCapability(
2588 SPIRV::Capability::CooperativeMatrixInvocationInstructionsINTEL);
2589 break;
2590 case SPIRV::OpConvertHandleToImageINTEL:
2591 case SPIRV::OpConvertHandleToSamplerINTEL:
2592 case SPIRV::OpConvertHandleToSampledImageINTEL: {
2593 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_bindless_images))
2594 report_fatal_error("OpConvertHandleTo[Image/Sampler/SampledImage]INTEL "
2595 "instructions require the following SPIR-V extension: "
2596 "SPV_INTEL_bindless_images",
2597 false);
2598 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
2599 SPIRV::AddressingModel::AddressingModel AddrModel = MAI.Addr;
2600 SPIRVTypeInst TyDef = GR->getSPIRVTypeForVReg(MI.getOperand(1).getReg());
2601 if (Op == SPIRV::OpConvertHandleToImageINTEL &&
2602 TyDef->getOpcode() != SPIRV::OpTypeImage) {
2603 report_fatal_error("Incorrect return type for the instruction "
2604 "OpConvertHandleToImageINTEL",
2605 false);
2606 } else if (Op == SPIRV::OpConvertHandleToSamplerINTEL &&
2607 TyDef->getOpcode() != SPIRV::OpTypeSampler) {
2608 report_fatal_error("Incorrect return type for the instruction "
2609 "OpConvertHandleToSamplerINTEL",
2610 false);
2611 } else if (Op == SPIRV::OpConvertHandleToSampledImageINTEL &&
2612 TyDef->getOpcode() != SPIRV::OpTypeSampledImage) {
2613 report_fatal_error("Incorrect return type for the instruction "
2614 "OpConvertHandleToSampledImageINTEL",
2615 false);
2616 }
2617 SPIRVTypeInst SpvTy =
2618 getRegType(MI.getOperand(2).getReg(), *MI.getMF(), GR);
2619 unsigned Bitwidth = GR->getScalarOrVectorBitWidth(SpvTy);
2620 if (!(Bitwidth == 32 && AddrModel == SPIRV::AddressingModel::Physical32) &&
2621 !(Bitwidth == 64 && AddrModel == SPIRV::AddressingModel::Physical64)) {
2623 "Parameter value must be a 32-bit scalar in case of "
2624 "Physical32 addressing model or a 64-bit scalar in case of "
2625 "Physical64 addressing model",
2626 false);
2627 }
2628 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_bindless_images);
2629 Reqs.addCapability(SPIRV::Capability::BindlessImagesINTEL);
2630 break;
2631 }
2632 case SPIRV::OpSubgroup2DBlockLoadINTEL:
2633 case SPIRV::OpSubgroup2DBlockLoadTransposeINTEL:
2634 case SPIRV::OpSubgroup2DBlockLoadTransformINTEL:
2635 case SPIRV::OpSubgroup2DBlockPrefetchINTEL:
2636 case SPIRV::OpSubgroup2DBlockStoreINTEL: {
2637 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_2d_block_io))
2638 report_fatal_error("OpSubgroup2DBlock[Load/LoadTranspose/LoadTransform/"
2639 "Prefetch/Store]INTEL instructions require the "
2640 "following SPIR-V extension: SPV_INTEL_2d_block_io",
2641 false);
2642 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_2d_block_io);
2643 Reqs.addCapability(SPIRV::Capability::Subgroup2DBlockIOINTEL);
2644
2645 if (Op == SPIRV::OpSubgroup2DBlockLoadTransposeINTEL) {
2646 Reqs.addCapability(SPIRV::Capability::Subgroup2DBlockTransposeINTEL);
2647 break;
2648 }
2649 if (Op == SPIRV::OpSubgroup2DBlockLoadTransformINTEL) {
2650 Reqs.addCapability(SPIRV::Capability::Subgroup2DBlockTransformINTEL);
2651 break;
2652 }
2653 break;
2654 }
2655 case SPIRV::OpKill: {
2656 Reqs.addCapability(SPIRV::Capability::Shader);
2657 } break;
2658 case SPIRV::OpDemoteToHelperInvocation:
2659 Reqs.addCapability(SPIRV::Capability::DemoteToHelperInvocation);
2660
2661 if (ST.canUseExtension(
2662 SPIRV::Extension::SPV_EXT_demote_to_helper_invocation)) {
2663 if (!ST.isAtLeastSPIRVVer(llvm::VersionTuple(1, 6)))
2664 Reqs.addExtension(
2665 SPIRV::Extension::SPV_EXT_demote_to_helper_invocation);
2666 }
2667 break;
2668 case SPIRV::OpSDot:
2669 case SPIRV::OpUDot:
2670 case SPIRV::OpSUDot:
2671 case SPIRV::OpSDotAccSat:
2672 case SPIRV::OpUDotAccSat:
2673 case SPIRV::OpSUDotAccSat:
2674 AddDotProductRequirements(MI, Reqs, ST);
2675 break;
2676 case SPIRV::OpImageSampleImplicitLod:
2677 case SPIRV::OpImageFetch:
2678 Reqs.addCapability(SPIRV::Capability::Shader);
2679 addImageOperandReqs(MI, Reqs, ST, 4);
2680 break;
2681 case SPIRV::OpImageSampleExplicitLod:
2682 addImageOperandReqs(MI, Reqs, ST, 4);
2683 break;
2684 case SPIRV::OpImageSampleDrefImplicitLod:
2685 case SPIRV::OpImageSampleDrefExplicitLod:
2686 case SPIRV::OpImageDrefGather:
2687 case SPIRV::OpImageGather:
2688 Reqs.addCapability(SPIRV::Capability::Shader);
2689 addImageOperandReqs(MI, Reqs, ST, 5);
2690 break;
2691 case SPIRV::OpImageRead: {
2692 Register ImageReg = MI.getOperand(2).getReg();
2693 SPIRVTypeInst TypeDef = ST.getSPIRVGlobalRegistry()->getResultType(
2694 ImageReg, const_cast<MachineFunction *>(MI.getMF()));
2695 // OpImageRead and OpImageWrite can use Unknown Image Formats
2696 // when the Kernel capability is declared. In the OpenCL environment we are
2697 // not allowed to produce
2698 // StorageImageReadWithoutFormat/StorageImageWriteWithoutFormat, see
2699 // https://github.com/KhronosGroup/SPIRV-Headers/issues/487
2700
2701 if (isImageTypeWithUnknownFormat(TypeDef) && ST.isShader())
2702 Reqs.addCapability(SPIRV::Capability::StorageImageReadWithoutFormat);
2703 break;
2704 }
2705 case SPIRV::OpImageWrite: {
2706 Register ImageReg = MI.getOperand(0).getReg();
2707 SPIRVTypeInst TypeDef = ST.getSPIRVGlobalRegistry()->getResultType(
2708 ImageReg, const_cast<MachineFunction *>(MI.getMF()));
2709 // OpImageRead and OpImageWrite can use Unknown Image Formats
2710 // when the Kernel capability is declared. In the OpenCL environment we are
2711 // not allowed to produce
2712 // StorageImageReadWithoutFormat/StorageImageWriteWithoutFormat, see
2713 // https://github.com/KhronosGroup/SPIRV-Headers/issues/487
2714
2715 if (isImageTypeWithUnknownFormat(TypeDef) && ST.isShader())
2716 Reqs.addCapability(SPIRV::Capability::StorageImageWriteWithoutFormat);
2717 break;
2718 }
2719 case SPIRV::OpTypeStructContinuedINTEL:
2720 case SPIRV::OpConstantCompositeContinuedINTEL:
2721 case SPIRV::OpSpecConstantCompositeContinuedINTEL:
2722 case SPIRV::OpCompositeConstructContinuedINTEL: {
2723 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_long_composites))
2725 "Continued instructions require the "
2726 "following SPIR-V extension: SPV_INTEL_long_composites",
2727 false);
2728 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_long_composites);
2729 Reqs.addCapability(SPIRV::Capability::LongCompositesINTEL);
2730 break;
2731 }
2732 case SPIRV::OpArbitraryFloatEQALTERA:
2733 case SPIRV::OpArbitraryFloatGEALTERA:
2734 case SPIRV::OpArbitraryFloatGTALTERA:
2735 case SPIRV::OpArbitraryFloatLEALTERA:
2736 case SPIRV::OpArbitraryFloatLTALTERA:
2737 case SPIRV::OpArbitraryFloatCbrtALTERA:
2738 case SPIRV::OpArbitraryFloatCosALTERA:
2739 case SPIRV::OpArbitraryFloatCosPiALTERA:
2740 case SPIRV::OpArbitraryFloatExp10ALTERA:
2741 case SPIRV::OpArbitraryFloatExp2ALTERA:
2742 case SPIRV::OpArbitraryFloatExpALTERA:
2743 case SPIRV::OpArbitraryFloatExpm1ALTERA:
2744 case SPIRV::OpArbitraryFloatHypotALTERA:
2745 case SPIRV::OpArbitraryFloatLog10ALTERA:
2746 case SPIRV::OpArbitraryFloatLog1pALTERA:
2747 case SPIRV::OpArbitraryFloatLog2ALTERA:
2748 case SPIRV::OpArbitraryFloatLogALTERA:
2749 case SPIRV::OpArbitraryFloatRecipALTERA:
2750 case SPIRV::OpArbitraryFloatSinCosALTERA:
2751 case SPIRV::OpArbitraryFloatSinCosPiALTERA:
2752 case SPIRV::OpArbitraryFloatSinALTERA:
2753 case SPIRV::OpArbitraryFloatSinPiALTERA:
2754 case SPIRV::OpArbitraryFloatSqrtALTERA:
2755 case SPIRV::OpArbitraryFloatACosALTERA:
2756 case SPIRV::OpArbitraryFloatACosPiALTERA:
2757 case SPIRV::OpArbitraryFloatAddALTERA:
2758 case SPIRV::OpArbitraryFloatASinALTERA:
2759 case SPIRV::OpArbitraryFloatASinPiALTERA:
2760 case SPIRV::OpArbitraryFloatATan2ALTERA:
2761 case SPIRV::OpArbitraryFloatATanALTERA:
2762 case SPIRV::OpArbitraryFloatATanPiALTERA:
2763 case SPIRV::OpArbitraryFloatCastFromIntALTERA:
2764 case SPIRV::OpArbitraryFloatCastALTERA:
2765 case SPIRV::OpArbitraryFloatCastToIntALTERA:
2766 case SPIRV::OpArbitraryFloatDivALTERA:
2767 case SPIRV::OpArbitraryFloatMulALTERA:
2768 case SPIRV::OpArbitraryFloatPowALTERA:
2769 case SPIRV::OpArbitraryFloatPowNALTERA:
2770 case SPIRV::OpArbitraryFloatPowRALTERA:
2771 case SPIRV::OpArbitraryFloatRSqrtALTERA:
2772 case SPIRV::OpArbitraryFloatSubALTERA: {
2773 if (!ST.canUseExtension(
2774 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_floating_point))
2776 "Floating point instructions can't be translated correctly without "
2777 "enabled SPV_ALTERA_arbitrary_precision_floating_point extension!",
2778 false);
2779 Reqs.addExtension(
2780 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_floating_point);
2781 Reqs.addCapability(
2782 SPIRV::Capability::ArbitraryPrecisionFloatingPointALTERA);
2783 break;
2784 }
2785 case SPIRV::OpSubgroupMatrixMultiplyAccumulateINTEL: {
2786 if (!ST.canUseExtension(
2787 SPIRV::Extension::SPV_INTEL_subgroup_matrix_multiply_accumulate))
2789 "OpSubgroupMatrixMultiplyAccumulateINTEL instruction requires the "
2790 "following SPIR-V "
2791 "extension: SPV_INTEL_subgroup_matrix_multiply_accumulate",
2792 false);
2793 Reqs.addExtension(
2794 SPIRV::Extension::SPV_INTEL_subgroup_matrix_multiply_accumulate);
2795 Reqs.addCapability(
2796 SPIRV::Capability::SubgroupMatrixMultiplyAccumulateINTEL);
2797 break;
2798 }
2799 case SPIRV::OpBitwiseFunctionINTEL: {
2800 if (!ST.canUseExtension(
2801 SPIRV::Extension::SPV_INTEL_ternary_bitwise_function))
2803 "OpBitwiseFunctionINTEL instruction requires the following SPIR-V "
2804 "extension: SPV_INTEL_ternary_bitwise_function",
2805 false);
2806 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_ternary_bitwise_function);
2807 Reqs.addCapability(SPIRV::Capability::TernaryBitwiseFunctionINTEL);
2808 break;
2809 }
2810 case SPIRV::OpCopyMemorySized: {
2811 Reqs.addCapability(SPIRV::Capability::Addresses);
2812 // TODO: Add UntypedPointersKHR when implemented.
2813 break;
2814 }
2815 case SPIRV::OpTypeUntypedPointerKHR:
2816 Reqs.getAndAddRequirements(SPIRV::OperandCategory::StorageClassOperand,
2817 MI.getOperand(1).getImm(), ST);
2818 [[fallthrough]];
2819 case SPIRV::OpUntypedVariableKHR:
2820 case SPIRV::OpUntypedAccessChainKHR:
2821 case SPIRV::OpUntypedInBoundsAccessChainKHR:
2822 case SPIRV::OpUntypedPtrAccessChainKHR:
2823 case SPIRV::OpUntypedInBoundsPtrAccessChainKHR:
2824 case SPIRV::OpUntypedPrefetchKHR:
2825 case SPIRV::OpUntypedGroupAsyncCopyKHR: {
2826 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_untyped_pointers))
2827 report_fatal_error("Untyped pointer instructions require the following "
2828 "SPIR-V extension: SPV_KHR_untyped_pointers",
2829 false);
2830 Reqs.addExtension(SPIRV::Extension::SPV_KHR_untyped_pointers);
2831 Reqs.addCapability(SPIRV::Capability::UntypedPointersKHR);
2832 break;
2833 }
2834 case SPIRV::OpPredicatedLoadINTEL:
2835 case SPIRV::OpPredicatedStoreINTEL: {
2836 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_predicated_io))
2838 "OpPredicated[Load/Store]INTEL instructions require "
2839 "the following SPIR-V extension: SPV_INTEL_predicated_io",
2840 false);
2841 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_predicated_io);
2842 Reqs.addCapability(SPIRV::Capability::PredicatedIOINTEL);
2843 break;
2844 }
2845 case SPIRV::OpFAddS:
2846 case SPIRV::OpFSubS:
2847 case SPIRV::OpFMulS:
2848 case SPIRV::OpFDivS:
2849 case SPIRV::OpFRemS:
2850 case SPIRV::OpFMod:
2851 case SPIRV::OpFNegate:
2852 case SPIRV::OpFAddV:
2853 case SPIRV::OpFSubV:
2854 case SPIRV::OpFMulV:
2855 case SPIRV::OpFDivV:
2856 case SPIRV::OpFRemV:
2857 case SPIRV::OpFNegateV: {
2858 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2859 SPIRVTypeInst TypeDef = MRI.getVRegDef(MI.getOperand(1).getReg());
2860 if (isVectorType(TypeDef))
2861 TypeDef = MRI.getVRegDef(TypeDef->getOperand(1).getReg());
2862 if (isBFloat16Type(TypeDef) && !addBFloat16ArithmeticRequirements(Reqs, ST))
2864 "Arithmetic instructions with bfloat16 arguments require the "
2865 "following SPIR-V extension: SPV_EXT_bfloat16_arithmetic",
2866 false);
2867 break;
2868 }
2869 case SPIRV::OpOrdered:
2870 case SPIRV::OpUnordered:
2871 case SPIRV::OpFOrdEqual:
2872 case SPIRV::OpFOrdNotEqual:
2873 case SPIRV::OpFOrdLessThan:
2874 case SPIRV::OpFOrdLessThanEqual:
2875 case SPIRV::OpFOrdGreaterThan:
2876 case SPIRV::OpFOrdGreaterThanEqual:
2877 case SPIRV::OpFUnordEqual:
2878 case SPIRV::OpFUnordNotEqual:
2879 case SPIRV::OpFUnordLessThan:
2880 case SPIRV::OpFUnordLessThanEqual:
2881 case SPIRV::OpFUnordGreaterThan:
2882 case SPIRV::OpFUnordGreaterThanEqual: {
2883 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2884 SPIRVTypeInst TypeDef = getRegType(MI.getOperand(2).getReg(), *MI.getMF(),
2885 ST.getSPIRVGlobalRegistry());
2886 assert(TypeDef && "Unexpected type instruction for comparison operand");
2887 if (isVectorType(TypeDef))
2888 TypeDef = MRI.getVRegDef(TypeDef->getOperand(1).getReg());
2889 if (isBFloat16Type(TypeDef) && !addBFloat16ArithmeticRequirements(Reqs, ST))
2891 "Relational instructions with bfloat16 arguments require the "
2892 "following SPIR-V extension: SPV_EXT_bfloat16_arithmetic",
2893 false);
2894 break;
2895 }
2896 case SPIRV::OpDPdxCoarse:
2897 case SPIRV::OpDPdyCoarse:
2898 case SPIRV::OpDPdxFine:
2899 case SPIRV::OpDPdyFine: {
2900 Reqs.addCapability(SPIRV::Capability::DerivativeControl);
2901 break;
2902 }
2903 case SPIRV::OpLoopControlINTEL: {
2904 Reqs.addExtension(SPIRV::Extension::SPV_INTEL_unstructured_loop_controls);
2905 Reqs.addCapability(SPIRV::Capability::UnstructuredLoopControlsINTEL);
2906 break;
2907 }
2908
2909 default:
2910 break;
2911 }
2912
2913 // If we require capability Shader, then we can remove the requirement for
2914 // the BitInstructions capability, since Shader is a superset capability
2915 // of BitInstructions.
2916 Reqs.removeCapabilityIf(SPIRV::Capability::BitInstructions,
2917 SPIRV::Capability::Shader);
2918}
2919
2920// Returns the first instruction in MF that uses a variable decorated BuiltIn
2921// PointSize, or nullptr.
2923 const MachineRegisterInfo &MRI = MF.getRegInfo();
2924 for (const MachineBasicBlock &MBB : MF)
2925 for (const MachineInstr &MI : MBB) {
2926 if (MI.getOpcode() != SPIRV::OpDecorate ||
2927 MI.getOperand(1).getImm() != SPIRV::Decoration::BuiltIn ||
2928 MI.getOperand(2).getImm() != SPIRV::BuiltIn::PointSize)
2929 continue;
2930 for (const MachineInstr &User :
2931 MRI.use_nodbg_instructions(MI.getOperand(0).getReg()))
2932 if (User.getOpcode() != SPIRV::OpDecorate &&
2933 User.getOpcode() != SPIRV::OpName)
2934 return &User;
2935 }
2936 return nullptr;
2937}
2938
2939// Vulkan allows BuiltIn PointSize only in the MeshEXT, MeshNV, Vertex,
2940// TessellationControl, TessellationEvaluation and Geometry execution models
2941// (VUID-PointSize-PointSize-04314), so the static call tree of a Fragment entry
2942// point must not access it.
2943static void checkFragmentPointSize(const Module &M,
2944 MachineFunctionGetter GetMF) {
2945 for (const Function &EntryF : M) {
2946 // Pixel shaders become Fragment entry points.
2947 if (EntryF.getFnAttribute("hlsl.shader").getValueAsString() != "pixel")
2948 continue;
2949
2950 // Walk its static call tree and report the first use of PointSize.
2952 SmallVector<const Function *, 8> Worklist = {&EntryF};
2953 while (!Worklist.empty()) {
2954 const Function *F = Worklist.pop_back_val();
2955 if (!Visited.insert(F).second)
2956 continue;
2957 const MachineFunction *MF = GetMF(*F);
2958 if (const MachineInstr *Use = MF ? findPointSizeUse(*MF) : nullptr) {
2960 "BuiltIn PointSize cannot be used in a Fragment "
2961 "entry point (VUID-PointSize-PointSize-04314)");
2962 break;
2963 }
2964
2965 // Queue the defined functions called by F.
2966 for (const Instruction &I : instructions(*F))
2967 if (const auto *Call = dyn_cast<CallBase>(&I))
2968 if (const Function *Callee = Call->getCalledFunction();
2969 Callee && !Callee->isDeclaration())
2970 Worklist.push_back(Callee);
2971 }
2972 }
2973}
2974
2976 MachineFunctionGetter GetMF, const SPIRVSubtarget &ST) {
2977 if (ST.isShader())
2978 checkFragmentPointSize(M, GetMF);
2979
2980 // Collect requirements for existing instructions.
2981 for (const Function &F : M) {
2982 MachineFunction *MF = GetMF(F);
2983 if (!MF)
2984 continue;
2985 for (const MachineBasicBlock &MBB : *MF)
2986 for (const MachineInstr &MI : MBB)
2987 addInstrRequirements(MI, MAI, ST);
2988 }
2989 // Collect requirements for OpExecutionMode instructions.
2990 auto Node = M.getNamedMetadata("spirv.ExecutionMode");
2991 if (Node) {
2992 bool RequireFloatControls = false, RequireIntelFloatControls2 = false,
2993 RequireKHRFloatControls2 = false,
2994 VerLower14 = !ST.isAtLeastSPIRVVer(VersionTuple(1, 4));
2995 bool HasIntelFloatControls2 =
2996 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_float_controls2);
2997 bool HasKHRFloatControls2 =
2998 ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2);
2999 for (unsigned i = 0; i < Node->getNumOperands(); i++) {
3000 MDNode *MDN = cast<MDNode>(Node->getOperand(i));
3001 const MDOperand &MDOp = MDN->getOperand(1);
3002 if (auto *CMeta = dyn_cast<ConstantAsMetadata>(MDOp)) {
3003 Constant *C = CMeta->getValue();
3004 if (ConstantInt *Const = dyn_cast<ConstantInt>(C)) {
3005 auto EM = Const->getZExtValue();
3006 // SPV_KHR_float_controls is not available until v1.4:
3007 // add SPV_KHR_float_controls if the version is too low
3008 switch (EM) {
3009 case SPIRV::ExecutionMode::DenormPreserve:
3010 case SPIRV::ExecutionMode::DenormFlushToZero:
3011 case SPIRV::ExecutionMode::RoundingModeRTE:
3012 case SPIRV::ExecutionMode::RoundingModeRTZ:
3013 RequireFloatControls = VerLower14;
3015 SPIRV::OperandCategory::ExecutionModeOperand, EM, ST);
3016 break;
3017 case SPIRV::ExecutionMode::RoundingModeRTPINTEL:
3018 case SPIRV::ExecutionMode::RoundingModeRTNINTEL:
3019 case SPIRV::ExecutionMode::FloatingPointModeALTINTEL:
3020 case SPIRV::ExecutionMode::FloatingPointModeIEEEINTEL:
3021 if (HasIntelFloatControls2) {
3022 RequireIntelFloatControls2 = true;
3024 SPIRV::OperandCategory::ExecutionModeOperand, EM, ST);
3025 }
3026 break;
3027 case SPIRV::ExecutionMode::FPFastMathDefault: {
3028 if (HasKHRFloatControls2) {
3029 RequireKHRFloatControls2 = true;
3031 SPIRV::OperandCategory::ExecutionModeOperand, EM, ST);
3032 }
3033 break;
3034 }
3035 case SPIRV::ExecutionMode::ContractionOff:
3036 case SPIRV::ExecutionMode::SignedZeroInfNanPreserve:
3037 if (HasKHRFloatControls2) {
3038 RequireKHRFloatControls2 = true;
3040 SPIRV::OperandCategory::ExecutionModeOperand,
3041 SPIRV::ExecutionMode::FPFastMathDefault, ST);
3042 } else {
3044 SPIRV::OperandCategory::ExecutionModeOperand, EM, ST);
3045 }
3046 break;
3047 default:
3049 SPIRV::OperandCategory::ExecutionModeOperand, EM, ST);
3050 }
3051 }
3052 }
3053 }
3054 if (RequireFloatControls &&
3055 ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls))
3056 MAI.Reqs.addExtension(SPIRV::Extension::SPV_KHR_float_controls);
3057 if (RequireIntelFloatControls2)
3058 MAI.Reqs.addExtension(SPIRV::Extension::SPV_INTEL_float_controls2);
3059 if (RequireKHRFloatControls2)
3060 MAI.Reqs.addExtension(SPIRV::Extension::SPV_KHR_float_controls2);
3061 }
3062 for (const Function &F : M) {
3063 if (F.isDeclaration())
3064 continue;
3065 if (F.getMetadata("reqd_work_group_size"))
3067 SPIRV::OperandCategory::ExecutionModeOperand,
3068 SPIRV::ExecutionMode::LocalSize, ST);
3069 if (F.getFnAttribute("hlsl.numthreads").isValid()) {
3071 SPIRV::OperandCategory::ExecutionModeOperand,
3072 SPIRV::ExecutionMode::LocalSize, ST);
3073 }
3074 if (F.getFnAttribute("enable-maximal-reconvergence").getValueAsBool()) {
3075 MAI.Reqs.addExtension(SPIRV::Extension::SPV_KHR_maximal_reconvergence);
3076 }
3077 if (F.getMetadata("work_group_size_hint"))
3079 SPIRV::OperandCategory::ExecutionModeOperand,
3080 SPIRV::ExecutionMode::LocalSizeHint, ST);
3081 if (F.getMetadata("intel_reqd_sub_group_size") ||
3082 F.getMetadata("reqd_sub_group_size"))
3084 SPIRV::OperandCategory::ExecutionModeOperand,
3085 SPIRV::ExecutionMode::SubgroupSize, ST);
3086 if (F.getMetadata("max_work_group_size"))
3088 SPIRV::OperandCategory::ExecutionModeOperand,
3089 SPIRV::ExecutionMode::MaxWorkgroupSizeINTEL, ST);
3090 if (F.getMetadata("vec_type_hint"))
3092 SPIRV::OperandCategory::ExecutionModeOperand,
3093 SPIRV::ExecutionMode::VecTypeHint, ST);
3094
3095 if (F.hasOptNone()) {
3096 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_optnone)) {
3097 MAI.Reqs.addExtension(SPIRV::Extension::SPV_INTEL_optnone);
3098 MAI.Reqs.addCapability(SPIRV::Capability::OptNoneINTEL);
3099 } else if (ST.canUseExtension(SPIRV::Extension::SPV_EXT_optnone)) {
3100 MAI.Reqs.addExtension(SPIRV::Extension::SPV_EXT_optnone);
3101 MAI.Reqs.addCapability(SPIRV::Capability::OptNoneEXT);
3102 }
3103 }
3104 }
3105}
3106
3107static unsigned getFastMathFlags(const MachineInstr &I,
3108 const SPIRVSubtarget &ST) {
3109 unsigned Flags = SPIRV::FPFastMathMode::None;
3110 bool CanUseKHRFloatControls2 =
3111 ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2);
3112 if (I.getFlag(MachineInstr::MIFlag::FmNoNans))
3113 Flags |= SPIRV::FPFastMathMode::NotNaN;
3114 if (I.getFlag(MachineInstr::MIFlag::FmNoInfs))
3115 Flags |= SPIRV::FPFastMathMode::NotInf;
3116 if (I.getFlag(MachineInstr::MIFlag::FmNsz))
3117 Flags |= SPIRV::FPFastMathMode::NSZ;
3118 if (I.getFlag(MachineInstr::MIFlag::FmArcp))
3119 Flags |= SPIRV::FPFastMathMode::AllowRecip;
3120 if (I.getFlag(MachineInstr::MIFlag::FmContract) && CanUseKHRFloatControls2)
3121 Flags |= SPIRV::FPFastMathMode::AllowContract;
3122 if (I.getFlag(MachineInstr::MIFlag::FmReassoc)) {
3123 if (CanUseKHRFloatControls2)
3124 // LLVM reassoc maps to SPIRV transform, see
3125 // https://github.com/KhronosGroup/SPIRV-Registry/issues/326 for details.
3126 // Because we are enabling AllowTransform, we must enable AllowReassoc and
3127 // AllowContract too, as required by SPIRV spec. Also, we used to map
3128 // MIFlag::FmReassoc to FPFastMathMode::Fast, which now should instead by
3129 // replaced by turning all the other bits instead. Therefore, we're
3130 // enabling every bit here except None and Fast.
3131 Flags |= SPIRV::FPFastMathMode::NotNaN | SPIRV::FPFastMathMode::NotInf |
3132 SPIRV::FPFastMathMode::NSZ | SPIRV::FPFastMathMode::AllowRecip |
3133 SPIRV::FPFastMathMode::AllowTransform |
3134 SPIRV::FPFastMathMode::AllowReassoc |
3135 SPIRV::FPFastMathMode::AllowContract;
3136 else
3137 Flags |= SPIRV::FPFastMathMode::Fast;
3138 }
3139
3140 if (CanUseKHRFloatControls2) {
3141 // Error out if SPIRV::FPFastMathMode::Fast is enabled.
3142 assert(!(Flags & SPIRV::FPFastMathMode::Fast) &&
3143 "SPIRV::FPFastMathMode::Fast is deprecated and should not be used "
3144 "anymore.");
3145
3146 // Error out if AllowTransform is enabled without AllowReassoc and
3147 // AllowContract.
3148 assert((!(Flags & SPIRV::FPFastMathMode::AllowTransform) ||
3149 ((Flags & SPIRV::FPFastMathMode::AllowReassoc &&
3150 Flags & SPIRV::FPFastMathMode::AllowContract))) &&
3151 "SPIRV::FPFastMathMode::AllowTransform requires AllowReassoc and "
3152 "AllowContract flags to be enabled as well.");
3153 }
3154
3155 return Flags;
3156}
3157
3159 if (ST.isKernel())
3160 return true;
3161 if (ST.getSPIRVVersion() < VersionTuple(1, 2))
3162 return false;
3163 return ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2);
3164}
3165
3167 MachineInstr &I, const SPIRVSubtarget &ST, const SPIRVInstrInfo &TII,
3169 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec) {
3170 bool Changed = false;
3171 // Insert after I so that the decorated register is defined before its use.
3172 MachineBasicBlock::iterator InsertPt = std::next(I.getIterator());
3173 auto Decorate = [&](SPIRV::Decoration::Decoration Dec,
3174 ArrayRef<uint32_t> DecArgs) {
3175 MachineIRBuilder MIRBuilder(*I.getParent(), InsertPt);
3176 MIRBuilder.setDebugLoc(I.getDebugLoc());
3177 buildOpDecorate(I.getOperand(0).getReg(), MIRBuilder, Dec, DecArgs);
3178 Changed = true;
3179 };
3180 if (TII.canUseIntegerWrapDecoration(I)) {
3181 if (I.getFlag(MachineInstr::MIFlag::NoSWrap) &&
3183 SPIRV::OperandCategory::DecorationOperand,
3184 SPIRV::Decoration::NoSignedWrap, ST, Reqs)
3185 .IsSatisfiable)
3186 Decorate(SPIRV::Decoration::NoSignedWrap, {});
3187 if (I.getFlag(MachineInstr::MIFlag::NoUWrap) &&
3189 SPIRV::OperandCategory::DecorationOperand,
3190 SPIRV::Decoration::NoUnsignedWrap, ST, Reqs)
3191 .IsSatisfiable)
3192 Decorate(SPIRV::Decoration::NoUnsignedWrap, {});
3193 }
3194 // In Kernel environments, FPFastMathMode on OpExtInst is valid per core
3195 // spec. For other instruction types, SPV_KHR_float_controls2 is required.
3196 bool CanUseFM =
3197 TII.canUseFastMathFlags(
3198 I, ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2)) ||
3199 (ST.isKernel() && I.getOpcode() == SPIRV::OpExtInst);
3200 if (!CanUseFM)
3201 return Changed;
3202
3203 unsigned FMFlags = getFastMathFlags(I, ST);
3204 if (FMFlags == SPIRV::FPFastMathMode::None) {
3205 // We also need to check if any FPFastMathDefault info was set for the
3206 // types used in this instruction.
3207 if (FPFastMathDefaultInfoVec.empty())
3208 return Changed;
3209
3210 // Use the first operand's FP type for arithmetic and comparisons,
3211 // and the result type for calls and extended instructions.
3212 SPIRVTypeInst FPType =
3213 I.getOpcode() == SPIRV::OpExtInst ||
3214 I.getOpcode() == SPIRV::OpFunctionCall
3215 ? I.getMF()->getRegInfo().getVRegDef(I.getOperand(1).getReg())
3216 : getRegType(I.getOperand(2).getReg(), *I.getMF(), GR);
3217 const Type *Ty = GR->getTypeForSPIRVType(FPType);
3218 Ty = Ty->isVectorTy() ? cast<VectorType>(Ty)->getElementType() : Ty;
3219
3220 // Match instruction type with the FPFastMathDefaultInfoVec.
3221 bool Emit = false;
3222 for (SPIRV::FPFastMathDefaultInfo &Elem : FPFastMathDefaultInfoVec) {
3223 if (Ty == Elem.Ty) {
3224 FMFlags = Elem.FastMathFlags;
3225 Emit = Elem.ContractionOff || Elem.SignedZeroInfNanPreserve ||
3226 Elem.FPFastMathDefault;
3227 break;
3228 }
3229 }
3230
3231 if (FMFlags == SPIRV::FPFastMathMode::None && !Emit)
3232 return Changed;
3233 }
3235 Decorate(SPIRV::Decoration::FPFastMathMode, {FMFlags});
3236 return Changed;
3237}
3238
3239static void addMBBNames(const Module &M, MachineFunctionGetter GetMF,
3241 for (const Function &F : M) {
3242 MachineFunction *MF = GetMF(F);
3243 if (!MF)
3244 continue;
3245 if (MF->getFunction()
3247 .isValid())
3248 continue;
3249 for (const auto &MBB : *MF) {
3250 if (!MBB.hasName() || MBB.empty())
3251 continue;
3252 MAI.MBBNames.emplace_back(MAI.getOrCreateMBBRegister(MBB), MBB.getName());
3253 }
3254 }
3255}
3256
3258 const Module &M,
3259 SPIRV::FPFastMathDefaultInfoMapTy &FPFastMathDefaultInfoMap,
3260 const Function *F) {
3261 auto it = FPFastMathDefaultInfoMap.find(F);
3262 if (it != FPFastMathDefaultInfoMap.end())
3263 return it->second;
3264
3265 // If the map does not contain the entry, create a new one. Initialize it to
3266 // contain all 3 elements sorted by bit width of target type: {half, float,
3267 // double}.
3268 SPIRV::FPFastMathDefaultInfoVector FPFastMathDefaultInfoVec;
3269 FPFastMathDefaultInfoVec.emplace_back(Type::getHalfTy(M.getContext()),
3270 SPIRV::FPFastMathMode::None);
3271 FPFastMathDefaultInfoVec.emplace_back(Type::getFloatTy(M.getContext()),
3272 SPIRV::FPFastMathMode::None);
3273 FPFastMathDefaultInfoVec.emplace_back(Type::getDoubleTy(M.getContext()),
3274 SPIRV::FPFastMathMode::None);
3275 return FPFastMathDefaultInfoMap[F] = std::move(FPFastMathDefaultInfoVec);
3276}
3277
3279 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec,
3280 const Type *Ty) {
3281 size_t BitWidth = Ty->getScalarSizeInBits();
3282 int Index =
3284 BitWidth);
3285 assert(Index >= 0 && Index < 3 &&
3286 "Expected FPFastMathDefaultInfo for half, float, or double");
3287 assert(FPFastMathDefaultInfoVec.size() == 3 &&
3288 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3289 return FPFastMathDefaultInfoVec[Index];
3290}
3291
3293 const Module &M,
3294 SPIRV::FPFastMathDefaultInfoMapTy &FPFastMathDefaultInfoMap,
3295 const SPIRVSubtarget &ST, const Function *OnlyF = nullptr) {
3296 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2))
3297 return;
3298
3299 // Store the FPFastMathDefaultInfo in the FPFastMathDefaultInfoMap.
3300 // We need the entry point (function) as the key, and the target
3301 // type and flags as the value.
3302 // We also need to check ContractionOff and SignedZeroInfNanPreserve
3303 // execution modes, as they are now deprecated and must be replaced
3304 // with FPFastMathDefaultInfo.
3305 auto Node = M.getNamedMetadata("spirv.ExecutionMode");
3306 if (!Node)
3307 return;
3308
3309 for (unsigned i = 0; i < Node->getNumOperands(); i++) {
3310 MDNode *MDN = cast<MDNode>(Node->getOperand(i));
3311 assert(MDN->getNumOperands() >= 2 && "Expected at least 2 operands");
3312 const Function *F = cast<Function>(
3313 cast<ConstantAsMetadata>(MDN->getOperand(0))->getValue());
3314 if (OnlyF && F != OnlyF)
3315 continue;
3316 const auto EM =
3318 cast<ConstantAsMetadata>(MDN->getOperand(1))->getValue())
3319 ->getZExtValue();
3320 if (EM == SPIRV::ExecutionMode::FPFastMathDefault) {
3321 assert(MDN->getNumOperands() == 4 &&
3322 "Expected 4 operands for FPFastMathDefault");
3323
3324 const Type *T = cast<ValueAsMetadata>(MDN->getOperand(2))->getType();
3325 unsigned Flags =
3327 cast<ConstantAsMetadata>(MDN->getOperand(3))->getValue())
3328 ->getZExtValue();
3329 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3330 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3332 getFPFastMathDefaultInfo(FPFastMathDefaultInfoVec, T);
3333 Info.FastMathFlags = Flags;
3334 Info.FPFastMathDefault = true;
3335 } else if (EM == SPIRV::ExecutionMode::ContractionOff) {
3336 assert(MDN->getNumOperands() == 2 &&
3337 "Expected no operands for ContractionOff");
3338
3339 // We need to save this info for every possible FP type, i.e. {half,
3340 // float, double, fp128}.
3341 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3342 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3343 for (SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3344 Info.ContractionOff = true;
3345 }
3346 } else if (EM == SPIRV::ExecutionMode::SignedZeroInfNanPreserve) {
3347 assert(MDN->getNumOperands() == 3 &&
3348 "Expected 1 operand for SignedZeroInfNanPreserve");
3349 unsigned TargetWidth =
3351 cast<ConstantAsMetadata>(MDN->getOperand(2))->getValue())
3352 ->getZExtValue();
3353 // We need to save this info only for the FP type with TargetWidth.
3354 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3355 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3358 assert(Index >= 0 && Index < 3 &&
3359 "Expected FPFastMathDefaultInfo for half, float, or double");
3360 assert(FPFastMathDefaultInfoVec.size() == 3 &&
3361 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3362 FPFastMathDefaultInfoVec[Index].SignedZeroInfNanPreserve = true;
3363 }
3364 }
3365}
3366
3370 : ST(&ST), GR(ST.getSPIRVGlobalRegistry()), TII(ST.getInstrInfo()),
3371 MAI(MAI), GetMF(GetMF) {}
3372
3374 setBaseInfo(M);
3375
3376 addMBBNames(M, GetMF, MAI);
3377 collectFPFastMathDefaults(M, MAI.FPFastMathDefaultInfoMap, *ST);
3378
3379 collectReqs(M, MAI, GetMF, *ST);
3380
3381 // Process type/const/global var/func decl instructions, number their
3382 // destination registers from 0 to N, collect Extensions and Capabilities.
3383 collectDeclarations(M);
3384
3385 // Number rest of registers from N+1 onwards.
3386 numberRegistersGlobally(M);
3387
3388 // Collect OpName, OpEntryPoint, OpDecorate etc, process other instructions.
3389 processOtherInstrs(M);
3390
3391 // If there are no entry points, we need the Linkage capability.
3392 if (MAI.MS[SPIRV::MB_EntryPoints].empty())
3393 MAI.Reqs.addCapability(SPIRV::Capability::Linkage);
3394
3395 // Set maximum ID used.
3396 GR->setBound(MAI.MaxID);
3397}
3398
3403
3405 SPIRVTargetMachine &TM =
3409 *TM.getSubtargetImpl(), MAI,
3410 [&MMI](const Function &F) { return MMI.getMachineFunction(F); })
3411 .run(M);
3412 return false;
3413}
3414
3415AnalysisKey SPIRVModuleAnalysis::Key;
3416
3419 const auto &TM = static_cast<const SPIRVTargetMachine &>(
3420 MAM.getResult<MachineModuleAnalysis>(M).getMMI().getTarget());
3422 MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
3423 Result MAI;
3424 SPIRVModuleAnalysisImpl(*TM.getSubtargetImpl(), MAI,
3425 [&FAM](const Function &F) -> MachineFunction * {
3426 MachineFunctionAnalysis::Result *MFA =
3427 FAM.getCachedResult<MachineFunctionAnalysis>(
3428 const_cast<Function &>(F));
3429 assert((MFA || F.isDeclaration()) &&
3430 "Missing MachineFunction for definition");
3431 return MFA ? &MFA->getMF() : nullptr;
3432 })
3433 .run(M);
3434 return MAI;
3435}
3436
3438 const auto &ST = MF.getSubtarget<SPIRVSubtarget>();
3439 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
3440 const SPIRVInstrInfo &TII = *ST.getInstrInfo();
3443 SPIRV::FPFastMathDefaultInfoMapTy FPFastMathDefaultInfoMap;
3444 const Function &F = MF.getFunction();
3445 collectFPFastMathDefaults(*F.getParent(), FPFastMathDefaultInfoMap, ST, &F);
3446 // Add decorations related to MI flags.
3447 bool Changed = false;
3448 for (auto &MBB : MF)
3449 for (auto &MI : make_early_inc_range(MBB))
3450 Changed |= handleMIFlagDecoration(MI, ST, TII, Reqs, GR,
3451 FPFastMathDefaultInfoMap[&F]);
3452 return Changed;
3453}
3454
3455namespace {
3456class SPIRVPrepareModuleAnalysisLegacy : public MachineFunctionPass {
3457public:
3458 static char ID;
3459 SPIRVPrepareModuleAnalysisLegacy() : MachineFunctionPass(ID) {}
3460 bool runOnMachineFunction(MachineFunction &MF) override {
3461 return prepareModuleAnalysis(MF);
3462 }
3463};
3464} // namespace
3465
3466char SPIRVPrepareModuleAnalysisLegacy::ID = 0;
3467
3468INITIALIZE_PASS(SPIRVPrepareModuleAnalysisLegacy,
3469 "spirv-prepare-module-analysis",
3470 "SPIRV prepare module analysis", false, false)
3471
3473 return new SPIRVPrepareModuleAnalysisLegacy();
3474}
3475
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
const AArch64InstrInfo & TII
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock & MBB
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
static Register UseReg(const MachineOperand &MO)
IRTranslator LLVM IR MI
unsigned Opc
#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
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
static const MachineInstr * findPointSizeUse(const MachineFunction &MF)
#define ATOM_FLT_REQ_EXT_MSG(ExtName)
static bool isFastMathModeAvailable(const SPIRVSubtarget &ST)
static void addMBBNames(const Module &M, MachineFunctionGetter GetMF, SPIRV::ModuleAnalysisInfo &MAI)
static void maybeAddScatterGatherReq(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static void addImageOperandReqs(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST, unsigned OpIdx)
bool isStorageImage(MachineInstr *ImageInst)
bool isInputAttachment(MachineInstr *ImageInst)
static bool isBFloat16Type(SPIRVTypeInst TypeDef)
static bool handleMIFlagDecoration(MachineInstr &I, const SPIRVSubtarget &ST, const SPIRVInstrInfo &TII, SPIRV::RequirementHandler &Reqs, const SPIRVGlobalRegistry *GR, SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec)
bool isSampledImage(MachineInstr *ImageInst)
static bool hasVertexOrTessellationEntryPoint(const MachineInstr &MI)
static bool isRoundedDivideSqrtTarget(const MachineInstr &MI)
static bool addBFloat16ArithmeticRequirements(SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static unsigned getInvokeOperandIdx(unsigned Opcode)
static SPIRV::FPFastMathDefaultInfo & getFPFastMathDefaultInfo(SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec, const Type *Ty)
static void collectFPFastMathDefaults(const Module &M, SPIRV::FPFastMathDefaultInfoMapTy &FPFastMathDefaultInfoMap, const SPIRVSubtarget &ST, const Function *OnlyF=nullptr)
static void collectOtherInstr(MachineInstr &MI, SPIRV::ModuleAnalysisInfo &MAI, SPIRV::ModuleSectionType MSType, InstrTraces &IS, bool Append=true)
void addPrintfRequirements(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static void addOpTypeImageReqs(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static void addQuadControlRequirements(SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST, StringRef Feature)
static bool isImageTypeWithUnknownFormat(SPIRVTypeInst TypeInst)
bool isUniformTexelBuffer(MachineInstr *ImageInst)
bool isStorageTexelBuffer(MachineInstr *ImageInst)
static void AddAtomicFloatRequirements(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
bool isCombinedImageSampler(MachineInstr *SampledImageInst)
bool hasNonUniformDecoration(Register Reg, const MachineRegisterInfo &MRI)
const char * Msg
void addInstrRequirements(const MachineInstr &MI, SPIRV::ModuleAnalysisInfo &MAI, const SPIRVSubtarget &ST)
static void collectReqs(const Module &M, SPIRV::ModuleAnalysisInfo &MAI, MachineFunctionGetter GetMF, const SPIRVSubtarget &ST)
static void addOpDecorateReqs(const MachineInstr &MI, unsigned DecIndex, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static InstrSignature instrToSignature(const MachineInstr &MI, SPIRV::ModuleAnalysisInfo &MAI, bool UseDefReg)
static void AddDotProductRequirements(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static SPIRV::Requirements getSymbolicOperandRequirements(SPIRV::OperandCategory::OperandCategory Category, unsigned i, const SPIRVSubtarget &ST, SPIRV::RequirementHandler &Reqs)
static SPIRVTypeInst getRegType(Register Reg, const MachineFunction &MF, const SPIRVGlobalRegistry *GR)
static void checkFragmentPointSize(const Module &M, MachineFunctionGetter GetMF)
static unsigned getMetadataUInt(MDNode *MdNode, unsigned OpIndex, unsigned DefaultVal=0)
static bool isDecoratingOutputVariable(const MachineInstr &MI)
static void addCoreInSPIRV13Capability(SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST, SPIRV::Capability::Capability Cap, SPIRV::Extension::Extension Ext)
void addOpAccessChainReqs(const MachineInstr &Instr, SPIRV::RequirementHandler &Handler, const SPIRVSubtarget &Subtarget)
static bool prepareModuleAnalysis(MachineFunction &MF)
static void appendDecorationsForReg(const MachineRegisterInfo &MRI, Register R, InstrSignature &Signature)
static SPIRV::FPFastMathDefaultInfoVector & getOrCreateFPFastMathDefaultInfoVec(const Module &M, SPIRV::FPFastMathDefaultInfoMapTy &FPFastMathDefaultInfoMap, const Function *F)
static bool shouldAvoidCapability(const SPIRVSubtarget &ST, SPIRV::Capability::Capability Cap)
static void AddAtomicVectorFloatRequirements(const MachineInstr &MI, SPIRV::RequirementHandler &Reqs, const SPIRVSubtarget &ST)
static unsigned getFastMathFlags(const MachineInstr &I, const SPIRVSubtarget &ST)
#define SPIRV_BACKEND_SERVICE_FUN_NAME
Definition SPIRVUtils.h:555
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
#define LLVM_DEBUG(...)
Definition Debug.h:119
Target-Independent Code Generator Pass Configuration Options pass.
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
Value * RHS
Value * LHS
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:260
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This is an important base class in LLVM.
Definition Constant.h:44
Diagnostic information for unsupported feature in backend.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
constexpr bool isValid() const
Definition MCRegister.h:87
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
Tracking metadata reference owned by Metadata.
Definition Metadata.h:908
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
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 setDebugLoc(const DebugLoc &DL)
Set the debug location to DL for all the next build instructions.
Register getReg(unsigned Idx) const
Get the register for the operand index.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
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
An analysis that produces MachineModuleInfo for a module.
This class contains meta information specific to a module.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
LLVM_ABI void print(raw_ostream &os, const TargetRegisterInfo *TRI=nullptr) const
Print the MachineOperand to os.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static MachineOperand CreateImm(int64_t Val)
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
iterator find(const KeyT &Key)
Definition MapVector.h:157
iterator end()
Definition MapVector.h:70
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
unsigned getScalarOrVectorBitWidth(SPIRVTypeInst Type) const
SPIRVTypeInst getResultType(Register VReg, MachineFunction *MF=nullptr)
const Type * getTypeForSPIRVType(SPIRVTypeInst Ty) const
SPIRVTypeInst getSPIRVTypeForVReg(Register VReg, const MachineFunction *MF=nullptr) const
SPIRVModuleAnalysisImpl(const SPIRVSubtarget &ST, SPIRV::ModuleAnalysisInfo &MAI, MachineFunctionGetter GetMF)
SPIRV::ModuleAnalysisInfo Result
Result run(Module &M, ModuleAnalysisManager &MAM)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const SPIRVSubtarget * getSubtargetImpl() 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.
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
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
Target-Independent Code Generator Pass Configuration Options.
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
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
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
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Represents a version number in the form major[.minor[.subminor[.build]]].
bool empty() const
Determine whether this version information is empty (e.g., all version components are zero).
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
MapVector< const Function *, FPFastMathDefaultInfoVector > FPFastMathDefaultInfoMapTy
SmallVector< const MachineInstr * > InstrList
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
Definition STLExtras.h:2132
std::string getStringImm(const MachineInstr &MI, unsigned StartIndex)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
hash_code hash_value(const FixedPointSemantics &Val)
ExtensionList getSymbolicOperandExtensions(SPIRV::OperandCategory::OperandCategory Category, uint32_t Value)
CapabilityList getSymbolicOperandCapabilities(SPIRV::OperandCategory::OperandCategory Category, uint32_t Value)
SmallVector< SPIRV::Extension::Extension, 8 > ExtensionList
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
SmallVector< size_t > InstrSignature
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
static void reportUnsupported(MachineIRBuilder &MIRBuilder, const Twine &Msg)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, ArrayRef< uint32_t > DecArgs, StringRef StrImm)
bool isVectorType(SPIRVTypeInst SPVTy)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
VersionTuple getSymbolicOperandMaxVersion(SPIRV::OperandCategory::OperandCategory Category, uint32_t Value)
function_ref< MachineFunction *(const Function &)> MachineFunctionGetter
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2220
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
CapabilityList getCapabilitiesEnabledByExtension(SPIRV::Extension::Extension Extension)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
FunctionPass * createSPIRVPrepareModuleAnalysisLegacyPass()
std::string getSymbolicOperandMnemonic(SPIRV::OperandCategory::OperandCategory Category, int32_t Value)
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool requiresLongVectorEXT(unsigned NumComponents, bool CanUseVector16=true)
Definition SPIRVUtils.h:510
DWARFExpression::Operation Op
VersionTuple getSymbolicOperandMinVersion(SPIRV::OperandCategory::OperandCategory Category, uint32_t Value)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
std::map< SmallVector< size_t >, MCRegister > InstrGRegsMap
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
SmallVector< SPIRV::Capability::Capability, 8 > CapabilityList
std::set< InstrSignature > InstrTraces
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
static size_t computeFPFastMathDefaultInfoVecIndex(size_t BitWidth)
Definition SPIRVUtils.h:149
void setSkipEmission(const MachineInstr *MI)
MCRegister getRegisterAlias(const MachineFunction *MF, Register Reg)
MCRegister getOrCreateMBBRegister(const MachineBasicBlock &MBB)
InstrList MS[NUM_MODULE_SECTIONS]
AddressingModel::AddressingModel Addr
SmallVector< std::pair< MCRegister, StringRef > > MBBNames
void checkSatisfiable(const SPIRVSubtarget &ST) const
void getAndAddRequirements(SPIRV::OperandCategory::OperandCategory Category, uint32_t i, const SPIRVSubtarget &ST)
void addRequirements(const Requirements &Req)
bool isCapabilityAvailable(Capability::Capability Cap) const
void removeCapabilityIf(const Capability::Capability ToRemove, const Capability::Capability IfPresent)
void addExtensions(const ExtensionList &ToAdd)
void addAvailableCaps(const CapabilityList &ToAdd)
void addExtension(Extension::Extension ToAdd)
void initAvailableCapabilities(const SPIRVSubtarget &ST)
void addCapability(Capability::Capability ToAdd)
void addCapabilities(const CapabilityList &ToAdd)
const std::optional< Capability::Capability > Cap