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 // Vector of untyped pointers: build with the deduced pointee instead of
166 // the default i8 (mismatches typed uses downstream).
167 Argument *Arg = F.getArg(ArgIdx);
168 if (auto *VTy = dyn_cast<FixedVectorType>(OriginalArgType);
169 VTy && isUntypedPointerTy(VTy->getElementType()))
170 if (Type *ElemTy = GR->findDeducedElementType(Arg))
173 ElemTy, MIRBuilder,
175 getPointerAddressSpace(OriginalArgType), ST)),
176 VTy->getNumElements(), MIRBuilder, true);
177
178 // If OriginalArgType is non-pointer, use the OriginalArgType (the type cannot
179 // be legally reassigned later).
180 if (!isPointerTy(OriginalArgType))
181 return GR->getOrCreateSPIRVType(OriginalArgType, MIRBuilder, ArgAccessQual,
182 true);
183
184 Type *ArgType = Arg->getType();
185 if (isTypedPointerTy(ArgType)) {
187 cast<TypedPointerType>(ArgType)->getElementType(), MIRBuilder,
189 }
190
191 // In case OriginalArgType is of untyped pointer type, there are three
192 // possibilities:
193 // 1) This is a pointer of an LLVM IR element type, passed byval/byref.
194 // 2) This is an OpenCL/SPIR-V builtin type if there is spv_assign_type
195 // intrinsic assigning a TargetExtType.
196 // 3) This is a pointer, try to retrieve pointer element type from a
197 // spv_assign_ptr_type intrinsic or otherwise use default pointer element
198 // type.
199 if (hasPointeeTypeAttr(Arg)) {
201 getPointeeTypeByAttr(Arg), MIRBuilder,
203 }
204
205 for (auto User : Arg->users()) {
207 // Check if this is spv_assign_type assigning OpenCL/SPIR-V builtin type.
208 if (II && II->getIntrinsicID() == Intrinsic::spv_assign_type) {
209 MetadataAsValue *VMD = cast<MetadataAsValue>(II->getOperand(1));
210 Type *BuiltinType =
211 cast<ConstantAsMetadata>(VMD->getMetadata())->getType();
212 assert(BuiltinType->isTargetExtTy() && "Expected TargetExtType");
213 return GR->getOrCreateSPIRVType(BuiltinType, MIRBuilder, ArgAccessQual,
214 true);
215 }
216
217 // Check if this is spv_assign_ptr_type assigning pointer element type.
218 if (!II || II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type)
219 continue;
220
221 MetadataAsValue *VMD = cast<MetadataAsValue>(II->getOperand(1));
222 Type *ElementTy =
225 ElementTy, MIRBuilder,
227 cast<ConstantInt>(II->getOperand(2))->getZExtValue(), ST));
228 }
229
230 // Replace PointerType with TypedPointerType to be able to map SPIR-V types to
231 // LLVM types in a consistent manner
232 return GR->getOrCreateSPIRVType(toTypedPointer(OriginalArgType), MIRBuilder,
233 ArgAccessQual, true);
234}
235
236static SPIRV::ExecutionModel::ExecutionModel
239 "Environment must be resolved before lowering entry points.");
240
241 if (STI.isKernel())
242 return SPIRV::ExecutionModel::Kernel;
243
244 auto attribute = F.getFnAttribute("hlsl.shader");
245 if (!attribute.isValid()) {
247 "This entry point lacks mandatory hlsl.shader attribute.");
248 }
249
250 const auto value = attribute.getValueAsString();
251 if (value == "compute")
252 return SPIRV::ExecutionModel::GLCompute;
253 if (value == "vertex")
254 return SPIRV::ExecutionModel::Vertex;
255 if (value == "pixel")
256 return SPIRV::ExecutionModel::Fragment;
257
258 report_fatal_error("This HLSL entry point is not supported by this backend.");
259}
260
262 const Function &F,
264 FunctionLoweringInfo &FLI) const {
265 // Discard the internal service function
266 if (F.getFnAttribute(SPIRV_BACKEND_SERVICE_FUN_NAME).isValid())
267 return true;
268
269 assert(GR && "Must initialize the SPIRV type registry before lowering args.");
270 GR->setCurrentFunc(MIRBuilder.getMF());
271
272 // Get access to information about available extensions
273 const SPIRVSubtarget *ST =
274 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
275
276 // Assign types and names to all args, and store their types for later.
278 if (VRegs.size() > 0) {
279 unsigned i = 0;
280 for (const auto &Arg : F.args()) {
281 // Currently formal args should use single registers.
282 // TODO: handle the case of multiple registers.
283 if (VRegs[i].size() > 1)
284 return false;
285 SPIRVTypeInst SpirvTy = getArgSPIRVType(F, i, GR, MIRBuilder, *ST);
286 GR->assignSPIRVTypeToVReg(SpirvTy, VRegs[i][0], MIRBuilder.getMF());
287 ArgTypeVRegs.push_back(SpirvTy);
288
289 if (Arg.hasName())
290 buildOpName(VRegs[i][0], Arg.getName(), MIRBuilder);
291 if (isPointerTyOrWrapper(Arg.getType())) {
292 auto DerefBytes = static_cast<unsigned>(Arg.getDereferenceableBytes());
293 if (DerefBytes != 0)
294 buildOpDecorate(VRegs[i][0], MIRBuilder,
295 SPIRV::Decoration::MaxByteOffset, {DerefBytes});
296 }
297 if (Arg.hasAttribute(Attribute::Alignment) && !ST->isShader()) {
298 auto Alignment = static_cast<unsigned>(
299 Arg.getAttribute(Attribute::Alignment).getValueAsInt());
300 buildOpDecorate(VRegs[i][0], MIRBuilder, SPIRV::Decoration::Alignment,
301 {Alignment});
302 }
303 if (!ST->isShader()) {
304 if (Arg.hasAttribute(Attribute::ReadOnly)) {
305 auto Attr =
306 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoWrite);
307 buildOpDecorate(VRegs[i][0], MIRBuilder,
308 SPIRV::Decoration::FuncParamAttr, {Attr});
309 }
310 if (Arg.hasAttribute(Attribute::ZExt)) {
311 auto Attr =
312 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Zext);
313 buildOpDecorate(VRegs[i][0], MIRBuilder,
314 SPIRV::Decoration::FuncParamAttr, {Attr});
315 }
316 if (Arg.hasAttribute(Attribute::SExt)) {
317 auto Attr =
318 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sext);
319 buildOpDecorate(VRegs[i][0], MIRBuilder,
320 SPIRV::Decoration::FuncParamAttr, {Attr});
321 }
322 if (Arg.hasAttribute(Attribute::NoAlias)) {
323 auto Attr =
324 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoAlias);
325 buildOpDecorate(VRegs[i][0], MIRBuilder,
326 SPIRV::Decoration::FuncParamAttr, {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(Attribute::ByVal) ||
334 (Arg.hasAttribute(Attribute::ByRef) &&
335 F.getParent()->getTargetTriple().getVendor() ==
337 auto Attr =
338 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::ByVal);
339 buildOpDecorate(VRegs[i][0], MIRBuilder,
340 SPIRV::Decoration::FuncParamAttr, {Attr});
341 }
342 if (Arg.hasAttribute(Attribute::StructRet)) {
343 auto Attr =
344 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sret);
345 buildOpDecorate(VRegs[i][0], MIRBuilder,
346 SPIRV::Decoration::FuncParamAttr, {Attr});
347 }
348 }
349
350 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
351 std::vector<SPIRV::Decoration::Decoration> ArgTypeQualDecs =
353 for (SPIRV::Decoration::Decoration Decoration : ArgTypeQualDecs)
354 buildOpDecorate(VRegs[i][0], MIRBuilder, Decoration, {});
355 }
356
357 MDNode *Node = F.getMetadata("spirv.ParameterDecorations");
358 if (Node && i < Node->getNumOperands() &&
359 isa<MDNode>(Node->getOperand(i))) {
360 MDNode *MD = cast<MDNode>(Node->getOperand(i));
361 for (const MDOperand &MDOp : MD->operands()) {
362 MDNode *MD2 = dyn_cast<MDNode>(MDOp);
363 assert(MD2 && "Metadata operand is expected");
364 ConstantInt *Const = getConstInt(MD2, 0);
365 assert(Const && "MDOperand should be ConstantInt");
366 auto Dec =
367 static_cast<SPIRV::Decoration::Decoration>(Const->getZExtValue());
368 std::vector<uint32_t> DecVec;
369 for (unsigned j = 1; j < MD2->getNumOperands(); j++) {
370 ConstantInt *Const = getConstInt(MD2, j);
371 assert(Const && "MDOperand should be ConstantInt");
372 DecVec.push_back(static_cast<uint32_t>(Const->getZExtValue()));
373 }
374 buildOpDecorate(VRegs[i][0], MIRBuilder, Dec, DecVec);
375 }
376 }
377 ++i;
378 }
379 }
380
381 auto MRI = MIRBuilder.getMRI();
382 Register FuncVReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
383 MRI->setRegClass(FuncVReg, &SPIRV::iIDRegClass);
385 Type *FRetTy = FTy->getReturnType();
386 if (isUntypedPointerTy(FRetTy)) {
387 if (Type *FRetElemTy = GR->findDeducedElementType(&F)) {
389 toTypedPointer(FRetElemTy), getPointerAddressSpace(FRetTy));
390 GR->addReturnType(&F, DerivedTy);
391 FRetTy = DerivedTy;
392 }
393 }
394 SPIRVTypeInst RetTy = GR->getOrCreateSPIRVType(
395 FRetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
396 FTy = fixFunctionTypeIfPtrArgs(GR, F, FTy, RetTy, ArgTypeVRegs);
397 SPIRVTypeInst FuncTy = GR->getOrCreateOpTypeFunctionWithArgs(
398 FTy, RetTy, ArgTypeVRegs, MIRBuilder);
399 uint32_t FuncControl = getFunctionControl(F, ST);
400
401 // Add OpFunction instruction
402 MachineInstrBuilder MB = MIRBuilder.buildInstr(SPIRV::OpFunction)
403 .addDef(FuncVReg)
404 .addUse(GR->getSPIRVTypeID(RetTy))
405 .addImm(FuncControl)
406 .addUse(GR->getSPIRVTypeID(FuncTy));
407 GR->recordFunctionDefinition(&F, &MB.getInstr()->getOperand(0));
408 GR->addGlobalObject(&F, &MIRBuilder.getMF(), FuncVReg);
409 if (F.isDeclaration())
410 GR->add(&F, MB);
411
412 // Add OpFunctionParameter instructions
413 int i = 0;
414 for (const auto &Arg : F.args()) {
415 assert(VRegs[i].size() == 1 && "Formal arg has multiple vregs");
416 Register ArgReg = VRegs[i][0];
417 MRI->setRegClass(ArgReg, GR->getRegClass(ArgTypeVRegs[i]));
418 auto MIB = MIRBuilder.buildInstr(SPIRV::OpFunctionParameter)
419 .addDef(ArgReg)
420 .addUse(GR->getSPIRVTypeID(ArgTypeVRegs[i]));
421 if (F.isDeclaration())
422 GR->add(&Arg, MIB);
423 GR->addGlobalObject(&Arg, &MIRBuilder.getMF(), ArgReg);
424 i++;
425 }
426 // Name the function.
427 if (F.hasName())
428 buildOpName(FuncVReg, F.getName(), MIRBuilder);
429
430 // Handle entry points and function linkage.
431 if (isEntryPoint(F)) {
432 auto MIB = MIRBuilder.buildInstr(SPIRV::OpEntryPoint)
433 .addImm(static_cast<uint32_t>(getExecutionModel(*ST, F)))
434 .addUse(FuncVReg);
435 addStringImm(F.getName(), MIB);
436 } else if (const auto LnkTy = getSpirvLinkageTypeFor(*ST, F)) {
437 buildOpDecorate(FuncVReg, MIRBuilder, SPIRV::Decoration::LinkageAttributes,
438 {static_cast<uint32_t>(*LnkTy)}, F.getName());
439 }
440
441 // Handle function pointers decoration
442 bool hasFunctionPointers =
443 ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
444 if (hasFunctionPointers) {
445 if (F.hasFnAttribute("referenced-indirectly")) {
446 assert((F.getCallingConv() != CallingConv::SPIR_KERNEL) &&
447 "Unexpected 'referenced-indirectly' attribute of the kernel "
448 "function");
449 buildOpDecorate(FuncVReg, MIRBuilder,
450 SPIRV::Decoration::ReferencedIndirectlyINTEL, {});
451 }
452 }
453
454 return true;
455}
456
457// TODO:
458// - add a topological sort of IndirectCalls to ensure the best types knowledge
459// - we may need to fix function formal parameter types if they are opaque
460// pointers used as function pointers in these indirect calls
461// - defaulting to StorageClass::Function in the absence of the
462// SPV_INTEL_function_pointers extension seems wrong, as that might not be
463// able to hold a full width pointer to function, and it also does not model
464// the semantics of a pointer to function in a generic fashion.
465void SPIRVCallLowering::produceIndirectPtrType(
466 MachineIRBuilder &MIRBuilder,
467 const SPIRVCallLowering::SPIRVIndirectCall &IC) const {
468 // Create indirect call data type if any
469 MachineFunction &MF = MIRBuilder.getMF();
471 SPIRVTypeInst SpirvRetTy = GR->getOrCreateSPIRVType(
472 IC.RetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
473 SmallVector<SPIRVTypeInst, 4> SpirvArgTypes;
474 for (size_t i = 0; i < IC.ArgTys.size(); ++i) {
476 IC.ArgTys[i], MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
477 SpirvArgTypes.push_back(SPIRVTy);
478 if (!GR->getSPIRVTypeForVReg(IC.ArgRegs[i]))
479 GR->assignSPIRVTypeToVReg(SPIRVTy, IC.ArgRegs[i], MF);
480 }
481 // SPIR-V function type:
482 FunctionType *FTy =
483 FunctionType::get(const_cast<Type *>(IC.RetTy), IC.ArgTys, false);
485 FTy, SpirvRetTy, SpirvArgTypes, MIRBuilder);
486 // SPIR-V pointer to function type:
487 auto SC = ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)
488 ? SPIRV::StorageClass::CodeSectionINTEL
489 : SPIRV::StorageClass::Function;
490 SPIRVTypeInst IndirectFuncPtrTy =
491 GR->getOrCreateSPIRVPointerType(SpirvFuncTy, MIRBuilder, SC);
492 // Correct the Callee type
493 GR->assignSPIRVTypeToVReg(IndirectFuncPtrTy, IC.Callee, MF);
494}
495
497 CallLoweringInfo &Info) const {
498 // Currently call returns should have single vregs.
499 // TODO: handle the case of multiple registers.
500 if (Info.OrigRet.Regs.size() > 1)
501 return false;
502 MachineFunction &MF = MIRBuilder.getMF();
503 GR->setCurrentFunc(MF);
504 const Function *CF = nullptr;
505 std::string DemangledName;
506 const Type *OrigRetTy = Info.OrigRet.Ty;
507
508 // Emit a regular OpFunctionCall. If it's an externally declared function,
509 // be sure to emit its type and function declaration here. It will be hoisted
510 // globally later.
511 if (Info.Callee.isGlobal()) {
512 std::string FuncName = Info.Callee.getGlobal()->getName().str();
513 DemangledName = getOclOrSpirvBuiltinDemangledName(FuncName);
514 CF = dyn_cast_or_null<const Function>(Info.Callee.getGlobal());
515 // TODO: support constexpr casts and indirect calls.
516 if (CF == nullptr)
517 return false;
518
520 OrigRetTy = FTy->getReturnType();
521 if (isUntypedPointerTy(OrigRetTy)) {
522 if (auto *DerivedRetTy = GR->findReturnType(CF))
523 OrigRetTy = DerivedRetTy;
524 }
525 }
526
527 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
528 Register ResVReg =
529 Info.OrigRet.Regs.empty() ? Register(0) : Info.OrigRet.Regs[0];
530 const auto *ST = static_cast<const SPIRVSubtarget *>(&MF.getSubtarget());
531
532 bool isFunctionDecl = CF && CF->isDeclaration();
533 if (isFunctionDecl && !DemangledName.empty()) {
534 if (ResVReg.isValid()) {
535 if (!GR->getSPIRVTypeForVReg(ResVReg)) {
536 const Type *RetTy = OrigRetTy;
537 if (auto *PtrRetTy = dyn_cast<PointerType>(OrigRetTy)) {
538 const Value *OrigValue = Info.OrigRet.OrigValue;
539 if (!OrigValue)
540 OrigValue = Info.CB;
541 if (OrigValue)
542 if (Type *ElemTy = GR->findDeducedElementType(OrigValue))
543 RetTy =
544 TypedPointerType::get(ElemTy, PtrRetTy->getAddressSpace());
545 }
546 setRegClassType(ResVReg, RetTy, GR, MIRBuilder,
547 SPIRV::AccessQualifier::ReadWrite, true);
548 }
549 } else {
550 ResVReg = createVirtualRegister(OrigRetTy, GR, MIRBuilder,
551 SPIRV::AccessQualifier::ReadWrite, true);
552 }
554 for (auto Arg : Info.OrigArgs) {
555 assert(Arg.Regs.size() == 1 && "Call arg has multiple VRegs");
556 Register ArgReg = Arg.Regs[0];
557 ArgVRegs.push_back(ArgReg);
558 SPIRVTypeInst SpvType = GR->getSPIRVTypeForVReg(ArgReg);
559 if (!SpvType) {
560 Type *ArgTy = nullptr;
561 if (auto *PtrArgTy = dyn_cast<PointerType>(Arg.Ty)) {
562 // If Arg.Ty is an untyped pointer (i.e., ptr [addrspace(...)]) and we
563 // don't have access to original value in LLVM IR or info about
564 // deduced pointee type, then we should wait with setting the type for
565 // the virtual register until pre-legalizer step when we access
566 // @llvm.spv.assign.ptr.type.p...(...)'s info.
567 if (Arg.OrigValue)
568 if (Type *ElemTy = GR->findDeducedElementType(Arg.OrigValue))
569 ArgTy =
570 TypedPointerType::get(ElemTy, PtrArgTy->getAddressSpace());
571 } else {
572 ArgTy = Arg.Ty;
573 }
574 if (ArgTy) {
575 SpvType = GR->getOrCreateSPIRVType(
576 ArgTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
577 GR->assignSPIRVTypeToVReg(SpvType, ArgReg, MF);
578 }
579 }
580 if (!MRI->getRegClassOrNull(ArgReg)) {
581 // Either we have SpvType created, or Arg.Ty is an untyped pointer and
582 // we know its virtual register's class and type even if we don't know
583 // pointee type.
584 MRI->setRegClass(ArgReg, SpvType ? GR->getRegClass(SpvType)
585 : &SPIRV::pIDRegClass);
586 MRI->setType(
587 ArgReg,
588 SpvType ? GR->getRegType(SpvType)
589 : LLT::pointer(cast<PointerType>(Arg.Ty)->getAddressSpace(),
590 GR->getPointerSize()));
591 }
592 }
593 if (auto Res = SPIRV::lowerBuiltin(
594 DemangledName, ST->getPreferredInstructionSet(), MIRBuilder,
595 ResVReg, OrigRetTy, ArgVRegs, GR, *Info.CB))
596 return *Res;
597 }
598
599 if (isFunctionDecl && !GR->find(CF, &MF).isValid()) {
600 // Emit the type info and forward function declaration to the first MBB
601 // to ensure VReg definition dependencies are valid across all MBBs.
602 MachineIRBuilder FirstBlockBuilder;
603 FirstBlockBuilder.setMF(MF);
604 FirstBlockBuilder.setMBB(*MF.getBlockNumbered(0));
605
608 for (const Argument &Arg : CF->args()) {
609 if (MIRBuilder.getDataLayout().getTypeStoreSize(Arg.getType()).isZero())
610 continue; // Don't handle zero sized types.
612 MRI->setRegClass(Reg, &SPIRV::iIDRegClass);
613 ToInsert.push_back({Reg});
614 VRegArgs.push_back(ToInsert.back());
615 }
616 // TODO: Reuse FunctionLoweringInfo
617 FunctionLoweringInfo FuncInfo;
618 lowerFormalArguments(FirstBlockBuilder, *CF, VRegArgs, FuncInfo);
619 }
620
621 // Ignore the call if it's called from the internal service function
622 if (MIRBuilder.getMF()
623 .getFunction()
625 .isValid()) {
626 // insert a no-op
627 MIRBuilder.buildTrap();
628 return true;
629 }
630
631 unsigned CallOp;
632 if (Info.CB->isIndirectCall()) {
633 if (!ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
634 report_fatal_error("An indirect call is encountered but SPIR-V without "
635 "extensions does not support it",
636 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;
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(FTy->getParamType(I));
652 IndirectCall.ArgRegs.push_back(Info.OrigArgs[I].Regs[0]);
653 }
654 produceIndirectPtrType(MIRBuilder, 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(&SPIRV::iIDRegClass);
664 SPIRVTypeInst RetType = GR->assignTypeToVReg(
665 OrigRetTy, ResVReg, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
666
667 // Emit the call instruction and its args.
668 auto MIB = MIRBuilder.buildInstr(CallOp)
669 .addDef(ResVReg)
670 .addUse(GR->getSPIRVTypeID(RetType))
671 .add(Info.Callee);
672
673 for (const auto &Arg : Info.OrigArgs) {
674 // Currently call args should have single vregs.
675 if (Arg.Regs.size() > 1)
676 return false;
677 MIB.addUse(Arg.Regs[0]);
678 }
679
680 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing)) {
681 // Process aliasing metadata.
682 const CallBase *CI = Info.CB;
683 if (CI && CI->hasMetadata()) {
684 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_alias_scope))
685 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
686 SPIRV::Decoration::AliasScopeINTEL, MD);
687 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_noalias))
688 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
689 SPIRV::Decoration::NoAliasINTEL, MD);
690 }
691 }
692
693 MIB.constrainAllUses(MIRBuilder.getTII(), *ST->getRegisterInfo(),
694 *ST->getRegBankInfo());
695 return true;
696}
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:543
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:892
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:759
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:337
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
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1433
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1431
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1439
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(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.
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:1668
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:392
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
MDString * getOCLKernelArgAccessQual(const Function &F, unsigned ArgIdx)
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
bool isTypedPointerTy(const Type *T)
Definition SPIRVUtils.h:370
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:476
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:380
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:405
bool hasPointeeTypeAttr(Argument *Arg)
Definition SPIRVUtils.h:400
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:428
void addStringImm(const StringRef &Str, MCInst &Inst)
bool isUntypedPointerTy(const Type *T)
Definition SPIRVUtils.h:375