LLVM 23.0.0git
SPIRVCallLowering.cpp
Go to the documentation of this file.
1//===--- SPIRVCallLowering.cpp - Call lowering ------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the lowering of LLVM calls to machine code calls for
10// GlobalISel.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SPIRVCallLowering.h"
16#include "SPIRV.h"
17#include "SPIRVBuiltins.h"
18#include "SPIRVGlobalRegistry.h"
19#include "SPIRVISelLowering.h"
20#include "SPIRVMetadata.h"
21#include "SPIRVRegisterInfo.h"
22#include "SPIRVSubtarget.h"
23#include "SPIRVUtils.h"
26#include "llvm/IR/IntrinsicsSPIRV.h"
27#include "llvm/Support/ModRef.h"
28
29using namespace llvm;
30
34
36 const Value *Val, ArrayRef<Register> VRegs,
38 Register SwiftErrorVReg) const {
39 // Ignore if called from the internal service function
40 if (MIRBuilder.getMF()
43 .isValid())
44 return true;
45
46 // Currently all return types should use a single register.
47 // TODO: handle the case of multiple registers.
48 if (VRegs.size() > 1)
49 return false;
50 if (Val) {
51 const auto &STI = MIRBuilder.getMF().getSubtarget();
52 return MIRBuilder.buildInstr(SPIRV::OpReturnValue)
53 .addUse(VRegs[0])
54 .constrainAllUses(MIRBuilder.getTII(), *STI.getRegisterInfo(),
55 *STI.getRegBankInfo());
56 }
57 MIRBuilder.buildInstr(SPIRV::OpReturn);
58 return true;
59}
60
61// Based on the LLVM function attributes, get a SPIR-V FunctionControl.
63 const SPIRVSubtarget *ST) {
64 MemoryEffects MemEffects = F.getMemoryEffects();
65
66 uint32_t FuncControl = static_cast<uint32_t>(SPIRV::FunctionControl::None);
67
68 if (F.hasFnAttribute(Attribute::AttrKind::NoInline))
69 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::DontInline);
70 else if (F.hasFnAttribute(Attribute::AttrKind::AlwaysInline))
71 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Inline);
72
73 if (MemEffects.doesNotAccessMemory())
74 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Pure);
75 else if (MemEffects.onlyReadsMemory())
76 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Const);
77
78 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_optnone) ||
79 ST->canUseExtension(SPIRV::Extension::SPV_EXT_optnone))
80 if (F.hasFnAttribute(Attribute::OptimizeNone))
81 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::OptNoneEXT);
82
83 return FuncControl;
84}
85
86static ConstantInt *getConstInt(MDNode *MD, unsigned NumOp) {
87 if (MD->getNumOperands() > NumOp) {
88 auto *CMeta = dyn_cast<ConstantAsMetadata>(MD->getOperand(NumOp));
89 if (CMeta)
90 return dyn_cast<ConstantInt>(CMeta->getValue());
91 }
92 return nullptr;
93}
94
95// If the function has pointer arguments, we are forced to re-create this
96// function type from the very beginning, changing PointerType by
97// TypedPointerType for each pointer argument. Otherwise, the same `Type*`
98// potentially corresponds to different SPIR-V function type, effectively
99// invalidating logic behind global registry and duplicates tracker.
100static FunctionType *
102 FunctionType *FTy, const SPIRVType *SRetTy,
103 const SmallVector<SPIRVType *, 4> &SArgTys) {
104 bool hasArgPtrs = false;
105 for (auto &Arg : F.args()) {
106 // check if it's an instance of a non-typed PointerType
107 if (Arg.getType()->isPointerTy()) {
108 hasArgPtrs = true;
109 break;
110 }
111 }
112 if (!hasArgPtrs) {
113 Type *RetTy = FTy->getReturnType();
114 // check if it's an instance of a non-typed PointerType
115 if (!RetTy->isPointerTy())
116 return FTy;
117 }
118
119 // re-create function type, using TypedPointerType instead of PointerType to
120 // properly trace argument types
121 const Type *RetTy = GR->getTypeForSPIRVType(SRetTy);
123 for (auto SArgTy : SArgTys)
124 ArgTys.push_back(const_cast<Type *>(GR->getTypeForSPIRVType(SArgTy)));
125 return FunctionType::get(const_cast<Type *>(RetTy), ArgTys, false);
126}
127
128static SPIRV::AccessQualifier::AccessQualifier
129getArgAccessQual(const Function &F, unsigned ArgIdx) {
130 if (F.getCallingConv() != CallingConv::SPIR_KERNEL)
131 return SPIRV::AccessQualifier::ReadWrite;
132
133 MDString *ArgAttribute = getOCLKernelArgAccessQual(F, ArgIdx);
134 if (!ArgAttribute)
135 return SPIRV::AccessQualifier::ReadWrite;
136
137 if (ArgAttribute->getString() == "read_only")
138 return SPIRV::AccessQualifier::ReadOnly;
139 if (ArgAttribute->getString() == "write_only")
140 return SPIRV::AccessQualifier::WriteOnly;
141 return SPIRV::AccessQualifier::ReadWrite;
142}
143
144static std::vector<SPIRV::Decoration::Decoration>
145getKernelArgTypeQual(const Function &F, unsigned ArgIdx) {
146 MDString *ArgAttribute = getOCLKernelArgTypeQual(F, ArgIdx);
147 if (ArgAttribute && ArgAttribute->getString() == "volatile")
148 return {SPIRV::Decoration::Volatile};
149 return {};
150}
151
152static SPIRVType *getArgSPIRVType(const Function &F, unsigned ArgIdx,
154 MachineIRBuilder &MIRBuilder,
155 const SPIRVSubtarget &ST) {
156 // Read argument's access qualifier from metadata or default.
157 SPIRV::AccessQualifier::AccessQualifier ArgAccessQual =
158 getArgAccessQual(F, ArgIdx);
159
160 Type *OriginalArgType =
162
163 // If OriginalArgType is non-pointer, use the OriginalArgType (the type cannot
164 // be legally reassigned later).
165 if (!isPointerTy(OriginalArgType))
166 return GR->getOrCreateSPIRVType(OriginalArgType, MIRBuilder, ArgAccessQual,
167 true);
168
169 Argument *Arg = F.getArg(ArgIdx);
170 Type *ArgType = Arg->getType();
171 if (isTypedPointerTy(ArgType)) {
173 cast<TypedPointerType>(ArgType)->getElementType(), MIRBuilder,
175 }
176
177 // In case OriginalArgType is of untyped pointer type, there are three
178 // possibilities:
179 // 1) This is a pointer of an LLVM IR element type, passed byval/byref.
180 // 2) This is an OpenCL/SPIR-V builtin type if there is spv_assign_type
181 // intrinsic assigning a TargetExtType.
182 // 3) This is a pointer, try to retrieve pointer element type from a
183 // spv_assign_ptr_type intrinsic or otherwise use default pointer element
184 // type.
185 if (hasPointeeTypeAttr(Arg)) {
187 getPointeeTypeByAttr(Arg), MIRBuilder,
189 }
190
191 for (auto User : Arg->users()) {
193 // Check if this is spv_assign_type assigning OpenCL/SPIR-V builtin type.
194 if (II && II->getIntrinsicID() == Intrinsic::spv_assign_type) {
195 MetadataAsValue *VMD = cast<MetadataAsValue>(II->getOperand(1));
196 Type *BuiltinType =
197 cast<ConstantAsMetadata>(VMD->getMetadata())->getType();
198 assert(BuiltinType->isTargetExtTy() && "Expected TargetExtType");
199 return GR->getOrCreateSPIRVType(BuiltinType, MIRBuilder, ArgAccessQual,
200 true);
201 }
202
203 // Check if this is spv_assign_ptr_type assigning pointer element type.
204 if (!II || II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type)
205 continue;
206
207 MetadataAsValue *VMD = cast<MetadataAsValue>(II->getOperand(1));
208 Type *ElementTy =
211 ElementTy, MIRBuilder,
213 cast<ConstantInt>(II->getOperand(2))->getZExtValue(), ST));
214 }
215
216 // Replace PointerType with TypedPointerType to be able to map SPIR-V types to
217 // LLVM types in a consistent manner
218 return GR->getOrCreateSPIRVType(toTypedPointer(OriginalArgType), MIRBuilder,
219 ArgAccessQual, true);
220}
221
222static SPIRV::ExecutionModel::ExecutionModel
224 if (STI.isKernel())
225 return SPIRV::ExecutionModel::Kernel;
226
227 if (STI.isShader()) {
228 auto attribute = F.getFnAttribute("hlsl.shader");
229 if (!attribute.isValid()) {
231 "This entry point lacks mandatory hlsl.shader attribute.");
232 }
233
234 const auto value = attribute.getValueAsString();
235 if (value == "compute")
236 return SPIRV::ExecutionModel::GLCompute;
237 if (value == "vertex")
238 return SPIRV::ExecutionModel::Vertex;
239 if (value == "pixel")
240 return SPIRV::ExecutionModel::Fragment;
241
243 "This HLSL entry point is not supported by this backend.");
244 }
245
247 // "hlsl.shader" attribute is mandatory for Vulkan, so we can set Env to
248 // Shader whenever we find it, and to Kernel otherwise.
249
250 // We will now change the Env based on the attribute, so we need to strip
251 // `const` out of the ref to STI.
252 SPIRVSubtarget *NonConstSTI = const_cast<SPIRVSubtarget *>(&STI);
253 auto attribute = F.getFnAttribute("hlsl.shader");
254 if (!attribute.isValid()) {
255 NonConstSTI->setEnv(SPIRVSubtarget::Kernel);
256 return SPIRV::ExecutionModel::Kernel;
257 }
258 NonConstSTI->setEnv(SPIRVSubtarget::Shader);
259
260 const auto value = attribute.getValueAsString();
261 if (value == "compute")
262 return SPIRV::ExecutionModel::GLCompute;
263 if (value == "vertex")
264 return SPIRV::ExecutionModel::Vertex;
265 if (value == "pixel")
266 return SPIRV::ExecutionModel::Fragment;
267
268 report_fatal_error("This HLSL entry point is not supported by this backend.");
269}
270
272 const Function &F,
274 FunctionLoweringInfo &FLI) const {
275 // Discard the internal service function
276 if (F.getFnAttribute(SPIRV_BACKEND_SERVICE_FUN_NAME).isValid())
277 return true;
278
279 assert(GR && "Must initialize the SPIRV type registry before lowering args.");
280 GR->setCurrentFunc(MIRBuilder.getMF());
281
282 // Get access to information about available extensions
283 const SPIRVSubtarget *ST =
284 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
285
286 // Assign types and names to all args, and store their types for later.
287 SmallVector<SPIRVType *, 4> ArgTypeVRegs;
288 if (VRegs.size() > 0) {
289 unsigned i = 0;
290 for (const auto &Arg : F.args()) {
291 // Currently formal args should use single registers.
292 // TODO: handle the case of multiple registers.
293 if (VRegs[i].size() > 1)
294 return false;
295 auto *SpirvTy = getArgSPIRVType(F, i, GR, MIRBuilder, *ST);
296 GR->assignSPIRVTypeToVReg(SpirvTy, VRegs[i][0], MIRBuilder.getMF());
297 ArgTypeVRegs.push_back(SpirvTy);
298
299 if (Arg.hasName())
300 buildOpName(VRegs[i][0], Arg.getName(), MIRBuilder);
301 if (isPointerTyOrWrapper(Arg.getType())) {
302 auto DerefBytes = static_cast<unsigned>(Arg.getDereferenceableBytes());
303 if (DerefBytes != 0)
304 buildOpDecorate(VRegs[i][0], MIRBuilder,
305 SPIRV::Decoration::MaxByteOffset, {DerefBytes});
306 }
307 if (Arg.hasAttribute(Attribute::Alignment) && !ST->isShader()) {
308 auto Alignment = static_cast<unsigned>(
309 Arg.getAttribute(Attribute::Alignment).getValueAsInt());
310 buildOpDecorate(VRegs[i][0], MIRBuilder, SPIRV::Decoration::Alignment,
311 {Alignment});
312 }
313 if (Arg.hasAttribute(Attribute::ReadOnly)) {
314 auto Attr =
315 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoWrite);
316 buildOpDecorate(VRegs[i][0], MIRBuilder,
317 SPIRV::Decoration::FuncParamAttr, {Attr});
318 }
319 if (Arg.hasAttribute(Attribute::ZExt)) {
320 auto Attr =
321 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Zext);
322 buildOpDecorate(VRegs[i][0], MIRBuilder,
323 SPIRV::Decoration::FuncParamAttr, {Attr});
324 }
325 if (Arg.hasAttribute(Attribute::NoAlias)) {
326 auto Attr =
327 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoAlias);
328 buildOpDecorate(VRegs[i][0], MIRBuilder,
329 SPIRV::Decoration::FuncParamAttr, {Attr});
330 }
331 // TODO: the AMDGPU BE only supports ByRef argument passing, thus for
332 // AMDGCN flavoured SPIRV we CodeGen for ByRef, but lower it to
333 // ByVal, handling the impedance mismatch during reverse
334 // translation from SPIRV to LLVM IR; the vendor check should be
335 // removed once / if SPIRV adds ByRef support.
336 if (Arg.hasAttribute(Attribute::ByVal) ||
337 (Arg.hasAttribute(Attribute::ByRef) &&
338 F.getParent()->getTargetTriple().getVendor() ==
340 auto Attr =
341 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::ByVal);
342 buildOpDecorate(VRegs[i][0], MIRBuilder,
343 SPIRV::Decoration::FuncParamAttr, {Attr});
344 }
345 if (Arg.hasAttribute(Attribute::StructRet)) {
346 auto Attr =
347 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sret);
348 buildOpDecorate(VRegs[i][0], MIRBuilder,
349 SPIRV::Decoration::FuncParamAttr, {Attr});
350 }
351
352 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
353 std::vector<SPIRV::Decoration::Decoration> ArgTypeQualDecs =
355 for (SPIRV::Decoration::Decoration Decoration : ArgTypeQualDecs)
356 buildOpDecorate(VRegs[i][0], MIRBuilder, Decoration, {});
357 }
358
359 MDNode *Node = F.getMetadata("spirv.ParameterDecorations");
360 if (Node && i < Node->getNumOperands() &&
361 isa<MDNode>(Node->getOperand(i))) {
362 MDNode *MD = cast<MDNode>(Node->getOperand(i));
363 for (const MDOperand &MDOp : MD->operands()) {
364 MDNode *MD2 = dyn_cast<MDNode>(MDOp);
365 assert(MD2 && "Metadata operand is expected");
366 ConstantInt *Const = getConstInt(MD2, 0);
367 assert(Const && "MDOperand should be ConstantInt");
368 auto Dec =
369 static_cast<SPIRV::Decoration::Decoration>(Const->getZExtValue());
370 std::vector<uint32_t> DecVec;
371 for (unsigned j = 1; j < MD2->getNumOperands(); j++) {
372 ConstantInt *Const = getConstInt(MD2, j);
373 assert(Const && "MDOperand should be ConstantInt");
374 DecVec.push_back(static_cast<uint32_t>(Const->getZExtValue()));
375 }
376 buildOpDecorate(VRegs[i][0], MIRBuilder, Dec, DecVec);
377 }
378 }
379 ++i;
380 }
381 }
382
383 auto MRI = MIRBuilder.getMRI();
384 Register FuncVReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
385 MRI->setRegClass(FuncVReg, &SPIRV::iIDRegClass);
387 Type *FRetTy = FTy->getReturnType();
388 if (isUntypedPointerTy(FRetTy)) {
389 if (Type *FRetElemTy = GR->findDeducedElementType(&F)) {
391 toTypedPointer(FRetElemTy), getPointerAddressSpace(FRetTy));
392 GR->addReturnType(&F, DerivedTy);
393 FRetTy = DerivedTy;
394 }
395 }
396 SPIRVType *RetTy = GR->getOrCreateSPIRVType(
397 FRetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
398 FTy = fixFunctionTypeIfPtrArgs(GR, F, FTy, RetTy, ArgTypeVRegs);
399 SPIRVType *FuncTy = GR->getOrCreateOpTypeFunctionWithArgs(
400 FTy, RetTy, ArgTypeVRegs, MIRBuilder);
401 uint32_t FuncControl = getFunctionControl(F, ST);
402
403 // Add OpFunction instruction
404 MachineInstrBuilder MB = MIRBuilder.buildInstr(SPIRV::OpFunction)
405 .addDef(FuncVReg)
406 .addUse(GR->getSPIRVTypeID(RetTy))
407 .addImm(FuncControl)
408 .addUse(GR->getSPIRVTypeID(FuncTy));
409 GR->recordFunctionDefinition(&F, &MB.getInstr()->getOperand(0));
410 GR->addGlobalObject(&F, &MIRBuilder.getMF(), FuncVReg);
411 if (F.isDeclaration())
412 GR->add(&F, MB);
413
414 // Add OpFunctionParameter instructions
415 int i = 0;
416 for (const auto &Arg : F.args()) {
417 assert(VRegs[i].size() == 1 && "Formal arg has multiple vregs");
418 Register ArgReg = VRegs[i][0];
419 MRI->setRegClass(ArgReg, GR->getRegClass(ArgTypeVRegs[i]));
420 MRI->setType(ArgReg, GR->getRegType(ArgTypeVRegs[i]));
421 auto MIB = MIRBuilder.buildInstr(SPIRV::OpFunctionParameter)
422 .addDef(ArgReg)
423 .addUse(GR->getSPIRVTypeID(ArgTypeVRegs[i]));
424 if (F.isDeclaration())
425 GR->add(&Arg, MIB);
426 GR->addGlobalObject(&Arg, &MIRBuilder.getMF(), ArgReg);
427 i++;
428 }
429 // Name the function.
430 if (F.hasName())
431 buildOpName(FuncVReg, F.getName(), MIRBuilder);
432
433 // Handle entry points and function linkage.
434 if (isEntryPoint(F)) {
435 // EntryPoints can help us to determine the environment we're working on.
436 // Therefore, we need a non-const pointer to SPIRVSubtarget to update the
437 // environment if we need to.
438 const SPIRVSubtarget *ST =
439 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
440 auto MIB = MIRBuilder.buildInstr(SPIRV::OpEntryPoint)
441 .addImm(static_cast<uint32_t>(getExecutionModel(*ST, F)))
442 .addUse(FuncVReg);
443 addStringImm(F.getName(), MIB);
444 } else if (const auto LnkTy = getSpirvLinkageTypeFor(*ST, F)) {
445 buildOpDecorate(FuncVReg, MIRBuilder, SPIRV::Decoration::LinkageAttributes,
446 {static_cast<uint32_t>(*LnkTy)}, F.getName());
447 }
448
449 // Handle function pointers decoration
450 bool hasFunctionPointers =
451 ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
452 if (hasFunctionPointers) {
453 if (F.hasFnAttribute("referenced-indirectly")) {
454 assert((F.getCallingConv() != CallingConv::SPIR_KERNEL) &&
455 "Unexpected 'referenced-indirectly' attribute of the kernel "
456 "function");
457 buildOpDecorate(FuncVReg, MIRBuilder,
458 SPIRV::Decoration::ReferencedIndirectlyINTEL, {});
459 }
460 }
461
462 return true;
463}
464
465// TODO:
466// - add a topological sort of IndirectCalls to ensure the best types knowledge
467// - we may need to fix function formal parameter types if they are opaque
468// pointers used as function pointers in these indirect calls
469// - defaulting to StorageClass::Function in the absence of the
470// SPV_INTEL_function_pointers extension seems wrong, as that might not be
471// able to hold a full width pointer to function, and it also does not model
472// the semantics of a pointer to function in a generic fashion.
473void SPIRVCallLowering::produceIndirectPtrType(
474 MachineIRBuilder &MIRBuilder,
475 const SPIRVCallLowering::SPIRVIndirectCall &IC) const {
476 // Create indirect call data type if any
477 MachineFunction &MF = MIRBuilder.getMF();
479 SPIRVType *SpirvRetTy = GR->getOrCreateSPIRVType(
480 IC.RetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
481 SmallVector<SPIRVType *, 4> SpirvArgTypes;
482 for (size_t i = 0; i < IC.ArgTys.size(); ++i) {
483 SPIRVType *SPIRVTy = GR->getOrCreateSPIRVType(
484 IC.ArgTys[i], MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
485 SpirvArgTypes.push_back(SPIRVTy);
486 if (!GR->getSPIRVTypeForVReg(IC.ArgRegs[i]))
487 GR->assignSPIRVTypeToVReg(SPIRVTy, IC.ArgRegs[i], MF);
488 }
489 // SPIR-V function type:
490 FunctionType *FTy =
491 FunctionType::get(const_cast<Type *>(IC.RetTy), IC.ArgTys, false);
493 FTy, SpirvRetTy, SpirvArgTypes, MIRBuilder);
494 // SPIR-V pointer to function type:
495 auto SC = ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)
496 ? SPIRV::StorageClass::CodeSectionINTEL
497 : SPIRV::StorageClass::Function;
498 SPIRVType *IndirectFuncPtrTy =
499 GR->getOrCreateSPIRVPointerType(SpirvFuncTy, MIRBuilder, SC);
500 // Correct the Callee type
501 GR->assignSPIRVTypeToVReg(IndirectFuncPtrTy, IC.Callee, MF);
502}
503
505 CallLoweringInfo &Info) const {
506 // Currently call returns should have single vregs.
507 // TODO: handle the case of multiple registers.
508 if (Info.OrigRet.Regs.size() > 1)
509 return false;
510 MachineFunction &MF = MIRBuilder.getMF();
511 GR->setCurrentFunc(MF);
512 const Function *CF = nullptr;
513 std::string DemangledName;
514 const Type *OrigRetTy = Info.OrigRet.Ty;
515
516 // Emit a regular OpFunctionCall. If it's an externally declared function,
517 // be sure to emit its type and function declaration here. It will be hoisted
518 // globally later.
519 if (Info.Callee.isGlobal()) {
520 std::string FuncName = Info.Callee.getGlobal()->getName().str();
521 DemangledName = getOclOrSpirvBuiltinDemangledName(FuncName);
522 CF = dyn_cast_or_null<const Function>(Info.Callee.getGlobal());
523 // TODO: support constexpr casts and indirect calls.
524 if (CF == nullptr)
525 return false;
526
528 OrigRetTy = FTy->getReturnType();
529 if (isUntypedPointerTy(OrigRetTy)) {
530 if (auto *DerivedRetTy = GR->findReturnType(CF))
531 OrigRetTy = DerivedRetTy;
532 }
533 }
534
535 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
536 Register ResVReg =
537 Info.OrigRet.Regs.empty() ? Register(0) : Info.OrigRet.Regs[0];
538 const auto *ST = static_cast<const SPIRVSubtarget *>(&MF.getSubtarget());
539
540 bool isFunctionDecl = CF && CF->isDeclaration();
541 if (isFunctionDecl && !DemangledName.empty()) {
542 if (ResVReg.isValid()) {
543 if (!GR->getSPIRVTypeForVReg(ResVReg)) {
544 const Type *RetTy = OrigRetTy;
545 if (auto *PtrRetTy = dyn_cast<PointerType>(OrigRetTy)) {
546 const Value *OrigValue = Info.OrigRet.OrigValue;
547 if (!OrigValue)
548 OrigValue = Info.CB;
549 if (OrigValue)
550 if (Type *ElemTy = GR->findDeducedElementType(OrigValue))
551 RetTy =
552 TypedPointerType::get(ElemTy, PtrRetTy->getAddressSpace());
553 }
554 setRegClassType(ResVReg, RetTy, GR, MIRBuilder,
555 SPIRV::AccessQualifier::ReadWrite, true);
556 }
557 } else {
558 ResVReg = createVirtualRegister(OrigRetTy, GR, MIRBuilder,
559 SPIRV::AccessQualifier::ReadWrite, true);
560 }
562 for (auto Arg : Info.OrigArgs) {
563 assert(Arg.Regs.size() == 1 && "Call arg has multiple VRegs");
564 Register ArgReg = Arg.Regs[0];
565 ArgVRegs.push_back(ArgReg);
566 SPIRVType *SpvType = GR->getSPIRVTypeForVReg(ArgReg);
567 if (!SpvType) {
568 Type *ArgTy = nullptr;
569 if (auto *PtrArgTy = dyn_cast<PointerType>(Arg.Ty)) {
570 // If Arg.Ty is an untyped pointer (i.e., ptr [addrspace(...)]) and we
571 // don't have access to original value in LLVM IR or info about
572 // deduced pointee type, then we should wait with setting the type for
573 // the virtual register until pre-legalizer step when we access
574 // @llvm.spv.assign.ptr.type.p...(...)'s info.
575 if (Arg.OrigValue)
576 if (Type *ElemTy = GR->findDeducedElementType(Arg.OrigValue))
577 ArgTy =
578 TypedPointerType::get(ElemTy, PtrArgTy->getAddressSpace());
579 } else {
580 ArgTy = Arg.Ty;
581 }
582 if (ArgTy) {
583 SpvType = GR->getOrCreateSPIRVType(
584 ArgTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
585 GR->assignSPIRVTypeToVReg(SpvType, ArgReg, MF);
586 }
587 }
588 if (!MRI->getRegClassOrNull(ArgReg)) {
589 // Either we have SpvType created, or Arg.Ty is an untyped pointer and
590 // we know its virtual register's class and type even if we don't know
591 // pointee type.
592 MRI->setRegClass(ArgReg, SpvType ? GR->getRegClass(SpvType)
593 : &SPIRV::pIDRegClass);
594 MRI->setType(
595 ArgReg,
596 SpvType ? GR->getRegType(SpvType)
597 : LLT::pointer(cast<PointerType>(Arg.Ty)->getAddressSpace(),
598 GR->getPointerSize()));
599 }
600 }
601 if (auto Res = SPIRV::lowerBuiltin(
602 DemangledName, ST->getPreferredInstructionSet(), MIRBuilder,
603 ResVReg, OrigRetTy, ArgVRegs, GR, *Info.CB))
604 return *Res;
605 }
606
607 if (isFunctionDecl && !GR->find(CF, &MF).isValid()) {
608 // Emit the type info and forward function declaration to the first MBB
609 // to ensure VReg definition dependencies are valid across all MBBs.
610 MachineIRBuilder FirstBlockBuilder;
611 FirstBlockBuilder.setMF(MF);
612 FirstBlockBuilder.setMBB(*MF.getBlockNumbered(0));
613
616 for (const Argument &Arg : CF->args()) {
617 if (MIRBuilder.getDataLayout().getTypeStoreSize(Arg.getType()).isZero())
618 continue; // Don't handle zero sized types.
619 Register Reg = MRI->createGenericVirtualRegister(LLT::scalar(64));
620 MRI->setRegClass(Reg, &SPIRV::iIDRegClass);
621 ToInsert.push_back({Reg});
622 VRegArgs.push_back(ToInsert.back());
623 }
624 // TODO: Reuse FunctionLoweringInfo
625 FunctionLoweringInfo FuncInfo;
626 lowerFormalArguments(FirstBlockBuilder, *CF, VRegArgs, FuncInfo);
627 }
628
629 // Ignore the call if it's called from the internal service function
630 if (MIRBuilder.getMF()
631 .getFunction()
633 .isValid()) {
634 // insert a no-op
635 MIRBuilder.buildTrap();
636 return true;
637 }
638
639 unsigned CallOp;
640 if (Info.CB->isIndirectCall()) {
641 if (!ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
642 report_fatal_error("An indirect call is encountered but SPIR-V without "
643 "extensions does not support it",
644 false);
645 // Set instruction operation according to SPV_INTEL_function_pointers
646 CallOp = SPIRV::OpFunctionPointerCallINTEL;
647 // Collect information about the indirect call to create correct types.
648 Register CalleeReg = Info.Callee.getReg();
649 if (CalleeReg.isValid()) {
650 SPIRVCallLowering::SPIRVIndirectCall IndirectCall;
651 IndirectCall.Callee = CalleeReg;
653 IndirectCall.RetTy = OrigRetTy = FTy->getReturnType();
654 assert(FTy->getNumParams() == Info.OrigArgs.size() &&
655 "Function types mismatch");
656 for (unsigned I = 0; I != Info.OrigArgs.size(); ++I) {
657 assert(Info.OrigArgs[I].Regs.size() == 1 &&
658 "Call arg has multiple VRegs");
659 IndirectCall.ArgTys.push_back(FTy->getParamType(I));
660 IndirectCall.ArgRegs.push_back(Info.OrigArgs[I].Regs[0]);
661 }
662 produceIndirectPtrType(MIRBuilder, IndirectCall);
663 }
664 } else {
665 // Emit a regular OpFunctionCall
666 CallOp = SPIRV::OpFunctionCall;
667 }
668
669 // Make sure there's a valid return reg, even for functions returning void.
670 if (!ResVReg.isValid())
671 ResVReg = MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
672 SPIRVType *RetType = GR->assignTypeToVReg(
673 OrigRetTy, ResVReg, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
674
675 // Emit the call instruction and its args.
676 auto MIB = MIRBuilder.buildInstr(CallOp)
677 .addDef(ResVReg)
678 .addUse(GR->getSPIRVTypeID(RetType))
679 .add(Info.Callee);
680
681 for (const auto &Arg : Info.OrigArgs) {
682 // Currently call args should have single vregs.
683 if (Arg.Regs.size() > 1)
684 return false;
685 MIB.addUse(Arg.Regs[0]);
686 }
687
688 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing)) {
689 // Process aliasing metadata.
690 const CallBase *CI = Info.CB;
691 if (CI && CI->hasMetadata()) {
692 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_alias_scope))
693 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
694 SPIRV::Decoration::AliasScopeINTEL, MD);
695 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_noalias))
696 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
697 SPIRV::Decoration::NoAliasINTEL, MD);
698 }
699 }
700
701 return MIB.constrainAllUses(MIRBuilder.getTII(), *ST->getRegisterInfo(),
702 *ST->getRegBankInfo());
703}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
static ConstantInt * getConstInt(MDNode *MD, unsigned NumOp)
static SPIRV::ExecutionModel::ExecutionModel getExecutionModel(const SPIRVSubtarget &STI, const Function &F)
static uint32_t getFunctionControl(const Function &F, const SPIRVSubtarget *ST)
static SPIRV::AccessQualifier::AccessQualifier getArgAccessQual(const Function &F, unsigned ArgIdx)
static SPIRVType * getArgSPIRVType(const Function &F, unsigned ArgIdx, SPIRVGlobalRegistry *GR, MachineIRBuilder &MIRBuilder, const SPIRVSubtarget &ST)
static FunctionType * fixFunctionTypeIfPtrArgs(SPIRVGlobalRegistry *GR, const Function &F, FunctionType *FTy, const SPIRVType *SRetTy, const SmallVector< SPIRVType *, 4 > &SArgTys)
static std::vector< SPIRV::Decoration::Decoration > getKernelArgTypeQual(const Function &F, unsigned ArgIdx)
#define SPIRV_BACKEND_SERVICE_FUN_NAME
Definition SPIRVUtils.h:525
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:259
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
CallLowering(const TargetLowering *TLI)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:568
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Class to represent function types.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Type * getParamType(unsigned i) const
Parameter type accessors.
Type * getReturnType() const
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
iterator_range< arg_iterator > args()
Definition Function.h:896
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:764
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:329
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
Metadata node.
Definition Metadata.h:1080
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1444
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1442
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1450
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
A single uniqued string.
Definition Metadata.h:722
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:632
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineBasicBlock * getBlockNumbered(unsigned N) const
getBlockNumbered - MachineBasicBlocks are automatically numbered when they are inserted into the mach...
Function & getFunction()
Return the LLVM function that this machine code represents.
Helper class to build MachineInstr.
const TargetInstrInfo & getTII()
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineFunction & getMF()
Getter for the function we currently build.
void setMBB(MachineBasicBlock &MBB)
Set the insertion point to the end of MBB.
MachineInstrBuilder buildTrap(bool Debug=false)
Build and insert G_TRAP or G_DEBUGTRAP.
MachineRegisterInfo * getMRI()
Getter for MRI.
const DataLayout & getDataLayout() const
void setMF(MachineFunction &MF)
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
bool constrainAllUses(const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
const MachineOperand & getOperand(unsigned i) const
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:220
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
Definition ModRef.h:223
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:184
Metadata * getMetadata() const
Definition Metadata.h:202
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
bool lowerCall(MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info) const override
This hook must be implemented to lower the given call instruction, including argument and return valu...
bool lowerReturn(MachineIRBuilder &MIRBuiler, const Value *Val, ArrayRef< Register > VRegs, FunctionLoweringInfo &FLI, Register SwiftErrorVReg) const override
This hook must be implemented to lower outgoing return values, described by Val, into the specified v...
SPIRVCallLowering(const SPIRVTargetLowering &TLI, SPIRVGlobalRegistry *GR)
bool lowerFormalArguments(MachineIRBuilder &MIRBuilder, const Function &F, ArrayRef< ArrayRef< Register > > VRegs, FunctionLoweringInfo &FLI) const override
This hook must be implemented to lower the incoming (formal) arguments, described by VRegs,...
SPIRVType * getSPIRVTypeForVReg(Register VReg, const MachineFunction *MF=nullptr) const
void assignSPIRVTypeToVReg(SPIRVType *Type, Register VReg, const MachineFunction &MF)
const Type * getTypeForSPIRVType(const SPIRVType *Ty) const
SPIRVType * getOrCreateSPIRVType(const Type *Type, MachineInstr &I, SPIRV::AccessQualifier::AccessQualifier AQ, bool EmitIR)
SPIRVType * getOrCreateSPIRVPointerType(const Type *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SC)
SPIRVType * getOrCreateOpTypeFunctionWithArgs(const Type *Ty, SPIRVType *RetType, const SmallVectorImpl< SPIRVType * > &ArgTypes, MachineIRBuilder &MIRBuilder)
SPIRVEnvType getEnv() const
void setEnv(SPIRVEnvType E)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const TargetRegisterInfo & getRegisterInfo() const
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
A few GPU targets, such as DXIL and SPIR-V, have typed pointers.
static LLVM_ABI TypedPointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
iterator_range< user_iterator > users()
Definition Value.h:426
constexpr bool isZero() const
Definition TypeSize.h:153
@ SPIR_KERNEL
Used for SPIR kernel functions.
std::optional< bool > lowerBuiltin(const StringRef DemangledCall, SPIRV::InstructionSet::InstructionSet Set, MachineIRBuilder &MIRBuilder, const Register OrigRet, const Type *OrigRetTy, const SmallVectorImpl< Register > &Args, SPIRVGlobalRegistry *GR, const CallBase &CB)
FunctionType * getOriginalFunctionType(const Function &F)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
void buildOpName(Register Target, const StringRef &Name, MachineIRBuilder &MIRBuilder)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1667
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:367
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:301
MDString * getOCLKernelArgAccessQual(const Function &F, unsigned ArgIdx)
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
bool isTypedPointerTy(const Type *T)
Definition SPIRVUtils.h:351
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, const std::vector< uint32_t > &DecArgs, StringRef StrImm)
Register createVirtualRegister(SPIRVType *SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF)
Type * toTypedPointer(Type *Ty)
Definition SPIRVUtils.h:458
void setRegClassType(Register Reg, SPIRVType *SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF, bool Force)
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:361
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
const MachineInstr SPIRVType
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
std::optional< SPIRV::LinkageType::LinkageType > getSpirvLinkageTypeFor(const SPIRVSubtarget &ST, const GlobalValue &GV)
bool isEntryPoint(const Function &F)
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
MDString * getOCLKernelArgTypeQual(const Function &F, unsigned ArgIdx)
Type * getPointeeTypeByAttr(Argument *Arg)
Definition SPIRVUtils.h:380
bool hasPointeeTypeAttr(Argument *Arg)
Definition SPIRVUtils.h:375
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool isPointerTyOrWrapper(const Type *Ty)
Definition SPIRVUtils.h:410
void addStringImm(const StringRef &Str, MCInst &Inst)
bool isUntypedPointerTy(const Type *T)
Definition SPIRVUtils.h:356