| 1 |
//===- SPIRVBuiltinHelper.h - 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 |
#ifndef SPIRVBUILTINHELPER_H |
| 41 |
#define SPIRVBUILTINHELPER_H |
| 42 |
|
| 43 |
#include "LLVMSPIRVLib.h" |
| 44 |
#include "libSPIRV/SPIRVOpCode.h" |
| 45 |
#include "libSPIRV/SPIRVType.h" |
| 46 |
#include "llvm/ADT/SmallVector.h" |
| 47 |
#include "llvm/IR/Attributes.h" |
| 48 |
#include "llvm/IR/IRBuilder.h" |
| 49 |
#include "llvm/IR/TypedPointerType.h" |
| 50 |
|
| 51 |
namespace SPIRV { |
| 52 |
enum class ManglingRules { None, OpenCL, SPIRV }; |
| 53 |
|
| 54 |
namespace detail { |
| 55 |
/// This is a helper for triggering the static_assert in mapArg. |
| 56 |
template <typename> constexpr bool LegalFnType = false; |
| 57 |
} // namespace detail |
| 58 |
|
| 59 |
/// A helper class for changing OpenCL builtin function calls to SPIR-V function |
| 60 |
/// calls, or vice versa. Most of the functions will return a reference to the |
| 61 |
/// current instance, allowing calls to be chained together, for example: |
| 62 |
/// mutateCallInst(CI, NewFuncName) |
| 63 |
/// .removeArg(3) |
| 64 |
/// .appendArg(translateScope()); |
| 65 |
/// |
| 66 |
/// Only when the destuctor of this object is called will the original CallInst |
| 67 |
/// be destroyed and replaced with the new CallInst be created. |
| 68 |
class BuiltinCallMutator { |
| 69 |
// Original call instruction |
| 70 |
llvm::CallInst *CI; |
| 71 |
// New unmangled function name |
| 72 |
std::string FuncName; |
| 73 |
// Return type mutator. This needs to be saved, because we can't call it until |
| 74 |
// the new instruction is created. |
| 75 |
std::function<llvm::Value *(llvm::IRBuilder<> &, llvm::CallInst *)> MutateRet; |
| 76 |
typedef decltype(MutateRet) MutateRetFuncTy; |
| 77 |
// The attribute list for the new called function. |
| 78 |
llvm::AttributeList Attrs; |
| 79 |
// The attribute list for the new call instruction. |
| 80 |
llvm::AttributeList CallAttrs; |
| 81 |
// The return type for the new call instruction. |
| 82 |
llvm::Type *ReturnTy; |
| 83 |
// The arguments for the new call instruction. |
| 84 |
llvm::SmallVector<llvm::Value *, 8> Args; |
| 85 |
// The pointer element types for the new call instruction. |
| 86 |
llvm::SmallVector<llvm::Type *, 8> PointerTypes; |
| 87 |
// The mangler rules to use for the new call instruction. |
| 88 |
ManglingRules Rules; |
| 89 |
|
| 90 |
friend class BuiltinCallHelper; |
| 91 |
BuiltinCallMutator( |
| 92 |
llvm::CallInst *CI, std::string FuncName, ManglingRules Rules, |
| 93 |
std::function<std::string(llvm::StringRef)> NameMapFn = nullptr); |
| 94 |
|
| 95 |
// This does the actual work of creating of the new call, and will return the |
| 96 |
// new instruction. |
| 97 |
llvm::Value *doConversion(); |
| 98 |
|
| 99 |
public: |
| 100 |
~BuiltinCallMutator() { |
| 101 |
if (CI) |
| 102 |
doConversion(); |
| 103 |
} |
| 104 |
BuiltinCallMutator(const BuiltinCallMutator &) = delete; |
| 105 |
BuiltinCallMutator &operator=(const BuiltinCallMutator &) = delete; |
| 106 |
BuiltinCallMutator &operator=(BuiltinCallMutator &&) = delete; |
| 107 |
BuiltinCallMutator(BuiltinCallMutator &&); |
| 108 |
|
| 109 |
/// The builder used to generate IR for this call. |
| 110 |
llvm::IRBuilder<> Builder; |
| 111 |
|
| 112 |
/// Return the resulting new instruction. It is not possible to use any |
| 113 |
/// method on this object after calling this function. |
| 114 |
llvm::Value *getMutated() { return doConversion(); } |
| 115 |
|
| 116 |
/// Return the number of arguments currently specified for the new call. |
| 117 |
unsigned arg_size() const { return Args.size(); } |
| 118 |
|
| 119 |
/// Get the corresponding argument for the new call. |
| 120 |
llvm::Value *getArg(unsigned Index) const { return Args[Index]; } |
| 121 |
|
| 122 |
llvm::Type *getType(unsigned Index) const { return PointerTypes[Index]; } |
| 123 |
|
| 124 |
/// Return the pointer element type of the corresponding index, or nullptr if |
| 125 |
/// it is not a pointer. |
| 126 |
llvm::Type *getPointerElementType(unsigned Index) const { |
| 127 |
if (auto *TPT = llvm::dyn_cast<llvm::TypedPointerType>(PointerTypes[Index])) |
| 128 |
return TPT->getElementType(); |
| 129 |
return nullptr; |
| 130 |
} |
| 131 |
|
| 132 |
/// A pair representing both the LLVM value of an argument and its |
| 133 |
/// corresponding pointer element type. This type can be constructed from |
| 134 |
/// implicit conversion from an LLVM value object (but only if it is not of |
| 135 |
/// pointer type), or by the appropriate std::pair type. |
| 136 |
struct ValueTypePair : public std::pair<llvm::Value *, llvm::Type *> { |
| 137 |
ValueTypePair(llvm::Value *V) : pair(V, V->getType()) { |
| 138 |
assert(!V->getType()->isPointerTy() && |
| 139 |
"Must specify a pointer element type if value is a pointer."); |
| 140 |
} |
| 141 |
ValueTypePair(std::pair<llvm::Value *, llvm::Type *> P) : pair(P) {} |
| 142 |
ValueTypePair() = delete; |
| 143 |
using pair::pair; |
| 144 |
}; |
| 145 |
|
| 146 |
/// Use the following arguments as the arguments of the new call, replacing |
| 147 |
/// any previous arguments. This version may not be used if any argument is of |
| 148 |
/// pointer type. |
| 149 |
BuiltinCallMutator &setArgs(llvm::ArrayRef<llvm::Value *> Args); |
| 150 |
|
| 151 |
/// This will replace the return type of the call with a different return |
| 152 |
/// type. The second argument is a function that will be called with an |
| 153 |
/// IRBuilder parameter and the newly generated function, and will return the |
| 154 |
/// value to replace all uses of the original call instruction with. Example |
| 155 |
/// usage: |
| 156 |
/// |
| 157 |
/// BuiltinCallMutator Mutator = /* ... */; |
| 158 |
/// Mutator.changeReturnType(Int16Ty, [](IRBuilder<> &IRB, CallInst *CI) { |
| 159 |
/// return IRB.CreateZExt(CI, Int16Ty); |
| 160 |
/// }); |
| 161 |
BuiltinCallMutator &changeReturnType(llvm::Type *ReturnTy, |
| 162 |
MutateRetFuncTy MutateFunc); |
| 163 |
|
| 164 |
/// Insert an argument before the given index. |
| 165 |
BuiltinCallMutator &insertArg(unsigned Index, ValueTypePair Arg); |
| 166 |
|
| 167 |
/// Add an argument to the end of the argument list. |
| 168 |
BuiltinCallMutator &appendArg(ValueTypePair Arg) { |
| 169 |
return insertArg(Args.size(), Arg); |
| 170 |
} |
| 171 |
|
| 172 |
/// Replace the argument at the given index with a new value. |
| 173 |
BuiltinCallMutator &replaceArg(unsigned Index, ValueTypePair Arg); |
| 174 |
|
| 175 |
/// Remove the argument at the given index. |
| 176 |
BuiltinCallMutator &removeArg(unsigned Index); |
| 177 |
|
| 178 |
/// Remove all arguments in a range. |
| 179 |
BuiltinCallMutator &removeArgs(unsigned Start, unsigned Len) { |
| 180 |
for (unsigned I = 0; I < Len; I++) |
| 181 |
removeArg(Start); |
| 182 |
return *this; |
| 183 |
} |
| 184 |
|
| 185 |
/// Move the argument from the given index to the new index. |
| 186 |
BuiltinCallMutator &moveArg(unsigned FromIndex, unsigned ToIndex) { |
| 187 |
if (FromIndex == ToIndex) |
| 188 |
return *this; |
| 189 |
ValueTypePair Pair(Args[FromIndex], getType(FromIndex)); |
| 190 |
removeArg(FromIndex); |
| 191 |
insertArg(ToIndex, Pair); |
| 192 |
return *this; |
| 193 |
} |
| 194 |
|
| 195 |
/// Use a callback function or lambda to convert an argument to a new value. |
| 196 |
/// The expected return type of the lambda is anything that is convertible |
| 197 |
/// to ValueTypePair, which could be a single Value* (but only if it is not |
| 198 |
/// pointer-typed), or a std::pair<Value *, Type *>. The possible signatures |
| 199 |
/// of the function parameter are as follows: |
| 200 |
/// ValueTypePair func(IRBuilder<> &Builder, Value *, Type *); |
| 201 |
/// ValueTypePair func(IRBuilder<> &Builder, Value *); |
| 202 |
/// ValueTypePair func(Value *, Type *); |
| 203 |
/// ValueTypePair func(Value *); |
| 204 |
/// |
| 205 |
/// When present, the IRBuilder parameter corresponds to a builder that is set |
| 206 |
/// to insert immediately before the new call instruction. The Value parameter |
| 207 |
/// corresponds to the argument to be mutated. The Type parameter, when |
| 208 |
/// present, will be either a TypedPointerType representing the "true" type of |
| 209 |
/// the value, or the argument's type otherwise. |
| 210 |
template <typename FnType> |
| 211 |
BuiltinCallMutator &mapArg(unsigned Index, FnType Func) { |
| 212 |
using namespace llvm; |
| 213 |
using std::is_invocable; |
| 214 |
IRBuilder<> Builder(CI); |
| 215 |
Value *V = Args[Index]; |
| 216 |
[[maybe_unused]] Type *T = getType(Index); |
| 217 |
|
| 218 |
// Dispatch the function call as appropriate, based on the types that the |
| 219 |
// function may be called with. |
| 220 |
if constexpr (is_invocable<FnType, IRBuilder<> &, Value *, Type *>::value) |
| 221 |
replaceArg(Index, Func(Builder, V, T)); |
| 222 |
else if constexpr (is_invocable<FnType, IRBuilder<> &, Value *>::value) |
| 223 |
replaceArg(Index, Func(Builder, V)); |
| 224 |
else if constexpr (is_invocable<FnType, Value *, Type *>::value) |
| 225 |
replaceArg(Index, Func(V, T)); |
| 226 |
else if constexpr (is_invocable<FnType, Value *>::value) |
| 227 |
replaceArg(Index, Func(V)); |
| 228 |
else { |
| 229 |
// We need a helper value that is always false, but is dependent on the |
| 230 |
// template parameter to prevent this static_assert from firing when one |
| 231 |
// of the if constexprs above fires. |
| 232 |
static_assert(detail::LegalFnType<FnType>, |
| 233 |
"mapArg lambda signature is not satisfied"); |
| 234 |
} |
| 235 |
return *this; |
| 236 |
} |
| 237 |
|
| 238 |
/// Map all arguments according to the given function, as if mapArg(i, Func) |
| 239 |
/// had been called for every argument i. |
| 240 |
template <typename FnType> BuiltinCallMutator &mapArgs(FnType Func) { |
| 241 |
for (unsigned I = 0, E = Args.size(); I < E; I++) |
| 242 |
mapArg(I, Func); |
| 243 |
return *this; |
| 244 |
} |
| 245 |
}; |
| 246 |
|
| 247 |
/// A helper class for generating calls to SPIR-V builtins with appropriate name |
| 248 |
/// mangling rules. It is expected that transformation passes inherit from this |
| 249 |
/// class. |
| 250 |
class BuiltinCallHelper { |
| 251 |
ManglingRules Rules; |
| 252 |
std::function<std::string(llvm::StringRef)> NameMapFn; |
| 253 |
|
| 254 |
protected: |
| 255 |
llvm::Module *M = nullptr; |
| 256 |
bool UseTargetTypes = false; |
| 257 |
|
| 258 |
public: |
| 259 |
/// Initialize details about how to mangle and demangle builtins correctly. |
| 260 |
/// The Rules argument selects which name mangler to use for mangling. |
| 261 |
/// The NameMapFn function will map type names during demangling; it defaults |
| 262 |
/// to the identity function. |
| 263 |
explicit BuiltinCallHelper( |
| 264 |
ManglingRules Rules, |
| 265 |
std::function<std::string(llvm::StringRef)> NameMapFn = nullptr) |
| 266 |
: Rules(Rules), NameMapFn(std::move(NameMapFn)) {} |
| 267 |
|
| 268 |
/// Initialize the module that will be operated on. This method must be called |
| 269 |
/// before future methods. |
| 270 |
void initialize(llvm::Module &M); |
| 271 |
|
| 272 |
/// Return a mutator that will replace the given call instruction with a call |
| 273 |
/// to the given function name. The function name will have its name mangled |
| 274 |
/// in accordance with the argument types provided to the mutator. |
| 275 |
BuiltinCallMutator mutateCallInst(llvm::CallInst *CI, std::string FuncName); |
| 276 |
|
| 277 |
/// Return a mutator that will replace the given call instruction with a call |
| 278 |
/// to the given SPIR-V opcode (whose name is used in the lookup map of |
| 279 |
/// getSPIRVFuncName). |
| 280 |
BuiltinCallMutator mutateCallInst(llvm::CallInst *CI, spv::Op Opcode); |
| 281 |
|
| 282 |
/// Create a call to a SPIR-V builtin function (specified via opcode). |
| 283 |
/// The return type and argument types may be TypedPointerType, if the actual |
| 284 |
/// LLVM type is a pointer type. |
| 285 |
llvm::Value *addSPIRVCall(llvm::IRBuilder<> &Builder, spv::Op Opcode, |
| 286 |
llvm::Type *ReturnTy, |
| 287 |
llvm::ArrayRef<llvm::Value *> Args, |
| 288 |
llvm::ArrayRef<llvm::Type *> ArgTys, |
| 289 |
const llvm::Twine &Name = ""); |
| 290 |
|
| 291 |
/// Create a call to a SPIR-V builtin function, returning a value and type |
| 292 |
/// pair suitable for use in BuiltinCallMutator::replaceArg and similar |
| 293 |
/// functions. |
| 294 |
BuiltinCallMutator::ValueTypePair |
| 295 |
addSPIRVCallPair(llvm::IRBuilder<> &Builder, spv::Op Opcode, |
| 296 |
llvm::Type *ReturnTy, llvm::ArrayRef<llvm::Value *> Args, |
| 297 |
llvm::ArrayRef<llvm::Type *> ArgTys, |
| 298 |
const llvm::Twine &Name = "") { |
| 299 |
llvm::Value *V = |
| 300 |
addSPIRVCall(Builder, Opcode, ReturnTy, Args, ArgTys, Name); |
| 301 |
return BuiltinCallMutator::ValueTypePair(V, ReturnTy); |
| 302 |
} |
| 303 |
|
| 304 |
/// Adapt the various SPIR-V image types, for example changing a "spirv.Image" |
| 305 |
/// type into a "spirv.SampledImage" type with identical parameters. |
| 306 |
/// |
| 307 |
/// The input type is expected to be a TypedPointerType to either a |
| 308 |
/// "spirv.*" or "opencl.*" struct type. In the case of "opencl.*" struct |
| 309 |
/// types, it will first convert it into the corresponding "spirv.Image" |
| 310 |
/// struct type. |
| 311 |
/// |
| 312 |
/// If the image type does not match OldImageKind, this method will abort. |
| 313 |
llvm::Type *adjustImageType(llvm::Type *T, llvm::StringRef OldImageKind, |
| 314 |
llvm::StringRef NewImageKind); |
| 315 |
|
| 316 |
/// Create a new type representing a SPIR-V opaque type that takes no |
| 317 |
/// parameters (such as sampler types). |
| 318 |
/// |
| 319 |
/// If UseRealType is false, a typed pointer type may be returned; if it is |
| 320 |
/// true, a pointer type will be used instead. |
| 321 |
llvm::Type *getSPIRVType(spv::Op TypeOpcode, bool UseRealType = false); |
| 322 |
|
| 323 |
/// Create a new type representing a SPIR-V opaque type that takes only an |
| 324 |
/// access qualifier (such as pipe types). |
| 325 |
/// |
| 326 |
/// If UseRealType is false, a typed pointer type may be returned; if it is |
| 327 |
/// true, a pointer type will be used instead. |
| 328 |
llvm::Type *getSPIRVType(spv::Op TypeOpcode, spv::AccessQualifier Access, |
| 329 |
bool UseRealType = false); |
| 330 |
|
| 331 |
/// Create a new type representing a SPIR-V opaque type that is an image type |
| 332 |
/// of some kind. |
| 333 |
/// |
| 334 |
/// If UseRealType is false, a typed pointer type may be returned; if it is |
| 335 |
/// true, a pointer type will be used instead. |
| 336 |
llvm::Type *getSPIRVType(spv::Op TypeOpcode, llvm::Type *InnerType, |
| 337 |
SPIRVTypeImageDescriptor Desc, |
| 338 |
std::optional<spv::AccessQualifier> Access, |
| 339 |
bool UseRealType = false); |
| 340 |
|
| 341 |
/// Create a new type representing a SPIR-V opaque type that takes arbitrary |
| 342 |
/// parameters. |
| 343 |
/// |
| 344 |
/// If UseRealType is false, a typed pointer type may be returned; if it is |
| 345 |
/// true, a pointer type will be used instead. |
| 346 |
llvm::Type *getSPIRVType(spv::Op TypeOpcode, llvm::StringRef InnerTypeName, |
| 347 |
llvm::ArrayRef<unsigned> Parameters, |
| 348 |
bool UseRealType = false); |
| 349 |
|
| 350 |
private: |
| 351 |
llvm::SmallVector<llvm::Type *, 4> CachedParameterTypes; |
| 352 |
llvm::Function *CachedFunc = nullptr; |
| 353 |
|
| 354 |
public: |
| 355 |
BuiltinCallMutator::ValueTypePair getCallValue(llvm::CallInst *CI, |
| 356 |
unsigned ArgNo); |
| 357 |
|
| 358 |
llvm::Type *getCallValueType(llvm::CallInst *CI, unsigned ArgNo) { |
| 359 |
return getCallValue(CI, ArgNo).second; |
| 360 |
} |
| 361 |
}; |
| 362 |
|
| 363 |
} // namespace SPIRV |
| 364 |
|
| 365 |
#endif // SPIRVBUILTINHELPER_H |