LLVM 24.0.0git
SPIRVCallLowering.cpp
Go to the documentation of this file.
1//===--- SPIRVCallLowering.cpp - Call lowering ------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the lowering of LLVM calls to machine code calls for
10// GlobalISel.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SPIRVCallLowering.h"
16#include "SPIRV.h"
17#include "SPIRVBuiltins.h"
18#include "SPIRVGlobalRegistry.h"
19#include "SPIRVISelLowering.h"
20#include "SPIRVMetadata.h"
21#include "SPIRVRegisterInfo.h"
22#include "SPIRVSubtarget.h"
23#include "SPIRVUtils.h"
24#include "llvm/ADT/STLExtras.h"
27#include "llvm/IR/IntrinsicsSPIRV.h"
28#include "llvm/Support/ModRef.h"
29
30using namespace llvm;
31
35
37 const Value *Val, ArrayRef<Register> VRegs,
39 Register SwiftErrorVReg) const {
40 // Ignore if called from the internal service function
41 if (MIRBuilder.getMF()
44 .isValid())
45 return true;
46
47 // Currently all return types should use a single register.
48 // TODO: handle the case of multiple registers.
49 if (VRegs.size() > 1)
50 return false;
51
52 if (Val) {
53 const auto &STI = MIRBuilder.getMF().getSubtarget();
54 MIRBuilder.buildInstr(SPIRV::OpReturnValue)
55 .addUse(VRegs[0])
56 .constrainAllUses(MIRBuilder.getTII(), *STI.getRegisterInfo(),
57 *STI.getRegBankInfo());
58 return true;
59 }
60 MIRBuilder.buildInstr(SPIRV::OpReturn);
61 return true;
62}
63
64// Based on the LLVM function attributes, get a SPIR-V FunctionControl.
66 const SPIRVSubtarget *ST) {
67 MemoryEffects MemEffects = F.getMemoryEffects();
68
69 uint32_t FuncControl = static_cast<uint32_t>(SPIRV::FunctionControl::None);
70
71 if (F.hasFnAttribute(Attribute::AttrKind::NoInline))
72 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::DontInline);
73 else if (F.hasFnAttribute(Attribute::AttrKind::AlwaysInline))
74 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Inline);
75
76 if (MemEffects.doesNotAccessMemory())
77 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Pure);
78 else if (MemEffects.onlyReadsMemory())
79 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Const);
80
81 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_optnone) ||
82 ST->canUseExtension(SPIRV::Extension::SPV_EXT_optnone))
83 if (F.hasFnAttribute(Attribute::OptimizeNone))
84 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::OptNoneEXT);
85
86 return FuncControl;
87}
88
89// If the function has pointer arguments, we are forced to re-create this
90// function type from the very beginning, changing PointerType by
91// TypedPointerType for each pointer argument. Otherwise, the same `Type*`
92// potentially corresponds to different SPIR-V function type, effectively
93// invalidating logic behind global registry and duplicates tracker.
94static FunctionType *
96 FunctionType *FTy, SPIRVTypeInst SRetTy,
97 const SmallVector<SPIRVTypeInst, 4> &SArgTys) {
98 bool hasArgPtrs = any_of(F.args(), [](const Argument &Arg) {
99 // check if it's an instance of a non-typed PointerType
100 return Arg.getType()->isPointerTy();
101 });
102 if (!hasArgPtrs) {
103 Type *RetTy = FTy->getReturnType();
104 // check if it's an instance of a non-typed PointerType
105 if (!RetTy->isPointerTy())
106 return FTy;
107 }
108
109 // re-create function type, using TypedPointerType instead of PointerType to
110 // properly trace argument types
111 const Type *RetTy = GR->getTypeForSPIRVType(SRetTy);
113 for (auto SArgTy : SArgTys)
114 ArgTys.push_back(const_cast<Type *>(GR->getTypeForSPIRVType(SArgTy)));
115 return FunctionType::get(const_cast<Type *>(RetTy), ArgTys, false);
116}
117
118static SPIRV::AccessQualifier::AccessQualifier
119getArgAccessQual(const Function &F, unsigned ArgIdx) {
120 if (F.getCallingConv() != CallingConv::SPIR_KERNEL)
121 return SPIRV::AccessQualifier::ReadWrite;
122
123 MDString *ArgAttribute = getOCLKernelArgAccessQual(F, ArgIdx);
124 if (!ArgAttribute)
125 return SPIRV::AccessQualifier::ReadWrite;
126
127 if (ArgAttribute->getString() == "read_only")
128 return SPIRV::AccessQualifier::ReadOnly;
129 if (ArgAttribute->getString() == "write_only")
130 return SPIRV::AccessQualifier::WriteOnly;
131 return SPIRV::AccessQualifier::ReadWrite;
132}
133
134static SPIRVTypeInst getArgSPIRVType(const Function &F, unsigned ArgIdx,
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 =
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(ArgIdx);
148 if (auto *VTy = dyn_cast<FixedVectorType>(OriginalArgType);
149 VTy && isUntypedPointerTy(VTy->getElementType()))
150 if (Type *ElemTy = GR->findDeducedElementType(Arg))
153 ElemTy, MIRBuilder,
155 getPointerAddressSpace(OriginalArgType), ST)),
156 VTy->getNumElements(), MIRBuilder, true);
157
158 // If OriginalArgType is non-pointer, use the OriginalArgType (the type cannot
159 // be legally reassigned later).
160 if (!isPointerTy(OriginalArgType))
161 return GR->getOrCreateSPIRVType(OriginalArgType, MIRBuilder, ArgAccessQual,
162 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.
179 getPointeeTypeByAttr(Arg), MIRBuilder,
181 }
182
183 for (auto User : Arg->users()) {
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>(II->getOperand(1));
188 Type *BuiltinType =
189 cast<ConstantAsMetadata>(VMD->getMetadata())->getType();
190 assert(BuiltinType->isTargetExtTy() && "Expected TargetExtType");
191 return GR->getOrCreateSPIRVType(BuiltinType, MIRBuilder, ArgAccessQual,
192 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>(II->getOperand(1));
200 Type *ElementTy =
203 ElementTy, MIRBuilder,
205 cast<ConstantInt>(II->getOperand(2))->getZExtValue(), ST));
206 }
207
208 // Use the recorded pointee type for declarations.
209 if (F.isDeclaration())
210 if (Type *ElemTy = GR->findDeducedElementType(Arg))
212 ElemTy, MIRBuilder,
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(toTypedPointer(OriginalArgType), MIRBuilder,
218 ArgAccessQual, true);
219}
220
221static SPIRV::ExecutionModel::ExecutionModel
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("hlsl.shader");
230 if (!attribute.isValid()) {
232 "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("This HLSL entry point is not supported by this backend.");
244}
245
247 const Function &F,
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.
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, i, GR, MIRBuilder, *ST);
271 GR->assignSPIRVTypeToVReg(SpirvTy, VRegs[i][0], MIRBuilder.getMF());
272 ArgTypeVRegs.push_back(SpirvTy);
273
274 if (Arg.hasName())
275 buildOpName(VRegs[i][0], Arg.getName(), MIRBuilder);
276 if (isPointerTyOrWrapper(Arg.getType()) && !ST->isShader()) {
277 auto DerefBytes = static_cast<unsigned>(Arg.getDereferenceableBytes());
278 if (DerefBytes != 0 && ST->isAtLeastSPIRVVer(VersionTuple(1, 1)))
279 buildOpDecorate(VRegs[i][0], MIRBuilder,
280 SPIRV::Decoration::MaxByteOffset, {DerefBytes});
281 }
282 if (Arg.hasAttribute(Attribute::Alignment) && !ST->isShader()) {
283 auto Alignment = static_cast<unsigned>(
284 Arg.getAttribute(Attribute::Alignment).getValueAsInt());
285 buildOpDecorate(VRegs[i][0], MIRBuilder, SPIRV::Decoration::Alignment,
286 {Alignment});
287 }
288 if (ST->isKernel()) {
289 if (Arg.hasAttribute(Attribute::ReadOnly)) {
290 auto Attr =
291 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoWrite);
292 buildOpDecorate(VRegs[i][0], MIRBuilder,
293 SPIRV::Decoration::FuncParamAttr, {Attr});
294 }
295 if (Arg.hasAttribute(Attribute::ReadNone)) {
296 auto Attr = static_cast<unsigned>(
297 SPIRV::FunctionParameterAttribute::NoReadWrite);
298 buildOpDecorate(VRegs[i][0], MIRBuilder,
299 SPIRV::Decoration::FuncParamAttr, {Attr});
300 }
301 if (Arg.hasAttribute(Attribute::ZExt)) {
302 auto Attr =
303 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Zext);
304 buildOpDecorate(VRegs[i][0], MIRBuilder,
305 SPIRV::Decoration::FuncParamAttr, {Attr});
306 }
307 if (Arg.hasAttribute(Attribute::SExt)) {
308 auto Attr =
309 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sext);
310 buildOpDecorate(VRegs[i][0], MIRBuilder,
311 SPIRV::Decoration::FuncParamAttr, {Attr});
312 }
313 if (Arg.hasAttribute(Attribute::NoAlias)) {
314 auto Attr =
315 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoAlias);
316 buildOpDecorate(VRegs[i][0], MIRBuilder,
317 SPIRV::Decoration::FuncParamAttr, {Attr});
318 }
319 if (Arg.hasNoCaptureAttr()) {
320 auto Attr = static_cast<unsigned>(
321 SPIRV::FunctionParameterAttribute::NoCapture);
322 buildOpDecorate(VRegs[i][0], MIRBuilder,
323 SPIRV::Decoration::FuncParamAttr, {Attr});
324 }
325 // TODO: the AMDGPU BE only supports ByRef argument passing, thus for
326 // AMDGCN flavoured SPIRV we CodeGen for ByRef, but lower it to
327 // ByVal, handling the impedance mismatch during reverse
328 // translation from SPIRV to LLVM IR; the vendor check should be
329 // removed once / if SPIRV adds ByRef support.
330 if (Arg.hasAttribute(Attribute::ByVal) ||
331 (Arg.hasAttribute(Attribute::ByRef) &&
332 F.getParent()->getTargetTriple().getVendor() ==
334 auto Attr =
335 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::ByVal);
336 buildOpDecorate(VRegs[i][0], MIRBuilder,
337 SPIRV::Decoration::FuncParamAttr, {Attr});
338 }
339 if (Arg.hasAttribute(Attribute::StructRet)) {
340 auto Attr =
341 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sret);
342 buildOpDecorate(VRegs[i][0], MIRBuilder,
343 SPIRV::Decoration::FuncParamAttr, {Attr});
344 }
345 }
346
347 MDNode *Node = F.getMetadata("spirv.ParameterDecorations");
348 if (Node && i < Node->getNumOperands() &&
349 isa<MDNode>(Node->getOperand(i)))
350 buildOpSpirvDecorations(VRegs[i][0], MIRBuilder,
351 cast<MDNode>(Node->getOperand(i)), *ST);
352 ++i;
353 }
354 }
355
356 auto MRI = MIRBuilder.getMRI();
357 Register FuncVReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
358 MRI->setRegClass(FuncVReg, &SPIRV::iIDRegClass);
360 Type *FRetTy = FTy->getReturnType();
361 if (isUntypedPointerTy(FRetTy)) {
362 if (Type *FRetElemTy = GR->findDeducedElementType(&F)) {
364 toTypedPointer(FRetElemTy), getPointerAddressSpace(FRetTy));
365 GR->addReturnType(&F, DerivedTy);
366 FRetTy = DerivedTy;
367 }
368 }
369 SPIRVTypeInst RetTy = GR->getOrCreateSPIRVType(
370 FRetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
371 FTy = fixFunctionTypeIfPtrArgs(GR, F, FTy, RetTy, ArgTypeVRegs);
372 SPIRVTypeInst FuncTy = GR->getOrCreateOpTypeFunctionWithArgs(
373 FTy, RetTy, ArgTypeVRegs, MIRBuilder);
374 uint32_t FuncControl = getFunctionControl(F, ST);
375
376 // Add OpFunction instruction
377 MachineInstrBuilder MB = MIRBuilder.buildInstr(SPIRV::OpFunction)
378 .addDef(FuncVReg)
379 .addUse(GR->getSPIRVTypeID(RetTy))
380 .addImm(FuncControl)
381 .addUse(GR->getSPIRVTypeID(FuncTy));
382 GR->recordFunctionDefinition(&F, &MB.getInstr()->getOperand(0));
383 GR->addGlobalObject(&F, &MIRBuilder.getMF(), FuncVReg);
384 if (F.isDeclaration())
385 GR->add(&F, MB);
386
387 // Add OpFunctionParameter instructions
388 int i = 0;
389 for (const auto &Arg : F.args()) {
390 assert(VRegs[i].size() == 1 && "Formal arg has multiple vregs");
391 Register ArgReg = VRegs[i][0];
392 MRI->setRegClass(ArgReg, GR->getRegClass(ArgTypeVRegs[i]));
393 auto MIB = MIRBuilder.buildInstr(SPIRV::OpFunctionParameter)
394 .addDef(ArgReg)
395 .addUse(GR->getSPIRVTypeID(ArgTypeVRegs[i]));
396 if (F.isDeclaration())
397 GR->add(&Arg, MIB);
398 GR->addGlobalObject(&Arg, &MIRBuilder.getMF(), ArgReg);
399 i++;
400 }
401 if (!ST->isShader()) {
402 if (F.hasRetAttribute(Attribute::ZExt)) {
403 auto Attr =
404 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Zext);
405 buildOpDecorate(FuncVReg, MIRBuilder, SPIRV::Decoration::FuncParamAttr,
406 {Attr});
407 }
408 if (F.hasRetAttribute(Attribute::SExt)) {
409 auto Attr =
410 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sext);
411 buildOpDecorate(FuncVReg, MIRBuilder, SPIRV::Decoration::FuncParamAttr,
412 {Attr});
413 }
414 }
415
416 // Name the function.
417 if (F.hasName())
418 buildOpName(FuncVReg, F.getName(), MIRBuilder);
419
420 // Handle entry points and function linkage.
421 if (isEntryPoint(F)) {
422 if (F.getName().empty())
423 report_fatal_error("SPIR-V entry point function must have a name");
424 auto MIB = MIRBuilder.buildInstr(SPIRV::OpEntryPoint)
425 .addImm(static_cast<uint32_t>(getExecutionModel(*ST, F)))
426 .addUse(FuncVReg);
427 addStringImm(F.getName(), MIB);
428 } else if (const auto LnkTy = getSpirvLinkageTypeFor(*ST, F);
429 LnkTy && !F.getName().empty()) {
430 buildOpDecorate(FuncVReg, MIRBuilder, SPIRV::Decoration::LinkageAttributes,
431 {static_cast<uint32_t>(*LnkTy)}, F.getName());
432 }
433
434 // Handle function pointers decoration
435 bool hasFunctionPointers =
436 ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
437 if (hasFunctionPointers) {
438 if (F.hasFnAttribute("referenced-indirectly")) {
439 assert((F.getCallingConv() != CallingConv::SPIR_KERNEL) &&
440 "Unexpected 'referenced-indirectly' attribute of the kernel "
441 "function");
442 buildOpDecorate(FuncVReg, MIRBuilder,
443 SPIRV::Decoration::ReferencedIndirectlyINTEL, {});
444 }
445 }
446
447 if (MDNode *FuncMD = F.getMetadata("spirv.Decorations"))
448 buildOpSpirvDecorations(FuncVReg, MIRBuilder, FuncMD, *ST);
449
450 return true;
451}
452
453// TODO:
454// - add a topological sort of IndirectCalls to ensure the best types knowledge
455// - we may need to fix function formal parameter types if they are opaque
456// pointers used as function pointers in these indirect calls
457// - defaulting to StorageClass::Function in the absence of the
458// SPV_INTEL_function_pointers extension seems wrong, as that might not be
459// able to hold a full width pointer to function, and it also does not model
460// the semantics of a pointer to function in a generic fashion.
461void SPIRVCallLowering::produceIndirectPtrType(
462 MachineIRBuilder &MIRBuilder,
463 const SPIRVCallLowering::SPIRVIndirectCall &IC) const {
464 // Create indirect call data type if any
465 MachineFunction &MF = MIRBuilder.getMF();
467 SPIRVTypeInst SpirvRetTy = GR->getOrCreateSPIRVType(
468 IC.RetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
469 SmallVector<SPIRVTypeInst, 4> SpirvArgTypes;
470 for (size_t i = 0; i < IC.ArgTys.size(); ++i) {
472 IC.ArgTys[i], MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
473 SpirvArgTypes.push_back(SPIRVTy);
474 if (!GR->getSPIRVTypeForVReg(IC.ArgRegs[i]))
475 GR->assignSPIRVTypeToVReg(SPIRVTy, IC.ArgRegs[i], MF);
476 }
477 // SPIR-V function type:
478 FunctionType *FTy =
479 FunctionType::get(const_cast<Type *>(IC.RetTy), IC.ArgTys, false);
481 FTy, SpirvRetTy, SpirvArgTypes, MIRBuilder);
482 // SPIR-V pointer to function type:
483 auto SC = ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)
484 ? SPIRV::StorageClass::CodeSectionINTEL
485 : SPIRV::StorageClass::Function;
486 SPIRVTypeInst IndirectFuncPtrTy =
487 GR->getOrCreateSPIRVPointerType(SpirvFuncTy, MIRBuilder, SC);
488 // Correct the Callee type
489 GR->assignSPIRVTypeToVReg(IndirectFuncPtrTy, IC.Callee, MF);
490}
491
493 CallLoweringInfo &Info) const {
494 // Currently call returns should have single vregs.
495 // TODO: handle the case of multiple registers.
496 if (Info.OrigRet.Regs.size() > 1)
497 return false;
498 MachineFunction &MF = MIRBuilder.getMF();
499 GR->setCurrentFunc(MF);
500 const Function *CF = nullptr;
501 std::string DemangledName;
502 const Type *OrigRetTy = Info.OrigRet.Ty;
503
504 // Emit a regular OpFunctionCall. If it's an externally declared function,
505 // be sure to emit its type and function declaration here. It will be hoisted
506 // globally later.
507 if (Info.Callee.isGlobal()) {
508 std::string FuncName = Info.Callee.getGlobal()->getName().str();
509 DemangledName = getOclOrSpirvBuiltinDemangledName(FuncName);
510 CF = dyn_cast_or_null<const Function>(Info.Callee.getGlobal());
511 // TODO: support constexpr casts and indirect calls.
512 if (CF == nullptr)
513 return false;
514
516 OrigRetTy = FTy->getReturnType();
517 if (isUntypedPointerTy(OrigRetTy)) {
518 if (auto *DerivedRetTy = GR->findReturnType(CF))
519 OrigRetTy = DerivedRetTy;
520 }
521 }
522
523 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
524 Register ResVReg =
525 Info.OrigRet.Regs.empty() ? Register(0) : Info.OrigRet.Regs[0];
526 const auto *ST = static_cast<const SPIRVSubtarget *>(&MF.getSubtarget());
527
528 bool isFunctionDecl = CF && CF->isDeclaration();
529 if (isFunctionDecl && !DemangledName.empty()) {
530 if (ResVReg.isValid()) {
531 if (!GR->getSPIRVTypeForVReg(ResVReg)) {
532 const Type *RetTy = OrigRetTy;
533 if (auto *PtrRetTy = dyn_cast<PointerType>(OrigRetTy)) {
534 const Value *OrigValue = Info.OrigRet.OrigValue;
535 if (!OrigValue)
536 OrigValue = Info.CB;
537 if (OrigValue)
538 if (Type *ElemTy = GR->findDeducedElementType(OrigValue))
539 RetTy =
540 TypedPointerType::get(ElemTy, PtrRetTy->getAddressSpace());
541 }
542 setRegClassType(ResVReg, RetTy, GR, MIRBuilder,
543 SPIRV::AccessQualifier::ReadWrite, true);
544 }
545 } else {
546 ResVReg = createVirtualRegister(OrigRetTy, GR, MIRBuilder,
547 SPIRV::AccessQualifier::ReadWrite, true);
548 }
550 for (auto Arg : Info.OrigArgs) {
551 assert(Arg.Regs.size() == 1 && "Call arg has multiple VRegs");
552 Register ArgReg = Arg.Regs[0];
553 ArgVRegs.push_back(ArgReg);
554 SPIRVTypeInst SpvType = GR->getSPIRVTypeForVReg(ArgReg);
555 if (!SpvType) {
556 Type *ArgTy = nullptr;
557 if (auto *PtrArgTy = dyn_cast<PointerType>(Arg.Ty)) {
558 // If Arg.Ty is an untyped pointer (i.e., ptr [addrspace(...)]) and we
559 // don't have access to original value in LLVM IR or info about
560 // deduced pointee type, then we should wait with setting the type for
561 // the virtual register until pre-legalizer step when we access
562 // @llvm.spv.assign.ptr.type.p...(...)'s info.
563 if (Arg.OrigValue)
564 if (Type *ElemTy = GR->findDeducedElementType(Arg.OrigValue))
565 ArgTy =
566 TypedPointerType::get(ElemTy, PtrArgTy->getAddressSpace());
567 } else {
568 ArgTy = Arg.Ty;
569 }
570 if (ArgTy) {
571 SpvType = GR->getOrCreateSPIRVType(
572 ArgTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
573 GR->assignSPIRVTypeToVReg(SpvType, ArgReg, MF);
574 }
575 }
576 if (!MRI->getRegClassOrNull(ArgReg)) {
577 // Either we have SpvType created, or Arg.Ty is an untyped pointer and
578 // we know its virtual register's class and type even if we don't know
579 // pointee type.
580 MRI->setRegClass(ArgReg, SpvType ? GR->getRegClass(SpvType)
581 : &SPIRV::pIDRegClass);
582 MRI->setType(
583 ArgReg,
584 SpvType ? GR->getRegType(SpvType)
585 : LLT::pointer(cast<PointerType>(Arg.Ty)->getAddressSpace(),
586 GR->getPointerSize()));
587 }
588 }
589 if (auto Res = SPIRV::lowerBuiltin(
590 DemangledName, ST->getPreferredInstructionSet(), MIRBuilder,
591 ResVReg, OrigRetTy, ArgVRegs, GR, *Info.CB))
592 return *Res;
593 }
594
595 if (isFunctionDecl && !GR->find(CF, &MF).isValid()) {
596 // Emit the type info and forward function declaration to the first MBB
597 // to ensure VReg definition dependencies are valid across all MBBs.
598 MachineIRBuilder FirstBlockBuilder;
599 FirstBlockBuilder.setMF(MF);
600 FirstBlockBuilder.setMBB(*MF.getBlockNumbered(0));
601
604 for (const Argument &Arg : CF->args()) {
605 if (MIRBuilder.getDataLayout().getTypeStoreSize(Arg.getType()).isZero())
606 continue; // Don't handle zero sized types.
607 Register Reg = MRI->createGenericVirtualRegister(LLT::scalar(64));
608 MRI->setRegClass(Reg, &SPIRV::iIDRegClass);
609 ToInsert.push_back({Reg});
610 VRegArgs.push_back(ToInsert.back());
611 }
612 // TODO: Reuse FunctionLoweringInfo
613 FunctionLoweringInfo FuncInfo;
614 lowerFormalArguments(FirstBlockBuilder, *CF, VRegArgs, FuncInfo);
615 }
616
617 // Ignore the call if it's called from the internal service function
618 if (MIRBuilder.getMF()
619 .getFunction()
621 .isValid()) {
622 // insert a no-op
623 MIRBuilder.buildTrap();
624 return true;
625 }
626
627 unsigned CallOp;
628 if (Info.CB && Info.CB->isIndirectCall()) {
629 if (!ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
630 report_fatal_error("An indirect call is encountered but SPIR-V without "
631 "extensions does not support it",
632 false);
633 // Set instruction operation according to SPV_INTEL_function_pointers
634 CallOp = SPIRV::OpFunctionPointerCallINTEL;
635 // Collect information about the indirect call to create correct types.
636 Register CalleeReg = Info.Callee.getReg();
637 if (CalleeReg.isValid()) {
638 SPIRVCallLowering::SPIRVIndirectCall IndirectCall;
639 IndirectCall.Callee = CalleeReg;
641 IndirectCall.RetTy = OrigRetTy = FTy->getReturnType();
642 assert(FTy->getNumParams() == Info.OrigArgs.size() &&
643 "Function types mismatch");
644 for (unsigned I = 0; I != Info.OrigArgs.size(); ++I) {
645 assert(Info.OrigArgs[I].Regs.size() == 1 &&
646 "Call arg has multiple VRegs");
647 IndirectCall.ArgTys.push_back(FTy->getParamType(I));
648 IndirectCall.ArgRegs.push_back(Info.OrigArgs[I].Regs[0]);
649 }
650 produceIndirectPtrType(MIRBuilder, IndirectCall);
651 }
652 } else {
653 // Emit a regular OpFunctionCall
654 CallOp = SPIRV::OpFunctionCall;
655 }
656
657 // Make sure there's a valid return reg, even for functions returning void.
658 if (!ResVReg.isValid())
659 ResVReg = MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
660 SPIRVTypeInst RetType = GR->assignTypeToVReg(
661 OrigRetTy, ResVReg, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
662
663 // Emit the call instruction and its args.
664 auto MIB = MIRBuilder.buildInstr(CallOp)
665 .addDef(ResVReg)
666 .addUse(GR->getSPIRVTypeID(RetType))
667 .add(Info.Callee);
668 if (Info.NoMerge)
670
671 for (const auto &Arg : Info.OrigArgs) {
672 // Currently call args should have single vregs.
673 if (Arg.Regs.size() > 1)
674 return false;
675 MIB.addUse(Arg.Regs[0]);
676 }
677
678 if (Info.CB)
679 MIB.getInstr()->copyIRFlags(*Info.CB);
680
681 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing)) {
682 // Process aliasing metadata.
683 const CallBase *CI = Info.CB;
684 if (CI && CI->hasMetadata()) {
685 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_alias_scope))
686 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
687 SPIRV::Decoration::AliasScopeINTEL, MD);
688 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_noalias))
689 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
690 SPIRV::Decoration::NoAliasINTEL, MD);
691 }
692 }
693
694 MIB.constrainAllUses(MIRBuilder.getTII(), *ST->getRegisterInfo(),
695 *ST->getRegBankInfo());
696 return true;
697}
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
MachineRegisterInfo & MRI
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)
#define SPIRV_BACKEND_SERVICE_FUN_NAME
Definition SPIRVUtils.h:560
This file contains some templates that are useful if you are working with the STL at all.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:262
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
CallLowering(const TargetLowering *TLI)
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:877
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
Metadata node.
Definition Metadata.h:1081
A single uniqued string.
Definition Metadata.h:733
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:615
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 & setMIFlag(MachineInstr::MIFlag Flag) const
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.
LLVM_ABI void copyIRFlags(const Instruction &I)
Copy all flags to MachineInst MIFlags.
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: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 getOrCreateSPIRVPointerType(const Type *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SC, bool ForceTyped=false)
SPIRVTypeInst getOrCreateSPIRVTypedPointerType(const Type *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SC)
SPIRVTypeInst getOrCreateSPIRVVectorType(SPIRVTypeInst BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder, bool EmitIR)
const Type * getTypeForSPIRVType(SPIRVTypeInst Ty) const
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:277
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:257
iterator_range< user_iterator > users()
Definition Value.h:428
Represents a version number in the form major[.minor[.subminor[.build]]].
constexpr bool isZero() const
Definition TypeSize.h:154
@ SPIR_KERNEL
Used for SPIR kernel functions.
std::optional< bool > lowerBuiltin(StringRef DemangledCall, SPIRV::InstructionSet::InstructionSet Set, MachineIRBuilder &MIRBuilder, const Register OrigRet, const Type *OrigRetTy, const SmallVectorImpl< Register > &Args, SPIRVGlobalRegistry *GR, const CallBase &CB)
FunctionType * getOriginalFunctionType(const Function &F)
This is an optimization pass for GlobalISel generic memory operations.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
void addStringImm(StringRef Str, MCInst &Inst)
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:388
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
Register createVirtualRegister(SPIRVTypeInst SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF)
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, ArrayRef< uint32_t > DecArgs, StringRef StrImm)
MDString * getOCLKernelArgAccessQual(const Function &F, unsigned ArgIdx)
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void buildOpName(Register Target, StringRef Name, MachineIRBuilder &MIRBuilder)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
Type * toTypedPointer(Type *Ty)
Definition SPIRVUtils.h:472
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:376
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)
void buildOpSpirvDecorations(Register Reg, MachineIRBuilder &MIRBuilder, const MDNode *GVarMD, const SPIRVSubtarget &ST)
Type * getPointeeTypeByAttr(Argument *Arg)
Definition SPIRVUtils.h:401
bool hasPointeeTypeAttr(Argument *Arg)
Definition SPIRVUtils.h:396
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:424
bool isUntypedPointerTy(const Type *T)
Definition SPIRVUtils.h:371