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"
24#include "llvm/ADT/STLExtras.h"
27#include "llvm/IR/IntrinsicsSPIRV.h"
28#include "llvm/Support/ModRef.h"
29
30using namespace llvm;
31
35
37 const Value *Val, ArrayRef<Register> VRegs,
39 Register SwiftErrorVReg) const {
40 // Ignore if called from the internal service function
41 if (MIRBuilder.getMF()
44 .isValid())
45 return true;
46
47 // Currently all return types should use a single register.
48 // TODO: handle the case of multiple registers.
49 if (VRegs.size() > 1)
50 return false;
51
52 if (Val) {
53 const auto &STI = MIRBuilder.getMF().getSubtarget();
54 MIRBuilder.buildInstr(SPIRV::OpReturnValue)
55 .addUse(VRegs[0])
56 .constrainAllUses(MIRBuilder.getTII(), *STI.getRegisterInfo(),
57 *STI.getRegBankInfo());
58 return true;
59 }
60 MIRBuilder.buildInstr(SPIRV::OpReturn);
61 return true;
62}
63
64// Based on the LLVM function attributes, get a SPIR-V FunctionControl.
66 const SPIRVSubtarget *ST) {
67 MemoryEffects MemEffects = F.getMemoryEffects();
68
69 uint32_t FuncControl = static_cast<uint32_t>(SPIRV::FunctionControl::None);
70
71 if (F.hasFnAttribute(Attribute::AttrKind::NoInline))
72 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::DontInline);
73 else if (F.hasFnAttribute(Attribute::AttrKind::AlwaysInline))
74 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Inline);
75
76 if (MemEffects.doesNotAccessMemory())
77 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Pure);
78 else if (MemEffects.onlyReadsMemory())
79 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Const);
80
81 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_optnone) ||
82 ST->canUseExtension(SPIRV::Extension::SPV_EXT_optnone))
83 if (F.hasFnAttribute(Attribute::OptimizeNone))
84 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::OptNoneEXT);
85
86 return FuncControl;
87}
88
89// If the function has pointer arguments, we are forced to re-create this
90// function type from the very beginning, changing PointerType by
91// TypedPointerType for each pointer argument. Otherwise, the same `Type*`
92// potentially corresponds to different SPIR-V function type, effectively
93// invalidating logic behind global registry and duplicates tracker.
94static FunctionType *
96 FunctionType *FTy, SPIRVTypeInst SRetTy,
97 const SmallVector<SPIRVTypeInst, 4> &SArgTys) {
98 bool hasArgPtrs = any_of(F.args(), [](const Argument &Arg) {
99 // check if it's an instance of a non-typed PointerType
100 return Arg.getType()->isPointerTy();
101 });
102 if (!hasArgPtrs) {
103 Type *RetTy = FTy->getReturnType();
104 // check if it's an instance of a non-typed PointerType
105 if (!RetTy->isPointerTy())
106 return FTy;
107 }
108
109 // re-create function type, using TypedPointerType instead of PointerType to
110 // properly trace argument types
111 const Type *RetTy = GR->getTypeForSPIRVType(SRetTy);
113 for (auto SArgTy : SArgTys)
114 ArgTys.push_back(const_cast<Type *>(GR->getTypeForSPIRVType(SArgTy)));
115 return FunctionType::get(const_cast<Type *>(RetTy), ArgTys, false);
116}
117
118static SPIRV::AccessQualifier::AccessQualifier
119getArgAccessQual(const Function &F, unsigned ArgIdx) {
120 if (F.getCallingConv() != CallingConv::SPIR_KERNEL)
121 return SPIRV::AccessQualifier::ReadWrite;
122
123 MDString *ArgAttribute = getOCLKernelArgAccessQual(F, ArgIdx);
124 if (!ArgAttribute)
125 return SPIRV::AccessQualifier::ReadWrite;
126
127 if (ArgAttribute->getString() == "read_only")
128 return SPIRV::AccessQualifier::ReadOnly;
129 if (ArgAttribute->getString() == "write_only")
130 return SPIRV::AccessQualifier::WriteOnly;
131 return SPIRV::AccessQualifier::ReadWrite;
132}
133
134static std::vector<SPIRV::Decoration::Decoration>
135getKernelArgTypeQual(const Function &F, unsigned ArgIdx) {
136 MDString *ArgAttribute = getOCLKernelArgTypeQual(F, ArgIdx);
137 if (ArgAttribute && ArgAttribute->getString() == "volatile")
138 return {SPIRV::Decoration::Volatile};
139 return {};
140}
141
142static SPIRVTypeInst getArgSPIRVType(const Function &F, unsigned ArgIdx,
144 MachineIRBuilder &MIRBuilder,
145 const SPIRVSubtarget &ST) {
146 // Read argument's access qualifier from metadata or default.
147 SPIRV::AccessQualifier::AccessQualifier ArgAccessQual =
148 getArgAccessQual(F, ArgIdx);
149
150 Type *OriginalArgType =
152
153 // Vector of untyped pointers: build with the deduced pointee instead of
154 // the default i8 (mismatches typed uses downstream).
155 Argument *Arg = F.getArg(ArgIdx);
156 if (auto *VTy = dyn_cast<FixedVectorType>(OriginalArgType);
157 VTy && isUntypedPointerTy(VTy->getElementType()))
158 if (Type *ElemTy = GR->findDeducedElementType(Arg))
161 ElemTy, MIRBuilder,
163 getPointerAddressSpace(OriginalArgType), ST)),
164 VTy->getNumElements(), MIRBuilder, true);
165
166 // If OriginalArgType is non-pointer, use the OriginalArgType (the type cannot
167 // be legally reassigned later).
168 if (!isPointerTy(OriginalArgType))
169 return GR->getOrCreateSPIRVType(OriginalArgType, MIRBuilder, ArgAccessQual,
170 true);
171
172 Type *ArgType = Arg->getType();
173 if (isTypedPointerTy(ArgType)) {
175 cast<TypedPointerType>(ArgType)->getElementType(), MIRBuilder,
177 }
178
179 // In case OriginalArgType is of untyped pointer type, there are three
180 // possibilities:
181 // 1) This is a pointer of an LLVM IR element type, passed byval/byref.
182 // 2) This is an OpenCL/SPIR-V builtin type if there is spv_assign_type
183 // intrinsic assigning a TargetExtType.
184 // 3) This is a pointer, try to retrieve pointer element type from a
185 // spv_assign_ptr_type intrinsic or otherwise use default pointer element
186 // type.
187 if (hasPointeeTypeAttr(Arg)) {
189 getPointeeTypeByAttr(Arg), MIRBuilder,
191 }
192
193 for (auto User : Arg->users()) {
195 // Check if this is spv_assign_type assigning OpenCL/SPIR-V builtin type.
196 if (II && II->getIntrinsicID() == Intrinsic::spv_assign_type) {
197 MetadataAsValue *VMD = cast<MetadataAsValue>(II->getOperand(1));
198 Type *BuiltinType =
199 cast<ConstantAsMetadata>(VMD->getMetadata())->getType();
200 assert(BuiltinType->isTargetExtTy() && "Expected TargetExtType");
201 return GR->getOrCreateSPIRVType(BuiltinType, MIRBuilder, ArgAccessQual,
202 true);
203 }
204
205 // Check if this is spv_assign_ptr_type assigning pointer element type.
206 if (!II || II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type)
207 continue;
208
209 MetadataAsValue *VMD = cast<MetadataAsValue>(II->getOperand(1));
210 Type *ElementTy =
213 ElementTy, MIRBuilder,
215 cast<ConstantInt>(II->getOperand(2))->getZExtValue(), ST));
216 }
217
218 // Replace PointerType with TypedPointerType to be able to map SPIR-V types to
219 // LLVM types in a consistent manner
220 return GR->getOrCreateSPIRVType(toTypedPointer(OriginalArgType), MIRBuilder,
221 ArgAccessQual, true);
222}
223
224static SPIRV::ExecutionModel::ExecutionModel
227 "Environment must be resolved before lowering entry points.");
228
229 if (STI.isKernel())
230 return SPIRV::ExecutionModel::Kernel;
231
232 auto attribute = F.getFnAttribute("hlsl.shader");
233 if (!attribute.isValid()) {
235 "This entry point lacks mandatory hlsl.shader attribute.");
236 }
237
238 const auto value = attribute.getValueAsString();
239 if (value == "compute")
240 return SPIRV::ExecutionModel::GLCompute;
241 if (value == "vertex")
242 return SPIRV::ExecutionModel::Vertex;
243 if (value == "pixel")
244 return SPIRV::ExecutionModel::Fragment;
245
246 report_fatal_error("This HLSL entry point is not supported by this backend.");
247}
248
250 const Function &F,
252 FunctionLoweringInfo &FLI) const {
253 // Discard the internal service function
254 if (F.getFnAttribute(SPIRV_BACKEND_SERVICE_FUN_NAME).isValid())
255 return true;
256
257 assert(GR && "Must initialize the SPIRV type registry before lowering args.");
258 GR->setCurrentFunc(MIRBuilder.getMF());
259
260 // Get access to information about available extensions
261 const SPIRVSubtarget *ST =
262 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
263
264 // Assign types and names to all args, and store their types for later.
266 if (VRegs.size() > 0) {
267 unsigned i = 0;
268 for (const auto &Arg : F.args()) {
269 // Currently formal args should use single registers.
270 // TODO: handle the case of multiple registers.
271 if (VRegs[i].size() > 1)
272 return false;
273 SPIRVTypeInst SpirvTy = getArgSPIRVType(F, i, GR, MIRBuilder, *ST);
274 GR->assignSPIRVTypeToVReg(SpirvTy, VRegs[i][0], MIRBuilder.getMF());
275 ArgTypeVRegs.push_back(SpirvTy);
276
277 if (Arg.hasName())
278 buildOpName(VRegs[i][0], Arg.getName(), MIRBuilder);
279 if (isPointerTyOrWrapper(Arg.getType())) {
280 auto DerefBytes = static_cast<unsigned>(Arg.getDereferenceableBytes());
281 if (DerefBytes != 0)
282 buildOpDecorate(VRegs[i][0], MIRBuilder,
283 SPIRV::Decoration::MaxByteOffset, {DerefBytes});
284 }
285 if (Arg.hasAttribute(Attribute::Alignment) && !ST->isShader()) {
286 auto Alignment = static_cast<unsigned>(
287 Arg.getAttribute(Attribute::Alignment).getValueAsInt());
288 buildOpDecorate(VRegs[i][0], MIRBuilder, SPIRV::Decoration::Alignment,
289 {Alignment});
290 }
291 if (!ST->isShader()) {
292 if (Arg.hasAttribute(Attribute::ReadOnly)) {
293 auto Attr =
294 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoWrite);
295 buildOpDecorate(VRegs[i][0], MIRBuilder,
296 SPIRV::Decoration::FuncParamAttr, {Attr});
297 }
298 if (Arg.hasAttribute(Attribute::ZExt)) {
299 auto Attr =
300 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Zext);
301 buildOpDecorate(VRegs[i][0], MIRBuilder,
302 SPIRV::Decoration::FuncParamAttr, {Attr});
303 }
304 if (Arg.hasAttribute(Attribute::SExt)) {
305 auto Attr =
306 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sext);
307 buildOpDecorate(VRegs[i][0], MIRBuilder,
308 SPIRV::Decoration::FuncParamAttr, {Attr});
309 }
310 if (Arg.hasAttribute(Attribute::NoAlias)) {
311 auto Attr =
312 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoAlias);
313 buildOpDecorate(VRegs[i][0], MIRBuilder,
314 SPIRV::Decoration::FuncParamAttr, {Attr});
315 }
316 // TODO: the AMDGPU BE only supports ByRef argument passing, thus for
317 // AMDGCN flavoured SPIRV we CodeGen for ByRef, but lower it to
318 // ByVal, handling the impedance mismatch during reverse
319 // translation from SPIRV to LLVM IR; the vendor check should be
320 // removed once / if SPIRV adds ByRef support.
321 if (Arg.hasAttribute(Attribute::ByVal) ||
322 (Arg.hasAttribute(Attribute::ByRef) &&
323 F.getParent()->getTargetTriple().getVendor() ==
325 auto Attr =
326 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::ByVal);
327 buildOpDecorate(VRegs[i][0], MIRBuilder,
328 SPIRV::Decoration::FuncParamAttr, {Attr});
329 }
330 if (Arg.hasAttribute(Attribute::StructRet)) {
331 auto Attr =
332 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sret);
333 buildOpDecorate(VRegs[i][0], MIRBuilder,
334 SPIRV::Decoration::FuncParamAttr, {Attr});
335 }
336 }
337
338 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
339 std::vector<SPIRV::Decoration::Decoration> ArgTypeQualDecs =
341 for (SPIRV::Decoration::Decoration Decoration : ArgTypeQualDecs)
342 buildOpDecorate(VRegs[i][0], MIRBuilder, Decoration, {});
343 }
344
345 MDNode *Node = F.getMetadata("spirv.ParameterDecorations");
346 if (Node && i < Node->getNumOperands() &&
347 isa<MDNode>(Node->getOperand(i))) {
348 MDNode *MD = cast<MDNode>(Node->getOperand(i));
349 for (const MDOperand &MDOp : MD->operands()) {
350 MDNode *MD2 = dyn_cast<MDNode>(MDOp);
351 assert(MD2 && "Metadata operand is expected");
352 ConstantInt *Const = getMDOperandAsConstInt(MD2, 0);
353 assert(Const && "MDOperand should be ConstantInt");
354 auto Dec =
355 static_cast<SPIRV::Decoration::Decoration>(Const->getZExtValue());
356 std::vector<uint32_t> DecVec;
357 for (unsigned j = 1; j < MD2->getNumOperands(); j++) {
358 ConstantInt *Const = getMDOperandAsConstInt(MD2, j);
359 assert(Const && "MDOperand should be ConstantInt");
360 DecVec.push_back(static_cast<uint32_t>(Const->getZExtValue()));
361 }
362 buildOpDecorate(VRegs[i][0], MIRBuilder, Dec, DecVec);
363 }
364 }
365 ++i;
366 }
367 }
368
369 auto MRI = MIRBuilder.getMRI();
370 Register FuncVReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
371 MRI->setRegClass(FuncVReg, &SPIRV::iIDRegClass);
373 Type *FRetTy = FTy->getReturnType();
374 if (isUntypedPointerTy(FRetTy)) {
375 if (Type *FRetElemTy = GR->findDeducedElementType(&F)) {
377 toTypedPointer(FRetElemTy), getPointerAddressSpace(FRetTy));
378 GR->addReturnType(&F, DerivedTy);
379 FRetTy = DerivedTy;
380 }
381 }
382 SPIRVTypeInst RetTy = GR->getOrCreateSPIRVType(
383 FRetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
384 FTy = fixFunctionTypeIfPtrArgs(GR, F, FTy, RetTy, ArgTypeVRegs);
385 SPIRVTypeInst FuncTy = GR->getOrCreateOpTypeFunctionWithArgs(
386 FTy, RetTy, ArgTypeVRegs, MIRBuilder);
387 uint32_t FuncControl = getFunctionControl(F, ST);
388
389 // Add OpFunction instruction
390 MachineInstrBuilder MB = MIRBuilder.buildInstr(SPIRV::OpFunction)
391 .addDef(FuncVReg)
392 .addUse(GR->getSPIRVTypeID(RetTy))
393 .addImm(FuncControl)
394 .addUse(GR->getSPIRVTypeID(FuncTy));
395 GR->recordFunctionDefinition(&F, &MB.getInstr()->getOperand(0));
396 GR->addGlobalObject(&F, &MIRBuilder.getMF(), FuncVReg);
397 if (F.isDeclaration())
398 GR->add(&F, MB);
399
400 // Add OpFunctionParameter instructions
401 int i = 0;
402 for (const auto &Arg : F.args()) {
403 assert(VRegs[i].size() == 1 && "Formal arg has multiple vregs");
404 Register ArgReg = VRegs[i][0];
405 MRI->setRegClass(ArgReg, GR->getRegClass(ArgTypeVRegs[i]));
406 auto MIB = MIRBuilder.buildInstr(SPIRV::OpFunctionParameter)
407 .addDef(ArgReg)
408 .addUse(GR->getSPIRVTypeID(ArgTypeVRegs[i]));
409 if (F.isDeclaration())
410 GR->add(&Arg, MIB);
411 GR->addGlobalObject(&Arg, &MIRBuilder.getMF(), ArgReg);
412 i++;
413 }
414 // Name the function.
415 if (F.hasName())
416 buildOpName(FuncVReg, F.getName(), MIRBuilder);
417
418 // Handle entry points and function linkage.
419 if (isEntryPoint(F)) {
420 if (F.getName().empty())
421 report_fatal_error("SPIR-V entry point function must have a name");
422 auto MIB = MIRBuilder.buildInstr(SPIRV::OpEntryPoint)
423 .addImm(static_cast<uint32_t>(getExecutionModel(*ST, F)))
424 .addUse(FuncVReg);
425 addStringImm(F.getName(), MIB);
426 } else if (const auto LnkTy = getSpirvLinkageTypeFor(*ST, F);
427 LnkTy && !F.getName().empty()) {
428 buildOpDecorate(FuncVReg, MIRBuilder, SPIRV::Decoration::LinkageAttributes,
429 {static_cast<uint32_t>(*LnkTy)}, F.getName());
430 }
431
432 // Handle function pointers decoration
433 bool hasFunctionPointers =
434 ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
435 if (hasFunctionPointers) {
436 if (F.hasFnAttribute("referenced-indirectly")) {
437 assert((F.getCallingConv() != CallingConv::SPIR_KERNEL) &&
438 "Unexpected 'referenced-indirectly' attribute of the kernel "
439 "function");
440 buildOpDecorate(FuncVReg, MIRBuilder,
441 SPIRV::Decoration::ReferencedIndirectlyINTEL, {});
442 }
443 }
444
445 return true;
446}
447
448// TODO:
449// - add a topological sort of IndirectCalls to ensure the best types knowledge
450// - we may need to fix function formal parameter types if they are opaque
451// pointers used as function pointers in these indirect calls
452// - defaulting to StorageClass::Function in the absence of the
453// SPV_INTEL_function_pointers extension seems wrong, as that might not be
454// able to hold a full width pointer to function, and it also does not model
455// the semantics of a pointer to function in a generic fashion.
456void SPIRVCallLowering::produceIndirectPtrType(
457 MachineIRBuilder &MIRBuilder,
458 const SPIRVCallLowering::SPIRVIndirectCall &IC) const {
459 // Create indirect call data type if any
460 MachineFunction &MF = MIRBuilder.getMF();
462 SPIRVTypeInst SpirvRetTy = GR->getOrCreateSPIRVType(
463 IC.RetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
464 SmallVector<SPIRVTypeInst, 4> SpirvArgTypes;
465 for (size_t i = 0; i < IC.ArgTys.size(); ++i) {
467 IC.ArgTys[i], MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
468 SpirvArgTypes.push_back(SPIRVTy);
469 if (!GR->getSPIRVTypeForVReg(IC.ArgRegs[i]))
470 GR->assignSPIRVTypeToVReg(SPIRVTy, IC.ArgRegs[i], MF);
471 }
472 // SPIR-V function type:
473 FunctionType *FTy =
474 FunctionType::get(const_cast<Type *>(IC.RetTy), IC.ArgTys, false);
476 FTy, SpirvRetTy, SpirvArgTypes, MIRBuilder);
477 // SPIR-V pointer to function type:
478 auto SC = ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)
479 ? SPIRV::StorageClass::CodeSectionINTEL
480 : SPIRV::StorageClass::Function;
481 SPIRVTypeInst IndirectFuncPtrTy =
482 GR->getOrCreateSPIRVPointerType(SpirvFuncTy, MIRBuilder, SC);
483 // Correct the Callee type
484 GR->assignSPIRVTypeToVReg(IndirectFuncPtrTy, IC.Callee, MF);
485}
486
488 CallLoweringInfo &Info) const {
489 // Currently call returns should have single vregs.
490 // TODO: handle the case of multiple registers.
491 if (Info.OrigRet.Regs.size() > 1)
492 return false;
493 MachineFunction &MF = MIRBuilder.getMF();
494 GR->setCurrentFunc(MF);
495 const Function *CF = nullptr;
496 std::string DemangledName;
497 const Type *OrigRetTy = Info.OrigRet.Ty;
498
499 // Emit a regular OpFunctionCall. If it's an externally declared function,
500 // be sure to emit its type and function declaration here. It will be hoisted
501 // globally later.
502 if (Info.Callee.isGlobal()) {
503 std::string FuncName = Info.Callee.getGlobal()->getName().str();
504 DemangledName = getOclOrSpirvBuiltinDemangledName(FuncName);
505 CF = dyn_cast_or_null<const Function>(Info.Callee.getGlobal());
506 // TODO: support constexpr casts and indirect calls.
507 if (CF == nullptr)
508 return false;
509
511 OrigRetTy = FTy->getReturnType();
512 if (isUntypedPointerTy(OrigRetTy)) {
513 if (auto *DerivedRetTy = GR->findReturnType(CF))
514 OrigRetTy = DerivedRetTy;
515 }
516 }
517
518 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
519 Register ResVReg =
520 Info.OrigRet.Regs.empty() ? Register(0) : Info.OrigRet.Regs[0];
521 const auto *ST = static_cast<const SPIRVSubtarget *>(&MF.getSubtarget());
522
523 bool isFunctionDecl = CF && CF->isDeclaration();
524 if (isFunctionDecl && !DemangledName.empty()) {
525 if (ResVReg.isValid()) {
526 if (!GR->getSPIRVTypeForVReg(ResVReg)) {
527 const Type *RetTy = OrigRetTy;
528 if (auto *PtrRetTy = dyn_cast<PointerType>(OrigRetTy)) {
529 const Value *OrigValue = Info.OrigRet.OrigValue;
530 if (!OrigValue)
531 OrigValue = Info.CB;
532 if (OrigValue)
533 if (Type *ElemTy = GR->findDeducedElementType(OrigValue))
534 RetTy =
535 TypedPointerType::get(ElemTy, PtrRetTy->getAddressSpace());
536 }
537 setRegClassType(ResVReg, RetTy, GR, MIRBuilder,
538 SPIRV::AccessQualifier::ReadWrite, true);
539 }
540 } else {
541 ResVReg = createVirtualRegister(OrigRetTy, GR, MIRBuilder,
542 SPIRV::AccessQualifier::ReadWrite, true);
543 }
545 for (auto Arg : Info.OrigArgs) {
546 assert(Arg.Regs.size() == 1 && "Call arg has multiple VRegs");
547 Register ArgReg = Arg.Regs[0];
548 ArgVRegs.push_back(ArgReg);
549 SPIRVTypeInst SpvType = GR->getSPIRVTypeForVReg(ArgReg);
550 if (!SpvType) {
551 Type *ArgTy = nullptr;
552 if (auto *PtrArgTy = dyn_cast<PointerType>(Arg.Ty)) {
553 // If Arg.Ty is an untyped pointer (i.e., ptr [addrspace(...)]) and we
554 // don't have access to original value in LLVM IR or info about
555 // deduced pointee type, then we should wait with setting the type for
556 // the virtual register until pre-legalizer step when we access
557 // @llvm.spv.assign.ptr.type.p...(...)'s info.
558 if (Arg.OrigValue)
559 if (Type *ElemTy = GR->findDeducedElementType(Arg.OrigValue))
560 ArgTy =
561 TypedPointerType::get(ElemTy, PtrArgTy->getAddressSpace());
562 } else {
563 ArgTy = Arg.Ty;
564 }
565 if (ArgTy) {
566 SpvType = GR->getOrCreateSPIRVType(
567 ArgTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
568 GR->assignSPIRVTypeToVReg(SpvType, ArgReg, MF);
569 }
570 }
571 if (!MRI->getRegClassOrNull(ArgReg)) {
572 // Either we have SpvType created, or Arg.Ty is an untyped pointer and
573 // we know its virtual register's class and type even if we don't know
574 // pointee type.
575 MRI->setRegClass(ArgReg, SpvType ? GR->getRegClass(SpvType)
576 : &SPIRV::pIDRegClass);
577 MRI->setType(
578 ArgReg,
579 SpvType ? GR->getRegType(SpvType)
580 : LLT::pointer(cast<PointerType>(Arg.Ty)->getAddressSpace(),
581 GR->getPointerSize()));
582 }
583 }
584 if (auto Res = SPIRV::lowerBuiltin(
585 DemangledName, ST->getPreferredInstructionSet(), MIRBuilder,
586 ResVReg, OrigRetTy, ArgVRegs, GR, *Info.CB))
587 return *Res;
588 }
589
590 if (isFunctionDecl && !GR->find(CF, &MF).isValid()) {
591 // Emit the type info and forward function declaration to the first MBB
592 // to ensure VReg definition dependencies are valid across all MBBs.
593 MachineIRBuilder FirstBlockBuilder;
594 FirstBlockBuilder.setMF(MF);
595 FirstBlockBuilder.setMBB(*MF.getBlockNumbered(0));
596
599 for (const Argument &Arg : CF->args()) {
600 if (MIRBuilder.getDataLayout().getTypeStoreSize(Arg.getType()).isZero())
601 continue; // Don't handle zero sized types.
603 MRI->setRegClass(Reg, &SPIRV::iIDRegClass);
604 ToInsert.push_back({Reg});
605 VRegArgs.push_back(ToInsert.back());
606 }
607 // TODO: Reuse FunctionLoweringInfo
608 FunctionLoweringInfo FuncInfo;
609 lowerFormalArguments(FirstBlockBuilder, *CF, VRegArgs, FuncInfo);
610 }
611
612 // Ignore the call if it's called from the internal service function
613 if (MIRBuilder.getMF()
614 .getFunction()
616 .isValid()) {
617 // insert a no-op
618 MIRBuilder.buildTrap();
619 return true;
620 }
621
622 unsigned CallOp;
623 if (Info.CB->isIndirectCall()) {
624 if (!ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
625 report_fatal_error("An indirect call is encountered but SPIR-V without "
626 "extensions does not support it",
627 false);
628 // Set instruction operation according to SPV_INTEL_function_pointers
629 CallOp = SPIRV::OpFunctionPointerCallINTEL;
630 // Collect information about the indirect call to create correct types.
631 Register CalleeReg = Info.Callee.getReg();
632 if (CalleeReg.isValid()) {
633 SPIRVCallLowering::SPIRVIndirectCall IndirectCall;
634 IndirectCall.Callee = CalleeReg;
636 IndirectCall.RetTy = OrigRetTy = FTy->getReturnType();
637 assert(FTy->getNumParams() == Info.OrigArgs.size() &&
638 "Function types mismatch");
639 for (unsigned I = 0; I != Info.OrigArgs.size(); ++I) {
640 assert(Info.OrigArgs[I].Regs.size() == 1 &&
641 "Call arg has multiple VRegs");
642 IndirectCall.ArgTys.push_back(FTy->getParamType(I));
643 IndirectCall.ArgRegs.push_back(Info.OrigArgs[I].Regs[0]);
644 }
645 produceIndirectPtrType(MIRBuilder, IndirectCall);
646 }
647 } else {
648 // Emit a regular OpFunctionCall
649 CallOp = SPIRV::OpFunctionCall;
650 }
651
652 // Make sure there's a valid return reg, even for functions returning void.
653 if (!ResVReg.isValid())
654 ResVReg = MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
655 SPIRVTypeInst RetType = GR->assignTypeToVReg(
656 OrigRetTy, ResVReg, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
657
658 // Emit the call instruction and its args.
659 auto MIB = MIRBuilder.buildInstr(CallOp)
660 .addDef(ResVReg)
661 .addUse(GR->getSPIRVTypeID(RetType))
662 .add(Info.Callee);
663
664 for (const auto &Arg : Info.OrigArgs) {
665 // Currently call args should have single vregs.
666 if (Arg.Regs.size() > 1)
667 return false;
668 MIB.addUse(Arg.Regs[0]);
669 }
670
671 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing)) {
672 // Process aliasing metadata.
673 const CallBase *CI = Info.CB;
674 if (CI && CI->hasMetadata()) {
675 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_alias_scope))
676 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
677 SPIRV::Decoration::AliasScopeINTEL, MD);
678 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_noalias))
679 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
680 SPIRV::Decoration::NoAliasINTEL, MD);
681 }
682 }
683
684 MIB.constrainAllUses(MIRBuilder.getTII(), *ST->getRegisterInfo(),
685 *ST->getRegBankInfo());
686 return true;
687}
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 SPIRVTypeInst getArgSPIRVType(const Function &F, unsigned ArgIdx, SPIRVGlobalRegistry *GR, MachineIRBuilder &MIRBuilder, const SPIRVSubtarget &ST)
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 FunctionType * fixFunctionTypeIfPtrArgs(SPIRVGlobalRegistry *GR, const Function &F, FunctionType *FTy, SPIRVTypeInst SRetTy, const SmallVector< SPIRVTypeInst, 4 > &SArgTys)
static std::vector< SPIRV::Decoration::Decoration > getKernelArgTypeQual(const Function &F, unsigned ArgIdx)
#define SPIRV_BACKEND_SERVICE_FUN_NAME
Definition SPIRVUtils.h:537
This file contains some templates that are useful if you are working with the STL at all.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
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:579
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:866
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:758
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:408
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:1069
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1424
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
Tracking metadata reference owned by Metadata.
Definition Metadata.h:891
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)
void constrainAllUses(const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) const
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
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...
LLVM_ABI void setType(Register VReg, LLT Ty)
Set the low-level type of VReg to Ty.
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
LLVM_ABI Register createGenericVirtualRegister(LLT Ty, StringRef Name="")
Create and return a new generic virtual register with low-level type Ty.
const TargetRegisterClass * getRegClassOrNull(Register Reg) const
Return the register class of Reg, or null if Reg has not been assigned a register class yet.
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
Definition ModRef.h:249
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,...
void assignSPIRVTypeToVReg(SPIRVTypeInst Type, Register VReg, const MachineFunction &MF)
SPIRVTypeInst getOrCreateOpTypeFunctionWithArgs(const Type *Ty, SPIRVTypeInst RetType, const SmallVectorImpl< SPIRVTypeInst > &ArgTypes, MachineIRBuilder &MIRBuilder)
SPIRVTypeInst getOrCreateSPIRVVectorType(SPIRVTypeInst BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder, bool EmitIR)
const Type * getTypeForSPIRVType(SPIRVTypeInst Ty) const
SPIRVTypeInst getOrCreateSPIRVPointerType(const Type *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SC)
SPIRVTypeInst getOrCreateSPIRVType(const Type *Type, MachineInstr &I, SPIRV::AccessQualifier::AccessQualifier AQ, bool EmitIR)
SPIRVTypeInst getSPIRVTypeForVReg(Register VReg, const MachineFunction *MF=nullptr) const
Type * findDeducedElementType(const Value *Val)
SPIRVEnvType getEnv() const
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:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
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:255
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(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.
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:1669
void addStringImm(StringRef Str, MCInst &Inst)
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:386
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
Register createVirtualRegister(SPIRVTypeInst SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF)
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, ArrayRef< uint32_t > DecArgs, StringRef StrImm)
MDString * getOCLKernelArgAccessQual(const Function &F, unsigned ArgIdx)
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
bool isTypedPointerTy(const Type *T)
Definition SPIRVUtils.h:364
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void buildOpName(Register Target, StringRef Name, MachineIRBuilder &MIRBuilder)
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:1746
Type * toTypedPointer(Type *Ty)
Definition SPIRVUtils.h:470
ConstantInt * getMDOperandAsConstInt(const MDNode *N, unsigned I)
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:374
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
void setRegClassType(Register Reg, SPIRVTypeInst SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF, bool Force)
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:399
bool hasPointeeTypeAttr(Argument *Arg)
Definition SPIRVUtils.h:394
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:422
bool isUntypedPointerTy(const Type *T)
Definition SPIRVUtils.h:369