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
51 if (Val) {
52 const auto &STI = MIRBuilder.getMF().getSubtarget();
53 MIRBuilder.buildInstr(SPIRV::OpReturnValue)
54 .addUse(VRegs[0])
55 .constrainAllUses(MIRBuilder.getTII(), *STI.getRegisterInfo(),
56 *STI.getRegBankInfo());
57 return true;
58 }
59 MIRBuilder.buildInstr(SPIRV::OpReturn);
60 return true;
61}
62
63// Based on the LLVM function attributes, get a SPIR-V FunctionControl.
65 const SPIRVSubtarget *ST) {
66 MemoryEffects MemEffects = F.getMemoryEffects();
67
68 uint32_t FuncControl = static_cast<uint32_t>(SPIRV::FunctionControl::None);
69
70 if (F.hasFnAttribute(Attribute::AttrKind::NoInline))
71 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::DontInline);
72 else if (F.hasFnAttribute(Attribute::AttrKind::AlwaysInline))
73 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Inline);
74
75 if (MemEffects.doesNotAccessMemory())
76 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Pure);
77 else if (MemEffects.onlyReadsMemory())
78 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Const);
79
80 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_optnone) ||
81 ST->canUseExtension(SPIRV::Extension::SPV_EXT_optnone))
82 if (F.hasFnAttribute(Attribute::OptimizeNone))
83 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::OptNoneEXT);
84
85 return FuncControl;
86}
87
88static ConstantInt *getConstInt(MDNode *MD, unsigned NumOp) {
89 if (MD->getNumOperands() > NumOp) {
90 auto *CMeta = dyn_cast<ConstantAsMetadata>(MD->getOperand(NumOp));
91 if (CMeta)
92 return dyn_cast<ConstantInt>(CMeta->getValue());
93 }
94 return nullptr;
95}
96
97// If the function has pointer arguments, we are forced to re-create this
98// function type from the very beginning, changing PointerType by
99// TypedPointerType for each pointer argument. Otherwise, the same `Type*`
100// potentially corresponds to different SPIR-V function type, effectively
101// invalidating logic behind global registry and duplicates tracker.
102static FunctionType *
104 FunctionType *FTy, SPIRVTypeInst SRetTy,
105 const SmallVector<SPIRVTypeInst, 4> &SArgTys) {
106 bool hasArgPtrs = false;
107 for (auto &Arg : F.args()) {
108 // check if it's an instance of a non-typed PointerType
109 if (Arg.getType()->isPointerTy()) {
110 hasArgPtrs = true;
111 break;
112 }
113 }
114 if (!hasArgPtrs) {
115 Type *RetTy = FTy->getReturnType();
116 // check if it's an instance of a non-typed PointerType
117 if (!RetTy->isPointerTy())
118 return FTy;
119 }
120
121 // re-create function type, using TypedPointerType instead of PointerType to
122 // properly trace argument types
123 const Type *RetTy = GR->getTypeForSPIRVType(SRetTy);
125 for (auto SArgTy : SArgTys)
126 ArgTys.push_back(const_cast<Type *>(GR->getTypeForSPIRVType(SArgTy)));
127 return FunctionType::get(const_cast<Type *>(RetTy), ArgTys, false);
128}
129
130static SPIRV::AccessQualifier::AccessQualifier
131getArgAccessQual(const Function &F, unsigned ArgIdx) {
132 if (F.getCallingConv() != CallingConv::SPIR_KERNEL)
133 return SPIRV::AccessQualifier::ReadWrite;
134
135 MDString *ArgAttribute = getOCLKernelArgAccessQual(F, ArgIdx);
136 if (!ArgAttribute)
137 return SPIRV::AccessQualifier::ReadWrite;
138
139 if (ArgAttribute->getString() == "read_only")
140 return SPIRV::AccessQualifier::ReadOnly;
141 if (ArgAttribute->getString() == "write_only")
142 return SPIRV::AccessQualifier::WriteOnly;
143 return SPIRV::AccessQualifier::ReadWrite;
144}
145
146static std::vector<SPIRV::Decoration::Decoration>
147getKernelArgTypeQual(const Function &F, unsigned ArgIdx) {
148 MDString *ArgAttribute = getOCLKernelArgTypeQual(F, ArgIdx);
149 if (ArgAttribute && ArgAttribute->getString() == "volatile")
150 return {SPIRV::Decoration::Volatile};
151 return {};
152}
153
154static SPIRVTypeInst getArgSPIRVType(const Function &F, unsigned ArgIdx,
156 MachineIRBuilder &MIRBuilder,
157 const SPIRVSubtarget &ST) {
158 // Read argument's access qualifier from metadata or default.
159 SPIRV::AccessQualifier::AccessQualifier ArgAccessQual =
160 getArgAccessQual(F, ArgIdx);
161
162 Type *OriginalArgType =
164
165 // If OriginalArgType is non-pointer, use the OriginalArgType (the type cannot
166 // be legally reassigned later).
167 if (!isPointerTy(OriginalArgType))
168 return GR->getOrCreateSPIRVType(OriginalArgType, MIRBuilder, ArgAccessQual,
169 true);
170
171 Argument *Arg = F.getArg(ArgIdx);
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 (Arg.hasAttribute(Attribute::ReadOnly)) {
292 auto Attr =
293 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoWrite);
294 buildOpDecorate(VRegs[i][0], MIRBuilder,
295 SPIRV::Decoration::FuncParamAttr, {Attr});
296 }
297 if (Arg.hasAttribute(Attribute::ZExt)) {
298 auto Attr =
299 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Zext);
300 buildOpDecorate(VRegs[i][0], MIRBuilder,
301 SPIRV::Decoration::FuncParamAttr, {Attr});
302 }
303 if (Arg.hasAttribute(Attribute::NoAlias)) {
304 auto Attr =
305 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoAlias);
306 buildOpDecorate(VRegs[i][0], MIRBuilder,
307 SPIRV::Decoration::FuncParamAttr, {Attr});
308 }
309 // TODO: the AMDGPU BE only supports ByRef argument passing, thus for
310 // AMDGCN flavoured SPIRV we CodeGen for ByRef, but lower it to
311 // ByVal, handling the impedance mismatch during reverse
312 // translation from SPIRV to LLVM IR; the vendor check should be
313 // removed once / if SPIRV adds ByRef support.
314 if (Arg.hasAttribute(Attribute::ByVal) ||
315 (Arg.hasAttribute(Attribute::ByRef) &&
316 F.getParent()->getTargetTriple().getVendor() ==
318 auto Attr =
319 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::ByVal);
320 buildOpDecorate(VRegs[i][0], MIRBuilder,
321 SPIRV::Decoration::FuncParamAttr, {Attr});
322 }
323 if (Arg.hasAttribute(Attribute::StructRet)) {
324 auto Attr =
325 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sret);
326 buildOpDecorate(VRegs[i][0], MIRBuilder,
327 SPIRV::Decoration::FuncParamAttr, {Attr});
328 }
329
330 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
331 std::vector<SPIRV::Decoration::Decoration> ArgTypeQualDecs =
333 for (SPIRV::Decoration::Decoration Decoration : ArgTypeQualDecs)
334 buildOpDecorate(VRegs[i][0], MIRBuilder, Decoration, {});
335 }
336
337 MDNode *Node = F.getMetadata("spirv.ParameterDecorations");
338 if (Node && i < Node->getNumOperands() &&
339 isa<MDNode>(Node->getOperand(i))) {
340 MDNode *MD = cast<MDNode>(Node->getOperand(i));
341 for (const MDOperand &MDOp : MD->operands()) {
342 MDNode *MD2 = dyn_cast<MDNode>(MDOp);
343 assert(MD2 && "Metadata operand is expected");
344 ConstantInt *Const = getConstInt(MD2, 0);
345 assert(Const && "MDOperand should be ConstantInt");
346 auto Dec =
347 static_cast<SPIRV::Decoration::Decoration>(Const->getZExtValue());
348 std::vector<uint32_t> DecVec;
349 for (unsigned j = 1; j < MD2->getNumOperands(); j++) {
350 ConstantInt *Const = getConstInt(MD2, j);
351 assert(Const && "MDOperand should be ConstantInt");
352 DecVec.push_back(static_cast<uint32_t>(Const->getZExtValue()));
353 }
354 buildOpDecorate(VRegs[i][0], MIRBuilder, Dec, DecVec);
355 }
356 }
357 ++i;
358 }
359 }
360
361 auto MRI = MIRBuilder.getMRI();
362 Register FuncVReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
363 MRI->setRegClass(FuncVReg, &SPIRV::iIDRegClass);
365 Type *FRetTy = FTy->getReturnType();
366 if (isUntypedPointerTy(FRetTy)) {
367 if (Type *FRetElemTy = GR->findDeducedElementType(&F)) {
369 toTypedPointer(FRetElemTy), getPointerAddressSpace(FRetTy));
370 GR->addReturnType(&F, DerivedTy);
371 FRetTy = DerivedTy;
372 }
373 }
374 SPIRVTypeInst RetTy = GR->getOrCreateSPIRVType(
375 FRetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
376 FTy = fixFunctionTypeIfPtrArgs(GR, F, FTy, RetTy, ArgTypeVRegs);
377 SPIRVTypeInst FuncTy = GR->getOrCreateOpTypeFunctionWithArgs(
378 FTy, RetTy, ArgTypeVRegs, MIRBuilder);
379 uint32_t FuncControl = getFunctionControl(F, ST);
380
381 // Add OpFunction instruction
382 MachineInstrBuilder MB = MIRBuilder.buildInstr(SPIRV::OpFunction)
383 .addDef(FuncVReg)
384 .addUse(GR->getSPIRVTypeID(RetTy))
385 .addImm(FuncControl)
386 .addUse(GR->getSPIRVTypeID(FuncTy));
387 GR->recordFunctionDefinition(&F, &MB.getInstr()->getOperand(0));
388 GR->addGlobalObject(&F, &MIRBuilder.getMF(), FuncVReg);
389 if (F.isDeclaration())
390 GR->add(&F, MB);
391
392 // Add OpFunctionParameter instructions
393 int i = 0;
394 for (const auto &Arg : F.args()) {
395 assert(VRegs[i].size() == 1 && "Formal arg has multiple vregs");
396 Register ArgReg = VRegs[i][0];
397 MRI->setRegClass(ArgReg, GR->getRegClass(ArgTypeVRegs[i]));
398 MRI->setType(ArgReg, GR->getRegType(ArgTypeVRegs[i]));
399 auto MIB = MIRBuilder.buildInstr(SPIRV::OpFunctionParameter)
400 .addDef(ArgReg)
401 .addUse(GR->getSPIRVTypeID(ArgTypeVRegs[i]));
402 if (F.isDeclaration())
403 GR->add(&Arg, MIB);
404 GR->addGlobalObject(&Arg, &MIRBuilder.getMF(), ArgReg);
405 i++;
406 }
407 // Name the function.
408 if (F.hasName())
409 buildOpName(FuncVReg, F.getName(), MIRBuilder);
410
411 // Handle entry points and function linkage.
412 if (isEntryPoint(F)) {
413 auto MIB = MIRBuilder.buildInstr(SPIRV::OpEntryPoint)
414 .addImm(static_cast<uint32_t>(getExecutionModel(*ST, F)))
415 .addUse(FuncVReg);
416 addStringImm(F.getName(), MIB);
417 } else if (const auto LnkTy = getSpirvLinkageTypeFor(*ST, F)) {
418 buildOpDecorate(FuncVReg, MIRBuilder, SPIRV::Decoration::LinkageAttributes,
419 {static_cast<uint32_t>(*LnkTy)}, F.getName());
420 }
421
422 // Handle function pointers decoration
423 bool hasFunctionPointers =
424 ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
425 if (hasFunctionPointers) {
426 if (F.hasFnAttribute("referenced-indirectly")) {
427 assert((F.getCallingConv() != CallingConv::SPIR_KERNEL) &&
428 "Unexpected 'referenced-indirectly' attribute of the kernel "
429 "function");
430 buildOpDecorate(FuncVReg, MIRBuilder,
431 SPIRV::Decoration::ReferencedIndirectlyINTEL, {});
432 }
433 }
434
435 return true;
436}
437
438// TODO:
439// - add a topological sort of IndirectCalls to ensure the best types knowledge
440// - we may need to fix function formal parameter types if they are opaque
441// pointers used as function pointers in these indirect calls
442// - defaulting to StorageClass::Function in the absence of the
443// SPV_INTEL_function_pointers extension seems wrong, as that might not be
444// able to hold a full width pointer to function, and it also does not model
445// the semantics of a pointer to function in a generic fashion.
446void SPIRVCallLowering::produceIndirectPtrType(
447 MachineIRBuilder &MIRBuilder,
448 const SPIRVCallLowering::SPIRVIndirectCall &IC) const {
449 // Create indirect call data type if any
450 MachineFunction &MF = MIRBuilder.getMF();
452 SPIRVTypeInst SpirvRetTy = GR->getOrCreateSPIRVType(
453 IC.RetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
454 SmallVector<SPIRVTypeInst, 4> SpirvArgTypes;
455 for (size_t i = 0; i < IC.ArgTys.size(); ++i) {
457 IC.ArgTys[i], MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
458 SpirvArgTypes.push_back(SPIRVTy);
459 if (!GR->getSPIRVTypeForVReg(IC.ArgRegs[i]))
460 GR->assignSPIRVTypeToVReg(SPIRVTy, IC.ArgRegs[i], MF);
461 }
462 // SPIR-V function type:
463 FunctionType *FTy =
464 FunctionType::get(const_cast<Type *>(IC.RetTy), IC.ArgTys, false);
466 FTy, SpirvRetTy, SpirvArgTypes, MIRBuilder);
467 // SPIR-V pointer to function type:
468 auto SC = ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)
469 ? SPIRV::StorageClass::CodeSectionINTEL
470 : SPIRV::StorageClass::Function;
471 SPIRVTypeInst IndirectFuncPtrTy =
472 GR->getOrCreateSPIRVPointerType(SpirvFuncTy, MIRBuilder, SC);
473 // Correct the Callee type
474 GR->assignSPIRVTypeToVReg(IndirectFuncPtrTy, IC.Callee, MF);
475}
476
478 CallLoweringInfo &Info) const {
479 // Currently call returns should have single vregs.
480 // TODO: handle the case of multiple registers.
481 if (Info.OrigRet.Regs.size() > 1)
482 return false;
483 MachineFunction &MF = MIRBuilder.getMF();
484 GR->setCurrentFunc(MF);
485 const Function *CF = nullptr;
486 std::string DemangledName;
487 const Type *OrigRetTy = Info.OrigRet.Ty;
488
489 // Emit a regular OpFunctionCall. If it's an externally declared function,
490 // be sure to emit its type and function declaration here. It will be hoisted
491 // globally later.
492 if (Info.Callee.isGlobal()) {
493 std::string FuncName = Info.Callee.getGlobal()->getName().str();
494 DemangledName = getOclOrSpirvBuiltinDemangledName(FuncName);
495 CF = dyn_cast_or_null<const Function>(Info.Callee.getGlobal());
496 // TODO: support constexpr casts and indirect calls.
497 if (CF == nullptr)
498 return false;
499
501 OrigRetTy = FTy->getReturnType();
502 if (isUntypedPointerTy(OrigRetTy)) {
503 if (auto *DerivedRetTy = GR->findReturnType(CF))
504 OrigRetTy = DerivedRetTy;
505 }
506 }
507
508 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
509 Register ResVReg =
510 Info.OrigRet.Regs.empty() ? Register(0) : Info.OrigRet.Regs[0];
511 const auto *ST = static_cast<const SPIRVSubtarget *>(&MF.getSubtarget());
512
513 bool isFunctionDecl = CF && CF->isDeclaration();
514 if (isFunctionDecl && !DemangledName.empty()) {
515 if (ResVReg.isValid()) {
516 if (!GR->getSPIRVTypeForVReg(ResVReg)) {
517 const Type *RetTy = OrigRetTy;
518 if (auto *PtrRetTy = dyn_cast<PointerType>(OrigRetTy)) {
519 const Value *OrigValue = Info.OrigRet.OrigValue;
520 if (!OrigValue)
521 OrigValue = Info.CB;
522 if (OrigValue)
523 if (Type *ElemTy = GR->findDeducedElementType(OrigValue))
524 RetTy =
525 TypedPointerType::get(ElemTy, PtrRetTy->getAddressSpace());
526 }
527 setRegClassType(ResVReg, RetTy, GR, MIRBuilder,
528 SPIRV::AccessQualifier::ReadWrite, true);
529 }
530 } else {
531 ResVReg = createVirtualRegister(OrigRetTy, GR, MIRBuilder,
532 SPIRV::AccessQualifier::ReadWrite, true);
533 }
535 for (auto Arg : Info.OrigArgs) {
536 assert(Arg.Regs.size() == 1 && "Call arg has multiple VRegs");
537 Register ArgReg = Arg.Regs[0];
538 ArgVRegs.push_back(ArgReg);
539 SPIRVTypeInst SpvType = GR->getSPIRVTypeForVReg(ArgReg);
540 if (!SpvType) {
541 Type *ArgTy = nullptr;
542 if (auto *PtrArgTy = dyn_cast<PointerType>(Arg.Ty)) {
543 // If Arg.Ty is an untyped pointer (i.e., ptr [addrspace(...)]) and we
544 // don't have access to original value in LLVM IR or info about
545 // deduced pointee type, then we should wait with setting the type for
546 // the virtual register until pre-legalizer step when we access
547 // @llvm.spv.assign.ptr.type.p...(...)'s info.
548 if (Arg.OrigValue)
549 if (Type *ElemTy = GR->findDeducedElementType(Arg.OrigValue))
550 ArgTy =
551 TypedPointerType::get(ElemTy, PtrArgTy->getAddressSpace());
552 } else {
553 ArgTy = Arg.Ty;
554 }
555 if (ArgTy) {
556 SpvType = GR->getOrCreateSPIRVType(
557 ArgTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
558 GR->assignSPIRVTypeToVReg(SpvType, ArgReg, MF);
559 }
560 }
561 if (!MRI->getRegClassOrNull(ArgReg)) {
562 // Either we have SpvType created, or Arg.Ty is an untyped pointer and
563 // we know its virtual register's class and type even if we don't know
564 // pointee type.
565 MRI->setRegClass(ArgReg, SpvType ? GR->getRegClass(SpvType)
566 : &SPIRV::pIDRegClass);
567 MRI->setType(
568 ArgReg,
569 SpvType ? GR->getRegType(SpvType)
570 : LLT::pointer(cast<PointerType>(Arg.Ty)->getAddressSpace(),
571 GR->getPointerSize()));
572 }
573 }
574 if (auto Res = SPIRV::lowerBuiltin(
575 DemangledName, ST->getPreferredInstructionSet(), MIRBuilder,
576 ResVReg, OrigRetTy, ArgVRegs, GR, *Info.CB))
577 return *Res;
578 }
579
580 if (isFunctionDecl && !GR->find(CF, &MF).isValid()) {
581 // Emit the type info and forward function declaration to the first MBB
582 // to ensure VReg definition dependencies are valid across all MBBs.
583 MachineIRBuilder FirstBlockBuilder;
584 FirstBlockBuilder.setMF(MF);
585 FirstBlockBuilder.setMBB(*MF.getBlockNumbered(0));
586
589 for (const Argument &Arg : CF->args()) {
590 if (MIRBuilder.getDataLayout().getTypeStoreSize(Arg.getType()).isZero())
591 continue; // Don't handle zero sized types.
592 Register Reg = MRI->createGenericVirtualRegister(LLT::scalar(64));
593 MRI->setRegClass(Reg, &SPIRV::iIDRegClass);
594 ToInsert.push_back({Reg});
595 VRegArgs.push_back(ToInsert.back());
596 }
597 // TODO: Reuse FunctionLoweringInfo
598 FunctionLoweringInfo FuncInfo;
599 lowerFormalArguments(FirstBlockBuilder, *CF, VRegArgs, FuncInfo);
600 }
601
602 // Ignore the call if it's called from the internal service function
603 if (MIRBuilder.getMF()
604 .getFunction()
606 .isValid()) {
607 // insert a no-op
608 MIRBuilder.buildTrap();
609 return true;
610 }
611
612 unsigned CallOp;
613 if (Info.CB->isIndirectCall()) {
614 if (!ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
615 report_fatal_error("An indirect call is encountered but SPIR-V without "
616 "extensions does not support it",
617 false);
618 // Set instruction operation according to SPV_INTEL_function_pointers
619 CallOp = SPIRV::OpFunctionPointerCallINTEL;
620 // Collect information about the indirect call to create correct types.
621 Register CalleeReg = Info.Callee.getReg();
622 if (CalleeReg.isValid()) {
623 SPIRVCallLowering::SPIRVIndirectCall IndirectCall;
624 IndirectCall.Callee = CalleeReg;
626 IndirectCall.RetTy = OrigRetTy = FTy->getReturnType();
627 assert(FTy->getNumParams() == Info.OrigArgs.size() &&
628 "Function types mismatch");
629 for (unsigned I = 0; I != Info.OrigArgs.size(); ++I) {
630 assert(Info.OrigArgs[I].Regs.size() == 1 &&
631 "Call arg has multiple VRegs");
632 IndirectCall.ArgTys.push_back(FTy->getParamType(I));
633 IndirectCall.ArgRegs.push_back(Info.OrigArgs[I].Regs[0]);
634 }
635 produceIndirectPtrType(MIRBuilder, IndirectCall);
636 }
637 } else {
638 // Emit a regular OpFunctionCall
639 CallOp = SPIRV::OpFunctionCall;
640 }
641
642 // Make sure there's a valid return reg, even for functions returning void.
643 if (!ResVReg.isValid())
644 ResVReg = MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
645 SPIRVTypeInst RetType = GR->assignTypeToVReg(
646 OrigRetTy, ResVReg, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
647
648 // Emit the call instruction and its args.
649 auto MIB = MIRBuilder.buildInstr(CallOp)
650 .addDef(ResVReg)
651 .addUse(GR->getSPIRVTypeID(RetType))
652 .add(Info.Callee);
653
654 for (const auto &Arg : Info.OrigArgs) {
655 // Currently call args should have single vregs.
656 if (Arg.Regs.size() > 1)
657 return false;
658 MIB.addUse(Arg.Regs[0]);
659 }
660
661 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing)) {
662 // Process aliasing metadata.
663 const CallBase *CI = Info.CB;
664 if (CI && CI->hasMetadata()) {
665 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_alias_scope))
666 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
667 SPIRV::Decoration::AliasScopeINTEL, MD);
668 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_noalias))
669 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
670 SPIRV::Decoration::NoAliasINTEL, MD);
671 }
672 }
673
674 MIB.constrainAllUses(MIRBuilder.getTII(), *ST->getRegisterInfo(),
675 *ST->getRegBankInfo());
676 return true;
677}
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 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:528
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: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: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:892
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)
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...
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:223
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
Definition ModRef.h:226
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)
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
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: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:1669
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:370
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:313
MDString * getOCLKernelArgAccessQual(const Function &F, unsigned ArgIdx)
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
bool isTypedPointerTy(const Type *T)
Definition SPIRVUtils.h:354
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)
Type * toTypedPointer(Type *Ty)
Definition SPIRVUtils.h:461
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:364
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:383
bool hasPointeeTypeAttr(Argument *Arg)
Definition SPIRVUtils.h:378
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:413
void addStringImm(const StringRef &Str, MCInst &Inst)
bool isUntypedPointerTy(const Type *T)
Definition SPIRVUtils.h:359