File: GenIntrinsicFunctions.cpp

package info (click to toggle)
intel-graphics-compiler2 2.16.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 106,644 kB
  • sloc: cpp: 805,640; lisp: 287,672; ansic: 16,414; python: 3,952; yacc: 2,588; lex: 1,666; pascal: 313; sh: 186; makefile: 35
file content (309 lines) | stat: -rw-r--r-- 13,967 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*========================== begin_copyright_notice ============================

Copyright (C) 2017-2022 Intel Corporation

SPDX-License-Identifier: MIT

============================= end_copyright_notice ===========================*/

#include "GenIntrinsicFunctions.h"
#include "GenIntrinsicDefinition.h"
#include "GenIntrinsicLookup.h"
#include "Probe/Assertion.h"
#include "llvmWrapper/IR/DerivedTypes.h"
#include "llvmWrapper/IR/Type.h"
#include "llvmWrapper/IR/Module.h"

#include "common/LLVMWarningsPush.hpp"
#include <llvm/IR/Type.h>
#include <llvm/IR/Function.h>
#include <llvm/ADT/StringExtras.h>
#include <llvm/CodeGen/ValueTypes.h>
#include "common/LLVMWarningsPop.hpp"

namespace IGC {

constexpr uint32_t scBeginIntrinsicIndex = static_cast<uint32_t>(llvm::GenISAIntrinsic::ID::no_intrinsic) + 1;
constexpr uint32_t scNumIntrinsics =
    static_cast<uint32_t>(llvm::GenISAIntrinsic::ID::num_genisa_intrinsics) - scBeginIntrinsicIndex;

/// Returns a stable mangling for the type specified for use in the name
/// mangling scheme used by 'any' types in intrinsic signatures.  The mangling
/// of named types is simply their name.  Manglings for unnamed types consist
/// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
/// combined with the mangling of their component types.  A vararg function
/// type will have a suffix of 'vararg'.  Since function types can contain
/// other function types, we close a function type mangling with suffix 'f'
/// which can't be confused with it's prefix.  This ensures we don't have
/// collisions between two unrelated function types. Otherwise, you might
/// parse ffXX as f(fXX) or f(fX)X.  (X is a placeholder for any other type.)
std::string getMangledTypeStr(llvm::Type *Ty) {
  IGC_ASSERT(Ty);
  std::string Result;
  if (llvm::PointerType *PTyp = llvm::dyn_cast<llvm::PointerType>(Ty)) {
    Result += "p" + llvm::utostr(PTyp->getAddressSpace());
    if (!IGCLLVM::isOpaquePointerTy(PTyp)) {
      Result += getMangledTypeStr(IGCLLVM::getNonOpaquePtrEltTy(PTyp)); // Legacy code: getNonOpaquePtrEltTy
    }
  } else if (llvm::ArrayType *ATyp = llvm::dyn_cast<llvm::ArrayType>(Ty)) {
    Result += "a" + llvm::utostr(ATyp->getNumElements()) + getMangledTypeStr(ATyp->getElementType());
  } else if (llvm::StructType *STyp = llvm::dyn_cast<llvm::StructType>(Ty)) {
    if (!STyp->isLiteral())
      Result += STyp->getName();
    else {
      Result += "s" + llvm::utostr(STyp->getNumElements());
      for (unsigned int i = 0; i < STyp->getNumElements(); i++)
        Result += getMangledTypeStr(STyp->getElementType(i));
    }
  } else if (llvm::FunctionType *FT = llvm::dyn_cast<llvm::FunctionType>(Ty)) {
    Result += "f_" + getMangledTypeStr(FT->getReturnType());
    for (size_t i = 0; i < FT->getNumParams(); i++)
      Result += getMangledTypeStr(FT->getParamType(i));
    if (FT->isVarArg())
      Result += "vararg";
    // Ensure nested function types are distinguishable.
    Result += "f";
  } else if (llvm::isa<llvm::VectorType>(Ty))
    Result += "v" + llvm::utostr(llvm::cast<IGCLLVM::FixedVectorType>(Ty)->getNumElements()) +
              getMangledTypeStr(llvm::cast<llvm::VectorType>(Ty)->getElementType());
  else
    Result += llvm::EVT::getEVT(Ty).getEVTString();
  return Result;
}

template <llvm::GenISAIntrinsic::ID id> class IntrinsicFunctionImp : public llvm::Function {
public:
  static constexpr llvm::GenISAIntrinsic::ID scID = id;
  using IntrinsicDefinitionT = IntrinsicDefinition<scID>;
  using Argument = typename IntrinsicDefinitionT::Argument;

  static bool classof(const llvm::Value *pValue) {
    return llvm::isa<llvm::Function>(pValue) && llvm::isa<IntrinsicFunctionImp<id>>(llvm::cast<llvm::Function>(pValue));
  }

  static bool classof(const llvm::Function *pFunc) {
    if (pFunc != nullptr) {
      return llvm::GenISAIntrinsic::getIntrinsicID(pFunc) != llvm::GenISAIntrinsic::ID::no_intrinsic;
    }
    return false;
  }

  static IntrinsicFunctionImp<id> *Get(llvm::Module &module, const llvm::ArrayRef<llvm::Type *> &overloadedTypes,
                                       const llvm::ArrayRef<llvm::Type *> &overloadedPointeeTys) {
    return llvm::cast<IntrinsicFunctionImp<id>>(GetDeclaration(module, overloadedTypes, overloadedPointeeTys));
  }

  static llvm::Function *GetDeclaration(llvm::Module &module, const llvm::ArrayRef<llvm::Type *> &overloadedTypes,
                                        const llvm::ArrayRef<llvm::Type *> &overloadedPointeeTys) {
    return GetOrInsert(module, overloadedTypes, overloadedPointeeTys);
  }

  static std::string GetName(const llvm::ArrayRef<llvm::Type *> &overloadedTypes,
                             const llvm::ArrayRef<llvm::Type *> &overloadedPointeeTys) {
    std::string result = IntrinsicDefinitionT::scFunctionRootName;
    for (unsigned i = 0; i < overloadedTypes.size(); ++i) {
      result += "." + getMangledTypeStr(overloadedTypes[i]);
    }
    for (unsigned i = 0; i < overloadedPointeeTys.size(); ++i) {
      result += "." + getMangledTypeStr(overloadedPointeeTys[i]);
    }
    return result;
  }

  static llvm::GenISAIntrinsic::IntrinsicComments GetIntrinsicComments() {
    llvm::GenISAIntrinsic::IntrinsicComments result = {};
    result.funcDescription = IntrinsicDefinitionT::scMainComment;
    result.outputs = {IntrinsicDefinitionT::scResultComment};
    if constexpr (static_cast<uint32_t>(IntrinsicDefinitionT::Argument::Count) > 0) {
      std::transform(IntrinsicDefinitionT::scArgumentComments.begin(), IntrinsicDefinitionT::scArgumentComments.end(),
                     std::back_inserter(result.inputs), [](const auto &comment) { return comment; });
    }
    return result;
  }

private:
  static llvm::Function *GetOrInsert(llvm::Module &module, const llvm::ArrayRef<llvm::Type *> &overloadedTypes,
                                     const llvm::ArrayRef<llvm::Type *> &overloadedPointeeTys) {
    llvm::LLVMContext &ctx = module.getContext();
    std::string funcName = GetName(overloadedTypes, overloadedPointeeTys);
    llvm::FunctionType *pFuncType = GetType(ctx, overloadedTypes);
    llvm::AttributeList attribs = GetAttributeList(ctx, overloadedPointeeTys);
    // There can never be multiple globals with the same name of different types,
    // because intrinsics must be a specific type.
    IGCLLVM::Module &M = static_cast<IGCLLVM::Module &>(module);
    llvm::Function *pFunc = llvm::cast<llvm::Function>(M.getOrInsertFunction(funcName, pFuncType, attribs));

    IGC_ASSERT_MESSAGE(pFunc, "getOrInsertFunction probably returned constant expression!");
    // Since Function::isIntrinsic() will return true due to llvm.* prefix,
    // Module::getOrInsertFunction fails to add the attributes.
    // explicitly adding the attribute to handle this problem.
    // This since is setup on the function declaration, attribute assignment
    // is global and hence this approach suffices.
    pFunc->setAttributes(attribs);

    return pFunc;
  }

  static llvm::FunctionType *GetType(llvm::LLVMContext &ctx, const llvm::ArrayRef<llvm::Type *> &overloadedTypes) {
    constexpr uint8_t numArguments = static_cast<uint8_t>(Argument::Count);
    std::array<llvm::Type *, numArguments + 1> types{};

    uint8_t overloadedTypeIndex = 0;
    auto RetrieveType = [&overloadedTypeIndex, &ctx, &types, &overloadedTypes](uint8_t index,
                                                                               const TypeDescription &typeDef) {
      llvm::Type *&pDest = types[index];
      switch (typeDef.m_ID) {
      case TypeID::ArgumentReference: {
        uint8_t argIndex = typeDef.m_Reference.m_Index;
        IGC_ASSERT_MESSAGE(argIndex < overloadedTypes.size(),
                           "Argument reference index must point out one of the overloaded types");
        pDest = overloadedTypes[argIndex];
        break;
      }
      default:
        if (overloadedTypeIndex < overloadedTypes.size() && typeDef.IsOverloadable()) {
          pDest = overloadedTypes[overloadedTypeIndex++];
        } else {
          pDest = typeDef.GetType(ctx);
        }
        break;
      }
      IGC_ASSERT_MESSAGE(pDest != nullptr, "The type must be defined to determine the function type.");
      // IGC_ASSERT_MESSAGE(typeDef.VerifyType(pDest), "The type is inconsistent with the definition.");
    };

    constexpr uint8_t resTypeIndex = 0;
    RetrieveType(resTypeIndex, IntrinsicDefinitionT::scResTypes);

    if constexpr (numArguments > 0) {
      for (uint8_t i = 0; i < numArguments; i++) {
        RetrieveType(i + 1, IntrinsicDefinitionT::scArguments[i].m_Type);
      }
    }
    // IGC_ASSERT(overloadedTypeIndex == overloadedTypes.size());

    llvm::Type **pBegin = types.data() + 1;
    size_t size = types.size() - 1;
    llvm::Type *resultTy = types[0];
    llvm::SmallVector<llvm::Type *, 8> argTys(pBegin, pBegin + size);
    if (!argTys.empty() && argTys.back()->isVoidTy()) {
      argTys.pop_back();
      // Disable this path because of GenISA_UnmaskedRegionBegin and GenISA_UnmaskedRegionEnd
      // return llvm::FunctionType::get(resultTy, argTys, true);
    }
    return llvm::FunctionType::get(resultTy, argTys, false);
  }

  static llvm::AttributeList GetAttributeList(llvm::LLVMContext &ctx,
                                              const llvm::ArrayRef<llvm::Type *> &overloadedPointeeTys) {
    // 1. Instantiate regular attributes for the given intrinsic
    constexpr auto &attributeKinds = IntrinsicDefinitionT::scAttributeKinds;
    auto mainAttrList = llvm::AttributeList::get(ctx, llvm::AttributeList::FunctionIndex, attributeKinds);
    // 2. Gather the memory attribute(s) in a separate routine
    auto memoryAB = IntrinsicDefinitionT::scMemoryEffects.getAsAttrBuilder(ctx);
    mainAttrList = mainAttrList.addFnAttributes(ctx, memoryAB);
    // 3. Gather parameter attributes
    uint8_t overloadedTypeIndex = 0;
    auto RetrieveParamAttr = [&overloadedTypeIndex, &ctx, &overloadedPointeeTys,
                              &mainAttrList](uint8_t index, const ArgumentDescription &arg) {
      if (arg.m_AttrKind == llvm::Attribute::None) {
        return;
      }

      IGC_ASSERT_MESSAGE(llvm::Attribute::canUseAsParamAttr(arg.m_AttrKind), "Not a param attribute!");

      if (llvm::Attribute::isTypeAttrKind(arg.m_AttrKind)) {
        llvm::Type *pointeeType = nullptr;
        if (overloadedTypeIndex < overloadedPointeeTys.size() && arg.m_Type.IsOverloadable()) {
          pointeeType = overloadedPointeeTys[overloadedTypeIndex++];
        } else {
          pointeeType = arg.m_Type.m_Pointer.m_Type.GetType(ctx);
        }

        // IGC_ASSERT_MESSAGE(pointeeType, "Missing type for the type-dependent attribute!");
        if (!pointeeType)
          return;

        mainAttrList =
            mainAttrList.addParamAttribute(ctx, {index}, llvm::Attribute::get(ctx, arg.m_AttrKind, pointeeType));
      } else {
        mainAttrList = mainAttrList.addParamAttribute(ctx, {index}, llvm::Attribute::get(ctx, arg.m_AttrKind));
      }
    };

    constexpr uint8_t numArguments = static_cast<uint8_t>(Argument::Count);
    if constexpr (numArguments > 0) {
      for (uint8_t i = 0; i < numArguments; i++) {
        RetrieveParamAttr(i, IntrinsicDefinitionT::scArguments[i]);
      }
    }

    return mainAttrList;
  }
};

template <uint32_t... Is> static constexpr auto GetDeclarationFuncArrayImp(std::integer_sequence<uint32_t, Is...>) {
  return std::array{
      &(IntrinsicFunctionImp<static_cast<llvm::GenISAIntrinsic::ID>(Is + scBeginIntrinsicIndex)>::GetDeclaration)...};
}

static constexpr auto GetDeclarationFuncArray() {
  auto seq = std::make_integer_sequence<uint32_t, scNumIntrinsics>();
  return GetDeclarationFuncArrayImp(seq);
}

llvm::Function *GetDeclaration(llvm::Module *pModule, llvm::GenISAIntrinsic::ID id,
                               llvm::ArrayRef<llvm::Type *> overloadedTys,
                               llvm::ArrayRef<llvm::Type *> overloadedPointeeTys) {
  constexpr auto funcArray = GetDeclarationFuncArray();
  llvm::Function *pResult = nullptr;
  uint32_t index = static_cast<uint32_t>(id) - scBeginIntrinsicIndex;
  if (index < funcArray.size()) {
    pResult = funcArray[index](*pModule, overloadedTys, overloadedPointeeTys);
  }
  return pResult;
}

template <uint32_t... Is> static constexpr auto GetNameFuncArrayImp(std::integer_sequence<uint32_t, Is...>) {
  return std::array{
      &(IntrinsicFunctionImp<static_cast<llvm::GenISAIntrinsic::ID>(Is + scBeginIntrinsicIndex)>::GetName)...};
}

static constexpr auto GetNameFuncArray() {
  auto seq = std::make_integer_sequence<uint32_t, scNumIntrinsics>();
  return GetNameFuncArrayImp(seq);
}

std::string GetName(llvm::GenISAIntrinsic::ID id, llvm::ArrayRef<llvm::Type *> overloadedTys,
                    llvm::ArrayRef<llvm::Type *> overloadedPointeeTys) {
  constexpr auto funcArray = GetNameFuncArray();
  std::string result;
  uint32_t index = static_cast<uint32_t>(id) - scBeginIntrinsicIndex;
  if (index < funcArray.size()) {
    result = funcArray[index](overloadedTys, overloadedPointeeTys);
  }
  return result;
}

template <uint32_t... Is> static auto GetIntrinsicCommentsArrayImp(std::integer_sequence<uint32_t, Is...>) {
  return std::array{IntrinsicFunctionImp<static_cast<llvm::GenISAIntrinsic::ID>(
      Is + scBeginIntrinsicIndex)>::GetIntrinsicComments()...};
}

static auto GetIntrinsicCommentsArray() {
  auto seq = std::make_integer_sequence<uint32_t, scNumIntrinsics>();
  return GetIntrinsicCommentsArrayImp(seq);
}

llvm::GenISAIntrinsic::IntrinsicComments GetIntrinsicComments(llvm::GenISAIntrinsic::ID id) {
  static const auto intrinsicCommentsArray = GetIntrinsicCommentsArray();
  uint32_t index = static_cast<uint32_t>(id) - scBeginIntrinsicIndex;
  if (index < intrinsicCommentsArray.size()) {
    return intrinsicCommentsArray[index];
  }
  return {};
}

const char *GetIntrinsicPrefixName() { return scIntrinsicPrefix.data(); }

} // namespace IGC