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"
15#include "MCTargetDesc/SPIRVBaseInfo.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"
25#include "llvm/CodeGen/FunctionLoweringInfo.h"
26#include "llvm/IR/IntrinsicInst.h"
27#include "llvm/IR/IntrinsicsSPIRV.h"
28#include "llvm/Support/ModRef.h"
29
30using namespace llvm;
31
32SPIRVCallLowering::SPIRVCallLowering(const SPIRVTargetLowering &TLI,
33 SPIRVGlobalRegistry *GR)
34 : CallLowering(&TLI), GR(GR) {}
35
36bool SPIRVCallLowering::lowerReturn(MachineIRBuilder &MIRBuilder,
37 const Value *Val, ArrayRef<Register> VRegs,
38 FunctionLoweringInfo &FLI,
39 Register SwiftErrorVReg) const {
40 // Ignore if called from the internal service function
41 if (MIRBuilder.getMF()
42 .getFunction()
43 .getFnAttribute(SPIRV_BACKEND_SERVICE_FUN_NAME)
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(Opcode: SPIRV::OpReturnValue)
55 .addUse(RegNo: VRegs[0])
56 .constrainAllUses(TII: MIRBuilder.getTII(), TRI: *STI.getRegisterInfo(),
57 RBI: *STI.getRegBankInfo());
58 return true;
59 }
60 MIRBuilder.buildInstr(Opcode: SPIRV::OpReturn);
61 return true;
62}
63
64// Based on the LLVM function attributes, get a SPIR-V FunctionControl.
65static uint32_t getFunctionControl(const Function &F,
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.isNoInline())
72 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::DontInline);
73 else if (F.hasFnAttribute(Kind: 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(E: SPIRV::Extension::SPV_INTEL_optnone) ||
82 ST->canUseExtension(E: SPIRV::Extension::SPV_EXT_optnone))
83 if (F.hasFnAttribute(Kind: 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 *
95fixFunctionTypeIfPtrArgs(SPIRVGlobalRegistry *GR, const Function &F,
96 FunctionType *FTy, SPIRVTypeInst SRetTy,
97 const SmallVector<SPIRVTypeInst, 4> &SArgTys) {
98 bool hasArgPtrs = any_of(Range: F.args(), P: [](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(Ty: SRetTy);
112 SmallVector<Type *, 4> ArgTys;
113 for (auto SArgTy : SArgTys)
114 ArgTys.push_back(Elt: const_cast<Type *>(GR->getTypeForSPIRVType(Ty: SArgTy)));
115 return FunctionType::get(Result: const_cast<Type *>(RetTy), Params: ArgTys, isVarArg: 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 SPIRVTypeInst getArgSPIRVType(const Function &F, unsigned ArgIdx,
135 SPIRVGlobalRegistry *GR,
136 MachineIRBuilder &MIRBuilder,
137 const SPIRVSubtarget &ST) {
138 // Read argument's access qualifier from metadata or default.
139 SPIRV::AccessQualifier::AccessQualifier ArgAccessQual =
140 getArgAccessQual(F, ArgIdx);
141
142 Type *OriginalArgType =
143 SPIRV::getOriginalFunctionType(F)->getParamType(i: ArgIdx);
144
145 // Vector of untyped pointers: build with the deduced pointee instead of
146 // the default i8 (mismatches typed uses downstream).
147 Argument *Arg = F.getArg(i: ArgIdx);
148 if (auto *VTy = dyn_cast<FixedVectorType>(Val: OriginalArgType);
149 VTy && isUntypedPointerTy(T: VTy->getElementType()))
150 if (Type *ElemTy = GR->findDeducedElementType(Val: Arg))
151 return GR->getOrCreateSPIRVVectorType(
152 BaseType: GR->getOrCreateSPIRVPointerType(
153 BaseType: ElemTy, MIRBuilder,
154 SC: addressSpaceToStorageClass(
155 AddrSpace: getPointerAddressSpace(T: OriginalArgType), STI: ST)),
156 NumElements: VTy->getNumElements(), MIRBuilder, EmitIR: true);
157
158 // If OriginalArgType is non-pointer, use the OriginalArgType (the type cannot
159 // be legally reassigned later).
160 if (!isPointerTy(T: OriginalArgType))
161 return GR->getOrCreateSPIRVType(Type: OriginalArgType, MIRBuilder, AQ: ArgAccessQual,
162 EmitIR: true);
163
164 Type *ArgType = Arg->getType();
165
166 // In case OriginalArgType is of untyped pointer type, there are three
167 // possibilities:
168 // 1) This is a pointer of an LLVM IR element type, passed byval/byref.
169 // 2) This is an OpenCL/SPIR-V builtin type if there is spv_assign_type
170 // intrinsic assigning a TargetExtType.
171 // 3) This is a pointer, try to retrieve pointer element type from a
172 // spv_assign_ptr_type intrinsic or otherwise use default pointer element
173 // type.
174 if (hasPointeeTypeAttr(Arg)) {
175 // byval/byref/sret carry the aggregate layout in the pointee type, so keep
176 // a typed pointer here. An untyped one drops the type and breaks the
177 // argument ABI on the way back from SPIR-V.
178 return GR->getOrCreateSPIRVTypedPointerType(
179 BaseType: getPointeeTypeByAttr(Arg), MIRBuilder,
180 SC: addressSpaceToStorageClass(AddrSpace: getPointerAddressSpace(T: ArgType), STI: ST));
181 }
182
183 for (auto User : Arg->users()) {
184 auto *II = dyn_cast<IntrinsicInst>(Val: User);
185 // Check if this is spv_assign_type assigning OpenCL/SPIR-V builtin type.
186 if (II && II->getIntrinsicID() == Intrinsic::spv_assign_type) {
187 MetadataAsValue *VMD = cast<MetadataAsValue>(Val: II->getOperand(i_nocapture: 1));
188 Type *BuiltinType =
189 cast<ConstantAsMetadata>(Val: VMD->getMetadata())->getType();
190 assert(BuiltinType->isTargetExtTy() && "Expected TargetExtType");
191 return GR->getOrCreateSPIRVType(Type: BuiltinType, MIRBuilder, AQ: ArgAccessQual,
192 EmitIR: true);
193 }
194
195 // Check if this is spv_assign_ptr_type assigning pointer element type.
196 if (!II || II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type)
197 continue;
198
199 MetadataAsValue *VMD = cast<MetadataAsValue>(Val: II->getOperand(i_nocapture: 1));
200 Type *ElementTy =
201 toTypedPointer(Ty: cast<ConstantAsMetadata>(Val: VMD->getMetadata())->getType());
202 return GR->getOrCreateSPIRVPointerType(
203 BaseType: ElementTy, MIRBuilder,
204 SC: addressSpaceToStorageClass(
205 AddrSpace: cast<ConstantInt>(Val: II->getOperand(i_nocapture: 2))->getZExtValue(), STI: ST));
206 }
207
208 // Use the recorded pointee type for declarations.
209 if (F.isDeclaration())
210 if (Type *ElemTy = GR->findDeducedElementType(Val: Arg))
211 return GR->getOrCreateSPIRVPointerType(
212 BaseType: ElemTy, MIRBuilder,
213 SC: addressSpaceToStorageClass(AddrSpace: getPointerAddressSpace(T: ArgType), STI: ST));
214
215 // Replace PointerType with TypedPointerType to be able to map SPIR-V types to
216 // LLVM types in a consistent manner
217 return GR->getOrCreateSPIRVType(Type: toTypedPointer(Ty: OriginalArgType), MIRBuilder,
218 AQ: ArgAccessQual, EmitIR: true);
219}
220
221static SPIRV::ExecutionModel::ExecutionModel
222getExecutionModel(const SPIRVSubtarget &STI, const Function &F) {
223 assert(STI.getEnv() != SPIRVSubtarget::Unknown &&
224 "Environment must be resolved before lowering entry points.");
225
226 if (STI.isKernel())
227 return SPIRV::ExecutionModel::Kernel;
228
229 auto attribute = F.getFnAttribute(Kind: "hlsl.shader");
230 if (!attribute.isValid()) {
231 report_fatal_error(
232 reason: "This entry point lacks mandatory hlsl.shader attribute.");
233 }
234
235 const auto value = attribute.getValueAsString();
236 if (value == "compute")
237 return SPIRV::ExecutionModel::GLCompute;
238 if (value == "vertex")
239 return SPIRV::ExecutionModel::Vertex;
240 if (value == "pixel")
241 return SPIRV::ExecutionModel::Fragment;
242
243 report_fatal_error(reason: "This HLSL entry point is not supported by this backend.");
244}
245
246bool SPIRVCallLowering::lowerFormalArguments(MachineIRBuilder &MIRBuilder,
247 const Function &F,
248 ArrayRef<ArrayRef<Register>> VRegs,
249 FunctionLoweringInfo &FLI) const {
250 // Discard the internal service function
251 if (F.getFnAttribute(SPIRV_BACKEND_SERVICE_FUN_NAME).isValid())
252 return true;
253
254 assert(GR && "Must initialize the SPIRV type registry before lowering args.");
255 GR->setCurrentFunc(MIRBuilder.getMF());
256
257 // Get access to information about available extensions
258 const SPIRVSubtarget *ST =
259 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
260
261 // Assign types and names to all args, and store their types for later.
262 SmallVector<SPIRVTypeInst, 4> ArgTypeVRegs;
263 if (VRegs.size() > 0) {
264 unsigned i = 0;
265 for (const auto &Arg : F.args()) {
266 // Currently formal args should use single registers.
267 // TODO: handle the case of multiple registers.
268 if (VRegs[i].size() > 1)
269 return false;
270 SPIRVTypeInst SpirvTy = getArgSPIRVType(F, ArgIdx: i, GR, MIRBuilder, ST: *ST);
271 GR->assignSPIRVTypeToVReg(Type: SpirvTy, VReg: VRegs[i][0], MF: MIRBuilder.getMF());
272 ArgTypeVRegs.push_back(Elt: SpirvTy);
273
274 StringRef ArgName = Arg.getName();
275 if (F.getCallingConv() == CallingConv::SPIR_KERNEL)
276 if (MDString *MDName = getOCLKernelArgName(F, ArgIdx: i))
277 ArgName = MDName->getString();
278 buildOpName(Target: VRegs[i][0], Name: ArgName, MIRBuilder);
279 if (isPointerTyOrWrapper(Ty: Arg.getType()) && !ST->isShader()) {
280 auto DerefBytes = static_cast<unsigned>(Arg.getDereferenceableBytes());
281 if (DerefBytes != 0 && ST->isAtLeastSPIRVVer(VerToCompareTo: VersionTuple(1, 1)))
282 buildOpDecorate(Reg: VRegs[i][0], MIRBuilder,
283 Dec: SPIRV::Decoration::MaxByteOffset, DecArgs: {DerefBytes});
284 }
285 if (Arg.hasAttribute(Kind: Attribute::Alignment) && !ST->isShader()) {
286 auto Alignment = static_cast<unsigned>(
287 Arg.getAttribute(Kind: Attribute::Alignment).getValueAsInt());
288 buildOpDecorate(Reg: VRegs[i][0], MIRBuilder, Dec: SPIRV::Decoration::Alignment,
289 DecArgs: {Alignment});
290 }
291 if (ST->isKernel()) {
292 if (Arg.hasAttribute(Kind: Attribute::ReadOnly)) {
293 auto Attr =
294 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoWrite);
295 buildOpDecorate(Reg: VRegs[i][0], MIRBuilder,
296 Dec: SPIRV::Decoration::FuncParamAttr, DecArgs: {Attr});
297 }
298 if (Arg.hasAttribute(Kind: Attribute::ReadNone)) {
299 auto Attr = static_cast<unsigned>(
300 SPIRV::FunctionParameterAttribute::NoReadWrite);
301 buildOpDecorate(Reg: VRegs[i][0], MIRBuilder,
302 Dec: SPIRV::Decoration::FuncParamAttr, DecArgs: {Attr});
303 }
304 if (Arg.hasAttribute(Kind: Attribute::ZExt)) {
305 auto Attr =
306 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Zext);
307 buildOpDecorate(Reg: VRegs[i][0], MIRBuilder,
308 Dec: SPIRV::Decoration::FuncParamAttr, DecArgs: {Attr});
309 }
310 if (Arg.hasAttribute(Kind: Attribute::SExt)) {
311 auto Attr =
312 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sext);
313 buildOpDecorate(Reg: VRegs[i][0], MIRBuilder,
314 Dec: SPIRV::Decoration::FuncParamAttr, DecArgs: {Attr});
315 }
316 if (Arg.hasAttribute(Kind: Attribute::NoAlias)) {
317 auto Attr =
318 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoAlias);
319 buildOpDecorate(Reg: VRegs[i][0], MIRBuilder,
320 Dec: SPIRV::Decoration::FuncParamAttr, DecArgs: {Attr});
321 }
322 if (Arg.hasNoCaptureAttr()) {
323 auto Attr = static_cast<unsigned>(
324 SPIRV::FunctionParameterAttribute::NoCapture);
325 buildOpDecorate(Reg: VRegs[i][0], MIRBuilder,
326 Dec: SPIRV::Decoration::FuncParamAttr, DecArgs: {Attr});
327 }
328 // TODO: the AMDGPU BE only supports ByRef argument passing, thus for
329 // AMDGCN flavoured SPIRV we CodeGen for ByRef, but lower it to
330 // ByVal, handling the impedance mismatch during reverse
331 // translation from SPIRV to LLVM IR; the vendor check should be
332 // removed once / if SPIRV adds ByRef support.
333 if (Arg.hasAttribute(Kind: Attribute::ByVal) ||
334 (Arg.hasAttribute(Kind: Attribute::ByRef) &&
335 F.getParent()->getTargetTriple().getVendor() ==
336 Triple::VendorType::AMD)) {
337 auto Attr =
338 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::ByVal);
339 buildOpDecorate(Reg: VRegs[i][0], MIRBuilder,
340 Dec: SPIRV::Decoration::FuncParamAttr, DecArgs: {Attr});
341 }
342 if (Arg.hasAttribute(Kind: Attribute::StructRet)) {
343 auto Attr =
344 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sret);
345 buildOpDecorate(Reg: VRegs[i][0], MIRBuilder,
346 Dec: SPIRV::Decoration::FuncParamAttr, DecArgs: {Attr});
347 }
348 }
349
350 MDNode *Node = F.getMetadata(Kind: "spirv.ParameterDecorations");
351 if (Node && i < Node->getNumOperands() &&
352 isa<MDNode>(Val: Node->getOperand(I: i)))
353 buildOpSpirvDecorations(Reg: VRegs[i][0], MIRBuilder,
354 GVarMD: cast<MDNode>(Val: Node->getOperand(I: i)), ST: *ST);
355 ++i;
356 }
357 }
358
359 auto MRI = MIRBuilder.getMRI();
360 Register FuncVReg = MRI->createGenericVirtualRegister(Ty: LLT::scalar(SizeInBits: 64));
361 MRI->setRegClass(Reg: FuncVReg, RC: &SPIRV::iIDRegClass);
362 FunctionType *FTy = SPIRV::getOriginalFunctionType(F);
363 Type *FRetTy = FTy->getReturnType();
364 if (isUntypedPointerTy(T: FRetTy)) {
365 if (Type *FRetElemTy = GR->findDeducedElementType(Val: &F)) {
366 TypedPointerType *DerivedTy = TypedPointerType::get(
367 ElementType: toTypedPointer(Ty: FRetElemTy), AddressSpace: getPointerAddressSpace(T: FRetTy));
368 GR->addReturnType(ArgF: &F, DerivedTy);
369 FRetTy = DerivedTy;
370 }
371 }
372 SPIRVTypeInst RetTy = GR->getOrCreateSPIRVType(
373 Type: FRetTy, MIRBuilder, AQ: SPIRV::AccessQualifier::ReadWrite, EmitIR: true);
374 FTy = fixFunctionTypeIfPtrArgs(GR, F, FTy, SRetTy: RetTy, SArgTys: ArgTypeVRegs);
375 SPIRVTypeInst FuncTy = GR->getOrCreateOpTypeFunctionWithArgs(
376 Ty: FTy, RetType: RetTy, ArgTypes: ArgTypeVRegs, MIRBuilder);
377 uint32_t FuncControl = getFunctionControl(F, ST);
378
379 // Add OpFunction instruction
380 MachineInstrBuilder MB = MIRBuilder.buildInstr(Opcode: SPIRV::OpFunction)
381 .addDef(RegNo: FuncVReg)
382 .addUse(RegNo: GR->getSPIRVTypeID(SpirvType: RetTy))
383 .addImm(Val: FuncControl)
384 .addUse(RegNo: GR->getSPIRVTypeID(SpirvType: FuncTy));
385 GR->recordFunctionDefinition(F: &F, MO: &MB.getInstr()->getOperand(i: 0));
386 GR->addGlobalObject(V: &F, MF: &MIRBuilder.getMF(), R: FuncVReg);
387 if (F.isDeclaration())
388 GR->add(V: &F, MI: MB);
389
390 // Add OpFunctionParameter instructions
391 int i = 0;
392 for (const auto &Arg : F.args()) {
393 assert(VRegs[i].size() == 1 && "Formal arg has multiple vregs");
394 Register ArgReg = VRegs[i][0];
395 MRI->setRegClass(Reg: ArgReg, RC: GR->getRegClass(SpvType: ArgTypeVRegs[i]));
396 auto MIB = MIRBuilder.buildInstr(Opcode: SPIRV::OpFunctionParameter)
397 .addDef(RegNo: ArgReg)
398 .addUse(RegNo: GR->getSPIRVTypeID(SpirvType: ArgTypeVRegs[i]));
399 if (F.isDeclaration())
400 GR->add(V: &Arg, MI: MIB);
401 GR->addGlobalObject(V: &Arg, MF: &MIRBuilder.getMF(), R: ArgReg);
402 i++;
403 }
404 if (!ST->isShader()) {
405 if (F.hasRetAttribute(Kind: Attribute::ZExt)) {
406 auto Attr =
407 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Zext);
408 buildOpDecorate(Reg: FuncVReg, MIRBuilder, Dec: SPIRV::Decoration::FuncParamAttr,
409 DecArgs: {Attr});
410 }
411 if (F.hasRetAttribute(Kind: Attribute::SExt)) {
412 auto Attr =
413 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sext);
414 buildOpDecorate(Reg: FuncVReg, MIRBuilder, Dec: SPIRV::Decoration::FuncParamAttr,
415 DecArgs: {Attr});
416 }
417 }
418
419 // Name the function.
420 if (F.hasName())
421 buildOpName(Target: FuncVReg, Name: F.getName(), MIRBuilder);
422
423 // Handle entry points and function linkage.
424 if (isEntryPoint(F)) {
425 if (F.getName().empty())
426 report_fatal_error(reason: "SPIR-V entry point function must have a name");
427 auto MIB = MIRBuilder.buildInstr(Opcode: SPIRV::OpEntryPoint)
428 .addImm(Val: static_cast<uint32_t>(getExecutionModel(STI: *ST, F)))
429 .addUse(RegNo: FuncVReg);
430 addStringImm(Str: F.getName(), MIB);
431 } else if (const auto LnkTy = getSpirvLinkageTypeFor(ST: *ST, GV: F);
432 LnkTy && !F.getName().empty()) {
433 buildOpDecorate(Reg: FuncVReg, MIRBuilder, Dec: SPIRV::Decoration::LinkageAttributes,
434 DecArgs: {static_cast<uint32_t>(*LnkTy)}, StrImm: F.getName());
435 }
436
437 // Handle function pointers decoration
438 bool hasFunctionPointers =
439 ST->canUseExtension(E: SPIRV::Extension::SPV_INTEL_function_pointers);
440 if (hasFunctionPointers) {
441 if (F.hasFnAttribute(Kind: "referenced-indirectly")) {
442 assert((F.getCallingConv() != CallingConv::SPIR_KERNEL) &&
443 "Unexpected 'referenced-indirectly' attribute of the kernel "
444 "function");
445 buildOpDecorate(Reg: FuncVReg, MIRBuilder,
446 Dec: SPIRV::Decoration::ReferencedIndirectlyINTEL, DecArgs: {});
447 }
448 }
449
450 if (MDNode *FuncMD = F.getMetadata(Kind: "spirv.Decorations"))
451 buildOpSpirvDecorations(Reg: FuncVReg, MIRBuilder, GVarMD: FuncMD, ST: *ST);
452
453 return true;
454}
455
456// TODO:
457// - add a topological sort of IndirectCalls to ensure the best types knowledge
458// - we may need to fix function formal parameter types if they are opaque
459// pointers used as function pointers in these indirect calls
460// - defaulting to StorageClass::Function in the absence of the
461// SPV_INTEL_function_pointers extension seems wrong, as that might not be
462// able to hold a full width pointer to function, and it also does not model
463// the semantics of a pointer to function in a generic fashion.
464void SPIRVCallLowering::produceIndirectPtrType(
465 MachineIRBuilder &MIRBuilder,
466 const SPIRVCallLowering::SPIRVIndirectCall &IC) const {
467 // Create indirect call data type if any
468 MachineFunction &MF = MIRBuilder.getMF();
469 const SPIRVSubtarget &ST = MF.getSubtarget<SPIRVSubtarget>();
470 SPIRVTypeInst SpirvRetTy = GR->getOrCreateSPIRVType(
471 Type: IC.RetTy, MIRBuilder, AQ: SPIRV::AccessQualifier::ReadWrite, EmitIR: true);
472 SmallVector<SPIRVTypeInst, 4> SpirvArgTypes;
473 for (size_t i = 0; i < IC.ArgTys.size(); ++i) {
474 SPIRVTypeInst SPIRVTy = GR->getOrCreateSPIRVType(
475 Type: IC.ArgTys[i], MIRBuilder, AQ: SPIRV::AccessQualifier::ReadWrite, EmitIR: true);
476 SpirvArgTypes.push_back(Elt: SPIRVTy);
477 if (!GR->getSPIRVTypeForVReg(VReg: IC.ArgRegs[i]))
478 GR->assignSPIRVTypeToVReg(Type: SPIRVTy, VReg: IC.ArgRegs[i], MF);
479 }
480 // SPIR-V function type:
481 FunctionType *FTy =
482 FunctionType::get(Result: const_cast<Type *>(IC.RetTy), Params: IC.ArgTys, isVarArg: false);
483 SPIRVTypeInst SpirvFuncTy = GR->getOrCreateOpTypeFunctionWithArgs(
484 Ty: FTy, RetType: SpirvRetTy, ArgTypes: SpirvArgTypes, MIRBuilder);
485 // SPIR-V pointer to function type:
486 auto SC = ST.canUseExtension(E: SPIRV::Extension::SPV_INTEL_function_pointers)
487 ? SPIRV::StorageClass::CodeSectionINTEL
488 : SPIRV::StorageClass::Function;
489 SPIRVTypeInst IndirectFuncPtrTy =
490 GR->getOrCreateSPIRVPointerType(BaseType: SpirvFuncTy, MIRBuilder, SC);
491 // Correct the Callee type
492 GR->assignSPIRVTypeToVReg(Type: IndirectFuncPtrTy, VReg: IC.Callee, MF);
493}
494
495bool SPIRVCallLowering::lowerCall(MachineIRBuilder &MIRBuilder,
496 CallLoweringInfo &Info) const {
497 // Currently call returns should have single vregs.
498 // TODO: handle the case of multiple registers.
499 if (Info.OrigRet.Regs.size() > 1)
500 return false;
501 MachineFunction &MF = MIRBuilder.getMF();
502 GR->setCurrentFunc(MF);
503 const Function *CF = nullptr;
504 std::string DemangledName;
505 const Type *OrigRetTy = Info.OrigRet.Ty;
506
507 // Emit a regular OpFunctionCall. If it's an externally declared function,
508 // be sure to emit its type and function declaration here. It will be hoisted
509 // globally later.
510 if (Info.Callee.isGlobal()) {
511 std::string FuncName = Info.Callee.getGlobal()->getName().str();
512 DemangledName = getOclOrSpirvBuiltinDemangledName(Name: FuncName);
513 CF = dyn_cast_or_null<const Function>(Val: Info.Callee.getGlobal());
514 // TODO: support constexpr casts and indirect calls.
515 if (CF == nullptr)
516 return false;
517
518 FunctionType *FTy = SPIRV::getOriginalFunctionType(F: *CF);
519 OrigRetTy = FTy->getReturnType();
520 if (isUntypedPointerTy(T: OrigRetTy)) {
521 if (auto *DerivedRetTy = GR->findReturnType(ArgF: CF))
522 OrigRetTy = DerivedRetTy;
523 }
524 }
525
526 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
527 Register ResVReg =
528 Info.OrigRet.Regs.empty() ? Register(0) : Info.OrigRet.Regs[0];
529 const auto *ST = static_cast<const SPIRVSubtarget *>(&MF.getSubtarget());
530
531 bool isFunctionDecl = CF && CF->isDeclaration();
532 if (isFunctionDecl && !DemangledName.empty()) {
533 if (ResVReg.isValid()) {
534 if (!GR->getSPIRVTypeForVReg(VReg: ResVReg)) {
535 const Type *RetTy = OrigRetTy;
536 if (auto *PtrRetTy = dyn_cast<PointerType>(Val: OrigRetTy)) {
537 const Value *OrigValue = Info.OrigRet.OrigValue;
538 if (!OrigValue)
539 OrigValue = Info.CB;
540 if (OrigValue)
541 if (Type *ElemTy = GR->findDeducedElementType(Val: OrigValue))
542 RetTy =
543 TypedPointerType::get(ElementType: ElemTy, AddressSpace: PtrRetTy->getAddressSpace());
544 }
545 setRegClassType(Reg: ResVReg, Ty: RetTy, GR, MIRBuilder,
546 AccessQual: SPIRV::AccessQualifier::ReadWrite, EmitIR: true);
547 }
548 } else {
549 ResVReg = createVirtualRegister(Ty: OrigRetTy, GR, MIRBuilder,
550 AccessQual: SPIRV::AccessQualifier::ReadWrite, EmitIR: true);
551 }
552 SmallVector<Register, 8> ArgVRegs;
553 for (auto Arg : Info.OrigArgs) {
554 assert(Arg.Regs.size() == 1 && "Call arg has multiple VRegs");
555 Register ArgReg = Arg.Regs[0];
556 ArgVRegs.push_back(Elt: ArgReg);
557 SPIRVTypeInst SpvType = GR->getSPIRVTypeForVReg(VReg: ArgReg);
558 if (!SpvType) {
559 Type *ArgTy = nullptr;
560 if (auto *PtrArgTy = dyn_cast<PointerType>(Val: Arg.Ty)) {
561 // If Arg.Ty is an untyped pointer (i.e., ptr [addrspace(...)]) and we
562 // don't have access to original value in LLVM IR or info about
563 // deduced pointee type, then we should wait with setting the type for
564 // the virtual register until pre-legalizer step when we access
565 // @llvm.spv.assign.ptr.type.p...(...)'s info.
566 if (Arg.OrigValue)
567 if (Type *ElemTy = GR->findDeducedElementType(Val: Arg.OrigValue))
568 ArgTy =
569 TypedPointerType::get(ElementType: ElemTy, AddressSpace: PtrArgTy->getAddressSpace());
570 } else {
571 ArgTy = Arg.Ty;
572 }
573 if (ArgTy) {
574 SpvType = GR->getOrCreateSPIRVType(
575 Type: ArgTy, MIRBuilder, AQ: SPIRV::AccessQualifier::ReadWrite, EmitIR: true);
576 GR->assignSPIRVTypeToVReg(Type: SpvType, VReg: ArgReg, MF);
577 }
578 }
579 if (!MRI->getRegClassOrNull(Reg: ArgReg)) {
580 // Either we have SpvType created, or Arg.Ty is an untyped pointer and
581 // we know its virtual register's class and type even if we don't know
582 // pointee type.
583 MRI->setRegClass(Reg: ArgReg, RC: SpvType ? GR->getRegClass(SpvType)
584 : &SPIRV::pIDRegClass);
585 MRI->setType(
586 VReg: ArgReg,
587 Ty: SpvType ? GR->getRegType(SpvType)
588 : LLT::pointer(AddressSpace: cast<PointerType>(Val: Arg.Ty)->getAddressSpace(),
589 SizeInBits: GR->getPointerSize()));
590 }
591 }
592 if (auto Res = SPIRV::lowerBuiltin(
593 DemangledCall: DemangledName, Set: ST->getPreferredInstructionSet(), MIRBuilder,
594 OrigRet: ResVReg, OrigRetTy, Args: ArgVRegs, GR, CB: *Info.CB))
595 return *Res;
596 }
597
598 if (isFunctionDecl && !GR->find(V: CF, MF: &MF).isValid()) {
599 // Emit the type info and forward function declaration to the first MBB
600 // to ensure VReg definition dependencies are valid across all MBBs.
601 MachineIRBuilder FirstBlockBuilder;
602 FirstBlockBuilder.setMF(MF);
603 FirstBlockBuilder.setMBB(*MF.getBlockNumbered(N: 0));
604
605 SmallVector<ArrayRef<Register>, 8> VRegArgs;
606 SmallVector<SmallVector<Register, 1>, 8> ToInsert;
607 for (const Argument &Arg : CF->args()) {
608 if (MIRBuilder.getDataLayout().getTypeStoreSize(Ty: Arg.getType()).isZero())
609 continue; // Don't handle zero sized types.
610 Register Reg = MRI->createGenericVirtualRegister(Ty: LLT::scalar(SizeInBits: 64));
611 MRI->setRegClass(Reg, RC: &SPIRV::iIDRegClass);
612 ToInsert.push_back(Elt: {Reg});
613 VRegArgs.push_back(Elt: ToInsert.back());
614 }
615 // TODO: Reuse FunctionLoweringInfo
616 FunctionLoweringInfo FuncInfo;
617 lowerFormalArguments(MIRBuilder&: FirstBlockBuilder, F: *CF, VRegs: VRegArgs, FLI&: FuncInfo);
618 }
619
620 // Ignore the call if it's called from the internal service function
621 if (MIRBuilder.getMF()
622 .getFunction()
623 .getFnAttribute(SPIRV_BACKEND_SERVICE_FUN_NAME)
624 .isValid()) {
625 // insert a no-op
626 MIRBuilder.buildTrap();
627 Info.LoweredTailCall = true; // Do not emit an ill-formed G_ASSERT_ALIGN.
628 return true;
629 }
630
631 unsigned CallOp;
632 if (Info.CB && Info.CB->isIndirectCall()) {
633 if (!ST->canUseExtension(E: SPIRV::Extension::SPV_INTEL_function_pointers))
634 report_fatal_error(reason: "An indirect call is encountered but SPIR-V without "
635 "extensions does not support it",
636 gen_crash_diag: false);
637 // Set instruction operation according to SPV_INTEL_function_pointers
638 CallOp = SPIRV::OpFunctionPointerCallINTEL;
639 // Collect information about the indirect call to create correct types.
640 Register CalleeReg = Info.Callee.getReg();
641 if (CalleeReg.isValid()) {
642 SPIRVCallLowering::SPIRVIndirectCall IndirectCall;
643 IndirectCall.Callee = CalleeReg;
644 FunctionType *FTy = SPIRV::getOriginalFunctionType(CB: *Info.CB);
645 IndirectCall.RetTy = OrigRetTy = FTy->getReturnType();
646 assert(FTy->getNumParams() == Info.OrigArgs.size() &&
647 "Function types mismatch");
648 for (unsigned I = 0; I != Info.OrigArgs.size(); ++I) {
649 assert(Info.OrigArgs[I].Regs.size() == 1 &&
650 "Call arg has multiple VRegs");
651 IndirectCall.ArgTys.push_back(Elt: FTy->getParamType(i: I));
652 IndirectCall.ArgRegs.push_back(Elt: Info.OrigArgs[I].Regs[0]);
653 }
654 produceIndirectPtrType(MIRBuilder, IC: IndirectCall);
655 }
656 } else {
657 // Emit a regular OpFunctionCall
658 CallOp = SPIRV::OpFunctionCall;
659 }
660
661 // Make sure there's a valid return reg, even for functions returning void.
662 if (!ResVReg.isValid())
663 ResVReg = MIRBuilder.getMRI()->createVirtualRegister(RegClass: &SPIRV::iIDRegClass);
664 SPIRVTypeInst RetType = GR->assignTypeToVReg(
665 Type: OrigRetTy, VReg: ResVReg, MIRBuilder, AQ: SPIRV::AccessQualifier::ReadWrite, EmitIR: true);
666
667 // Emit the call instruction and its args.
668 auto MIB = MIRBuilder.buildInstr(Opcode: CallOp)
669 .addDef(RegNo: ResVReg)
670 .addUse(RegNo: GR->getSPIRVTypeID(SpirvType: RetType))
671 .add(MO: Info.Callee);
672 if (Info.NoMerge)
673 MIB.setMIFlag(MachineInstr::MIFlag::NoMerge);
674
675 for (const auto &Arg : Info.OrigArgs) {
676 // Currently call args should have single vregs.
677 if (Arg.Regs.size() > 1)
678 return false;
679 MIB.addUse(RegNo: Arg.Regs[0]);
680 }
681
682 if (Info.CB)
683 MIB.getInstr()->copyIRFlags(I: *Info.CB);
684
685 if (ST->canUseExtension(E: SPIRV::Extension::SPV_INTEL_memory_access_aliasing)) {
686 // Process aliasing metadata.
687 const CallBase *CI = Info.CB;
688 if (CI && CI->hasMetadata()) {
689 if (MDNode *MD = CI->getMetadata(KindID: LLVMContext::MD_alias_scope))
690 GR->buildMemAliasingOpDecorate(Reg: ResVReg, MIRBuilder,
691 Dec: SPIRV::Decoration::AliasScopeINTEL, GVarMD: MD);
692 if (MDNode *MD = CI->getMetadata(KindID: LLVMContext::MD_noalias))
693 GR->buildMemAliasingOpDecorate(Reg: ResVReg, MIRBuilder,
694 Dec: SPIRV::Decoration::NoAliasINTEL, GVarMD: MD);
695 }
696 }
697
698 MIB.constrainAllUses(TII: MIRBuilder.getTII(), TRI: *ST->getRegisterInfo(),
699 RBI: *ST->getRegBankInfo());
700 return true;
701}
702