Debian Codegraph @

llvm-project/llvm/projects/llvm-spirv/lib/SPIRV/SPIRVInternal.h

raw
1 //===- LLVMSPIRVInternal.h - SPIR-V internal header file -------*- C++ -*-===//
2 //
3 // The LLVM/SPIRV 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) 2014 Advanced Micro Devices, Inc. All rights reserved.
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 Advanced Micro Devices, Inc., 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 /// \file
35 ///
36 /// This file declares classes and functions shared by SPIR-V reader/writer.
37 ///
38 //===----------------------------------------------------------------------===//
39 #ifndef SPIRV_SPIRVINTERNAL_H
40 #define SPIRV_SPIRVINTERNAL_H
41
42 #include "NameMangleAPI.h"
43 #include "libSPIRV/SPIRVEnum.h"
44 #include "libSPIRV/SPIRVError.h"
45 #include "libSPIRV/SPIRVNameMapEnum.h"
46 #include "libSPIRV/SPIRVType.h"
47 #include "libSPIRV/SPIRVUtil.h"
48
49 #include "LLVMSPIRVLib.h"
50 #include "llvm/IR/Attributes.h"
51 #include "llvm/IR/Constants.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/TypedPointerType.h"
54
55 #include <functional>
56 #include <utility>
57
58 using namespace SPIRV;
59 using namespace llvm;
60
61 namespace llvm {
62 class IntrinsicInst;
63 class IRBuilderBase;
64 }
65
66 namespace SPIRV {
67
68 /// The LLVM/SPIR-V translator version used to fill the lower 16 bits of the
69 /// generator's magic number in the generated SPIR-V module.
70 /// This number should be bumped up whenever the generated SPIR-V changes.
71 const static unsigned short KTranslatorVer = 14;
72
73 class SPIRVOpaqueType;
74 typedef SPIRVMap<std::string, Op, SPIRVOpaqueType> SPIRVOpaqueTypeOpCodeMap;
75
76 // Ad hoc function used by LLVM/SPIRV converter for type casting
77 #define SPCV_CAST "spcv.cast"
78 #define LLVM_MEMCPY "llvm.memcpy"
79
80 // The name of function generated by Clang to initialize sampler(which is
81 // opaqueue type) by 32-bit integer. The name is taken from
82 // CodeGenModule::createOpenCLIntToSamplerConversion().
83 #define SAMPLER_INIT "__translate_sampler_initializer"
84
85 template <> inline void SPIRVMap<unsigned, Op>::init() {
86 #define _SPIRV_OP(x, y) add(Instruction::x, Op##y);
87 /* Casts */
88 _SPIRV_OP(ZExt, UConvert)
89 _SPIRV_OP(SExt, SConvert)
90 _SPIRV_OP(Trunc, UConvert)
91 _SPIRV_OP(FPToUI, ConvertFToU)
92 _SPIRV_OP(FPToSI, ConvertFToS)
93 _SPIRV_OP(UIToFP, ConvertUToF)
94 _SPIRV_OP(SIToFP, ConvertSToF)
95 _SPIRV_OP(FPTrunc, FConvert)
96 _SPIRV_OP(FPExt, FConvert)
97 _SPIRV_OP(PtrToInt, ConvertPtrToU)
98 _SPIRV_OP(IntToPtr, ConvertUToPtr)
99 _SPIRV_OP(BitCast, Bitcast)
100 _SPIRV_OP(AddrSpaceCast, GenericCastToPtr)
101 _SPIRV_OP(GetElementPtr, AccessChain)
102 _SPIRV_OP(FNeg, FNegate)
103 /*Binary*/
104 _SPIRV_OP(And, BitwiseAnd)
105 _SPIRV_OP(Or, BitwiseOr)
106 _SPIRV_OP(Xor, BitwiseXor)
107 _SPIRV_OP(Add, IAdd)
108 _SPIRV_OP(FAdd, FAdd)
109 _SPIRV_OP(Sub, ISub)
110 _SPIRV_OP(FSub, FSub)
111 _SPIRV_OP(Mul, IMul)
112 _SPIRV_OP(FMul, FMul)
113 _SPIRV_OP(UDiv, UDiv)
114 _SPIRV_OP(SDiv, SDiv)
115 _SPIRV_OP(FDiv, FDiv)
116 _SPIRV_OP(SRem, SRem)
117 _SPIRV_OP(FRem, FRem)
118 _SPIRV_OP(URem, UMod)
119 _SPIRV_OP(Shl, ShiftLeftLogical)
120 _SPIRV_OP(LShr, ShiftRightLogical)
121 _SPIRV_OP(AShr, ShiftRightArithmetic)
122 #undef _SPIRV_OP
123 }
124 typedef SPIRVMap<unsigned, Op> OpCodeMap;
125
126 template <> inline void SPIRVMap<CmpInst::Predicate, Op>::init() {
127 #define _SPIRV_OP(x, y) add(CmpInst::x, Op##y);
128 _SPIRV_OP(FCMP_OEQ, FOrdEqual)
129 _SPIRV_OP(FCMP_OGT, FOrdGreaterThan)
130 _SPIRV_OP(FCMP_OGE, FOrdGreaterThanEqual)
131 _SPIRV_OP(FCMP_OLT, FOrdLessThan)
132 _SPIRV_OP(FCMP_OLE, FOrdLessThanEqual)
133 _SPIRV_OP(FCMP_ONE, FOrdNotEqual)
134 _SPIRV_OP(FCMP_ORD, Ordered)
135 _SPIRV_OP(FCMP_UNO, Unordered)
136 _SPIRV_OP(FCMP_UEQ, FUnordEqual)
137 _SPIRV_OP(FCMP_UGT, FUnordGreaterThan)
138 _SPIRV_OP(FCMP_UGE, FUnordGreaterThanEqual)
139 _SPIRV_OP(FCMP_ULT, FUnordLessThan)
140 _SPIRV_OP(FCMP_ULE, FUnordLessThanEqual)
141 _SPIRV_OP(FCMP_UNE, FUnordNotEqual)
142 _SPIRV_OP(ICMP_EQ, IEqual)
143 _SPIRV_OP(ICMP_NE, INotEqual)
144 _SPIRV_OP(ICMP_UGT, UGreaterThan)
145 _SPIRV_OP(ICMP_UGE, UGreaterThanEqual)
146 _SPIRV_OP(ICMP_ULT, ULessThan)
147 _SPIRV_OP(ICMP_ULE, ULessThanEqual)
148 _SPIRV_OP(ICMP_SGT, SGreaterThan)
149 _SPIRV_OP(ICMP_SGE, SGreaterThanEqual)
150 _SPIRV_OP(ICMP_SLT, SLessThan)
151 _SPIRV_OP(ICMP_SLE, SLessThanEqual)
152 #undef _SPIRV_OP
153 }
154 typedef SPIRVMap<CmpInst::Predicate, Op> CmpMap;
155
156 class IntBoolOpMapId;
157 template <> inline void SPIRVMap<Op, Op, IntBoolOpMapId>::init() {
158 add(OpNot, OpLogicalNot);
159 add(OpBitwiseAnd, OpLogicalAnd);
160 add(OpBitwiseOr, OpLogicalOr);
161 add(OpBitwiseXor, OpLogicalNotEqual);
162 add(OpIEqual, OpLogicalEqual);
163 add(OpINotEqual, OpLogicalNotEqual);
164 }
165 typedef SPIRVMap<Op, Op, IntBoolOpMapId> IntBoolOpMap;
166
167 #define SPIR_TARGETTRIPLE32 "spir-unknown-unknown"
168 #define SPIR_TARGETTRIPLE64 "spir64-unknown-unknown"
169 #define SPIR_DATALAYOUT32 \
170 "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32" \
171 "-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32" \
172 "-v32:32:32-v48:64:64-v64:64:64-v96:128:128" \
173 "-v128:128:128-v192:256:256-v256:256:256" \
174 "-v512:512:512-v1024:1024:1024"
175 #define SPIR_DATALAYOUT64 \
176 "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32" \
177 "-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32" \
178 "-v32:32:32-v48:64:64-v64:64:64-v96:128:128" \
179 "-v128:128:128-v192:256:256-v256:256:256" \
180 "-v512:512:512-v1024:1024:1024"
181
182 enum SPIRAddressSpace {
183 SPIRAS_Private,
184 SPIRAS_Global,
185 SPIRAS_Constant,
186 SPIRAS_Local,
187 SPIRAS_Generic,
188 SPIRAS_GlobalDevice,
189 SPIRAS_GlobalHost,
190 SPIRAS_Input,
191 SPIRAS_Output,
192 SPIRAS_CodeSectionINTEL,
193 SPIRAS_Count,
194 };
195
196 template <> inline void SPIRVMap<SPIRAddressSpace, std::string>::init() {
197 add(SPIRAS_Private, "Private");
198 add(SPIRAS_Global, "Global");
199 add(SPIRAS_Constant, "Constant");
200 add(SPIRAS_Local, "Local");
201 add(SPIRAS_Generic, "Generic");
202 add(SPIRAS_Input, "Input");
203 add(SPIRAS_CodeSectionINTEL, "CodeSectionINTEL");
204
205 add(SPIRAS_GlobalDevice, "GlobalDevice");
206 add(SPIRAS_GlobalHost, "GlobalHost");
207 }
208 typedef SPIRVMap<SPIRAddressSpace, SPIRVStorageClassKind>
209 SPIRAddrSpaceCapitalizedNameMap;
210
211 template <>
212 inline void SPIRVMap<SPIRAddressSpace, SPIRVStorageClassKind>::init() {
213 add(SPIRAS_Private, StorageClassFunction);
214 add(SPIRAS_Global, StorageClassCrossWorkgroup);
215 add(SPIRAS_Constant, StorageClassUniformConstant);
216 add(SPIRAS_Local, StorageClassWorkgroup);
217 add(SPIRAS_Generic, StorageClassGeneric);
218 add(SPIRAS_Input, StorageClassInput);
219 add(SPIRAS_GlobalDevice, StorageClassDeviceOnlyINTEL);
220 add(SPIRAS_GlobalHost, StorageClassHostOnlyINTEL);
221 add(SPIRAS_CodeSectionINTEL, StorageClassCodeSectionINTEL);
222 }
223 typedef SPIRVMap<SPIRAddressSpace, SPIRVStorageClassKind> SPIRSPIRVAddrSpaceMap;
224
225 // Maps OCL builtin function to SPIRV builtin variable.
226 template <>
227 inline void SPIRVMap<std::string, SPIRVAccessQualifierKind>::init() {
228 add("read_only", AccessQualifierReadOnly);
229 add("write_only", AccessQualifierWriteOnly);
230 add("read_write", AccessQualifierReadWrite);
231 }
232 typedef SPIRVMap<std::string, SPIRVAccessQualifierKind>
233 SPIRSPIRVAccessQualifierMap;
234
235 template <>
236 inline void SPIRVMap<Attribute::AttrKind, SPIRVFuncParamAttrKind>::init() {
237 add(Attribute::ZExt, FunctionParameterAttributeZext);
238 add(Attribute::SExt, FunctionParameterAttributeSext);
239 add(Attribute::ByVal, FunctionParameterAttributeByVal);
240 add(Attribute::StructRet, FunctionParameterAttributeSret);
241 add(Attribute::NoAlias, FunctionParameterAttributeNoAlias);
242 add(Attribute::NoCapture, FunctionParameterAttributeNoCapture);
243 add(Attribute::ReadOnly, FunctionParameterAttributeNoWrite);
244 add(Attribute::ReadNone, FunctionParameterAttributeNoReadWrite);
245 }
246 typedef SPIRVMap<Attribute::AttrKind, SPIRVFuncParamAttrKind>
247 SPIRSPIRVFuncParamAttrMap;
248
249 template <>
250 inline void
251 SPIRVMap<Attribute::AttrKind, SPIRVFunctionControlMaskKind>::init() {
252 add(Attribute::AlwaysInline, FunctionControlInlineMask);
253 add(Attribute::NoInline, FunctionControlDontInlineMask);
254 add(Attribute::OptimizeNone, FunctionControlOptNoneEXTMask);
255 }
256 typedef SPIRVMap<Attribute::AttrKind, SPIRVFunctionControlMaskKind>
257 SPIRSPIRVFuncCtlMaskMap;
258
259 class SPIRVExtSetShortName;
260 template <>
261 inline void
262 SPIRVMap<SPIRVExtInstSetKind, std::string, SPIRVExtSetShortName>::init() {
263 add(SPIRVEIS_OpenCL, "ocl");
264 }
265 typedef SPIRVMap<SPIRVExtInstSetKind, std::string, SPIRVExtSetShortName>
266 SPIRVExtSetShortNameMap;
267
268 #define SPIR_MD_COMPILER_OPTIONS "opencl.compiler.options"
269 #define SPIR_MD_KERNEL_ARG_ADDR_SPACE "kernel_arg_addr_space"
270 #define SPIR_MD_KERNEL_ARG_ACCESS_QUAL "kernel_arg_access_qual"
271 #define SPIR_MD_KERNEL_ARG_TYPE "kernel_arg_type"
272 #define SPIR_MD_KERNEL_ARG_BASE_TYPE "kernel_arg_base_type"
273 #define SPIR_MD_KERNEL_ARG_TYPE_QUAL "kernel_arg_type_qual"
274 #define SPIR_MD_KERNEL_ARG_NAME "kernel_arg_name"
275
276 #define SPIRV_MD_PARAMETER_DECORATIONS "spirv.ParameterDecorations"
277 #define SPIRV_MD_DECORATIONS "spirv.Decorations"
278
279 #define OCL_TYPE_NAME_SAMPLER_T "sampler_t"
280 #define SPIR_TYPE_NAME_EVENT_T "opencl.event_t"
281 #define SPIR_TYPE_NAME_CLK_EVENT_T "opencl.clk_event_t"
282 #define SPIR_TYPE_NAME_BLOCK_T "opencl.block"
283 #define SPIR_INTRINSIC_BLOCK_BIND "spir_block_bind"
284 #define SPIR_INTRINSIC_GET_BLOCK_INVOKE "spir_get_block_invoke"
285 #define SPIR_INTRINSIC_GET_BLOCK_CONTEXT "spir_get_block_context"
286 #define SPIR_TEMP_NAME_PREFIX_BLOCK "block"
287 #define SPIR_TEMP_NAME_PREFIX_CALL "call"
288
289 namespace kLLVMTypeName {
290 const static char StructPrefix[] = "struct.";
291 } // namespace kLLVMTypeName
292
293 namespace kSPIRVImageSampledTypeName {
294 const static char Float[] = "float";
295 const static char Half[] = "half";
296 const static char Int[] = "int";
297 const static char UInt[] = "uint";
298 const static char Long[] = "long";
299 const static char ULong[] = "ulong";
300 const static char Void[] = "void";
301 } // namespace kSPIRVImageSampledTypeName
302
303 namespace kSPIRVTypeName {
304 const static char Delimiter = '.';
305 const static char DeviceEvent[] = "DeviceEvent";
306 const static char Event[] = "Event";
307 const static char Image[] = "Image";
308 const static char Pipe[] = "Pipe";
309 const static char PostfixDelim = '_';
310 const static char Prefix[] = "spirv";
311 const static char PrefixAndDelim[] = "spirv.";
312 const static char Queue[] = "Queue";
313 const static char ReserveId[] = "ReserveId";
314 const static char SampledImg[] = "SampledImage";
315 const static char Sampler[] = "Sampler";
316 const static char ConstantSampler[] = "ConstantSampler";
317 const static char PipeStorage[] = "PipeStorage";
318 const static char ConstantPipeStorage[] = "ConstantPipeStorage";
319 const static char VmeImageINTEL[] = "VmeImageINTEL";
320 const static char JointMatrixINTEL[] = "JointMatrixINTEL";
321 const static char CooperativeMatrixKHR[] = "CooperativeMatrixKHR";
322 const static char BufferSurfaceINTEL[] = "BufferSurfaceINTEL";
323 } // namespace kSPIRVTypeName
324
325 namespace kSPR2TypeName {
326 const static char Delimiter = '.';
327 const static char OCLPrefix[] = "opencl.";
328 const static char ImagePrefix[] = "opencl.image";
329 const static char PipeRO[] = "opencl.pipe_ro_t";
330 const static char PipeWO[] = "opencl.pipe_wo_t";
331 const static char Sampler[] = "opencl.sampler_t";
332 const static char Event[] = "opencl.event_t";
333 } // namespace kSPR2TypeName
334
335 namespace kAccessQualName {
336 const static char ReadOnly[] = "read_only";
337 const static char WriteOnly[] = "write_only";
338 const static char ReadWrite[] = "read_write";
339 } // namespace kAccessQualName
340
341 namespace kAccessQualPostfix {
342 const static char ReadOnly[] = "_ro";
343 const static char WriteOnly[] = "_wo";
344 const static char ReadWrite[] = "_rw";
345 const static char Type[] = "_t";
346 } // namespace kAccessQualPostfix
347
348 namespace kMangledName {
349 const static char Sampler[] = "11ocl_sampler";
350 const static char AtomicPrefixIncoming[] = "U7_Atomic";
351 const static char AtomicPrefixInternal[] = "atomic_";
352 } // namespace kMangledName
353
354 namespace kSPIRVName {
355 const static char GroupPrefix[] = "group_";
356 const static char GroupNonUniformPrefix[] = "group_non_uniform_";
357 const static char ClusteredPrefix[] = "clustered_";
358 const static char Prefix[] = "__spirv_";
359 const static char Postfix[] = "__";
360 const static char ImageQuerySize[] = "ImageQuerySize";
361 const static char ImageQuerySizeLod[] = "ImageQuerySizeLod";
362 const static char ImageSampleExplicitLod[] = "ImageSampleExplicitLod";
363 const static char ReservedPrefix[] = "reserved_";
364 const static char SampledImage[] = "SampledImage";
365 const static char TempSampledImage[] = "TempSampledImage";
366 const static char TranslateOCLMemOrder[] = "__translate_ocl_memory_order";
367 const static char TranslateOCLMemScope[] = "__translate_ocl_memory_scope";
368 const static char TranslateSPIRVMemOrder[] = "__translate_spirv_memory_order";
369 const static char TranslateSPIRVMemScope[] = "__translate_spirv_memory_scope";
370 const static char TranslateSPIRVMemFence[] = "__translate_spirv_memory_fence";
371 const static char EntrypointPrefix[] = "__spirv_entry_";
372 const static char ConvertHandleToImageINTEL[] = "ConvertHandleToImageINTEL";
373 const static char ConvertHandleToSamplerINTEL[] = "ConvertHandleToSamplerINTEL";
374 const static char ConvertHandleToSampledImageINTEL[] =
375 "ConvertHandleToSampledImageINTEL";
376 const static char InternalBuiltinPrefix[] = "__builtin_spirv_";
377 } // namespace kSPIRVName
378
379 namespace kSPIRVPostfix {
380 const static char ToGlobal[] = "ToGlobal";
381 const static char ToLocal[] = "ToLocal";
382 const static char ToPrivate[] = "ToPrivate";
383 const static char Sat[] = "sat";
384 const static char Rtz[] = "rtz";
385 const static char Rte[] = "rte";
386 const static char Rtp[] = "rtp";
387 const static char Rtn[] = "rtn";
388 const static char Rt[] = "rt";
389 const static char Return[] = "R";
390 const static char Divider[] = "_";
391 /// Divider between extended instruction name and postfix
392 const static char ExtDivider[] = "__";
393 } // namespace kSPIRVPostfix
394
395 namespace kSPIRVMD {
396 const static char Capability[] = "spirv.Capability";
397 const static char EntryPoint[] = "spirv.EntryPoint";
398 const static char ExecutionMode[] = "spirv.ExecutionMode";
399 const static char Extension[] = "spirv.Extension";
400 const static char Generator[] = "spirv.Generator";
401 const static char Source[] = "spirv.Source";
402 const static char SourceExtension[] = "spirv.SourceExtension";
403 const static char MemoryModel[] = "spirv.MemoryModel";
404 } // namespace kSPIRVMD
405
406 namespace kSPIR2MD {
407 const static char Extensions[] = "opencl.used.extensions";
408 const static char FPContract[] = "opencl.enable.FP_CONTRACT";
409 const static char OCLVer[] = "opencl.ocl.version";
410 const static char OptFeatures[] = "opencl.used.optional.core.features";
411 const static char SPIRVer[] = "opencl.spir.version";
412 const static char VecTyHint[] = "vec_type_hint";
413 const static char WGSize[] = "reqd_work_group_size";
414 const static char WGSizeHint[] = "work_group_size_hint";
415 const static char SubgroupSize[] = "intel_reqd_sub_group_size";
416 const static char MaxWGSize[] = "max_work_group_size";
417 const static char NoGlobalOffset[] = "no_global_work_offset";
418 const static char MaxWGDim[] = "max_global_work_dim";
419 const static char NumSIMD[] = "num_simd_work_items";
420 const static char StallEnable[] = "stall_enable";
421 const static char FmaxMhz[] = "scheduler_target_fmax_mhz";
422 const static char LoopFuse[] = "loop_fuse";
423 const static char PreferDSP[] = "prefer_dsp";
424 const static char PropDSPPref[] = "propagate_dsp_preference";
425 const static char InitiationInterval[] = "initiation_interval";
426 const static char MaxConcurrency[] = "max_concurrency";
427 const static char DisableLoopPipelining[] = "disable_loop_pipelining";
428 const static char IntelFPGAIPInterface[] = "ip_interface";
429 } // namespace kSPIR2MD
430
431 enum Spir2SamplerKind {
432 CLK_ADDRESS_NONE = 0x0000,
433 CLK_ADDRESS_CLAMP = 0x0004,
434 CLK_ADDRESS_CLAMP_TO_EDGE = 0x0002,
435 CLK_ADDRESS_REPEAT = 0x0006,
436 CLK_ADDRESS_MIRRORED_REPEAT = 0x0008,
437 CLK_NORMALIZED_COORDS_FALSE = 0x0000,
438 CLK_NORMALIZED_COORDS_TRUE = 0x0001,
439 CLK_FILTER_NEAREST = 0x0010,
440 CLK_FILTER_LINEAR = 0x0020,
441 };
442
443 /// Additional information for mangling a function argument type.
444 struct BuiltinArgTypeMangleInfo {
445 bool IsSigned;
446 bool IsVoidPtr;
447 bool IsEnum;
448 bool IsSampler;
449 bool IsAtomic;
450 bool IsLocalArgBlock;
451 SPIR::TypePrimitiveEnum Enum;
452 unsigned Attr;
453 Type *PointerTy;
454 BuiltinArgTypeMangleInfo()
455 : IsSigned(true), IsVoidPtr(false), IsEnum(false), IsSampler(false),
456 IsAtomic(false), IsLocalArgBlock(false), Enum(SPIR::PRIMITIVE_NONE),
457 Attr(0), PointerTy(nullptr) {}
458 };
459
460 /// Information for mangling builtin function.
461 class BuiltinFuncMangleInfo {
462 public:
463 /// Translate builtin function name and set
464 /// argument attributes and unsigned args.
465 BuiltinFuncMangleInfo(const std::string &UniqName = "")
466 : VarArgIdx(-1), DontMangle(false) {
467 if (!UniqName.empty())
468 init(UniqName);
469 }
470 virtual ~BuiltinFuncMangleInfo() {}
471 const std::string &getUnmangledName() const { return UnmangledName; }
472 void addUnsignedArg(int Ndx) {
473 if (Ndx == -1)
474 return addUnsignedArgs(0, 10); // 10 is enough for everybody, right?
475 getTypeMangleInfo(Ndx).IsSigned = false;
476 }
477 void addUnsignedArgs(int StartNdx, int StopNdx) {
478 assert(StartNdx < StopNdx && "wrong parameters");
479 for (int I = StartNdx; I <= StopNdx; ++I)
480 addUnsignedArg(I);
481 }
482 void addVoidPtrArg(unsigned Ndx) { getTypeMangleInfo(Ndx).IsVoidPtr = true; }
483 void addSamplerArg(unsigned Ndx) { getTypeMangleInfo(Ndx).IsSampler = true; }
484 void addAtomicArg(unsigned Ndx) { getTypeMangleInfo(Ndx).IsAtomic = true; }
485 void setLocalArgBlock(unsigned Ndx) {
486 getTypeMangleInfo(Ndx).IsLocalArgBlock = true;
487 }
488 void setEnumArg(unsigned Ndx, SPIR::TypePrimitiveEnum Enum) {
489 auto &Info = getTypeMangleInfo(Ndx);
490 Info.IsEnum = true;
491 Info.Enum = Enum;
492 }
493 void setArgAttr(unsigned Ndx, unsigned Attr) {
494 getTypeMangleInfo(Ndx).Attr = Attr;
495 }
496 void setVarArg(int Ndx) {
497 assert(0 <= Ndx && "it is not allowed to set less than zero index");
498 VarArgIdx = Ndx;
499 }
500 void setAsDontMangle() { DontMangle = true; }
501 bool avoidMangling() { return DontMangle; }
502 // get ellipsis index, single ellipsis at the end of the function is possible
503 // only return value < 0 if none
504 int getVarArg() const { return VarArgIdx; }
505 BuiltinArgTypeMangleInfo &getTypeMangleInfo(unsigned Ndx) {
506 while (Ndx >= ArgInfo.size())
507 ArgInfo.emplace_back();
508 BuiltinArgTypeMangleInfo &Info = ArgInfo[Ndx];
509 return Info;
510 }
511 virtual void init(StringRef UniqUnmangledName) {
512 UnmangledName = UniqUnmangledName.str();
513 }
514
515 protected:
516 std::string UnmangledName;
517 std::vector<BuiltinArgTypeMangleInfo> ArgInfo;
518 int VarArgIdx; // index of ellipsis argument, idx < 0 if none
519 private:
520 bool DontMangle; // clang doesn't apply mangling for some builtin functions
521 // (i.e. enqueue_kernel)
522 };
523
524 /// \returns a vector of types for a collection of values.
525 template <class T> std::vector<Type *> getTypes(llvm::ArrayRef<T> V) {
526 std::vector<Type *> Tys;
527 for (auto &I : V)
528 Tys.push_back(I->getType());
529 return Tys;
530 }
531
532 /// Move elements of std::vector from [begin, end) to target.
533 template <typename T>
534 void move(std::vector<T> &V, size_t Begin, size_t End, size_t Target) {
535 assert(Begin < End && End <= V.size() && Target <= V.size() &&
536 !(Begin < Target && Target < End));
537 if (Begin <= Target && Target <= End)
538 return;
539 auto B = V.begin() + Begin, E = V.begin() + End;
540 if (Target > V.size())
541 Target = V.size();
542 if (Target > End)
543 Target -= (End - Begin);
544 std::vector<T> Segment(B, E);
545 V.erase(B, E);
546 V.insert(V.begin() + Target, Segment.begin(), Segment.end());
547 }
548
549 /// Find position of first pointer type value in a vector.
550 template <typename Container>
551 inline unsigned findFirstPtr(const Container &Args) {
552 auto PtArg = std::find_if(Args.begin(), Args.end(), [](Value *V) {
553 return V->getType()->isPointerTy();
554 });
555 return PtArg - Args.begin();
556 }
557
558 bool isSupportedTriple(Triple T);
559 void removeFnAttr(CallInst *Call, Attribute::AttrKind Attr);
560 void addFnAttr(CallInst *Call, Attribute::AttrKind Attr);
561 void saveLLVMModule(Module *M, const std::string &OutputFile);
562 std::string mapLLVMTypeToOCLType(const Type *Ty, bool Signed,
563 Type *PointerElementType = nullptr);
564 SPIRVDecorate *mapPostfixToDecorate(StringRef Postfix, SPIRVEntry *Target);
565
566 /// Return vector V extended with poison elements to match the number of
567 /// components of NewType.
568 Value *extendVector(Value *V, FixedVectorType *NewType, IRBuilderBase &Builder);
569
570 /// Add decorations to a SPIR-V entry.
571 /// \param Decs Each string is a postfix without _ at the beginning.
572 SPIRVValue *addDecorations(SPIRVValue *Target,
573 const SmallVectorImpl<std::string> &Decs);
574
575 StructType *getOrCreateOpaqueStructType(Module *M, StringRef Name);
576 void getFunctionTypeParameterTypes(llvm::FunctionType *FT,
577 std::vector<Type *> &ArgTys);
578 Function *getOrCreateFunction(Module *M, Type *RetTy, ArrayRef<Type *> ArgTypes,
579 StringRef Name,
580 BuiltinFuncMangleInfo *Mangle = nullptr,
581 AttributeList *Attrs = nullptr,
582 bool TakeName = true);
583
584 /// Get function call arguments.
585 /// \param Start Starting index.
586 /// \param End Ending index.
587 std::vector<Value *> getArguments(CallInst *CI, unsigned Start = 0,
588 unsigned End = 0);
589
590 /// Get constant function call argument as an integer.
591 /// \param I argument index.
592 uint64_t getArgAsInt(CallInst *CI, unsigned I);
593
594 /// Get constant function call argument as type \param T.
595 /// \param I argument index.
596 template <typename T> T getArgAs(CallInst *CI, unsigned I) {
597 return static_cast<T>(getArgAsInt(CI, I));
598 }
599
600 /// Get constant function call argument as a Scope enum.
601 /// \param I argument index.
602 Scope getArgAsScope(CallInst *CI, unsigned I);
603
604 /// Get constant function call argument as a Decoration enum.
605 /// \param I argument index.
606 Decoration getArgAsDecoration(CallInst *CI, unsigned I);
607
608 /// Check if a type is OCL image type.
609 /// \return type name without "opencl." prefix.
610 bool isOCLImageType(llvm::Type *Ty, StringRef *Name = nullptr);
611
612 /// \param BaseTyName is the type name as in spirv.BaseTyName.Postfixes
613 /// \param Postfix contains postfixes extracted from the SPIR-V image
614 /// type name as spirv.BaseTyName.Postfixes.
615 bool isSPIRVStructType(llvm::Type *Ty, StringRef BaseTyName,
616 StringRef *Postfix = 0);
617
618 bool isSYCLHalfType(llvm::Type *Ty);
619
620 bool isSYCLBfloat16Type(llvm::Type *Ty);
621
622 /// Decorate a function name as __spirv_{Name}_
623 std::string decorateSPIRVFunction(const std::string &S);
624
625 /// Remove prefix/postfix from __spirv_{Name}_
626 StringRef undecorateSPIRVFunction(StringRef S);
627
628 /// Check if a function has decorated name as __spirv_{Name}_
629 /// and get the original name.
630 bool isDecoratedSPIRVFunc(const Function *F, StringRef &UndecName);
631
632 std::string prefixSPIRVName(const std::string &S);
633
634 StringRef dePrefixSPIRVName(StringRef R, SmallVectorImpl<StringRef> &Postfix);
635
636 /// Get a canonical function name for a SPIR-V op code.
637 std::string getSPIRVFuncName(Op OC, StringRef PostFix = "");
638
639 std::string getSPIRVFuncName(Op OC, const Type *PRetTy, bool IsSigned = false,
640 Type *PointerElementType = nullptr);
641
642 std::string getSPIRVFuncName(SPIRVBuiltinVariableKind BVKind);
643
644 /// Get a canonical function name for a SPIR-V extended instruction
645 std::string getSPIRVExtFuncName(SPIRVExtInstSetKind Set, unsigned ExtOp,
646 StringRef PostFix = "");
647
648 /// Get SPIR-V op code given the canonical function name.
649 /// Assume \param Name is either IA64 mangled or unmangled, and the unmangled
650 /// name takes the __spirv_{OpName}_{Postfixes} format.
651 /// \return op code if the unmangled function name is a valid op code name,
652 /// otherwise return OpNop.
653 /// \param Dec contains decorations decoded from function name if it is
654 /// not nullptr.
655 Op getSPIRVFuncOC(StringRef Name, SmallVectorImpl<std::string> *Dec = nullptr);
656
657 /// Get SPIR-V builtin variable enum given the canonical builtin name
658 /// Assume \param Name is in format __spirv_BuiltIn{Name}
659 /// \return false if \param Name is not a valid builtin name.
660 bool getSPIRVBuiltin(const std::string &Name, spv::BuiltIn &Builtin);
661
662 /// \param Name LLVM function name
663 /// \param DemangledName demangled name of the OpenCL built-in function
664 /// \returns true if Name is the name of the OpenCL built-in function,
665 /// false for other functions
666 bool oclIsBuiltin(StringRef Name, StringRef &DemangledName, bool IsCpp = false);
667
668 /// Check if a function returns void
669 bool isVoidFuncTy(FunctionType *FT);
670
671 /// \returns true if function \p F has array type argument.
672 bool hasArrayArg(Function *F);
673
674 /// Mutates function call instruction by changing the arguments.
675 /// \param ArgMutate mutates the function arguments.
676 /// \return mutated call instruction.
677 CallInst *mutateCallInst(
678 Module *M, CallInst *CI,
679 std::function<std::string(CallInst *, std::vector<Value *> &)> ArgMutate,
680 BuiltinFuncMangleInfo *Mangle = nullptr, AttributeList *Attrs = nullptr,
681 bool TakeName = false);
682
683 /// Mutates function call instruction by changing the arguments and return
684 /// value.
685 /// \param ArgMutate mutates the function arguments.
686 /// \param RetMutate mutates the return value.
687 /// \return mutated instruction.
688 Instruction *mutateCallInst(
689 Module *M, CallInst *CI,
690 std::function<std::string(CallInst *, std::vector<Value *> &, Type *&RetTy)>
691 ArgMutate,
692 std::function<Instruction *(CallInst *)> RetMutate,
693 BuiltinFuncMangleInfo *Mangle = nullptr, AttributeList *Attrs = nullptr,
694 bool TakeName = false);
695
696 /// Mutate function by change the arguments.
697 /// \param ArgMutate mutates the function arguments.
698 /// \param TakeName Take the original function's name if a new function with
699 /// different type needs to be created.
700 void mutateFunction(
701 Function *F,
702 std::function<std::string(CallInst *, std::vector<Value *> &)> ArgMutate,
703 BuiltinFuncMangleInfo *Mangle = nullptr, AttributeList *Attrs = nullptr,
704 bool TakeName = true);
705
706 /// Mutate function by change the arguments & the return type.
707 /// \param ArgMutate mutates the function arguments.
708 /// \param RetMutate mutates the function return value.
709 /// \param TakeName Take the original function's name if a new function with
710 /// different type needs to be created.
711 void mutateFunction(
712 Function *F,
713 std::function<std::string(CallInst *, std::vector<Value *> &, Type *&RetTy)>
714 ArgMutate,
715 std::function<Instruction *(CallInst *)> RetMutate,
716 BuiltinFuncMangleInfo *Mangle = nullptr, AttributeList *Attrs = nullptr,
717 bool TakeName = true);
718
719 /// Add a call instruction at \p Pos.
720 CallInst *addCallInst(Module *M, StringRef FuncName, Type *RetTy,
721 ArrayRef<Value *> Args, AttributeList *Attrs,
722 Instruction *Pos, BuiltinFuncMangleInfo *Mangle = nullptr,
723 StringRef InstName = SPIR_TEMP_NAME_PREFIX_CALL,
724 bool TakeFuncName = true);
725
726 /// Check if an LLVM type is spirv.CooperativeMatrixKHR.
727 bool isLLVMCooperativeMatrixType(llvm::Type *Ty);
728
729 /// Add a call instruction for SPIR-V builtin function.
730 CallInst *addCallInstSPIRV(Module *M, StringRef FuncName, Type *RetTy,
731 ArrayRef<Value *> Args, AttributeList *Attrs,
732 ArrayRef<Type *> PointerElementTypes,
733 Instruction *Pos, StringRef InstName);
734
735 typedef std::pair<std::vector<Value *>::iterator,
736 std::vector<Value *>::iterator>
737 ValueVecRange;
738
739 /// Add a vector at \param InsPos.
740 Value *addVector(Instruction *InsPos, ValueVecRange Range);
741
742 /// Replace scalar values with a vector created at \param InsPos.
743 void makeVector(Instruction *InsPos, std::vector<Value *> &Ops,
744 ValueVecRange Range);
745
746 /// Get size_t type.
747 IntegerType *getSizetType(Module *M);
748
749 /// Get void(void) function type.
750 Type *getVoidFuncType(Module *M);
751
752 /// Get void(void) function pointer type.
753 Type *getVoidFuncPtrType(Module *M, unsigned AddrSpace = 0);
754
755 /// Get a 64 bit integer constant.
756 ConstantInt *getInt64(Module *M, int64_t Value);
757
758 /// Get a 32 bit integer constant.
759 ConstantInt *getInt32(Module *M, int Value);
760
761 /// Get a 32 bit unsigned integer constant.
762 ConstantInt *getUInt32(Module *M, unsigned Value);
763
764 /// Get 32 bit integer constant if the value fits in 32 bits,
765 /// return 64 bit integer constant otherwise
766 ConstantInt *getInt(Module *M, int64_t Value);
767
768 /// Get 32 bit unsigned integer constant if the value fits in 32 bits,
769 /// return 64 bit unsigned integer constant otherwise
770 ConstantInt *getUInt(Module *M, uint64_t Value);
771
772 /// Get a 16 bit unsigned integer constant.
773 ConstantInt *getUInt16(Module *M, unsigned short Value);
774
775 // Get a 32 bit floating point constant.
776 Constant *getFloat32(Module *M, float Value);
777
778 /// Get a 32 bit integer constant vector.
779 std::vector<Value *> getInt32(Module *M, const std::vector<int> &Value);
780
781 /// Get a size_t type constant.
782 ConstantInt *getSizet(Module *M, uint64_t Value);
783
784 /// Get metadata operand as int.
785 int64_t getMDOperandAsInt(MDNode *N, unsigned I);
786
787 /// Get metadata operand as string.
788 StringRef getMDOperandAsString(MDNode *N, unsigned I);
789
790 /// Get metadata operand as another metadata node
791 MDNode *getMDOperandAsMDNode(MDNode *N, unsigned I);
792
793 /// Get metadata operand as type.
794 Type *getMDOperandAsType(MDNode *N, unsigned I);
795
796 /// Get a named metadata as a set of string.
797 /// Assume the named metadata has one or more operands each of which might
798 /// contain set of strings. For instance:
799 /// !opencl.used.optional.core.features = !{!0}
800 /// !0 = !{!"cl_doubles", !"cl_images"}
801 /// or if we linked two modules we may have
802 /// !opencl.used.optional.core.features = !{!0, !1}
803 /// !0 = !{!"cl_doubles"}
804 /// !1 = !{!"cl_images"}
805 std::set<std::string> getNamedMDAsStringSet(Module *M,
806 const std::string &MDName);
807
808 /// Get SPIR-V language by SPIR-V metadata spirv.Source
809 std::tuple<unsigned, unsigned, std::string> getSPIRVSource(Module *M);
810
811 /// Map an unsigned integer constant by applying a function.
812 ConstantInt *mapUInt(Module *M, ConstantInt *I,
813 std::function<unsigned(unsigned)> F);
814
815 /// Map a signed integer constant by applying a function.
816 ConstantInt *mapSInt(Module *M, ConstantInt *I, std::function<int(int)> F);
817
818 /// Get postfix for given decoration.
819 /// The returned postfix does not include "_" at the beginning.
820 std::string getPostfix(Decoration Dec, unsigned Value = 0);
821
822 /// Get postfix _R{ReturnType} for return type
823 /// The returned postfix does not includ "_" at the beginning
824 std::string getPostfixForReturnType(CallInst *CI, bool IsSigned = false);
825 std::string getPostfixForReturnType(const Type *PRetTy, bool IsSigned = false,
826 Type *PointerElementType = nullptr);
827
828 Constant *getScalarOrVectorConstantInt(Type *T, uint64_t V,
829 bool IsSigned = false);
830
831 /// Get a constant int or a constant int array.
832 /// \param T is the type of the constant. It should be an integer type or
833 // an integer pointer type.
834 /// \param Len is the length of the array.
835 /// \param V is the value to fill the array.
836 Value *getScalarOrArrayConstantInt(Instruction *P, Type *T, unsigned Len,
837 uint64_t V, bool IsSigned = false);
838
839 /// Get the array from GEP.
840 /// \param V is a GEP whose pointer operand is a pointer to an array of size
841 /// \param Size.
842 Value *getScalarOrArray(Value *V, unsigned Size, Instruction *Pos);
843
844 void dumpUsers(Value *V, StringRef Prompt = "");
845
846 /// Get SPIR-V type name as spirv.BaseTyName.Postfixes.
847 std::string getSPIRVTypeName(StringRef BaseTyName, StringRef Postfixes = "");
848
849 /// Checks if given type name is either ConstantSampler or ConsantPipeStorage.
850 bool isSPIRVConstantName(StringRef TyName);
851
852 /// Get the sampled type name used in postfix of image type in SPIR-V
853 /// friendly LLVM IR.
854 std::string getSPIRVImageSampledTypeName(SPIRVType *Ty);
855
856 /// Get LLVM type for sampled type of SPIR-V image type by postfix.
857 Type *getLLVMTypeForSPIRVImageSampledTypePostfix(StringRef Postfix,
858 LLVMContext &Ctx);
859
860 /// Convert an LLVM type to a string postfix name.
861 std::string convertTypeToPostfix(Type *T);
862
863 /// Return the unqualified and unsuffixed base name of an image type.
864 /// E.g. opencl.image2d_ro_t.3 -> image2d_t
865 std::string getImageBaseTypeName(StringRef Name);
866
867 /// Extract the image type descriptor from the given image type.
868 SPIRVTypeImageDescriptor getImageDescriptor(Type *Ty);
869
870 /// Return the index of image operands given an image op.
871 size_t getImageOperandsIndex(Op OpCode);
872
873 /// Check if access qualifier is encoded in the type name.
874 bool hasAccessQualifiedName(StringRef TyName);
875
876 /// Get access qualifier from the type name.
877 SPIRVAccessQualifierKind getAccessQualifier(StringRef TyName);
878
879 /// Get access qualifier from the type name.
880 StringRef getAccessQualifierPostfix(SPIRVAccessQualifierKind Access);
881
882 bool eraseUselessFunctions(Module *M);
883
884 /// Erase a function if it is declaration, has internal linkage and has no use.
885 bool eraseIfNoUse(Function *F);
886
887 void eraseIfNoUse(Value *V);
888
889 // Check if a mangled type name is unsigned
890 bool isMangledTypeUnsigned(char Mangled);
891
892 // Check if a mangled type name is signed
893 bool isMangledTypeSigned(char Mangled);
894
895 // Check if a mangled type name is floating point (except half)
896 bool isMangledTypeFP(char Mangled);
897
898 // Check if a mangled type name is half
899 bool isMangledTypeHalf(std::string Mangled);
900
901 // Check if \param I is valid vector size: 2, 3, 4, 8, 16.
902 bool isValidVectorSize(unsigned I);
903
904 enum class ParamType { FLOAT = 0, SIGNED = 1, UNSIGNED = 2, UNKNOWN = 3 };
905
906 ParamType lastFuncParamType(StringRef MangledName);
907
908 // Check if the last function parameter is signed
909 bool isLastFuncParamSigned(StringRef MangledName);
910
911 // Check if a mangled function name contains unsigned atomic type
912 bool containsUnsignedAtomicType(StringRef Name);
913
914 /// Mangle builtin function name.
915 /// \return \param UniqName if \param BtnInfo is null pointer, otherwise
916 /// return IA64 mangled name.
917 std::string mangleBuiltin(StringRef UniqName, ArrayRef<Type *> ArgTypes,
918 BuiltinFuncMangleInfo *BtnInfo);
919
920 /// Extract the true pointer types, expressed as a TypedPointerType, of
921 /// arguments from a mangled function name. If the corresponding type is not a
922 /// pointer type, its value will be the argument's actual type instead. Returns
923 /// true if the function name was successfully demangled.
924 bool getParameterTypes(
925 Function *F, SmallVectorImpl<Type *> &ArgTys,
926 std::function<std::string(StringRef)> StructNameMapFn = nullptr);
927 inline bool getParameterTypes(CallInst *CI, SmallVectorImpl<Type *> &ArgTys) {
928 return getParameterTypes(CI->getCalledFunction(), ArgTys);
929 }
930
931 /// Mangle a function from OpenCL extended instruction set in SPIR-V friendly IR
932 /// manner
933 std::string getSPIRVFriendlyIRFunctionName(OCLExtOpKind ExtOpId,
934 ArrayRef<Type *> ArgTys,
935 Type *RetTy = nullptr);
936
937 /// Mangle a function in SPIR-V friendly IR manner
938 /// \param UniqName full unmangled name of the SPIR-V built-in function that
939 /// contains possible postfixes that depend not on opcode but on decorations or
940 /// return type, for example __spirv_UConvert_Rint_sat.
941 /// \param OC opcode of corresponding built-in instruction. Used to gather info
942 /// for unsigned/constant arguments.
943 /// \param Types of arguments of SPIR-V built-in function
944 /// \param Ops Operands of SPIRVInstruction
945 /// \return IA64 mangled name.
946 std::string getSPIRVFriendlyIRFunctionName(const std::string &UniqName,
947 spv::Op OC, ArrayRef<Type *> ArgTys,
948 ArrayRef<SPIRVValue *> Ops);
949
950 /// Cast a function to a void(void) funtion pointer.
951 Constant *castToVoidFuncPtr(Function *F);
952
953 /// Get i8* with the same address space.
954 PointerType *getInt8PtrTy(PointerType *T);
955
956 /// Cast a value to a i8* by inserting a cast instruction.
957 Value *castToInt8Ptr(Value *V, Instruction *Pos);
958
959 template <> inline void SPIRVMap<std::string, Op, SPIRVOpaqueType>::init() {
960 #define _SPIRV_OP(x) add(#x, OpType##x);
961 _SPIRV_OP(DeviceEvent)
962 _SPIRV_OP(Event)
963 _SPIRV_OP(Image)
964 _SPIRV_OP(Pipe)
965 _SPIRV_OP(Queue)
966 _SPIRV_OP(ReserveId)
967 _SPIRV_OP(Sampler)
968 _SPIRV_OP(SampledImage)
969 _SPIRV_OP(PipeStorage)
970 // SPV_INTEL_device_side_avc_motion_estimation types
971 _SPIRV_OP(AvcMcePayloadINTEL)
972 _SPIRV_OP(AvcImePayloadINTEL)
973 _SPIRV_OP(AvcRefPayloadINTEL)
974 _SPIRV_OP(AvcSicPayloadINTEL)
975 _SPIRV_OP(AvcMceResultINTEL)
976 _SPIRV_OP(AvcImeResultINTEL)
977 _SPIRV_OP(AvcImeResultSingleReferenceStreamoutINTEL)
978 _SPIRV_OP(AvcImeResultDualReferenceStreamoutINTEL)
979 _SPIRV_OP(AvcImeSingleReferenceStreaminINTEL)
980 _SPIRV_OP(AvcImeDualReferenceStreaminINTEL)
981 _SPIRV_OP(AvcRefResultINTEL)
982 _SPIRV_OP(AvcSicResultINTEL)
983 _SPIRV_OP(VmeImageINTEL)
984 _SPIRV_OP(BufferSurfaceINTEL)
985 _SPIRV_OP(CooperativeMatrixKHR)
986 #undef _SPIRV_OP
987 add("JointMatrixINTEL", internal::OpTypeJointMatrixINTEL);
988 }
989
990 // Check if the module contains llvm.loop.* metadata
991 bool hasLoopMetadata(const Module *M);
992
993 // Check if CI is a call to instruction from OpenCL Extended Instruction Set.
994 // If so, return it's extended opcode in ExtOp.
995 bool isSPIRVOCLExtInst(const CallInst *CI, OCLExtOpKind *ExtOp);
996
997 /// Returns true if a function name corresponds to an OpenCL builtin that is not
998 /// expected to have name mangling.
999 bool isNonMangledOCLBuiltin(StringRef Name);
1000
1001 // check LLVM Intrinsics type(s) for validity
1002 bool checkTypeForSPIRVExtendedInstLowering(IntrinsicInst *II, SPIRVModule *BM);
1003
1004 /// Decode SPIR-V type name in the format spirv.{TypeName}._{Postfixes}
1005 /// where Postfixes are strings separated by underscores.
1006 /// \return TypeName.
1007 /// \param Strs contains the integers decoded from postfixes.
1008 std::string decodeSPIRVTypeName(StringRef Name,
1009 SmallVectorImpl<std::string> &Strs);
1010
1011 // Copy attributes from function to call site.
1012 CallInst *setAttrByCalledFunc(CallInst *Call);
1013 bool isSPIRVBuiltinVariable(GlobalVariable *GV, SPIRVBuiltinVariableKind *Kind);
1014 // Transform builtin variable from GlobalVariable to builtin call.
1015 // e.g.
1016 // - GlobalInvocationId[x] -> _Z33__spirv_BuiltInGlobalInvocationIdi(x)
1017 // - WorkDim -> _Z22__spirv_BuiltInWorkDimv()
1018 bool lowerBuiltinVariableToCall(GlobalVariable *GV,
1019 SPIRVBuiltinVariableKind Kind);
1020 // Transform all builtin variables into calls
1021 bool lowerBuiltinVariablesToCalls(Module *M);
1022
1023 // Transform all builtin calls into variables
1024 bool lowerBuiltinCallsToVariables(Module *M);
1025
1026 // Transform all builtins into variables or calls
1027 // depending on user specification
1028 bool lowerBuiltins(SPIRVModule *BM, Module *M);
1029
1030 /// \brief Post-process OpenCL or SPIRV builtin function returning struct type.
1031 ///
1032 /// Some builtin functions are translated to SPIR-V instructions with
1033 /// struct type result, e.g. NDRange creation functions. Such functions
1034 /// need to be post-processed to return the struct through sret argument.
1035 bool postProcessBuiltinReturningStruct(Function *F);
1036
1037 /// \brief Post-process OpenCL or SPIRV builtin function having array argument.
1038 ///
1039 /// These functions are translated to functions with array type argument
1040 /// first, then post-processed to have pointer arguments.
1041 bool postProcessBuiltinWithArrayArguments(Function *F, StringRef DemangledName);
1042
1043 bool postProcessBuiltinsReturningStruct(Module *M, bool IsCpp = false);
1044
1045 bool postProcessBuiltinsWithArrayArguments(Module *M, bool IsCpp = false);
1046
1047 template <typename T>
1048 MetadataAsValue *map2MDString(LLVMContext &C, SPIRVValue *V);
1049
1050 /// \param MangledName LLVM function name.
1051 /// \param DemangledName demangled name of the input function if it is the
1052 /// translator's internal built-in function.
1053 /// \returns true if MangledName is the name of the translator's internal
1054 /// built-in function, false for other functions.
1055 /// Used for 'mini'-floats conversion functions
1056 bool isInternalSPIRVBuiltin(StringRef MangledName, std::string &DemangledName);
1057
1058 // Wrapper around SPIR-V 1.6.4 FP Encoding to be used in the conversion
1059 // descriptor
1060 enum FPEncodingWrap {
1061 Integer = FPEncoding::FPEncodingMax - 1,
1062 IEEE754 = FPEncoding::FPEncodingMax,
1063 BF16 = FPEncoding::FPEncodingBFloat16KHR,
1064 E4M3 = FPEncoding::FPEncodingFloat8E4M3EXT,
1065 E5M2 = FPEncoding::FPEncodingFloat8E5M2EXT,
1066 E2M1 = internal::FPEncodingFloat4E2M1INTEL,
1067 };
1068
1069 // Structure describing non-trivial conversions (FP8 and int4)
1070 struct FPConversionDesc {
1071 FPEncodingWrap SrcEncoding;
1072 FPEncodingWrap DstEncoding;
1073 SPIRVWord ConvOpCode;
1074
1075 // To use as a key in std::map
1076 bool operator==(const FPConversionDesc &Other) const {
1077 return SrcEncoding == Other.SrcEncoding &&
1078 DstEncoding == Other.DstEncoding && ConvOpCode == Other.ConvOpCode;
1079 }
1080
1081 bool operator<(const FPConversionDesc &Other) const {
1082 if (ConvOpCode != Other.ConvOpCode)
1083 return ConvOpCode < Other.ConvOpCode;
1084 if (SrcEncoding != Other.SrcEncoding)
1085 return SrcEncoding < Other.SrcEncoding;
1086 return DstEncoding < Other.DstEncoding;
1087 }
1088 };
1089
1090 // Maps internal builtin name to conversion descriptor
1091 typedef SPIRVMap<llvm::StringRef, FPConversionDesc> FPConvertToEncodingMap;
1092
1093 // clang-format off
1094 template <> inline void FPConvertToEncodingMap::init() {
1095 // 4-bit conversions
1096 add("ConvertE2M1ToE4M3INTEL",
1097 {FPEncodingWrap::E2M1, FPEncodingWrap::E4M3, OpFConvert});
1098 add("ConvertE2M1ToE5M2INTEL",
1099 {FPEncodingWrap::E2M1, FPEncodingWrap::E5M2, OpFConvert});
1100 add("ConvertE2M1ToFP16INTEL",
1101 {FPEncodingWrap::E2M1, FPEncodingWrap::IEEE754, OpFConvert});
1102 add("ConvertE2M1ToBF16INTEL",
1103 {FPEncodingWrap::E2M1, FPEncodingWrap::BF16, OpFConvert});
1104
1105 add("ConvertInt4ToE4M3INTEL",
1106 {FPEncodingWrap::Integer, FPEncodingWrap::E4M3, OpConvertSToF});
1107 add("ConvertInt4ToE5M2INTEL",
1108 {FPEncodingWrap::Integer, FPEncodingWrap::E5M2, OpConvertSToF});
1109 add("ConvertInt4ToFP16INTEL",
1110 {FPEncodingWrap::Integer, FPEncodingWrap::IEEE754, OpConvertSToF});
1111 add("ConvertInt4ToBF16INTEL",
1112 {FPEncodingWrap::Integer, FPEncodingWrap::BF16, OpConvertSToF});
1113 add("ConvertInt4ToInt8INTEL",
1114 {FPEncodingWrap::Integer, FPEncodingWrap::Integer, OpSConvert});
1115
1116 add("ConvertFP16ToE2M1INTEL",
1117 {FPEncodingWrap::IEEE754, FPEncodingWrap::E2M1, OpFConvert});
1118 add("ConvertBF16ToE2M1INTEL",
1119 {FPEncodingWrap::BF16, FPEncodingWrap::E2M1, OpFConvert});
1120 add("ConvertFP16ToInt4INTEL",
1121 {FPEncodingWrap::IEEE754, FPEncodingWrap::Integer, OpConvertFToS});
1122 add("ConvertBF16ToInt4INTEL",
1123 {FPEncodingWrap::BF16, FPEncodingWrap::Integer, OpConvertFToS});
1124
1125 // 8-bit conversions
1126 add("ConvertE4M3ToFP16EXT",
1127 {FPEncodingWrap::E4M3, FPEncodingWrap::IEEE754, OpFConvert});
1128 add("ConvertE5M2ToFP16EXT",
1129 {FPEncodingWrap::E5M2, FPEncodingWrap::IEEE754, OpFConvert});
1130 add("ConvertE4M3ToBF16EXT",
1131 {FPEncodingWrap::E4M3, FPEncodingWrap::BF16, OpFConvert});
1132 add("ConvertE5M2ToBF16EXT",
1133 {FPEncodingWrap::E5M2, FPEncodingWrap::BF16, OpFConvert});
1134 add("ConvertFP16ToE4M3EXT",
1135 {FPEncodingWrap::IEEE754, FPEncodingWrap::E4M3, OpFConvert});
1136 add("ConvertFP16ToE5M2EXT",
1137 {FPEncodingWrap::IEEE754, FPEncodingWrap::E5M2, OpFConvert});
1138 add("ConvertBF16ToE4M3EXT",
1139 {FPEncodingWrap::BF16, FPEncodingWrap::E4M3, OpFConvert});
1140 add("ConvertBF16ToE5M2EXT",
1141 {FPEncodingWrap::BF16, FPEncodingWrap::E5M2, OpFConvert});
1142
1143 // SPV_INTEL_fp_conversions
1144 add("ClampConvertFP16ToE2M1INTEL",
1145 {FPEncodingWrap::IEEE754, FPEncodingWrap::E2M1,
1146 internal::OpClampConvertFToFINTEL});
1147 add("ClampConvertBF16ToE2M1INTEL",
1148 {FPEncodingWrap::BF16, FPEncodingWrap::E2M1,
1149 internal::OpClampConvertFToFINTEL});
1150 add("ClampConvertFP16ToE4M3INTEL",
1151 {FPEncodingWrap::IEEE754, FPEncodingWrap::E4M3,
1152 internal::OpClampConvertFToFINTEL});
1153 add("ClampConvertBF16ToE4M3INTEL",
1154 {FPEncodingWrap::BF16, FPEncodingWrap::E4M3,
1155 internal::OpClampConvertFToFINTEL});
1156 add("ClampConvertFP16ToE5M2INTEL",
1157 {FPEncodingWrap::IEEE754, FPEncodingWrap::E5M2,
1158 internal::OpClampConvertFToFINTEL});
1159 add("ClampConvertBF16ToE5M2INTEL",
1160 {FPEncodingWrap::BF16, FPEncodingWrap::E5M2,
1161 internal::OpClampConvertFToFINTEL});
1162 add("ClampConvertFP16ToInt4INTEL",
1163 {FPEncodingWrap::IEEE754, FPEncodingWrap::Integer,
1164 internal::OpClampConvertFToSINTEL});
1165 add("ClampConvertBF16ToInt4INTEL",
1166 {FPEncodingWrap::BF16, FPEncodingWrap::Integer,
1167 internal::OpClampConvertFToSINTEL});
1168
1169 add("StochasticRoundFP16ToE5M2INTEL",
1170 {FPEncodingWrap::IEEE754, FPEncodingWrap::E5M2,
1171 internal::OpStochasticRoundFToFINTEL});
1172 add("StochasticRoundFP16ToE4M3INTEL",
1173 {FPEncodingWrap::IEEE754, FPEncodingWrap::E4M3,
1174 internal::OpStochasticRoundFToFINTEL});
1175 add("StochasticRoundBF16ToE5M2INTEL",
1176 {FPEncodingWrap::BF16, FPEncodingWrap::E5M2,
1177 internal::OpStochasticRoundFToFINTEL});
1178 add("StochasticRoundBF16ToE4M3INTEL",
1179 {FPEncodingWrap::BF16, FPEncodingWrap::E4M3,
1180 internal::OpStochasticRoundFToFINTEL});
1181 add("StochasticRoundFP16ToE2M1INTEL",
1182 {FPEncodingWrap::IEEE754, FPEncodingWrap::E2M1,
1183 internal::OpStochasticRoundFToFINTEL});
1184 add("StochasticRoundBF16ToE2M1INTEL",
1185 {FPEncodingWrap::BF16, FPEncodingWrap::E2M1,
1186 internal::OpStochasticRoundFToFINTEL});
1187 add("ClampStochasticRoundFP16ToInt4INTEL",
1188 {FPEncodingWrap::IEEE754, FPEncodingWrap::Integer,
1189 internal::OpClampStochasticRoundFToSINTEL});
1190 add("ClampStochasticRoundBF16ToInt4INTEL",
1191 {FPEncodingWrap::BF16, FPEncodingWrap::Integer,
1192 internal::OpClampStochasticRoundFToSINTEL});
1193
1194 add("ClampStochasticRoundFP16ToE5M2INTEL",
1195 {FPEncodingWrap::IEEE754, FPEncodingWrap::E5M2,
1196 internal::OpClampStochasticRoundFToFINTEL});
1197 add("ClampStochasticRoundFP16ToE4M3INTEL",
1198 {FPEncodingWrap::IEEE754, FPEncodingWrap::E4M3,
1199 internal::OpClampStochasticRoundFToFINTEL});
1200 add("ClampStochasticRoundBF16ToE5M2INTEL",
1201 {FPEncodingWrap::BF16, FPEncodingWrap::E5M2,
1202 internal::OpClampStochasticRoundFToFINTEL});
1203 add("ClampStochasticRoundBF16ToE4M3INTEL",
1204 {FPEncodingWrap::BF16, FPEncodingWrap::E4M3,
1205 internal::OpClampStochasticRoundFToFINTEL});
1206 }
1207
1208 // clang-format on
1209
1210 } // namespace SPIRV
1211
1212 #endif // SPIRV_SPIRVINTERNAL_H