Debian Codegraph @

llvm-project/llvm/projects/llvm-spirv/lib/SPIRV/SPIRVBuiltinHelper.cpp

raw
1 //===- SPIRVBuiltinHelper.cpp - Helpers for managing calls to builtins ----===//
2 //
3 // The LLVM/SPIR-V Translator
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 // Copyright (c) 2022 The Khronos Group Inc.
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining a
11 // copy of this software and associated documentation files (the "Software"),
12 // to deal with the Software without restriction, including without limitation
13 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
14 // and/or sell copies of the Software, and to permit persons to whom the
15 // Software is furnished to do so, subject to the following conditions:
16 //
17 // Redistributions of source code must retain the above copyright notice,
18 // this list of conditions and the following disclaimers.
19 // Redistributions in binary form must reproduce the above copyright notice,
20 // this list of conditions and the following disclaimers in the documentation
21 // and/or other materials provided with the distribution.
22 // Neither the names of The Khronos Group, nor the names of its
23 // contributors may be used to endorse or promote products derived from this
24 // Software without specific prior written permission.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28 // CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
31 // THE SOFTWARE.
32 //
33 //===----------------------------------------------------------------------===//
34 //
35 // This file implements helper functions for adding calls to OpenCL or SPIR-V
36 // builtin functions, or for rewriting calls to one into calls to the other.
37 //
38 //===----------------------------------------------------------------------===//
39
40 #include "SPIRVBuiltinHelper.h"
41
42 #include "OCLUtil.h"
43 #include "SPIRVInternal.h"
44
45 using namespace llvm;
46 using namespace SPIRV;
47
48 static std::unique_ptr<BuiltinFuncMangleInfo> makeMangler(CallBase *CB,
49 ManglingRules Rules) {
50 switch (Rules) {
51 case ManglingRules::None:
52 return nullptr;
53 case ManglingRules::SPIRV:
54 return std::make_unique<BuiltinFuncMangleInfo>();
55 case ManglingRules::OpenCL:
56 return OCLUtil::makeMangler(*CB->getCalledFunction());
57 }
58 llvm_unreachable("Unknown mangling rules to make a name mangler");
59 }
60
61 BuiltinCallMutator::BuiltinCallMutator(
62 CallInst *CI, std::string FuncName, ManglingRules Rules,
63 std::function<std::string(StringRef)> NameMapFn)
64 : CI(CI), FuncName(FuncName),
65 Attrs(CI->getCalledFunction()->getAttributes()),
66 CallAttrs(CI->getAttributes()), ReturnTy(CI->getType()), Args(CI->args()),
67 Rules(Rules), Builder(CI) {
68 bool DidDemangle = getParameterTypes(CI->getCalledFunction(), PointerTypes,
69 std::move(NameMapFn));
70 if (!DidDemangle) {
71 // TODO: PipeBlocking.ll causes demangling failures.
72 // assert(isNonMangledOCLBuiltin(CI->getCalledFunction()->getName()) &&
73 // "SPIR-V builtin functions should be mangled");
74 for (Value *Arg : Args)
75 PointerTypes.push_back(Arg->getType());
76 }
77 }
78
79 BuiltinCallMutator::BuiltinCallMutator(BuiltinCallMutator &&Other)
80 : CI(Other.CI), FuncName(std::move(Other.FuncName)),
81 MutateRet(std::move(Other.MutateRet)), Attrs(Other.Attrs),
82 CallAttrs(Other.CallAttrs), ReturnTy(Other.ReturnTy),
83 Args(std::move(Other.Args)), PointerTypes(std::move(Other.PointerTypes)),
84 Rules(std::move(Other.Rules)), Builder(CI) {
85 // Clear the other's CI instance so that it knows not to construct the actual
86 // call.
87 Other.CI = nullptr;
88 }
89
90 Value *BuiltinCallMutator::doConversion() {
91 assert(CI && "Need to have a call instruction to do the conversion");
92 auto Mangler = makeMangler(CI, Rules);
93 for (unsigned I = 0; I < Args.size(); I++) {
94 Mangler->getTypeMangleInfo(I).PointerTy =
95 dyn_cast<TypedPointerType>(PointerTypes[I]);
96 }
97 assert(Attrs.getNumAttrSets() <= Args.size() + 2 && "Too many attributes?");
98
99 // Sanitize the return type, in case it's a TypedPointerType.
100 if (auto *TPT = dyn_cast<TypedPointerType>(ReturnTy))
101 ReturnTy = PointerType::get(TPT->getElementType(), TPT->getAddressSpace());
102
103 CallInst *NewCall =
104 Builder.Insert(addCallInst(CI->getModule(), FuncName, ReturnTy, Args,
105 &Attrs, nullptr, Mangler.get()));
106 NewCall->copyMetadata(*CI);
107 NewCall->setAttributes(CallAttrs);
108 NewCall->setTailCall(CI->isTailCall());
109 if (isa<FPMathOperator>(CI))
110 NewCall->setFastMathFlags(CI->getFastMathFlags());
111
112 if (CI->hasFnAttr("fpbuiltin-max-error")) {
113 auto Attr = CI->getFnAttr("fpbuiltin-max-error");
114 NewCall->addFnAttr(Attr);
115 }
116 Value *Result = MutateRet ? MutateRet(Builder, NewCall) : NewCall;
117 Result->takeName(CI);
118 if (!CI->getType()->isVoidTy())
119 CI->replaceAllUsesWith(Result);
120 CI->dropAllReferences();
121 CI->eraseFromParent();
122 CI = nullptr;
123 return Result;
124 }
125
126 BuiltinCallMutator &BuiltinCallMutator::setArgs(ArrayRef<Value *> NewArgs) {
127 // Retain only the function attributes, not any parameter attributes.
128 Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttrs(),
129 Attrs.getRetAttrs(), {});
130 CallAttrs = AttributeList::get(CI->getContext(), CallAttrs.getFnAttrs(),
131 CallAttrs.getRetAttrs(), {});
132 Args.clear();
133 PointerTypes.clear();
134 for (Value *Arg : NewArgs) {
135 assert(!Arg->getType()->isPointerTy() &&
136 "Cannot use this signature with pointer types");
137 Args.push_back(Arg);
138 PointerTypes.push_back(Arg->getType());
139 }
140 return *this;
141 }
142
143 // This is a helper method to handle splicing of the attribute lists, as
144 // llvm::AttributeList doesn't have any helper methods for this sort of design.
145 // (It's designed to be manually built-up, not adjusted to add/remove
146 // arguments on the fly).
147 static void moveAttributes(LLVMContext &Ctx, AttributeList &Attrs,
148 unsigned Start, unsigned Len, unsigned Dest) {
149 SmallVector<std::pair<unsigned, AttributeSet>, 6> NewAttrs;
150 for (unsigned Index : Attrs.indexes()) {
151 AttributeSet AttrSet = Attrs.getAttributes(Index);
152 if (!AttrSet.hasAttributes())
153 continue;
154
155 // If the attribute is a parameter index, check to see how its index should
156 // be adjusted.
157 if (Index > AttributeList::FirstArgIndex) {
158 unsigned ParamIndex = Index - AttributeList::FirstArgIndex;
159 if (ParamIndex >= Start && ParamIndex < Start + Len)
160 // A parameter in this range needs to have its index adjusted to its
161 // destination location.
162 Index += Dest - Start;
163 else if (ParamIndex >= Dest && ParamIndex < Dest + Len)
164 // This parameter will be overwritten by one of the moved parameters, so
165 // omit it entirely.
166 continue;
167 }
168
169 // The array is usually going to be sorted, but because of the above
170 // adjustment, we might end up out of order. This logic ensures that the
171 // array always remains in sorted order.
172 std::pair<unsigned, AttributeSet> ToInsert(Index, AttrSet);
173 NewAttrs.insert(llvm::lower_bound(NewAttrs, ToInsert, llvm::less_first()),
174 ToInsert);
175 }
176 Attrs = AttributeList::get(Ctx, NewAttrs);
177 }
178
179 BuiltinCallMutator &BuiltinCallMutator::insertArg(unsigned Index,
180 ValueTypePair Arg) {
181 Args.insert(Args.begin() + Index, Arg.first);
182 PointerTypes.insert(PointerTypes.begin() + Index, Arg.second);
183 moveAttributes(CI->getContext(), Attrs, Index, Args.size() - Index,
184 Index + 1);
185 moveAttributes(CI->getContext(), CallAttrs, Index, Args.size() - Index,
186 Index + 1);
187 return *this;
188 }
189
190 BuiltinCallMutator &BuiltinCallMutator::replaceArg(unsigned Index,
191 ValueTypePair Arg) {
192 Args[Index] = Arg.first;
193 PointerTypes[Index] = Arg.second;
194 Attrs = Attrs.removeParamAttributes(CI->getContext(), Index);
195 CallAttrs = CallAttrs.removeParamAttributes(CI->getContext(), Index);
196 return *this;
197 }
198
199 BuiltinCallMutator &BuiltinCallMutator::removeArg(unsigned Index) {
200 // If the argument being dropped is the last one, there is nothing to move, so
201 // just remove the attributes.
202 auto &Ctx = CI->getContext();
203 if (Index == Args.size() - 1) {
204 Attrs = Attrs.removeParamAttributes(Ctx, Index);
205 CallAttrs = CallAttrs.removeParamAttributes(Ctx, Index);
206 } else {
207 moveAttributes(Ctx, Attrs, Index + 1, Args.size() - Index - 1, Index);
208 moveAttributes(Ctx, CallAttrs, Index + 1, Args.size() - Index - 1, Index);
209 }
210 Args.erase(Args.begin() + Index);
211 PointerTypes.erase(PointerTypes.begin() + Index);
212 return *this;
213 }
214
215 BuiltinCallMutator &
216 BuiltinCallMutator::changeReturnType(Type *NewReturnTy,
217 MutateRetFuncTy MutateFunc) {
218 ReturnTy = NewReturnTy;
219 MutateRet = std::move(MutateFunc);
220 return *this;
221 }
222
223 BuiltinCallMutator BuiltinCallHelper::mutateCallInst(CallInst *CI,
224 spv::Op Opcode) {
225 return mutateCallInst(CI, getSPIRVFuncName(Opcode));
226 }
227
228 BuiltinCallMutator BuiltinCallHelper::mutateCallInst(CallInst *CI,
229 std::string FuncName) {
230 assert(CI->getCalledFunction() && "Can only mutate direct function calls.");
231 return BuiltinCallMutator(CI, std::move(FuncName), Rules, NameMapFn);
232 }
233
234 Value *BuiltinCallHelper::addSPIRVCall(IRBuilder<> &Builder, spv::Op Opcode,
235 Type *ReturnTy, ArrayRef<Value *> Args,
236 ArrayRef<Type *> ArgTys,
237 const Twine &Name) {
238 // Sanitize the return type, in case it's a TypedPointerType.
239 if (auto *TPT = dyn_cast<TypedPointerType>(ReturnTy))
240 ReturnTy = PointerType::get(TPT->getElementType(), TPT->getAddressSpace());
241
242 // Copy the types into the mangling info.
243 BuiltinFuncMangleInfo BtnInfo;
244 for (unsigned I = 0; I < ArgTys.size(); I++) {
245 if (Args[I]->getType()->isPointerTy()) {
246 assert(cast<PointerType>(Args[I]->getType())
247 ->isOpaqueOrPointeeTypeMatches(
248 cast<TypedPointerType>(ArgTys[I])->getElementType()));
249 BtnInfo.getTypeMangleInfo(I).PointerTy = ArgTys[I];
250 }
251 }
252
253 // Create the function and the call.
254 auto *F = getOrCreateFunction(M, ReturnTy, getTypes(Args),
255 getSPIRVFuncName(Opcode), &BtnInfo);
256 return Builder.CreateCall(F, Args, ReturnTy->isVoidTy() ? "" : Name);
257 }
258
259 Type *BuiltinCallHelper::adjustImageType(Type *T, StringRef OldImageKind,
260 StringRef NewImageKind) {
261 if (auto *TypedPtrTy = dyn_cast<TypedPointerType>(T)) {
262 Type *StructTy = TypedPtrTy->getElementType();
263 // Adapt opencl.* struct type names to spirv.* struct type names.
264 if (isOCLImageType(T)) {
265 if (OldImageKind != kSPIRVTypeName::Image)
266 report_fatal_error("Type was not an image type");
267 auto ImageTypeName = StructTy->getStructName();
268 auto Desc =
269 map<SPIRVTypeImageDescriptor>(getImageBaseTypeName(ImageTypeName));
270 spv::AccessQualifier Acc = AccessQualifierReadOnly;
271 if (hasAccessQualifiedName(ImageTypeName))
272 Acc = getAccessQualifier(ImageTypeName);
273 auto NewImageType = SPIRVOpaqueTypeOpCodeMap::map(NewImageKind.str());
274 return getSPIRVType(NewImageType, Type::getVoidTy(M->getContext()), Desc,
275 Acc);
276 }
277
278 // Change type name (e.g., spirv.Image -> spirv.SampledImg) if necessary.
279 StringRef Postfixes;
280 if (isSPIRVStructType(StructTy, OldImageKind, &Postfixes))
281 StructTy = getOrCreateOpaqueStructType(
282 M, getSPIRVTypeName(NewImageKind, Postfixes));
283 else {
284 report_fatal_error("Type did not have expected image kind");
285 }
286 return TypedPointerType::get(StructTy, TypedPtrTy->getAddressSpace());
287 }
288
289 if (auto *TargetTy = dyn_cast<TargetExtType>(T)) {
290 StringRef Name = TargetTy->getName();
291 if (!Name.consume_front(kSPIRVTypeName::PrefixAndDelim) ||
292 Name != OldImageKind)
293 report_fatal_error("Type did not have expected image kind");
294 return TargetExtType::get(
295 TargetTy->getContext(),
296 (Twine(kSPIRVTypeName::PrefixAndDelim) + NewImageKind).str(),
297 TargetTy->type_params(), TargetTy->int_params());
298 }
299
300 report_fatal_error("Expected type to be a SPIRV image type");
301 }
302
303 Type *BuiltinCallHelper::getSPIRVType(spv::Op TypeOpcode, bool UseRealType) {
304 return getSPIRVType(TypeOpcode, "", {}, UseRealType);
305 }
306
307 Type *BuiltinCallHelper::getSPIRVType(spv::Op TypeOpcode,
308 spv::AccessQualifier Access,
309 bool UseRealType) {
310 return getSPIRVType(TypeOpcode, "", {(unsigned)Access}, UseRealType);
311 }
312
313 Type *BuiltinCallHelper::getSPIRVType(
314 spv::Op TypeOpcode, Type *InnerType, SPIRVTypeImageDescriptor Desc,
315 std::optional<spv::AccessQualifier> Access, bool UseRealType) {
316 return getSPIRVType(TypeOpcode, convertTypeToPostfix(InnerType),
317 {(unsigned)Desc.Dim, (unsigned)Desc.Depth,
318 (unsigned)Desc.Arrayed, (unsigned)Desc.MS,
319 (unsigned)Desc.Sampled, (unsigned)Desc.Format,
320 (unsigned)Access.value_or(AccessQualifierReadOnly)},
321 UseRealType);
322 }
323
324 Type *BuiltinCallHelper::getSPIRVType(spv::Op TypeOpcode,
325 StringRef InnerTypeName,
326 ArrayRef<unsigned> Parameters,
327 bool UseRealType) {
328 if (UseTargetTypes) {
329 std::string BaseName = (Twine(kSPIRVTypeName::PrefixAndDelim) +
330 SPIRVOpaqueTypeOpCodeMap::rmap(TypeOpcode))
331 .str();
332 SmallVector<Type *, 1> TypeParams;
333 if (!InnerTypeName.empty()) {
334 TypeParams.push_back(getLLVMTypeForSPIRVImageSampledTypePostfix(
335 InnerTypeName, M->getContext()));
336 }
337 return TargetExtType::get(M->getContext(), BaseName, TypeParams,
338 Parameters);
339 }
340
341 std::string FullName;
342 {
343 raw_string_ostream OS(FullName);
344 OS << kSPIRVTypeName::PrefixAndDelim
345 << SPIRVOpaqueTypeOpCodeMap::rmap(TypeOpcode);
346 if (!InnerTypeName.empty() || !Parameters.empty())
347 OS << kSPIRVTypeName::Delimiter;
348 if (!InnerTypeName.empty())
349 OS << kSPIRVTypeName::PostfixDelim << InnerTypeName;
350 for (unsigned IntParam : Parameters)
351 OS << kSPIRVTypeName::PostfixDelim << IntParam;
352 }
353 auto *STy = StructType::getTypeByName(M->getContext(), FullName);
354 if (!STy)
355 STy = StructType::create(M->getContext(), FullName);
356
357 unsigned AddrSpace = getOCLOpaqueTypeAddrSpace(TypeOpcode);
358 return UseRealType ? (Type *)PointerType::get(STy, AddrSpace)
359 : TypedPointerType::get(STy, AddrSpace);
360 }
361
362 void BuiltinCallHelper::initialize(llvm::Module &M) {
363 this->M = &M;
364 // We want to use pointers-to-opaque-structs for the special types if:
365 // * We are translating from SPIR-V to LLVM IR (which means we are using
366 // OpenCL mangling rules)
367 // * There are %opencl.* or %spirv.* struct type names already present.
368 UseTargetTypes = Rules != ManglingRules::OpenCL;
369 for (StructType *Ty : M.getIdentifiedStructTypes()) {
370 if (!Ty->isOpaque() || !Ty->hasName())
371 continue;
372 StringRef Name = Ty->getName();
373 if (Name.startswith("opencl.") || Name.startswith("spirv.")) {
374 UseTargetTypes = false;
375 }
376 }
377 }
378
379 BuiltinCallMutator::ValueTypePair
380 BuiltinCallHelper::getCallValue(CallInst *CI, unsigned ArgNo) {
381 Function *CalledFunc = CI->getCalledFunction();
382 assert(CalledFunc && "Unexpected indirect call");
383 if (CalledFunc != CachedFunc) {
384 CachedFunc = CalledFunc;
385 [[maybe_unused]] bool DidDemangle =
386 getParameterTypes(CalledFunc, CachedParameterTypes, NameMapFn);
387 assert(DidDemangle && "Expected SPIR-V builtins to be properly mangled");
388 }
389
390 Value *ParamValue = CI->getArgOperand(ArgNo);
391 Type *ParamType = CachedParameterTypes[ArgNo];
392 return {ParamValue, ParamType};
393 }