31#include "llvm/IR/IntrinsicsSPIRV.h"
67#define DEBUG_TYPE "spirv-emit-intrinsics"
70#define GET_BuiltinGroup_DECL
71#include "SPIRVGenTables.inc"
76class GlobalVariableUsers {
77 template <
typename T1,
typename T2>
78 using OneToManyMapTy = DenseMap<T1, SmallPtrSet<T2, 4>>;
80 OneToManyMapTy<const GlobalVariable *, const Function *> GlobalIsUsedByFun;
82 void collectGlobalUsers(
83 const GlobalVariable *GV,
84 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
85 &GlobalIsUsedByGlobal) {
87 while (!
Stack.empty()) {
91 GlobalIsUsedByFun[GV].insert(
I->getFunction());
96 GlobalIsUsedByGlobal[GV].insert(UserGV);
101 Stack.append(
C->user_begin(),
C->user_end());
105 bool propagateGlobalToGlobalUsers(
106 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
107 &GlobalIsUsedByGlobal) {
110 for (
auto &[GV, UserGlobals] : GlobalIsUsedByGlobal) {
111 OldUsersGlobals.
assign(UserGlobals.begin(), UserGlobals.end());
112 for (
const GlobalVariable *UserGV : OldUsersGlobals) {
113 auto It = GlobalIsUsedByGlobal.find(UserGV);
114 if (It == GlobalIsUsedByGlobal.end())
122 void propagateGlobalToFunctionReferences(
123 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
124 &GlobalIsUsedByGlobal) {
125 for (
auto &[GV, UserGlobals] : GlobalIsUsedByGlobal) {
126 auto &UserFunctions = GlobalIsUsedByFun[GV];
127 for (
const GlobalVariable *UserGV : UserGlobals) {
128 auto It = GlobalIsUsedByFun.find(UserGV);
129 if (It == GlobalIsUsedByFun.end())
140 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
141 GlobalIsUsedByGlobal;
142 GlobalIsUsedByFun.clear();
143 for (GlobalVariable &GV :
M.globals())
144 collectGlobalUsers(&GV, GlobalIsUsedByGlobal);
147 while (propagateGlobalToGlobalUsers(GlobalIsUsedByGlobal))
150 propagateGlobalToFunctionReferences(GlobalIsUsedByGlobal);
153 using FunctionSetType =
decltype(GlobalIsUsedByFun)::mapped_type;
154 const FunctionSetType &
155 getTransitiveUserFunctions(
const GlobalVariable &GV)
const {
156 auto It = GlobalIsUsedByFun.find(&GV);
157 if (It != GlobalIsUsedByFun.end())
160 static const FunctionSetType
Empty{};
165static bool isaGEP(
const Value *
V) {
171static std::optional<uint64_t> getByteAddressingMultiplier(
Type *Ty) {
177 return AT->getNumElements();
193static void foldConstantOffsetIntoArrayIndex(
Function &
F) {
196 if (!Outer ||
Outer->getNumIndices() != 1 ||
197 !
Outer->getSourceElementType()->isIntegerTy(8))
201 if (!
Offset || !Inner || Inner->getNumIndices() != 1)
203 Value *Index = Inner->getOperand(1);
204 std::optional<uint64_t> Stride =
205 getByteAddressingMultiplier(Inner->getSourceElementType());
210 Type *IdxTy =
F.getDataLayout().getIndexType(Inner->getType());
211 int64_t Bytes =
Offset->getValue()
214 int64_t
Size = *Stride;
223 Value *NewIndex =
B.CreateAdd(
B.CreateSExtOrTrunc(Index, IdxTy),
225 Value *Ptr =
B.CreateGEP(Inner->getSourceElementType(),
226 Inner->getPointerOperand(), NewIndex,
"", NW);
227 if (int64_t Remainder =
mod(Bytes,
Size))
228 Ptr =
B.CreateGEP(
B.getInt8Ty(), Ptr, ConstantInt::get(IdxTy, Remainder),
231 Outer->replaceAllUsesWith(Ptr);
232 Outer->eraseFromParent();
233 if (Inner->use_empty())
234 Inner->eraseFromParent();
238class SPIRVEmitIntrinsicsImpl
239 :
public InstVisitor<SPIRVEmitIntrinsicsImpl, Instruction *> {
240 const SPIRVTargetMachine &TM;
241 SPIRVGlobalRegistry *GR =
nullptr;
243 bool TrackConstants =
true;
244 bool HaveFunPtrs =
false;
245 bool CanUseAnyVectorRank =
false;
246 DenseMap<Instruction *, Constant *> AggrConsts;
247 DenseMap<Instruction *, Type *> AggrConstTypes;
248 SmallPtrSet<Instruction *, 0> AggrStores;
249 GlobalVariableUsers GVUsers;
250 SmallPtrSet<Value *, 0> Named;
252 SmallPtrSet<GetElementPtrInst *, 4> InvalidGEPs;
255 MapVector<Function *, SmallVector<std::pair<unsigned, Type *>>> FDeclPtrTys;
258 bool CanTodoType =
true;
259 unsigned TodoTypeSz = 0;
260 DenseMap<Value *, bool> TodoType;
261 void insertTodoType(
Value *
Op) {
263 if (CanTodoType && !isaGEP(
Op)) {
264 auto It = TodoType.try_emplace(
Op,
true);
269 void eraseTodoType(
Value *
Op) {
270 auto It = TodoType.find(
Op);
271 if (It != TodoType.end() && It->second) {
279 auto It = TodoType.find(
Op);
280 return It != TodoType.end() && It->second;
284 SmallPtrSet<Instruction *, 0> TypeValidated;
287 SmallVector<Instruction *> RetypedToRevalidate;
288 bool RevalidatingRetyped =
false;
291 enum WellKnownTypes { Event };
294 Type *deduceElementType(
Value *
I,
bool UnknownElemTypeI8);
295 Type *deduceElementTypeHelper(
Value *
I,
bool UnknownElemTypeI8);
296 Type *deduceElementTypeHelper(
Value *
I, SmallPtrSetImpl<Value *> &Visited,
297 bool UnknownElemTypeI8,
298 bool IgnoreKnownType =
false);
299 Type *deduceElementTypeByValueDeep(
Type *ValueTy,
Value *Operand,
300 bool UnknownElemTypeI8);
301 Type *deduceElementTypeByValueDeep(
Type *ValueTy,
Value *Operand,
302 SmallPtrSetImpl<Value *> &Visited,
303 bool UnknownElemTypeI8,
304 std::optional<unsigned> AddrSpace = {});
306 SmallPtrSetImpl<Value *> &Visited,
307 bool UnknownElemTypeI8);
309 bool UnknownElemTypeI8);
312 Type *deduceNestedTypeHelper(User *U,
bool UnknownElemTypeI8);
313 Type *deduceNestedTypeHelper(User *U,
Type *Ty,
314 SmallPtrSetImpl<Value *> &Visited,
315 bool UnknownElemTypeI8);
319 deduceOperandElementType(Instruction *
I,
320 SmallPtrSetImpl<Instruction *> *IncompleteRets,
321 const SmallPtrSetImpl<Value *> *AskOps =
nullptr,
322 bool IsPostprocessing =
false);
327 void insertCompositeAggregateArms(Instruction *
I,
IRBuilder<> &
B);
329 void simplifyNullAddrSpaceCasts();
331 Type *reconstructType(
Value *
Op,
bool UnknownElemTypeI8,
332 bool IsPostprocessing);
334 void replaceMemInstrUses(Instruction *Old, Instruction *New,
IRBuilder<> &
B);
336 bool insertAssignPtrTypeIntrs(Instruction *
I,
IRBuilder<> &
B,
337 bool UnknownElemTypeI8);
339 void insertAssignPtrTypeTargetExt(TargetExtType *AssignedType,
Value *
V,
341 void replacePointerOperandWithPtrCast(Instruction *
I,
Value *Pointer,
342 Type *ExpectedElementType,
343 unsigned OperandToReplace,
345 void insertPtrCastOrAssignTypeInstr(Instruction *
I,
IRBuilder<> &
B);
346 bool shouldTryToAddMemAliasingDecoration(Instruction *Inst);
348 void insertConstantsForFPFastMathDefault(
Module &M);
351 void processGlobalValue(GlobalVariable &GV,
IRBuilder<> &
B);
354 Type *deduceFunParamElementType(
Function *
F,
unsigned OpIdx);
356 SmallPtrSetImpl<Function *> &FVisited);
358 bool deduceOperandElementTypeCalledFunction(
360 Type *&KnownElemTy,
bool &Incomplete);
361 void deduceOperandElementTypeFunctionPointer(
363 Type *&KnownElemTy,
bool IsPostprocessing);
364 bool deduceOperandElementTypeFunctionRet(
365 Instruction *
I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
366 const SmallPtrSetImpl<Value *> *AskOps,
bool IsPostprocessing,
370 void replaceUsesOfWithSpvPtrcast(
Value *
Op,
Type *ElemTy, Instruction *
I,
371 DenseMap<Function *, CallInst *> Ptrcasts);
373 DenseSet<std::pair<Value *, Value *>> &VisitedSubst);
376 DenseSet<std::pair<Value *, Value *>> &VisitedSubst);
377 void propagateElemTypeRec(
Value *
Op,
Type *PtrElemTy,
Type *CastElemTy,
378 DenseSet<std::pair<Value *, Value *>> &VisitedSubst,
379 SmallPtrSetImpl<Value *> &Visited,
380 DenseMap<Function *, CallInst *> Ptrcasts);
383 void replaceAllUsesWithAndErase(
IRBuilder<> &
B, Instruction *Src,
384 Instruction *Dest,
bool DeleteOld =
true);
388 GetElementPtrInst *simplifyZeroLengthArrayGepInst(GetElementPtrInst *
GEP);
391 bool postprocessTypes(
Module &M);
392 bool processFunctionPointers(
Module &M);
393 void parseFunDeclarations(
Module &M);
394 void useRoundingMode(ConstrainedFPIntrinsic *FPI,
IRBuilder<> &
B);
395 bool processMaskedMemIntrinsic(IntrinsicInst &
I);
396 bool convertMaskedMemIntrinsics(
Module &M);
397 bool preprocessModule(
Module &M);
398 void preprocessBoolVectorBitcasts(
Function &
F);
399 void scalarizeVectorPtrCasts(
Function &
F);
418 Expected<bool> walkLogicalAccessChain(
419 GetElementPtrInst &
GEP,
420 const std::function<
void(
Type *PointedType,
uint64_t Index)>
423 uint64_t Multiplier)> &OnDynamicIndexing);
425 bool walkLogicalAccessChainDynamic(
427 const std::function<
void(
Type *,
uint64_t)> &OnLiteralIndexing,
430 Expected<bool> walkLogicalAccessChainConstant(
432 const std::function<
void(
Type *,
uint64_t)> &OnLiteralIndexing);
434 void recordAccessChainError(GetElementPtrInst &
GEP,
Error Err);
440 Type *getGEPType(GetElementPtrInst *
GEP);
447 Type *getGEPTypeLogical(GetElementPtrInst *
GEP);
449 Instruction *buildLogicalAccessChainFromGEP(GetElementPtrInst &
GEP);
454 SPIRVEmitIntrinsicsImpl(
const SPIRVTargetMachine &TM) : TM(TM) {}
457 Instruction *visitGetElementPtrInst(GetElementPtrInst &
I);
460 Instruction *visitInsertElementInst(InsertElementInst &
I);
461 Instruction *visitExtractElementInst(ExtractElementInst &
I);
463 Instruction *visitExtractValueInst(ExtractValueInst &
I);
467 Instruction *visitAtomicCmpXchgInst(AtomicCmpXchgInst &
I);
472 bool runOnModule(
Module &M);
475class SPIRVEmitIntrinsicsLegacy :
public ModulePass {
476 const SPIRVTargetMachine &TM;
480 SPIRVEmitIntrinsicsLegacy(
const SPIRVTargetMachine &TM)
481 : ModulePass(ID), TM(TM) {}
483 StringRef getPassName()
const override {
return "SPIRV emit intrinsics"; }
485 bool runOnModule(
Module &M)
override {
486 return SPIRVEmitIntrinsicsImpl(TM).runOnModule(M);
492 Intrinsic::experimental_convergence_loop,
493 Intrinsic::experimental_convergence_anchor>());
496bool expectIgnoredInIRTranslation(
const Instruction *
I) {
499 Intrinsic::spv_resource_handlefrombinding_mdname,
500 Intrinsic::spv_resource_getbasepointer,
501 Intrinsic::spv_resource_getpointer>());
508 return getPointerRoot(
V);
514char SPIRVEmitIntrinsicsLegacy::ID = 0;
517 "SPIRV emit intrinsics",
false,
false)
544 B.SetInsertPoint(
I->getParent()->getFirstNonPHIOrAlloca());
550 B.SetCurrentDebugLocation(
I->getDebugLoc());
551 if (
I->getType()->isVoidTy())
552 B.SetInsertPoint(
I->getNextNode());
554 B.SetInsertPoint(*
I->getInsertionPointAfterDef());
564 if (
I->getType()->isTokenTy())
566 "does not support token type",
572 if (!
I->hasName() ||
I->getType()->isAggregateType() ||
573 expectIgnoredInIRTranslation(
I))
578 bool KeepName = CLOpts.emit_op_names;
584 if (
F &&
F->getName().starts_with(
"llvm.spv.alloca"))
595 std::vector<Value *> Args = {
598 B.CreateIntrinsic(Intrinsic::spv_assign_name, {
I->getType()}, Args);
601void SPIRVEmitIntrinsicsImpl::replaceAllUsesWith(
Value *Src,
Value *Dest,
605 if (isTodoType(Src)) {
608 insertTodoType(Dest);
612void SPIRVEmitIntrinsicsImpl::replaceAllUsesWithAndErase(
IRBuilder<> &
B,
617 std::string
Name = Src->hasName() ? Src->getName().str() :
"";
618 Src->eraseFromParent();
621 if (Named.
insert(Dest).second)
636 V =
V->stripPointerCasts();
666Type *SPIRVEmitIntrinsicsImpl::reconstructType(
Value *
Op,
667 bool UnknownElemTypeI8,
668 bool IsPostprocessing) {
672 if (
auto It = AggrConstTypes.
find(OpI); It != AggrConstTypes.
end())
686 if (UnknownElemTypeI8) {
687 if (!IsPostprocessing)
703 B.SetInsertPointPastAllocas(OpA->getParent());
706 B.SetInsertPoint(
F->getEntryBlock().getFirstNonPHIOrAlloca());
708 Type *OpTy =
Op->getType();
710 SmallVector<Value *, 2>
Args = {
713 CallInst *PtrCasted =
714 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_ptrcast, {
Types},
Args);
719void SPIRVEmitIntrinsicsImpl::replaceUsesOfWithSpvPtrcast(
721 DenseMap<Function *, CallInst *> Ptrcasts) {
723 CallInst *PtrCastedI =
nullptr;
724 auto It = Ptrcasts.
find(
F);
725 if (It == Ptrcasts.
end()) {
726 PtrCastedI = buildSpvPtrcast(
F,
Op, ElemTy);
727 Ptrcasts[
F] = PtrCastedI;
729 PtrCastedI = It->second;
731 I->replaceUsesOfWith(
Op, PtrCastedI);
734void SPIRVEmitIntrinsicsImpl::propagateElemType(
736 DenseSet<std::pair<Value *, Value *>> &VisitedSubst) {
737 DenseMap<Function *, CallInst *> Ptrcasts;
739 for (
auto *U :
Users) {
742 if (!VisitedSubst.insert(std::make_pair(U,
Op)).second)
747 if (isaGEP(UI) || TypeValidated.
find(UI) != TypeValidated.
end())
748 replaceUsesOfWithSpvPtrcast(
Op, ElemTy, UI, Ptrcasts);
752void SPIRVEmitIntrinsicsImpl::propagateElemTypeRec(
754 DenseSet<std::pair<Value *, Value *>> &VisitedSubst) {
755 SmallPtrSet<Value *, 0> Visited;
756 DenseMap<Function *, CallInst *> Ptrcasts;
757 propagateElemTypeRec(
Op, PtrElemTy, CastElemTy, VisitedSubst, Visited,
758 std::move(Ptrcasts));
761void SPIRVEmitIntrinsicsImpl::propagateElemTypeRec(
763 DenseSet<std::pair<Value *, Value *>> &VisitedSubst,
764 SmallPtrSetImpl<Value *> &Visited,
765 DenseMap<Function *, CallInst *> Ptrcasts) {
769 for (
auto *U :
Users) {
772 if (!VisitedSubst.insert(std::make_pair(U,
Op)).second)
777 if (isaGEP(UI) || TypeValidated.
find(UI) != TypeValidated.
end())
778 replaceUsesOfWithSpvPtrcast(
Op, CastElemTy, UI, Ptrcasts);
785Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByValueDeep(
786 Type *ValueTy,
Value *Operand,
bool UnknownElemTypeI8) {
787 SmallPtrSet<Value *, 0> Visited;
788 return deduceElementTypeByValueDeep(ValueTy, Operand, Visited,
792Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByValueDeep(
793 Type *ValueTy,
Value *Operand, SmallPtrSetImpl<Value *> &Visited,
794 bool UnknownElemTypeI8, std::optional<unsigned> AddrSpace) {
799 deduceElementTypeHelper(Operand, Visited, UnknownElemTypeI8))
801 NestedTy, AddrSpace.value_or(PtrTy->getAddressSpace()));
811Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByUsersDeep(
812 Value *
Op, SmallPtrSetImpl<Value *> &Visited,
bool UnknownElemTypeI8) {
824 for (User *OpU :
Op->users()) {
826 if (
Type *Ty = deduceElementTypeHelper(Inst, Visited, UnknownElemTypeI8))
838 Function *CalledF,
unsigned OpIdx) {
843 if (OpIdx == 0 && (Name ==
"printf" || Name ==
"get_fence"))
846 if (OpIdx == 2 && (Name ==
"capture_event_profiling_info" ||
847 Name ==
"__spirv_CaptureEventProfilingInfo"))
854Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeHelper(
Value *
I,
855 bool UnknownElemTypeI8) {
856 SmallPtrSet<Value *, 0> Visited;
857 return deduceElementTypeHelper(
I, Visited, UnknownElemTypeI8);
860void SPIRVEmitIntrinsicsImpl::maybeAssignPtrType(
Type *&Ty,
Value *
Op,
862 bool UnknownElemTypeI8) {
864 if (!UnknownElemTypeI8)
873bool SPIRVEmitIntrinsicsImpl::walkLogicalAccessChainDynamic(
875 const std::function<
void(
Type *,
uint64_t)> &OnLiteralIndexing,
882 if (
ST->getNumElements() == 0)
884 CurType =
ST->getElementType(0);
885 OnLiteralIndexing(CurType, 0);
893 OnDynamicIndexing(AT->getElementType(), Operand, Multiplier);
894 return AT ==
nullptr;
897Expected<bool> SPIRVEmitIntrinsicsImpl::walkLogicalAccessChainConstant(
899 const std::function<
void(
Type *,
uint64_t)> &OnLiteralIndexing) {
905 uint64_t EltTypeSize =
DL.getTypeAllocSize(AT->getElementType());
909 CurType = AT->getElementType();
910 OnLiteralIndexing(CurType, Index);
912 uint32_t StructSize =
DL.getTypeSizeInBits(ST) / 8;
915 const auto &STL =
DL.getStructLayout(ST);
916 unsigned Element = STL->getElementContainingOffset(
Offset);
917 Offset -= STL->getElementOffset(Element);
918 CurType =
ST->getElementType(Element);
919 OnLiteralIndexing(CurType, Element);
921 Type *EltTy = VT->getElementType();
922 TypeSize EltSizeBits =
DL.getTypeSizeInBits(EltTy);
923 assert(EltSizeBits % 8 == 0 &&
924 "Element type size in bits must be a multiple of 8.");
925 uint32_t EltTypeSize = EltSizeBits / 8;
926 if (
Offset >= VT->getNumElements() * EltTypeSize)
928 "Cannot lower an access to vector padding for Logical SPIR-V");
932 OnLiteralIndexing(CurType, Index);
937 "Cannot lower a byte offset within a scalar or padding for "
945Expected<bool> SPIRVEmitIntrinsicsImpl::walkLogicalAccessChain(
946 GetElementPtrInst &
GEP,
947 const std::function<
void(
Type *,
uint64_t)> &OnLiteralIndexing,
951 std::optional<uint64_t> MultiplierOpt =
952 getByteAddressingMultiplier(
GEP.getSourceElementType());
953 assert(MultiplierOpt &&
"We only rewrite byte-addressing GEP");
954 uint64_t Multiplier = *MultiplierOpt;
957 Value *Src = getPointerRoot(
GEP.getPointerOperand());
958 Type *CurType = deduceElementType(Src,
true);
961 "Cannot lower byte addressing with an unsized type for Logical SPIR-V");
967 APInt
Offset(
DL.getIndexSizeInBits(
GEP.getPointerAddressSpace()), 0);
969 assert(IsConstant &&
"a constant index must give a constant offset");
970 return walkLogicalAccessChainConstant(CurType,
Offset.getZExtValue(),
974 return walkLogicalAccessChainDynamic(CurType, Operand, Multiplier,
975 OnLiteralIndexing, OnDynamicIndexing);
978void SPIRVEmitIntrinsicsImpl::recordAccessChainError(GetElementPtrInst &
GEP,
982 std::move(AccessChainErrors),
984 GEP.getFunction()->getName() +
"')"));
991Value *SPIRVEmitIntrinsicsImpl::truncateGEPIndex(
Value *Idx,
Type *IdxTy,
997 insertAssignTypeIntrs(TruncI,
B);
1001Instruction *SPIRVEmitIntrinsicsImpl::buildLogicalAccessChainFromGEP(
1002 GetElementPtrInst &
GEP) {
1008 B.SetInsertPoint(&
GEP);
1010 std::vector<Value *> Indices;
1011 Indices.push_back(ConstantInt::get(
1012 IntegerType::getInt32Ty(CurrF->
getContext()), 0,
false));
1013 Type *IdxTy =
DL.getIndexType(
GEP.getPointerOperandType());
1014 auto Result = walkLogicalAccessChain(
1017 Indices.push_back(ConstantInt::get(IdxTy, Index,
false));
1023 uint32_t EltTypeSize =
DL.getTypeSizeInBits(EltType) / 8;
1025 if (Multiplier == EltTypeSize) {
1027 }
else if (EltTypeSize % Multiplier == 0) {
1030 EltTypeSize / Multiplier,
1034 ConstantInt::get(
Offset->getType(), Multiplier,
1037 Index =
B.CreateUDiv(Index,
1038 ConstantInt::get(
Offset->getType(), EltTypeSize,
1042 Indices.push_back(Index);
1045 recordAccessChainError(
GEP,
Result.takeError());
1049 B.SetInsertPoint(&
GEP);
1051 SmallVector<Value *, 4>
Args;
1052 Args.push_back(
B.getInt1(
GEP.isInBounds()));
1053 Args.push_back(
GEP.getOperand(0));
1056 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, {
Types}, {
Args});
1057 replaceAllUsesWithAndErase(
B, &
GEP, NewI);
1061Type *SPIRVEmitIntrinsicsImpl::getGEPTypeLogical(GetElementPtrInst *
GEP) {
1065 Type *CurType =
GEP->getResultElementType();
1067 auto Result = walkLogicalAccessChain(
1068 *
GEP, [&CurType](
Type *EltType,
uint64_t Index) { CurType = EltType; },
1071 recordAccessChainError(*
GEP,
Result.takeError());
1075 return *
Result ?
GEP->getResultElementType() : CurType;
1078Type *SPIRVEmitIntrinsicsImpl::getGEPType(GetElementPtrInst *
Ref) {
1079 if (getByteAddressingMultiplier(
Ref->getSourceElementType()) &&
1081 return getGEPTypeLogical(
Ref);
1088 Ty =
Ref->getSourceElementType();
1092 Ty =
Ref->getResultElementType();
1097Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeHelper(
1098 Value *
I, SmallPtrSetImpl<Value *> &Visited,
bool UnknownElemTypeI8,
1099 bool IgnoreKnownType) {
1105 if (!IgnoreKnownType)
1110 if (!Visited.
insert(
I).second)
1117 maybeAssignPtrType(Ty,
I,
Ref->getAllocatedType(), UnknownElemTypeI8);
1119 Ty = getGEPType(
Ref);
1121 Ty = SGEP->getResultElementType();
1126 KnownTy =
Op->getType();
1128 maybeAssignPtrType(Ty,
I, ElemTy, UnknownElemTypeI8);
1131 Ty = SPIRV::getOriginalFunctionType(*Fn);
1138 std::optional<unsigned> ProgramAS;
1143 SPIRV::Extension::SPV_INTEL_function_pointers))
1147 Ty = deduceElementTypeByValueDeep(
Ref->getValueType(),
Op, Visited,
1148 UnknownElemTypeI8, ProgramAS);
1151 Type *RefTy = deduceElementTypeHelper(
Ref->getPointerOperand(), Visited,
1153 maybeAssignPtrType(Ty,
I, RefTy, UnknownElemTypeI8);
1155 maybeAssignPtrType(Ty,
I,
Ref->getDestTy(), UnknownElemTypeI8);
1157 if (
Type *Src =
Ref->getSrcTy(), *Dest =
Ref->getDestTy();
1159 Ty = deduceElementTypeHelper(
Ref->getOperand(0), Visited,
1165 reconstructType(
Ref->getAggregateOperand(),
false,
false),
1170 Ty = deduceElementTypeHelper(
Op, Visited, UnknownElemTypeI8);
1174 Ty = deduceElementTypeHelper(
Op, Visited, UnknownElemTypeI8);
1176 Type *BestTy =
nullptr;
1178 DenseMap<Type *, unsigned> PhiTys;
1179 for (
int i =
Ref->getNumIncomingValues() - 1; i >= 0; --i) {
1180 Ty = deduceElementTypeByUsersDeep(
Ref->getIncomingValue(i), Visited,
1187 if (It.first->second > MaxN) {
1188 MaxN = It.first->second;
1196 for (
Value *
Op : {
Ref->getTrueValue(),
Ref->getFalseValue()}) {
1200 ? deduceElementTypeHelper(
Op, Visited, UnknownElemTypeI8)
1201 : deduceElementTypeByUsersDeep(
Op, Visited, UnknownElemTypeI8);
1206 static StringMap<unsigned> ResTypeByArg = {
1212 {
"__to_private", 0},
1213 {
"__spirv_GenericCastToPtr_ToGlobal", 0},
1214 {
"__spirv_GenericCastToPtr_ToLocal", 0},
1215 {
"__spirv_GenericCastToPtr_ToPrivate", 0},
1216 {
"__spirv_GenericCastToPtrExplicit_ToGlobal", 0},
1217 {
"__spirv_GenericCastToPtrExplicit_ToLocal", 0},
1218 {
"__spirv_GenericCastToPtrExplicit_ToPrivate", 0}};
1222 if (
II && (
II->getIntrinsicID() == Intrinsic::spv_resource_getbasepointer ||
1223 II->getIntrinsicID() == Intrinsic::spv_resource_getpointer)) {
1225 if (HandleType->getTargetExtName() ==
"spirv.Image" ||
1226 HandleType->getTargetExtName() ==
"spirv.SignedImage") {
1227 for (Instruction *U :
II->users()) {
1228 Ty =
U->getAccessType();
1232 }
else if (HandleType->getTargetExtName() ==
"spirv.VulkanBuffer") {
1234 Ty = HandleType->getTypeParameter(0);
1235 if (
II->getIntrinsicID() == Intrinsic::spv_resource_getpointer) {
1249 }
else if (
II &&
II->getIntrinsicID() ==
1250 Intrinsic::spv_generic_cast_to_ptr_explicit) {
1254 std::string DemangledName =
1256 if (DemangledName.length() > 0)
1257 DemangledName = SPIRV::lookupBuiltinNameHelper(DemangledName);
1258 auto AsArgIt = ResTypeByArg.
find(DemangledName);
1259 if (AsArgIt != ResTypeByArg.
end())
1260 Ty = deduceElementTypeHelper(CI->
getArgOperand(AsArgIt->second),
1261 Visited, UnknownElemTypeI8);
1268 if (Ty && !IgnoreKnownType) {
1279Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(User *U,
1280 bool UnknownElemTypeI8) {
1281 SmallPtrSet<Value *, 0> Visited;
1282 return deduceNestedTypeHelper(U,
U->getType(), Visited, UnknownElemTypeI8);
1285Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(
1286 User *U,
Type *OrigTy, SmallPtrSetImpl<Value *> &Visited,
1287 bool UnknownElemTypeI8) {
1297 if (!Visited.
insert(U).second)
1308 if (
Type *NestedTy =
1309 deduceElementTypeHelper(
Op, Visited, UnknownElemTypeI8))
1316 bool Change =
false;
1317 for (
unsigned i = 0; i <
U->getNumOperands(); ++i) {
1319 assert(
Op &&
"Operands should not be null.");
1320 Type *OpTy =
Op->getType();
1321 Type *Ty = DeduceOpTy(
Op, OpTy);
1323 Change |= Ty != OpTy;
1327 Tys, OrigStructTy->isLiteral() ?
"" : OrigStructTy->getName(),
1328 OrigStructTy->isPacked());
1334 Type *OpTy = ArrTy->getElementType();
1335 Type *Ty = DeduceOpTy(
Op, OpTy);
1337 Type *NewTy = ArrayType::get(Ty, ArrTy->getNumElements());
1344 Type *OpTy = VecTy->getElementType();
1345 Type *Ty = DeduceOpTy(
Op, OpTy);
1347 Type *NewTy = VectorType::get(Ty, VecTy->getElementCount());
1358Type *SPIRVEmitIntrinsicsImpl::deduceElementType(
Value *
I,
1359 bool UnknownElemTypeI8) {
1360 if (
Type *Ty = deduceElementTypeHelper(
I, UnknownElemTypeI8))
1362 if (!UnknownElemTypeI8)
1365 return IntegerType::getInt8Ty(
I->getContext());
1369 Value *PointerOperand) {
1375 return I->getType();
1383bool SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeCalledFunction(
1385 Type *&KnownElemTy,
bool &Incomplete) {
1389 std::string DemangledName =
1391 if (DemangledName.length() > 0 &&
1393 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*CalledF);
1394 auto [Grp, Opcode, ExtNo] = SPIRV::mapBuiltinToOpcode(
1395 DemangledName,
ST.getPreferredInstructionSet());
1396 if (Opcode == SPIRV::OpGroupAsyncCopy) {
1397 for (
unsigned i = 0, PtrCnt = 0; i < CI->
arg_size() && PtrCnt < 2; ++i) {
1403 KnownElemTy = ElemTy;
1404 Ops.push_back(std::make_pair(
Op, i));
1406 }
else if (Grp == SPIRV::Atomic || Grp == SPIRV::AtomicFloating) {
1413 case SPIRV::OpAtomicFAddEXT:
1414 case SPIRV::OpAtomicFMinEXT:
1415 case SPIRV::OpAtomicFMaxEXT:
1416 case SPIRV::OpAtomicLoad:
1417 case SPIRV::OpAtomicCompareExchangeWeak:
1418 case SPIRV::OpAtomicCompareExchange:
1419 case SPIRV::OpAtomicExchange:
1420 case SPIRV::OpAtomicIAdd:
1421 case SPIRV::OpAtomicISub:
1422 case SPIRV::OpAtomicOr:
1423 case SPIRV::OpAtomicXor:
1424 case SPIRV::OpAtomicAnd:
1425 case SPIRV::OpAtomicUMin:
1426 case SPIRV::OpAtomicUMax:
1427 case SPIRV::OpAtomicSMin:
1428 case SPIRV::OpAtomicSMax: {
1433 Incomplete = isTodoType(
Op);
1434 Ops.push_back(std::make_pair(
Op, 0));
1436 case SPIRV::OpAtomicStore: {
1445 Incomplete = isTodoType(
Op);
1446 Ops.push_back(std::make_pair(
Op, 0));
1455void SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeFunctionPointer(
1457 Type *&KnownElemTy,
bool IsPostprocessing) {
1461 Ops.push_back(std::make_pair(
Op, std::numeric_limits<unsigned>::max()));
1462 FunctionType *FTy = SPIRV::getOriginalFunctionType(*CI);
1463 bool IsNewFTy =
false, IsIncomplete =
false;
1466 Type *ArgTy = Arg->getType();
1471 if (isTodoType(Arg))
1472 IsIncomplete =
true;
1474 IsIncomplete =
true;
1477 ArgTy = FTy->getFunctionParamType(ParmIdx);
1481 Type *RetTy = FTy->getReturnType();
1488 IsIncomplete =
true;
1490 IsIncomplete =
true;
1493 if (!IsPostprocessing && IsIncomplete)
1496 IsNewFTy ? FunctionType::get(RetTy, ArgTys, FTy->isVarArg()) : FTy;
1499bool SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeFunctionRet(
1500 Instruction *
I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
1501 const SmallPtrSetImpl<Value *> *AskOps,
bool IsPostprocessing,
1513 DenseSet<std::pair<Value *, Value *>> VisitedSubst{std::make_pair(
I,
Op)};
1514 for (User *U :
F->users()) {
1523 propagateElemType(CI, PrevElemTy, VisitedSubst);
1533 for (Instruction *IncompleteRetI : *IncompleteRets)
1534 deduceOperandElementType(IncompleteRetI,
nullptr, AskOps,
1536 }
else if (IncompleteRets) {
1547void SPIRVEmitIntrinsicsImpl::deduceOperandElementType(
1548 Instruction *
I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
1549 const SmallPtrSetImpl<Value *> *AskOps,
bool IsPostprocessing) {
1551 Type *KnownElemTy =
nullptr;
1552 bool Incomplete =
false;
1558 Incomplete = isTodoType(
I);
1559 for (
unsigned i = 0; i <
Ref->getNumIncomingValues(); i++) {
1562 Ops.push_back(std::make_pair(
Op, i));
1568 Incomplete = isTodoType(
I);
1569 Ops.push_back(std::make_pair(
Ref->getPointerOperand(), 0));
1576 Incomplete = isTodoType(
I);
1577 Ops.push_back(std::make_pair(
Ref->getOperand(0), 0));
1581 KnownElemTy =
Ref->getSourceElementType();
1582 Ops.push_back(std::make_pair(
Ref->getPointerOperand(),
1587 KnownElemTy =
Ref->getBaseType();
1588 Ops.push_back(std::make_pair(
Ref->getPointerOperand(),
1591 KnownElemTy =
I->getType();
1598 Value *Root =
Ref->getPointerOperand()->stripPointerCasts();
1607 Ops.push_back(std::make_pair(
Ref->getPointerOperand(),
1611 reconstructType(
Ref->getValueOperand(),
false, IsPostprocessing)))
1616 Ops.push_back(std::make_pair(
Ref->getPointerOperand(),
1624 Incomplete = isTodoType(
Ref->getPointerOperand());
1625 Ops.push_back(std::make_pair(
Ref->getPointerOperand(),
1633 Incomplete = isTodoType(
Ref->getPointerOperand());
1634 Ops.push_back(std::make_pair(
Ref->getPointerOperand(),
1640 Incomplete = isTodoType(
I);
1641 for (
unsigned i = 0; i <
Ref->getNumOperands(); i++) {
1644 Ops.push_back(std::make_pair(
Op, i));
1652 if (deduceOperandElementTypeFunctionRet(
I, IncompleteRets, AskOps,
1653 IsPostprocessing, KnownElemTy,
Op,
1656 Incomplete = isTodoType(CurrF);
1657 Ops.push_back(std::make_pair(
Op, 0));
1663 bool Incomplete0 = isTodoType(Op0);
1664 bool Incomplete1 = isTodoType(Op1);
1666 Type *ElemTy0 = (Incomplete0 && !Incomplete1 && ElemTy1)
1668 : GR->findDeducedElementType(Op0);
1670 KnownElemTy = ElemTy0;
1671 Incomplete = Incomplete0;
1672 Ops.push_back(std::make_pair(Op1, 1));
1673 }
else if (ElemTy1) {
1674 KnownElemTy = ElemTy1;
1675 Incomplete = Incomplete1;
1676 Ops.push_back(std::make_pair(Op0, 0));
1680 deduceOperandElementTypeCalledFunction(CI,
Ops, KnownElemTy, Incomplete);
1681 else if (HaveFunPtrs)
1682 deduceOperandElementTypeFunctionPointer(CI,
Ops, KnownElemTy,
1687 if (!KnownElemTy ||
Ops.size() == 0)
1691 for (
auto &OpIt :
Ops) {
1695 Type *AskTy =
nullptr;
1696 CallInst *AskCI =
nullptr;
1697 if (IsPostprocessing && AskOps) {
1703 if (Ty == KnownElemTy)
1706 Type *OpTy =
Op->getType();
1712 if (
Op->hasUseList() && !WouldClobberPtrWithNonPtr &&
1720 else if (!IsPostprocessing)
1724 if (AssignCI ==
nullptr) {
1733 DenseSet<std::pair<Value *, Value *>> VisitedSubst{
1734 std::make_pair(
I,
Op)};
1735 propagateElemTypeRec(
Op, KnownElemTy, PrevElemTy, VisitedSubst);
1746 CallInst *PtrCastI =
1747 buildSpvPtrcast(
I->getParent()->getParent(),
Op, KnownElemTy);
1748 if (OpIt.second == std::numeric_limits<unsigned>::max())
1751 I->setOperand(OpIt.second, PtrCastI);
1758 if (RevalidatingRetyped)
1760 RevalidatingRetyped =
true;
1761 while (!RetypedToRevalidate.
empty())
1762 deduceOperandElementType(RetypedToRevalidate.
pop_back_val(),
nullptr,
1763 nullptr, IsPostprocessing);
1764 RevalidatingRetyped =
false;
1767void SPIRVEmitIntrinsicsImpl::replaceMemInstrUses(Instruction *Old,
1772 if (isAssignTypeInstr(U)) {
1773 B.SetInsertPoint(U);
1774 SmallVector<Value *, 2>
Args = {
New,
U->getOperand(1)};
1775 CallInst *AssignCI =
B.CreateIntrinsicWithoutFolding(
1776 Intrinsic::spv_assign_type, {
New->getType()},
Args);
1778 U->eraseFromParent();
1781 U->replaceUsesOfWith(Old, New);
1789 Type *NewArgTy =
New->getType();
1791 if (NewArgTy != ExpectedArgTy) {
1794 M, Intrinsic::spv_abort, {NewArgTy});
1804 "aggregate PHI/select/freeze should have been mutated to value-id "
1806 U->replaceUsesOfWith(Old, New);
1811 New->copyMetadata(*Old);
1813 TypeValidated.
erase(Old);
1819 bool HasPoisonExt) {
1826 LLVM_DEBUG(
dbgs() <<
"SPV_KHR_poison_freeze is not enabled. Poison is "
1827 "lowered as undef\n");
1829 Intrinsic::ID IID = AsPoison ? Intrinsic::spv_poison : Intrinsic::spv_undef;
1830 Type *Ty = UV->getType();
1836 AsPoison ?
B.CreateIntrinsicWithoutFolding(IID, {
B.getInt32Ty()}, {})
1837 :
B.CreateIntrinsicWithoutFolding(IID, {});
1838 AggrConsts[
Call] = UV;
1839 AggrConstTypes[
Call] = Ty;
1844 return B.CreateIntrinsic(IID, {Ty}, {});
1851void SPIRVEmitIntrinsicsImpl::preprocessUndefsAndPoisons(
IRBuilder<> &
B) {
1856 SmallVector<Instruction *, 16> Insts;
1860 for (Instruction *
I : Insts) {
1861 bool BPrepared =
false;
1863 for (
unsigned Idx = 0;
Idx <
I->getNumOperands(); ++
Idx) {
1867 bool IsScalar = !
Op->getType()->isAggregateType();
1870 if (IsScalar && !AsPoison)
1874 if (IsScalar && Phi)
1875 B.SetInsertPoint(
Phi->getIncomingBlock(Idx)->getTerminator());
1876 else if (!BPrepared) {
1880 if (
Value *Repl = lowerUndefOrPoison(
Op,
B, HasPoisonExt))
1881 I->setOperand(Idx, Repl);
1890void SPIRVEmitIntrinsicsImpl::simplifyNullAddrSpaceCasts() {
1894 ASC->replaceAllUsesWith(
1896 ASC->eraseFromParent();
1904 if (!
V->getType()->isAggregateType())
1913 I.getType()->isAggregateType();
1919void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *
I,
1924 SmallDenseMap<BasicBlock *, Value *> PhiArms;
1925 for (Use &U :
I->operands()) {
1929 if (
Value *Arm = Phi ? PhiArms.
lookup(
Phi->getIncomingBlock(U)) :
nullptr) {
1936 B.SetInsertPoint(
Phi->getIncomingBlock(U)->getTerminator());
1941 for (
unsigned Idx = 0,
E = AggrTy->getNumElements(); Idx !=
E; ++Idx) {
1943 Composite =
B.CreateInsertValue(Composite,
Field, Idx);
1947 PhiArms[
Phi->getIncomingBlock(U)] = Composite;
1955 bool HasPoisonExt) {
1957 CE &&
CE->getOpcode() == Instruction::AddrSpaceCast &&
1961 if (
Value *Repl = lowerUndefOrPoison(
Op,
B, HasPoisonExt))
1966void SPIRVEmitIntrinsicsImpl::preprocessCompositeConstants(
IRBuilder<> &
B) {
1970 std::queue<Instruction *> Worklist;
1974 while (!Worklist.empty()) {
1975 auto *
I = Worklist.front();
1978 bool KeepInst =
false;
1979 for (
const auto &
Op :
I->operands()) {
1981 Type *ResTy =
nullptr;
1984 ResTy = COp->getType();
1996 ResTy =
Op->getType()->isVectorTy() ? COp->getType() :
B.getInt32Ty();
1999 auto PrepareInsert = [&]() {
2002 IsPhi ?
B.SetInsertPointPastAllocas(
I->getParent()->getParent())
2003 :
B.SetInsertPoint(
I);
2007 Type *DeducedTy = deduceNestedTypeHelper(AggrConst,
false);
2011 if (DeducedTy != AggrConst->
getType() &&
2020 Value *LoweredBase =
2021 lowerCompositeMember(Composite,
B, HasPoisonExt);
2022 Value *LoweredMember =
2023 lowerCompositeMember(Member,
B, HasPoisonExt);
2027 Composite, Member,
B.getInt32(Idx),
"",
B.GetInsertPoint());
2030 B.GetInsertPoint());
2031 Insert->setOperand(0, LoweredBase);
2032 Insert->setOperand(1, LoweredMember);
2033 Worklist.push(Insert);
2036 I->replaceUsesOfWith(
Op, Composite);
2042 for (
unsigned i = 0; i < COp->getNumElements(); ++i)
2043 Args.push_back(COp->getElementAsConstant(i));
2046 Args.push_back(lowerCompositeMember(
Op,
B, HasPoisonExt));
2047 auto *CI =
B.CreateIntrinsicWithoutFolding(
2048 Intrinsic::spv_const_composite, {ResTy}, {
Args});
2052 AggrConsts[CI] = AggrConst;
2053 AggrConstTypes[CI] = DeducedTy;
2065 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {
I->getType()},
2070 unsigned RoundingModeDeco,
2077 ConstantInt::get(Int32Ty, SPIRV::Decoration::FPRoundingMode)),
2086 MDNode *SaturatedConversionNode =
2088 Int32Ty, SPIRV::Decoration::SaturatedConversion))});
2108 MDString *ConstraintString =
2113 for (
unsigned OpIdx = 0; OpIdx <
Call.
arg_size(); OpIdx++)
2117 B.SetInsertPoint(&
Call);
2118 B.CreateIntrinsic(Intrinsic::spv_inline_asm, {
Args});
2123void SPIRVEmitIntrinsicsImpl::useRoundingMode(ConstrainedFPIntrinsic *FPI,
2126 if (!
RM.has_value())
2128 unsigned RoundingModeDeco = std::numeric_limits<unsigned>::max();
2129 switch (
RM.value()) {
2133 case RoundingMode::NearestTiesToEven:
2134 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTE;
2136 case RoundingMode::TowardNegative:
2137 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTN;
2139 case RoundingMode::TowardPositive:
2140 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTP;
2142 case RoundingMode::TowardZero:
2143 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTZ;
2145 case RoundingMode::Dynamic:
2146 case RoundingMode::NearestTiesToAway:
2150 if (RoundingModeDeco == std::numeric_limits<unsigned>::max())
2156Instruction *SPIRVEmitIntrinsicsImpl::visitSwitchInst(SwitchInst &
I) {
2160 B.SetInsertPoint(&
I);
2161 SmallVector<Value *, 4>
Args;
2163 Args.push_back(
I.getCondition());
2166 for (
auto &Case :
I.cases()) {
2167 Args.push_back(Case.getCaseValue());
2168 BBCases.
push_back(Case.getCaseSuccessor());
2171 CallInst *NewI =
B.CreateIntrinsicWithoutFolding(
2172 Intrinsic::spv_switch, {
I.getOperand(0)->getType()}, {
Args});
2176 I.eraseFromParent();
2179 B.SetInsertPoint(ParentBB);
2180 IndirectBrInst *BrI =
B.CreateIndirectBr(
2183 for (BasicBlock *BBCase : BBCases)
2192Instruction *SPIRVEmitIntrinsicsImpl::visitIntrinsicInst(IntrinsicInst &
I) {
2198 B.SetInsertPoint(&
I);
2200 SmallVector<Value *, 4>
Args;
2201 Args.push_back(
B.getInt1(
true));
2202 Args.push_back(
I.getOperand(0));
2203 Args.push_back(
B.getInt32(0));
2204 for (
unsigned J = 0; J < SGEP->getNumIndices(); ++J)
2205 Args.push_back(SGEP->getIndexOperand(J));
2208 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, Types, Args);
2209 replaceAllUsesWithAndErase(
B, &
I, NewI);
2214SPIRVEmitIntrinsicsImpl::visitGetElementPtrInst(GetElementPtrInst &
I) {
2216 B.SetInsertPoint(&
I);
2221 unsigned N = RetVTy->getNumElements();
2222 Value *PtrOp =
I.getPointerOperand();
2224 Type *ResultPtrTy = RetVTy->getElementType();
2227 Value *InBounds =
B.getInt1(
I.isInBounds());
2228 Type *LanePointeeTy = getGEPType(&
I);
2231 Type *SrcElemTy =
I.getSourceElementType();
2240 for (
unsigned Lane = 0; Lane <
N; ++Lane) {
2241 Value *LaneIdx =
B.getInt32(Lane);
2242 Value *ScalarPtr = PtrOp;
2246 ScalarPtr =
B.CreateIntrinsic(Intrinsic::spv_extractelt, {ExtractTypes},
2250 SmallVector<Value *, 4>
Args;
2251 Args.push_back(InBounds);
2252 Args.push_back(ScalarPtr);
2253 for (
Value *Idx :
I.indices()) {
2261 Args.push_back(visitExtractElementInst(*EI));
2265 Args.push_back(Idx);
2268 Value *ScalarGep =
B.CreateIntrinsic(Intrinsic::spv_gep, GepTypes, Args);
2270 VecResult =
B.CreateInsertElement(VecResult, ScalarGep, LaneIdx);
2274 replaceAllUsesWithAndErase(
B, &
I, NewI);
2294 if (getByteAddressingMultiplier(
I.getSourceElementType())) {
2295 return buildLogicalAccessChainFromGEP(
I);
2300 Value *PtrOp =
I.getPointerOperand();
2301 Type *SrcElemTy =
I.getSourceElementType();
2302 Type *DeducedPointeeTy = deduceElementType(PtrOp,
true);
2305 if (ArrTy->getElementType() == SrcElemTy) {
2307 for (
Value *Idx :
I.indices())
2308 NewIndices.
push_back(truncateGEPIndex(Idx, IdxTy,
B));
2310 ConstantInt::get(NewIndices.
front()->getType(), 0));
2313 SmallVector<Value *, 4>
Args;
2314 Args.push_back(
B.getInt1(
I.isInBounds()));
2315 Args.push_back(
I.getPointerOperand());
2318 Instruction *NewI =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep,
2320 replaceAllUsesWithAndErase(
B, &
I, NewI);
2327 SmallVector<Value *, 4>
Args;
2328 Args.push_back(
B.getInt1(
I.isInBounds()));
2329 Args.push_back(
I.getPointerOperand());
2330 for (
Value *Idx :
I.indices())
2331 Args.push_back(IsLogical ? truncateGEPIndex(Idx, IdxTy,
B) : Idx);
2333 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, {
Types}, {
Args});
2334 replaceAllUsesWithAndErase(
B, &
I, NewI);
2338Instruction *SPIRVEmitIntrinsicsImpl::visitBitCastInst(BitCastInst &
I) {
2340 B.SetInsertPoint(&
I);
2349 I.eraseFromParent();
2356 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_bitcast, {
Types}, {
Args});
2357 replaceAllUsesWithAndErase(
B, &
I, NewI);
2361void SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeTargetExt(
2368 if (ElemTy != AssignedType)
2381 if (CurrentType == AssignedType)
2388 " for value " +
V->getName(),
2397void SPIRVEmitIntrinsicsImpl::replacePointerOperandWithPtrCast(
2398 Instruction *
I,
Value *Pointer,
Type *ExpectedElementType,
2403 Type *PointerElemTy = deduceElementTypeHelper(Pointer,
false);
2404 if (PointerElemTy == ExpectedElementType ||
2409 Value *ExpectedElementVal =
2411 MetadataAsValue *VMD =
buildMD(ExpectedElementVal);
2413 bool FirstPtrCastOrAssignPtrType =
true;
2419 for (
auto User :
Pointer->users()) {
2422 (
II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type &&
2423 II->getIntrinsicID() != Intrinsic::spv_ptrcast) ||
2424 II->getOperand(0) != Pointer)
2429 FirstPtrCastOrAssignPtrType =
false;
2430 if (
II->getOperand(1) != VMD ||
2437 if (
II->getIntrinsicID() != Intrinsic::spv_ptrcast)
2442 if (
II->getParent() !=
I->getParent())
2445 I->setOperand(OperandToReplace,
II);
2460 if (FirstPtrCastOrAssignPtrType) {
2465 }
else if (isTodoType(Pointer)) {
2466 eraseTodoType(Pointer);
2474 DenseSet<std::pair<Value *, Value *>> VisitedSubst{
2475 std::make_pair(
I, Pointer)};
2477 propagateElemType(Pointer, PrevElemTy, VisitedSubst);
2490 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_ptrcast, {
Types},
Args);
2496void SPIRVEmitIntrinsicsImpl::insertPtrCastOrAssignTypeInstr(Instruction *
I,
2501 replacePointerOperandWithPtrCast(
2502 I,
SI->getValueOperand(), IntegerType::getInt8Ty(CurrF->
getContext()),
2508 Type *OpTy =
Op->getType();
2511 if (
auto It = AggrConstTypes.
find(OpI); It != AggrConstTypes.
end())
2514 if (OpTy ==
Op->getType())
2515 OpTy = deduceElementTypeByValueDeep(OpTy,
Op,
false);
2516 replacePointerOperandWithPtrCast(
I, Pointer, OpTy, 1,
B);
2521 Type *OpTy = LI->getType();
2532 Type *NewOpTy = OpTy;
2533 OpTy = deduceElementTypeByValueDeep(OpTy, LI,
false);
2534 if (OpTy == NewOpTy)
2535 insertTodoType(Pointer);
2538 replacePointerOperandWithPtrCast(
I, Pointer, OpTy, 0,
B);
2543 Type *OpTy =
nullptr;
2555 OpTy = GEPI->getSourceElementType();
2557 replacePointerOperandWithPtrCast(
I, Pointer, OpTy, 0,
B);
2559 insertTodoType(Pointer);
2565 Value *
Op = IVI->getInsertedValueOperand();
2567 replacePointerOperandWithPtrCast(
2575 Value *
Op = IEI->getOperand(1);
2577 replacePointerOperandWithPtrCast(
2578 I,
Op, IntegerType::getInt8Ty(
I->getContext()), 1,
B);
2590 std::string DemangledName =
2594 bool HaveTypes =
false;
2595 for (
unsigned OpIdx = 0; OpIdx < CalledF->
arg_size(); ++OpIdx) {
2613 for (User *U : CalledArg->
users()) {
2615 if ((ElemTy = deduceElementTypeHelper(Inst,
false)) !=
nullptr)
2621 HaveTypes |= ElemTy !=
nullptr;
2626 if (DemangledName.empty() && !HaveTypes)
2630 TM.
getSubtarget<SPIRVSubtarget>(*CalledF).getPreferredInstructionSet();
2632 bool ParseBuiltinTypes =
2633 !DemangledName.empty() &&
2634 (!CalledF->
isDeclaration() || SPIRV::isBuiltin(DemangledName, Set));
2635 for (
unsigned OpIdx = 0; OpIdx < CI->
arg_size(); OpIdx++) {
2652 Type *ExpectedType =
2653 OpIdx < CalledArgTys.
size() ? CalledArgTys[OpIdx] :
nullptr;
2654 if (!ExpectedType && ParseBuiltinTypes)
2655 ExpectedType = SPIRV::parseBuiltinCallArgumentBaseType(
2656 DemangledName, OpIdx,
I->getContext());
2657 if (!ExpectedType || ExpectedType->
isVoidTy())
2665 replacePointerOperandWithPtrCast(CI, ArgOperand, ExpectedType, OpIdx,
B);
2670SPIRVEmitIntrinsicsImpl::visitInsertElementInst(InsertElementInst &
I) {
2673 if (
isVector1(
I.getType()) && !CanUseAnyVectorRank)
2677 I.getOperand(1)->getType(),
2678 I.getOperand(2)->getType()};
2680 B.SetInsertPoint(&
I);
2682 Instruction *NewI =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertelt,
2684 replaceAllUsesWithAndErase(
B, &
I, NewI);
2689SPIRVEmitIntrinsicsImpl::visitExtractElementInst(ExtractElementInst &
I) {
2692 if (
isVector1(
I.getVectorOperandType()) && !CanUseAnyVectorRank)
2696 B.SetInsertPoint(&
I);
2698 I.getIndexOperand()->getType()};
2699 SmallVector<Value *, 2>
Args = {
I.getVectorOperand(),
I.getIndexOperand()};
2700 Instruction *NewI =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractelt,
2702 replaceAllUsesWithAndErase(
B, &
I, NewI);
2710void SPIRVEmitIntrinsicsImpl::scalarizeVectorPtrCasts(
Function &
F) {
2714 if (
ST.canUseExtension(SPIRV::Extension::SPV_INTEL_masked_gather_scatter))
2717 SmallVector<Instruction *, 8> ToErase;
2722 if (!VecTy || !VecTy->getElementType()->isPointerTy())
2726 unsigned NumElems = VecTy->getNumElements();
2730 for (
unsigned Idx = 0;
Idx < NumElems; ++
Idx) {
2733 ElemPtr =
B.CreateExtractElement(PTI->getOperand(0),
B.getInt32(Idx));
2734 Value *Conv =
B.CreatePtrToInt(ElemPtr, ElemIntTy);
2735 Result =
B.CreateInsertElement(Result, Conv,
B.getInt32(Idx));
2738 PTI->replaceAllUsesWith(Result);
2742 if (!VecTy || !VecTy->getElementType()->isPointerTy())
2748 bool AllUsersExtract =
llvm::all_of(ITP->users(), [&](User *U) {
2749 auto *EE = dyn_cast<ExtractElementInst>(U);
2750 return EE && isa<ConstantInt>(EE->getIndexOperand());
2752 if (!AllUsersExtract)
2756 Type *ElemPtrTy = VecTy->getElementType();
2762 B.SetInsertPoint(EE);
2764 B.CreateExtractElement(ITP->getOperand(0),
B.getInt32(Idx));
2765 Value *Conv =
B.CreateIntToPtr(Elem, ElemPtrTy);
2774 if (ToErase.
empty())
2777 for (Instruction *
I : ToErase) {
2778 for (
Value *
Op :
I->operand_values())
2780 I->eraseFromParent();
2785Instruction *SPIRVEmitIntrinsicsImpl::visitInsertValueInst(InsertValueInst &
I) {
2787 B.SetInsertPoint(&
I);
2790 Value *AggregateOp =
I.getAggregateOperand();
2794 Args.push_back(AggregateOp);
2795 Args.push_back(
I.getInsertedValueOperand());
2796 for (
auto &
Op :
I.indices())
2797 Args.push_back(
B.getInt32(
Op));
2799 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertv, {
Types}, {
Args});
2800 replaceMemInstrUses(&
I, NewI,
B);
2805SPIRVEmitIntrinsicsImpl::visitExtractValueInst(ExtractValueInst &
I) {
2807 B.SetInsertPoint(&
I);
2808 if (
I.getAggregateOperand()->getType()->isAggregateType()) {
2817 for (
auto &
Op :
I.indices())
2818 Args.push_back(
B.getInt32(
Op));
2819 Instruction *NewI =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractv,
2820 {
I.getType()}, {
Args});
2825 Type *AggrTy =
I.getType();
2826 AggrConstTypes[NewI] = AggrTy;
2828 replaceMemInstrUses(&
I, NewI,
B);
2835 replaceAllUsesWithAndErase(
B, &
I, NewI);
2839Instruction *SPIRVEmitIntrinsicsImpl::visitLoadInst(LoadInst &
I) {
2840 if (!
I.getType()->isAggregateType())
2843 B.SetInsertPoint(&
I);
2844 TrackConstants =
false;
2849 unsigned IntrinsicId;
2850 SmallVector<Value *, 4>
Args = {
I.getPointerOperand(),
B.getInt16(Flags)};
2851 if (!
I.isAtomic()) {
2852 IntrinsicId = Intrinsic::spv_load;
2855 IntrinsicId = Intrinsic::spv_atomic_load;
2856 Args.push_back(
B.getInt8(
static_cast<uint8_t
>(
I.getOrdering())));
2858 CallInst *NewI =
B.CreateIntrinsicWithoutFolding(
2859 IntrinsicId, {
I.getOperand(0)->getType()},
Args);
2861 replaceMemInstrUses(&
I, NewI,
B);
2865Instruction *SPIRVEmitIntrinsicsImpl::visitStoreInst(StoreInst &
I) {
2869 B.SetInsertPoint(&
I);
2870 TrackConstants =
false;
2874 auto *PtrOp =
I.getPointerOperand();
2876 if (
I.getValueOperand()->getType()->isAggregateType()) {
2884 "Unexpected argument of aggregate type, should be spv_extractv!");
2888 unsigned IntrinsicId;
2889 SmallVector<Value *, 4>
Args = {
I.getValueOperand(), PtrOp,
2891 if (!
I.isAtomic()) {
2892 IntrinsicId = Intrinsic::spv_store;
2895 IntrinsicId = Intrinsic::spv_atomic_store;
2896 Args.push_back(
B.getInt8(
static_cast<uint8_t
>(
I.getOrdering())));
2899 IntrinsicId, {
I.getValueOperand()->getType(), PtrOp->
getType()},
Args);
2901 I.eraseFromParent();
2905Instruction *SPIRVEmitIntrinsicsImpl::visitAllocaInst(AllocaInst &
I) {
2906 Value *ArraySize =
nullptr;
2907 if (
I.isArrayAllocation()) {
2910 SPIRV::Extension::SPV_INTEL_variable_length_array))
2912 "array allocation: this instruction requires the following "
2913 "SPIR-V extension: SPV_INTEL_variable_length_array",
2915 ArraySize =
I.getArraySize();
2918 B.SetInsertPoint(&
I);
2919 TrackConstants =
false;
2920 Type *PtrTy =
I.getType();
2923 ?
B.CreateIntrinsicWithoutFolding(
2924 Intrinsic::spv_alloca_array, {PtrTy, ArraySize->
getType()},
2925 {ArraySize,
B.getInt32(
I.getAlign().value())})
2926 :
B.CreateIntrinsicWithoutFolding(
Intrinsic::spv_alloca, {PtrTy},
2927 {
B.getInt32(
I.getAlign().value())});
2928 replaceAllUsesWithAndErase(
B, &
I, NewI);
2933SPIRVEmitIntrinsicsImpl::visitAtomicCmpXchgInst(AtomicCmpXchgInst &
I) {
2934 assert(
I.getType()->isAggregateType() &&
"Aggregate result is expected");
2936 B.SetInsertPoint(&
I);
2939 Args.push_back(
B.getInt32(
static_cast<uint32_t
>(
2943 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*
I.getFunction());
2944 unsigned AS =
I.getPointerOperand()->getType()->getPointerAddressSpace();
2945 uint32_t ScSem =
static_cast<uint32_t
>(
2954 Intrinsic::spv_cmpxchg, {
I.getPointerOperand()->getType()}, {
Args});
2955 replaceMemInstrUses(&
I, NewI,
B);
2959Instruction *SPIRVEmitIntrinsicsImpl::visitAtomicRMWInst(AtomicRMWInst &
I) {
2960 auto Op =
I.getOperation();
2971 B.SetInsertPoint(&
I);
2973 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*
I.getFunction());
2974 unsigned AS =
I.getPointerOperand()->getType()->getPointerAddressSpace();
2976 uint32_t
Scope =
static_cast<uint32_t
>(
2977 getMemScope(
M->getTargetTriple(),
I.getContext(),
I.getSyncScopeID()));
2978 uint32_t ScSem =
static_cast<uint32_t
>(
2981 M->getTargetTriple(),
2985 ?
"__translate_spirv_atomic_uinc_wrap"
2986 :
"__translate_spirv_atomic_udec_wrap");
2988 Type *ValTy =
I.getValOperand()->getType();
2989 Type *PtrTy =
I.getPointerOperand()->getType();
2991 raw_svector_ostream OS(FuncName);
2992 OS <<
"_p" << AS <<
"_";
2994 OS <<
"v" << VecTy->getNumElements();
2997 Type *Int32Ty =
B.getInt32Ty();
2998 Type *BoolTy =
B.getInt1Ty();
3000 ValTy, BoolTy, BoolTy};
3001 FunctionType *FT = FunctionType::get(ValTy, ArgTys,
false);
3002 FunctionCallee
FC =
M->getOrInsertFunction(FuncName, FT);
3006 I.getPointerOperand(),
B.getInt32(Scope),
3007 B.getInt32(MemSem),
I.getValOperand(),
3008 B.getInt1(
I.isVolatile()),
B.getInt1(
I.isElementwise())};
3009 CallInst *CI =
B.CreateCall(FC, Args);
3015 replaceAllUsesWithAndErase(
B, &
I, CI);
3024 case Intrinsic::spv_abort:
3026 case Intrinsic::trap:
3027 case Intrinsic::ubsantrap:
3029 return ST.canUseExtension(SPIRV::Extension::SPV_KHR_abort);
3045 [&ST](
const Instruction &
II) { return isAbortCall(II, ST); }) &&
3046 "abort-like call must be the last non-debug instruction before its "
3047 "block's terminator");
3051Instruction *SPIRVEmitIntrinsicsImpl::visitUnreachableInst(UnreachableInst &
I) {
3052 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*
I.getFunction());
3056 B.CreateIntrinsic(Intrinsic::spv_unreachable, {});
3063 return Name ==
"llvm.compiler.used" || Name ==
"llvm.used";
3077 while (!Stack.empty()) {
3078 const Value *
V = Stack.pop_back_val();
3079 if (!Visited.
insert(
V).second)
3087 Stack.append(
C->user_begin(),
C->user_end());
3103 auto &UserFunctions = GVUsers.getTransitiveUserFunctions(GV);
3104 if (UserFunctions.contains(
F))
3109 if (!UserFunctions.empty())
3114 const Module &M = *
F->getParent();
3115 const Function &FirstDefinition = *M.getFunctionDefs().
begin();
3116 return F == &FirstDefinition;
3119Value *SPIRVEmitIntrinsicsImpl::buildSpvUndefComposite(
Type *AggrTy,
3121 auto MakeLeaf = [&](
Type *ElemTy) -> Instruction * {
3122 CallInst *Leaf =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_undef, {});
3124 AggrConstTypes[Leaf] = ElemTy;
3127 SmallVector<Value *, 4> Elems;
3129 Elems.
assign(ArrTy->getNumElements(), MakeLeaf(ArrTy->getElementType()));
3132 DenseMap<Type *, Instruction *> LeafByType;
3133 for (
unsigned I = 0;
I < StructTy->getNumElements(); ++
I) {
3135 auto &
Entry = LeafByType[ElemTy];
3137 Entry = MakeLeaf(ElemTy);
3141 CallInst *Composite =
B.CreateIntrinsicWithoutFolding(
3142 Intrinsic::spv_const_composite, {
B.getInt32Ty()}, Elems);
3144 AggrConstTypes[Composite] = AggrTy;
3153void SPIRVEmitIntrinsicsImpl::reconstructAggregateReturns(
Function &Func,
3158 for (BasicBlock &BB : Func) {
3162 Value *RetVal = RI->getReturnValue();
3169 B.SetInsertPoint(RI);
3172 Value *Elt =
B.CreateExtractValue(RetVal,
I);
3173 Rebuilt =
B.CreateInsertValue(Rebuilt, Elt,
I);
3175 RI->setOperand(0, Rebuilt);
3179void SPIRVEmitIntrinsicsImpl::processGlobalValue(GlobalVariable &GV,
3189 deduceElementTypeHelper(&GV,
false);
3201 CallInst *
Call =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_poison,
3202 {
B.getInt32Ty()}, {});
3204 AggrConstTypes[
Call] =
Init->getType();
3207 InitOp = buildSpvUndefComposite(
Init->getType(),
B);
3212 CallInst *InitInst =
B.CreateIntrinsicWithoutFolding(
3213 Intrinsic::spv_init_global, {GV.
getType(), Ty}, {&GV,
Const});
3219 B.CreateIntrinsic(Intrinsic::spv_unref_global, GV.
getType(), &GV);
3225bool SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeIntrs(Instruction *
I,
3227 bool UnknownElemTypeI8) {
3233 if (
Type *ElemTy = deduceElementType(
I, UnknownElemTypeI8)) {
3240void SPIRVEmitIntrinsicsImpl::insertAssignTypeIntrs(Instruction *
I,
3243 static StringMap<unsigned> ResTypeWellKnown = {
3244 {
"async_work_group_copy", WellKnownTypes::Event},
3245 {
"async_work_group_strided_copy", WellKnownTypes::Event},
3246 {
"__spirv_GroupAsyncCopy", WellKnownTypes::Event}};
3250 bool IsKnown =
false;
3255 std::string DemangledName =
3258 if (DemangledName.length() > 0)
3260 SPIRV::lookupBuiltinNameHelper(DemangledName, &DecorationId);
3261 auto ResIt = ResTypeWellKnown.
find(DemangledName);
3262 if (ResIt != ResTypeWellKnown.
end()) {
3265 switch (ResIt->second) {
3266 case WellKnownTypes::Event:
3269 CanUseAnyVectorRank);
3274 switch (DecorationId) {
3277 case FPDecorationId::SAT:
3280 case FPDecorationId::RTE:
3282 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTE,
B);
3284 case FPDecorationId::RTZ:
3286 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTZ,
B);
3288 case FPDecorationId::RTP:
3290 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTP,
B);
3292 case FPDecorationId::RTN:
3294 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTN,
B);
3300 Type *Ty =
I->getType();
3303 Type *TypeToAssign = Ty;
3306 auto It = AggrConstTypes.
find(
II);
3307 if (It == AggrConstTypes.
end())
3309 TypeToAssign = It->second;
3310 }
else if (
II->getIntrinsicID() == Intrinsic::spv_poison) {
3311 if (
auto It = AggrConstTypes.
find(
II); It != AggrConstTypes.
end())
3312 TypeToAssign = It->second;
3314 }
else if (
auto It = AggrConstTypes.
find(
I); It != AggrConstTypes.
end())
3315 TypeToAssign = It->second;
3319 for (
const auto &
Op :
I->operands()) {
3327 Type *OpTy =
Op->getType();
3329 CallInst *AssignCI =
3334 Type *OpTy =
Op->getType();
3350 Intrinsic::spv_assign_type, {OpTy},
3360bool SPIRVEmitIntrinsicsImpl::shouldTryToAddMemAliasingDecoration(
3361 Instruction *Inst) {
3363 if (!STI->
canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing))
3373void SPIRVEmitIntrinsicsImpl::insertSpirvDecorations(Instruction *
I,
3375 if (MDNode *MD =
I->getMetadata(
"spirv.Decorations")) {
3377 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {
I->getType()},
3382 auto processMemAliasingDecoration = [&](
unsigned Kind) {
3383 if (MDNode *AliasListMD =
I->getMetadata(Kind)) {
3384 if (shouldTryToAddMemAliasingDecoration(
I)) {
3385 uint32_t Dec =
Kind == LLVMContext::MD_alias_scope
3386 ? SPIRV::Decoration::AliasScopeINTEL
3387 : SPIRV::Decoration::NoAliasINTEL;
3389 I, ConstantInt::get(
B.getInt32Ty(), Dec),
3392 B.CreateIntrinsic(Intrinsic::spv_assign_aliasing_decoration,
3393 {
I->getType()}, {
Args});
3397 processMemAliasingDecoration(LLVMContext::MD_alias_scope);
3398 processMemAliasingDecoration(LLVMContext::MD_noalias);
3401 if (MDNode *MD =
I->getMetadata(LLVMContext::MD_fpmath)) {
3403 bool AllowFPMaxError =
3405 if (!AllowFPMaxError)
3409 B.CreateIntrinsic(Intrinsic::spv_assign_fpmaxerror_decoration,
3415 LLVMContext &Ctx =
B.getContext();
3417 B.getInt32Ty(), SPIRV::Decoration::AuxDataInstructionMetadata));
3420 if (
I->hasMetadata(
"amdgpu.no.fine.grained.memory"))
3422 Ctx, {AuxMD,
MDString::get(Ctx,
"amdgpu.no.fine.grained.memory")}));
3423 if (
I->hasMetadata(
"amdgpu.no.remote.memory"))
3425 Ctx, {AuxMD,
MDString::get(Ctx,
"amdgpu.no.remote.memory")}));
3426 if (
I->hasMetadata(LLVMContext::MD_atomic_ignore_denormal_mode))
3428 Ctx, {AuxMD,
MDString::get(Ctx,
"atomic.ignore.denormal.mode")}));
3431 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {
I->getType()},
3440 &FPFastMathDefaultInfoMap,
3442 auto it = FPFastMathDefaultInfoMap.
find(
F);
3443 if (it != FPFastMathDefaultInfoMap.
end())
3451 SPIRV::FPFastMathMode::None);
3453 SPIRV::FPFastMathMode::None);
3455 SPIRV::FPFastMathMode::None);
3456 return FPFastMathDefaultInfoMap[
F] = std::move(FPFastMathDefaultInfoVec);
3462 size_t BitWidth = Ty->getScalarSizeInBits();
3466 assert(Index >= 0 && Index < 3 &&
3467 "Expected FPFastMathDefaultInfo for half, float, or double");
3468 assert(FPFastMathDefaultInfoVec.
size() == 3 &&
3469 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3470 return FPFastMathDefaultInfoVec[Index];
3473void SPIRVEmitIntrinsicsImpl::insertConstantsForFPFastMathDefault(
Module &M) {
3475 if (!
ST->canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2))
3484 auto Node =
M.getNamedMetadata(
"spirv.ExecutionMode");
3486 if (!
M.getNamedMetadata(
"opencl.enable.FP_CONTRACT")) {
3494 ConstantInt::get(Type::getInt32Ty(
M.getContext()), 0);
3497 [[maybe_unused]] GlobalVariable *GV =
3498 new GlobalVariable(M,
3499 Type::getInt32Ty(
M.getContext()),
3513 MapVector<Function *, SPIRV::FPFastMathDefaultInfoVector>
3514 FPFastMathDefaultInfoMap;
3516 for (
unsigned i = 0; i <
Node->getNumOperands(); i++) {
3525 if (EM == SPIRV::ExecutionMode::FPFastMathDefault) {
3527 "Expected 4 operands for FPFastMathDefault");
3533 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3535 SPIRV::FPFastMathDefaultInfo &
Info =
3538 Info.FPFastMathDefault =
true;
3539 }
else if (EM == SPIRV::ExecutionMode::ContractionOff) {
3541 "Expected no operands for ContractionOff");
3545 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3547 for (SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3548 Info.ContractionOff =
true;
3550 }
else if (EM == SPIRV::ExecutionMode::SignedZeroInfNanPreserve) {
3552 "Expected 1 operand for SignedZeroInfNanPreserve");
3553 unsigned TargetWidth =
3558 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3562 assert(Index >= 0 && Index < 3 &&
3563 "Expected FPFastMathDefaultInfo for half, float, or double");
3564 assert(FPFastMathDefaultInfoVec.
size() == 3 &&
3565 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3566 FPFastMathDefaultInfoVec[
Index].SignedZeroInfNanPreserve =
true;
3570 DenseMap<unsigned, GlobalVariable *> GlobalVars;
3571 for (
auto &[Func, FPFastMathDefaultInfoVec] : FPFastMathDefaultInfoMap) {
3572 if (FPFastMathDefaultInfoVec.
empty())
3575 for (
const SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3576 assert(
Info.Ty &&
"Expected target type for FPFastMathDefaultInfo");
3579 if (Flags == SPIRV::FPFastMathMode::None && !
Info.ContractionOff &&
3580 !
Info.SignedZeroInfNanPreserve && !
Info.FPFastMathDefault)
3584 if (
Info.ContractionOff && (Flags & SPIRV::FPFastMathMode::AllowContract))
3586 "and AllowContract");
3588 if (
Info.SignedZeroInfNanPreserve &&
3590 (SPIRV::FPFastMathMode::NotNaN | SPIRV::FPFastMathMode::NotInf |
3591 SPIRV::FPFastMathMode::NSZ))) {
3592 if (
Info.FPFastMathDefault)
3594 "SignedZeroInfNanPreserve but at least one of "
3595 "NotNaN/NotInf/NSZ is enabled.");
3598 if ((Flags & SPIRV::FPFastMathMode::AllowTransform) &&
3599 !((Flags & SPIRV::FPFastMathMode::AllowReassoc) &&
3600 (Flags & SPIRV::FPFastMathMode::AllowContract))) {
3602 "AllowTransform requires AllowReassoc and "
3603 "AllowContract to be set.");
3606 auto it = GlobalVars.
find(Flags);
3607 GlobalVariable *GV =
nullptr;
3608 if (it != GlobalVars.
end()) {
3614 ConstantInt::get(Type::getInt32Ty(
M.getContext()), Flags);
3617 GV =
new GlobalVariable(M,
3618 Type::getInt32Ty(
M.getContext()),
3623 GlobalVars[
Flags] = GV;
3629void SPIRVEmitIntrinsicsImpl::processInstrAfterVisit(Instruction *
I,
3632 bool IsConstComposite =
3633 II &&
II->getIntrinsicID() == Intrinsic::spv_const_composite;
3634 if (IsConstComposite && TrackConstants) {
3636 auto t = AggrConsts.
find(
I);
3640 {
II->getType(),
II->getType()}, t->second,
I, {},
B);
3642 NewOp->setArgOperand(0,
I);
3645 for (
const auto &
Op :
I->operands()) {
3649 unsigned OpNo =
Op.getOperandNo();
3650 if (
II && ((
II->getIntrinsicID() == Intrinsic::spv_gep && OpNo == 0) ||
3651 (!
II->isBundleOperand(OpNo) &&
3652 II->paramHasAttr(OpNo, Attribute::ImmArg))))
3656 IsPhi ?
B.SetInsertPointPastAllocas(
I->getParent()->getParent())
3657 :
B.SetInsertPoint(
I);
3660 Type *OpTy =
Op->getType();
3668 {OpTy, OpTyVal->
getType()},
Op, OpTyVal, {},
B);
3670 if (!IsConstComposite &&
isPointerTy(OpTy) && OpElemTy !=
nullptr &&
3671 OpElemTy != IntegerType::getInt8Ty(
I->getContext())) {
3673 SmallVector<Value *, 2>
Args = {
3677 CallInst *PtrCasted =
B.CreateIntrinsicWithoutFolding(
3683 I->setOperand(OpNo, NewOp);
3689Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(
Function *
F,
3691 SmallPtrSet<Function *, 0> FVisited;
3692 return deduceFunParamElementType(
F, OpIdx, FVisited);
3695Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(
3696 Function *
F,
unsigned OpIdx, SmallPtrSetImpl<Function *> &FVisited) {
3698 if (!FVisited.
insert(
F).second)
3701 SmallPtrSet<Value *, 0> Visited;
3704 for (User *U :
F->users()) {
3706 if (!CI || OpIdx >= CI->
arg_size())
3716 if (
Type *Ty = deduceElementTypeHelper(OpArg, Visited,
false))
3719 for (User *OpU : OpArg->
users()) {
3721 if (!Inst || Inst == CI)
3724 if (
Type *Ty = deduceElementTypeHelper(Inst, Visited,
false))
3731 if (FVisited.
find(OuterF) != FVisited.
end())
3733 for (
unsigned i = 0; i < OuterF->
arg_size(); ++i) {
3734 if (OuterF->
getArg(i) == OpArg) {
3735 Lookup.push_back(std::make_pair(OuterF, i));
3742 for (
auto &Pair :
Lookup) {
3743 if (
Type *Ty = deduceFunParamElementType(Pair.first, Pair.second, FVisited))
3750void SPIRVEmitIntrinsicsImpl::processParamTypesByFunHeader(
Function *
F,
3752 B.SetInsertPointPastAllocas(
F);
3753 for (
unsigned OpIdx = 0; OpIdx <
F->arg_size(); ++OpIdx) {
3759 for (User *U : Arg->
users()) {
3761 if (
GEP &&
GEP->getPointerOperand() == Arg) {
3779 for (User *U :
F->users()) {
3781 if (!CI || OpIdx >= CI->
arg_size())
3795 for (User *U : Arg->
users()) {
3799 CI->
getParent()->getParent() == CurrF) {
3801 deduceOperandElementTypeFunctionPointer(CI,
Ops, ElemTy,
false);
3813 B.SetInsertPointPastAllocas(
F);
3814 for (
unsigned OpIdx = 0; OpIdx <
F->arg_size(); ++OpIdx) {
3819 if (!ElemTy && (ElemTy = deduceFunParamElementType(
F, OpIdx)) !=
nullptr) {
3821 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
3825 propagateElemType(Arg, IntegerType::getInt8Ty(
F->getContext()),
3837 bool IsNewFTy =
false;
3853bool SPIRVEmitIntrinsicsImpl::processFunctionPointers(
Module &M) {
3856 if (
F.isIntrinsic())
3858 if (
F.isDeclaration()) {
3859 for (User *U :
F.users()) {
3862 UF &&
UF->hasPersonalityFn() &&
UF->getPersonalityFn() == &
F)
3876 for (User *U :
F.users()) {
3878 if (!
II ||
II->arg_size() != 3 ||
II->getOperand(0) != &
F)
3880 if (
II->getIntrinsicID() == Intrinsic::spv_assign_ptr_type ||
3881 II->getIntrinsicID() == Intrinsic::spv_ptrcast) {
3889 if (Worklist.
empty())
3892 LLVMContext &Ctx =
M.getContext();
3899 for (
const auto &Arg :
F->args())
3902 IRB.CreateCall(
F, Args)->setTailCall(
true);
3904 IRB.CreateRetVoid();
3910void SPIRVEmitIntrinsicsImpl::applyDemangledPtrArgTypes(
IRBuilder<> &
B) {
3911 DenseMap<Function *, CallInst *> Ptrcasts;
3912 for (
auto It : FDeclPtrTys) {
3914 for (
auto *U :
F->users()) {
3919 for (
auto [Idx, ElemTy] : It.second) {
3927 B.SetInsertPointPastAllocas(Arg->
getParent());
3934 replaceUsesOfWithSpvPtrcast(
3935 Param,
normalizeType(ElemTy, CanUseAnyVectorRank), CI, Ptrcasts);
3944 .getFirstNonPHIOrAlloca());
3962 FDeclPtrTys.
clear();
3965GetElementPtrInst *SPIRVEmitIntrinsicsImpl::simplifyZeroLengthArrayGepInst(
3966 GetElementPtrInst *
GEP) {
3973 Type *SrcTy =
GEP->getSourceElementType();
3974 SmallVector<Value *, 8> Indices(
GEP->indices());
3976 if (ArrTy && ArrTy->getNumElements() == 0 &&
match(Indices[0],
m_Zero())) {
3977 Indices.erase(Indices.begin());
3978 SrcTy = ArrTy->getElementType();
3980 GEP->getNoWrapFlags(),
"",
3981 GEP->getIterator());
3986void SPIRVEmitIntrinsicsImpl::emitUnstructuredLoopControls(
Function &
F,
3993 if (
ST->canUseExtension(
3994 SPIRV::Extension::SPV_INTEL_unstructured_loop_controls)) {
3995 for (BasicBlock &BB :
F) {
3997 MDNode *LoopMD =
Term->getMetadata(LLVMContext::MD_loop);
4001 SmallVector<unsigned, 1>
Ops =
4003 unsigned LC =
Ops[0];
4004 if (LC == SPIRV::LoopControl::None)
4008 B.SetInsertPoint(Term);
4009 SmallVector<Value *, 4> IntrArgs;
4010 for (
unsigned Op :
Ops)
4012 B.CreateIntrinsic(Intrinsic::spv_loop_control_intel, IntrArgs);
4024 SmallPtrSet<BasicBlock *, 8> UsedMergeBlocks;
4031 SmallVector<unsigned, 1> LoopControlOps =
4033 if (LoopControlOps[0] == SPIRV::LoopControl::None)
4046 for (BasicBlock *BB : {Latch, Header}) {
4050 if (!
L->contains(Succ) && !UsedMergeBlocks.
contains(Succ))
4053 if (!MergeBlock || !UsedMergeBlocks.
insert(MergeBlock).second)
4056 B.SetInsertPoint(Header->getTerminator());
4059 SmallVector<Value *, 4>
Args = {MergeAddress, ContinueAddress};
4060 for (
unsigned Imm : LoopControlOps)
4061 Args.emplace_back(
B.getInt32(
Imm));
4062 B.CreateIntrinsic(Intrinsic::spv_loop_merge, {
Args});
4066bool SPIRVEmitIntrinsicsImpl::runOnFunction(
Function &Func) {
4067 if (
Func.isDeclaration())
4076 GR =
ST.getSPIRVGlobalRegistry();
4080 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
4082 CanUseAnyVectorRank =
4083 ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector);
4087 AggrConstTypes.
clear();
4090 scalarizeVectorPtrCasts(Func);
4091 processParamTypesByFunHeader(CurrF,
B);
4093 if (
ST.isLogicalSPIRV())
4094 foldConstantOffsetIntoArrayIndex(Func);
4098 SmallPtrSet<Instruction *, 4> DeadInsts;
4101 Type *ElTy =
SI->getValueOperand()->getType();
4116 normalizeType(SGEP->getResultElementType(), CanUseAnyVectorRank));
4120 GetElementPtrInst *NewGEP = simplifyZeroLengthArrayGepInst(
GEP);
4122 GEP->replaceAllUsesWith(NewGEP);
4126 if (
Type *GepTy = getGEPType(
GEP))
4130 for (
auto *
I : DeadInsts) {
4131 assert(
I->use_empty() &&
"Dead instruction should not have any uses left");
4132 I->eraseFromParent();
4134 if (AccessChainErrors)
4137 B.SetInsertPoint(
Func.getEntryBlock().begin());
4138 for (
auto &GV :
Func.getParent()->globals())
4139 processGlobalValue(GV,
B);
4141 reconstructAggregateReturns(Func,
B);
4146 insertCompositeAggregateArms(&
I,
B);
4147 preprocessUndefsAndPoisons(
B);
4148 simplifyNullAddrSpaceCasts();
4149 preprocessCompositeConstants(
B);
4157 Type *I32Ty =
B.getInt32Ty();
4161 AggrConstTypes[&
I] =
I.getType();
4162 I.mutateType(I32Ty);
4165 preprocessBoolVectorBitcasts(Func);
4166 SmallVector<Instruction *> Worklist(
4169 applyDemangledPtrArgTypes(
B);
4172 for (
auto &
I : Worklist) {
4174 if (isConvergenceIntrinsic(
I))
4177 bool Postpone = insertAssignPtrTypeIntrs(
I,
B,
false);
4179 insertAssignTypeIntrs(
I,
B);
4180 insertPtrCastOrAssignTypeInstr(
I,
B);
4185 insertAssignPtrTypeIntrs(
I,
B,
true);
4188 useRoundingMode(FPI,
B);
4193 SmallPtrSet<Instruction *, 4> IncompleteRets;
4195 deduceOperandElementType(&
I, &IncompleteRets);
4199 for (BasicBlock &BB : Func)
4200 for (PHINode &Phi : BB.
phis())
4202 deduceOperandElementType(&Phi,
nullptr);
4204 for (
auto *
I : Worklist) {
4205 TrackConstants =
true;
4211 if (AccessChainErrors)
4217 if (isConvergenceIntrinsic(
I))
4221 processInstrAfterVisit(
I,
B);
4224 emitUnstructuredLoopControls(Func,
B);
4230bool SPIRVEmitIntrinsicsImpl::postprocessTypes(
Module &M) {
4231 if (!GR || TodoTypeSz == 0)
4234 unsigned SzTodo = TodoTypeSz;
4235 DenseMap<Value *, SmallPtrSet<Value *, 4>> ToProcess;
4242 if (!KnownTy || !AssignCI)
4248 SmallPtrSet<Value *, 0> Visited;
4249 if (
Type *ElemTy = deduceElementTypeHelper(
Op, Visited,
false,
true)) {
4250 if (ElemTy != KnownTy) {
4251 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
4252 propagateElemType(CI, ElemTy, VisitedSubst);
4259 if (
Op->hasUseList()) {
4260 for (User *U :
Op->users()) {
4267 if (TodoTypeSz == 0)
4272 SmallPtrSet<Instruction *, 4> IncompleteRets;
4274 auto It = ToProcess.
find(&
I);
4275 if (It == ToProcess.
end())
4277 It->second.remove_if([
this](
Value *
V) {
return !isTodoType(
V); });
4278 if (It->second.size() == 0)
4280 deduceOperandElementType(&
I, &IncompleteRets, &It->second,
true);
4281 if (TodoTypeSz == 0)
4286 return SzTodo > TodoTypeSz;
4300 .Cases({
"char",
"signed char",
"unsigned char",
"short",
4301 "unsigned short",
"int",
"unsigned int",
"_Float16",
"float",
4309 unsigned NumElts = 0;
4310 if (
Count.getAsInteger(10, NumElts) || NumElts == 0)
4317 TypeStr.
split(Quals,
' ', -1,
false);
4320 if (Qual !=
"const" && Qual !=
"volatile" && Qual !=
"restrict" &&
4321 !(Qual.consume_front(
"AS") && !Qual.getAsInteger(10, AS)))
4328void SPIRVEmitIntrinsicsImpl::parseFunDeclarations(
Module &M) {
4330 if (!
F.isDeclaration() ||
F.isIntrinsic())
4333 if (DemangledName.empty())
4336 auto Set =
ST.getPreferredInstructionSet();
4337 auto [Grp, Opcode, ExtNo] = SPIRV::mapBuiltinToOpcode(DemangledName, Set);
4339 const bool IsBuiltin = Grp >= 0 || SPIRV::isBuiltin(DemangledName, Set);
4340 if (IsBuiltin && Opcode != SPIRV::OpGroupAsyncCopy)
4342 SmallVector<unsigned> Idxs;
4343 for (Argument &Arg :
F.args())
4348 LLVMContext &Ctx =
F.getContext();
4350 SPIRV::parseBuiltinTypeStr(TypeStrs, DemangledName, Ctx);
4351 if (TypeStrs.
empty())
4354 if (!IsBuiltin && (!
F.getName().starts_with(
"_Z") ||
F.hasStructRetAttr() ||
4355 StringRef(DemangledName).
count(
'(') != 1 ||
4356 StringRef(DemangledName).
count(
')') != 1 ||
4357 StringRef(DemangledName).
contains(
'<') ||
4358 TypeStrs.
size() !=
F.arg_size()))
4360 bool AllowLongVectors =
4361 ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector);
4362 for (
unsigned Idx : Idxs) {
4363 if (Idx >= TypeStrs.
size())
4365 StringRef TypeStr = TypeStrs[
Idx].trim();
4366 Type *ElemTy = IsBuiltin
4367 ? SPIRV::parseBuiltinCallArgumentType(TypeStr, Ctx)
4377 FDeclPtrTys[&
F].emplace_back(Idx, ElemTy);
4379 ST.getSPIRVGlobalRegistry()->addDeducedElementType(
F.getArg(Idx),
4385bool SPIRVEmitIntrinsicsImpl::processMaskedMemIntrinsic(IntrinsicInst &
I) {
4386 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*
I.getFunction());
4388 if (
I.getIntrinsicID() == Intrinsic::masked_gather) {
4389 if (!
ST.canUseExtension(
4390 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
4391 I.getContext().emitError(
4392 &
I,
"llvm.masked.gather requires SPV_INTEL_masked_gather_scatter "
4396 I.eraseFromParent();
4402 Value *Ptrs =
I.getArgOperand(0);
4404 Value *Passthru =
I.getArgOperand(2);
4407 uint32_t
Alignment =
I.getParamAlign(0).valueOrOne().value();
4409 SmallVector<Value *, 4>
Args = {Ptrs,
B.getInt32(Alignment),
Mask,
4414 auto *NewI =
B.CreateIntrinsic(Intrinsic::spv_masked_gather, Types, Args);
4416 I.eraseFromParent();
4420 if (
I.getIntrinsicID() == Intrinsic::masked_scatter) {
4421 if (!
ST.canUseExtension(
4422 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
4423 I.getContext().emitError(
4424 &
I,
"llvm.masked.scatter requires SPV_INTEL_masked_gather_scatter "
4427 I.eraseFromParent();
4434 Value *Ptrs =
I.getArgOperand(1);
4439 uint32_t
Alignment =
I.getParamAlign(1).valueOrOne().value();
4441 SmallVector<Value *, 4>
Args = {
Values, Ptrs,
B.getInt32(Alignment),
Mask};
4445 B.CreateIntrinsic(Intrinsic::spv_masked_scatter, Types, Args);
4446 I.eraseFromParent();
4457void SPIRVEmitIntrinsicsImpl::preprocessBoolVectorBitcasts(
Function &
F) {
4458 struct BoolVecBitcast {
4460 FixedVectorType *BoolVecTy;
4464 auto getAsBoolVec = [](
Type *Ty) -> FixedVectorType * {
4466 return (VTy && VTy->getElementType()->
isIntegerTy(1)) ? VTy :
nullptr;
4474 if (
auto *BVTy = getAsBoolVec(BC->getSrcTy()))
4476 else if (
auto *BVTy = getAsBoolVec(BC->getDestTy()))
4480 for (
auto &[BC, BoolVecTy, SrcIsBoolVec] : ToReplace) {
4482 Value *Src = BC->getOperand(0);
4483 unsigned BoolVecN = BoolVecTy->getNumElements();
4486 Type *OtherTy = SrcIsBoolVec ? BC->getDestTy() : Src->getType();
4487 unsigned NumElts = 1;
4489 NumElts = VTy->getNumElements();
4495 if (!SrcIsBoolVec) {
4498 auto GetLane = [&](
unsigned I) {
4501 Elt =
B.CreateExtractElement(IntVal,
B.getInt32(
I / EltBits));
4505 return B.CreateICmpNE(
And, ConstantInt::get(EltTy, 0));
4513 if (!Idx ||
Idx->getValue().uge(BoolVecN))
4515 B.SetInsertPoint(EE);
4516 EE->replaceAllUsesWith(GetLane(
Idx->getZExtValue()));
4517 EE->eraseFromParent();
4519 if (BC->use_empty()) {
4520 BC->eraseFromParent();
4524 B.SetInsertPoint(BC);
4526 for (
unsigned I = 0;
I < BoolVecN; ++
I)
4527 Result =
B.CreateInsertElement(Result, GetLane(
I),
B.getInt32(
I));
4531 for (
unsigned J = 0; J < NumElts; ++J) {
4532 Value *Elt = ConstantInt::get(EltTy, 0);
4533 for (
unsigned Bit = 0;
Bit < EltBits; ++
Bit) {
4535 B.CreateExtractElement(Src,
B.getInt32(J * EltBits + Bit));
4536 Value *Ext =
B.CreateZExt(Lane, EltTy);
4538 Ext =
B.CreateShl(Ext, ConstantInt::get(EltTy, Bit));
4539 Elt =
B.CreateOr(Elt, Ext);
4541 IntVal = NumElts > 1 ?
B.CreateInsertElement(IntVal, Elt,
B.getInt32(J))
4544 Result =
B.CreateBitCast(IntVal, BC->getDestTy());
4547 BC->replaceAllUsesWith(Result);
4548 BC->eraseFromParent();
4552bool SPIRVEmitIntrinsicsImpl::convertMaskedMemIntrinsics(
Module &M) {
4556 if (!
F.isIntrinsic())
4559 if (IID != Intrinsic::masked_gather && IID != Intrinsic::masked_scatter)
4564 Changed |= processMaskedMemIntrinsic(*
II);
4568 F.eraseFromParent();
4574bool SPIRVEmitIntrinsicsImpl::preprocessModule(
Module &M) {
4578 Type *I32Ty = Type::getInt32Ty(
M.getContext());
4580 if (
F.isDeclaration())
4586 CE &&
CE->getOpcode() == Instruction::GetElementPtr)
4593 if (!AI || !AI->isStaticAlloca() || !AI->isArrayAllocation() ||
4594 AI->getAddressSpace() !=
4599 if (
Count->isZero() || !
Count->getValue().isIntN(32))
4601 AI->setAllocatedType(
4602 ArrayType::get(AI->getAllocatedType(),
Count->getZExtValue()));
4603 AI->setOperand(0, ConstantInt::get(I32Ty, 1));
4607 Changed |= convertMaskedMemIntrinsics(M);
4615 GEPs,
nullptr,
false,
true);
4620bool SPIRVEmitIntrinsicsImpl::runOnModule(
Module &M) {
4621 bool Changed = preprocessModule(M);
4623 parseFunDeclarations(M);
4624 insertConstantsForFPFastMathDefault(M);
4630 if (AccessChainErrors)
4637 if (!
F.isDeclaration() && !
F.isIntrinsic()) {
4639 processParamTypes(&
F,
B);
4643 CanTodoType =
false;
4644 Changed |= postprocessTypes(M);
4647 Changed |= processFunctionPointers(M);
4654 if (SPIRVEmitIntrinsicsImpl(TM).runOnModule(M))
4660 return new SPIRVEmitIntrinsicsLegacy(TM);
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static void replaceAllUsesWith(Value *Old, Value *New, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
Replace all old uses with new ones, and push the updated BBs into FreshBBs.
static Type * getPointeeType(Value *Ptr, const DataLayout &DL)
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
static bool runOnFunction(Function &F, bool PostInlining)
iv Induction Variable Users
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
if(!TBB||Cond.size()< 1) return false
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
static bool isMemInstrToReplace(Instruction *I)
static bool isAggrConstForceInt32(const Value *V)
static Type * getAtomicElemTy(SPIRVGlobalRegistry *GR, Instruction *I, Value *PointerOperand)
static void reportFatalOnTokenType(const Instruction *I)
static void setInsertPointAfterDef(IRBuilder<> &B, Instruction *I)
static SPIRV::FPFastMathDefaultInfoVector & getOrCreateFPFastMathDefaultInfoVec(const Module &M, MapVector< Function *, SPIRV::FPFastMathDefaultInfoVector > &FPFastMathDefaultInfoMap, Function *F)
static bool isArtificialGlobal(StringRef Name)
static Type * getPointeeTypeByCallInst(StringRef DemangledName, Function *CalledF, unsigned OpIdx)
static void createRoundingModeDecoration(Instruction *I, unsigned RoundingModeDeco, IRBuilder<> &B)
static void createDecorationIntrinsic(Instruction *I, MDNode *Node, IRBuilder<> &B)
static void emitAssignName(const SPIRVOptions &CLOpts, Instruction *I, IRBuilder<> &B)
static bool hasOnlyArtificialUses(const GlobalVariable &GV)
static bool isAggregateValueIdInstr(const Instruction &I)
static SPIRV::FPFastMathDefaultInfo & getFPFastMathDefaultInfo(SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec, const Type *Ty)
static bool isAbortCall(const Instruction &I, const SPIRVSubtarget &ST)
static bool tracesToPointerAlloca(Value *V)
static bool isUseListGlobal(StringRef Name)
static bool IsKernelArgInt8(Function *F, StoreInst *SI)
static void addSaturatedDecorationToIntrinsic(Instruction *I, IRBuilder<> &B)
static bool isFirstIndexZero(const GetElementPtrInst *GEP)
static void setInsertPointSkippingPhis(IRBuilder<> &B, Instruction *I)
static bool isSpvAggrPlaceholder(const Value *V)
static Type * getMemberPointeeType(Type *AggrTy, ArrayRef< unsigned > Indices)
static bool precededByAbortIntrinsic(const UnreachableInst &I, const SPIRVSubtarget &ST)
static FunctionType * getFunctionPointerElemType(Function *F, SPIRVGlobalRegistry *GR)
static bool isMultiRegisterAggregate(Value *V)
static void createSaturatedConversionDecoration(Instruction *I, IRBuilder<> &B)
static Type * parseDeclPtrElemType(StringRef TypeStr, LLVMContext &Ctx)
static bool shouldEmitIntrinsicsForGlobalValue(const GlobalVariableUsers &GVUsers, const GlobalVariable &GV, const Function *F)
static Type * restoreMutatedType(SPIRVGlobalRegistry *GR, Instruction *I, Type *Ty)
static bool requireAssignType(Instruction *I)
static void insertSpirvDecorations(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
static SymbolRef::Type getType(const Symbol *Sym)
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
This class represents an incoming formal argument to a Function.
const Function * getParent() const
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
static unsigned getPointerOperandIndex()
static unsigned getPointerOperandIndex()
@ UIncWrap
Increment one up to a maximum value.
@ UDecWrap
Decrement one until a minimum value or zero.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
bool isInlineAsm() const
Check if this call is an inline asm statement.
void setCallingConv(CallingConv::ID CC)
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
This class represents a function call, abstracting a target machine's calling convention.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
uint64_t getNumOperands() const
unsigned getProgramAddressSpace() const
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
iterator find(const_arg_type_t< KeyT > Val)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
static ErrorSuccess success()
Create a success value.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Type * getParamType(unsigned i) const
Parameter type accessors.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Type * getReturnType() const
Returns the type of the ret val.
Argument * getArg(unsigned i) const
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static unsigned getPointerOperandIndex()
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
@ InternalLinkage
Rename collisions when linking (static functions).
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static unsigned getInsertedValueOperandIndex()
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Base class for instruction visitors.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
This is an important class for using LLVM in a threaded context.
static unsigned getPointerOperandIndex()
SmallVector< LoopT *, 4 > getLoopsInPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
void analyze(ParentT F)
Create the loop forest for a function.
const MDOperand & getOperand(unsigned I) const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
unsigned getNumOperands() const
Return number of MDNode operands.
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Flags
Flags values. These may be or'd together.
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
A Module instance is used to store all the information related to an LLVM module.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void buildAssignType(IRBuilder<> &B, Type *Ty, Value *Arg, bool CanUseAnyVectorRank)
void addAssignPtrTypeInstr(Value *Val, CallInst *AssignPtrTyCI)
void buildAssignPtr(IRBuilder<> &B, Type *ElemTy, Value *Arg)
Type * findDeducedCompositeType(const Value *Val)
void replaceAllUsesWith(Value *Old, Value *New, bool DeleteOld=true)
void addDeducedElementType(Value *Val, Type *Ty)
void addReturnType(const Function *ArgF, TypedPointerType *DerivedTy)
Type * findMutated(const Value *Val)
void addDeducedCompositeType(Value *Val, Type *Ty)
void removeAssignPtrTypeInstr(Value *OldVal)
Type * findDeducedElementType(const Value *Val)
void updateAssignType(CallInst *AssignCI, Value *Arg, Value *OfType)
CallInst * findAssignPtrTypeInstr(const Value *Val)
const SPIRVTargetLowering * getTargetLowering() const override
bool isLogicalSPIRV() const
bool canUseExtension(SPIRV::Extension::Extension E) const
const SPIRVOptions & getCLOpts() const
const SPIRVSubtarget * getSubtargetImpl() const
bool erase(PtrType Ptr)
Remove pointer from the set.
iterator find(ConstPtrType Ptr) const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
static unsigned getPointerOperandIndex()
iterator find(StringRef Key)
Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
A switch()-like statement whose cases are string literals.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
static unsigned getPointerOperandIndex()
static LLVM_ABI TargetExtType * get(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters.
MachineMemOperand::Flags getLoadMemOperandFlags(const LoadInst &LI, const DataLayout &DL, AssumptionCache *AC=nullptr, const TargetLibraryInfo *LibInfo=nullptr, CodeGenOptLevel OptLevel=CodeGenOptLevel::Default) const
MachineMemOperand::Flags getStoreMemOperandFlags(const StoreInst &SI, const DataLayout &DL) const
const Triple & getTargetTriple() const
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
VendorType getVendor() const
Get the parsed vendor type of this triple.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isPointerTy() const
True if this is an instance of PointerType.
Type * getArrayElementType() const
bool isSized() const
Return true if it makes sense to take the size of this type.
LLVM_ABI StringRef getTargetExtName() const
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isStructTy() const
True if this is an instance of StructType.
bool isTargetExtTy() const
Return true if this is a target extension type.
bool isAggregateType() const
Return true if the type is an aggregate type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
bool isIntegerTy() const
True if this is an instance of IntegerType.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
bool isVoidTy() const
Return true if this is 'void'.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static LLVM_ABI TypedPointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
void setOperand(unsigned i, Value *Val)
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
user_iterator user_begin()
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
const ParentTy * getParent() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
auto m_AnyIntrinsic()
Matches any intrinsic call and ignore it.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
std::string lookupBuiltinNameHelper(StringRef DemangledCall, FPDecorationId *DecorationId)
Parses the name part of the demangled builtin call.
@ CE
Windows NT (Windows on ARM)
initializer< Ty > init(const Ty &Val)
@ Init
Initialization function, sets up the coroutine frame.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
NodeAddr< NodeBase * > Node
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
unsigned getNumElements(Type *Ty)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt mod(const DynamicAPInt &LHS, const DynamicAPInt &RHS)
is always non-negative.
ModulePass * createSPIRVEmitIntrinsicsPass(const SPIRVTargetMachine &TM)
bool isTypedPointerWrapper(const TargetExtType *ExtTy)
RelativeUniformCounterPtr Values
uint32_t getMemSemanticsWithStorageClass(const Triple &TT, uint32_t OrderSem, uint32_t StorageClassSem)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
unsigned getPointerAddressSpace(const Type *T)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
constexpr T divideFloorSigned(U Numerator, V Denominator)
Returns the integer floor(Numerator / Denominator).
CallInst * buildIntrWithMD(Intrinsic::ID IntrID, ArrayRef< Type * > Types, Value *Arg, Value *Arg2, ArrayRef< Constant * > Imms, IRBuilder<> &B)
bool isUntypedPointerVectorTy(const Type *T)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
bool sortBlocks(Function &F)
bool isa_and_nonnull(const Y &Val)
SPIRV::Scope::Scope getMemScope(const Triple &TT, LLVMContext &Ctx, SyncScope::ID Id)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
SPIRV::MemorySemantics::MemorySemantics getMemSemanticsForStorageClass(SPIRV::StorageClass::StorageClass SC)
constexpr unsigned storageClassToAddressSpace(SPIRV::StorageClass::StorageClass SC)
bool isNestedPointer(const Type *Ty)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Function * getOrCreateBackendServiceFunction(Module &M)
MetadataAsValue * buildMD(Value *Arg)
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
LLVM_ABI bool convertUsersOfConstantsToInstructions(ArrayRef< Constant * > Consts, Function *RestrictToFunc=nullptr, bool RemoveDeadConstants=true, bool IncludeSelf=false)
Replace constant expressions users of the given constants with instructions.
SmallVector< unsigned, 1 > getSpirvLoopControlOperandsFromLoopMetadata(MDNode *LoopMD)
Type * normalizeType(Type *Ty, bool CanUseAnyVectorRank)
auto reverse(ContainerTy &&C)
Type * getTypedPointerWrapper(Type *ElemTy, unsigned AS)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isPointerTy(const Type *T)
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
@ Ref
The access may reference the value stored in memory.
uint32_t getMemoryAccessAlignment(Align A)
@ And
Bitwise or logical AND of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
LLVM_ABI Value * findScalarElement(Value *V, unsigned EltNo)
Given a vector and an element number, see if the scalar value is already around as a register,...
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
bool isLongVectorEXT(const Type *Ty, bool CanUseVector16=true)
Type * parseBasicTypeName(StringRef &TypeName, LLVMContext &Ctx)
DWARFExpression::Operation Op
Type * getPointeeTypeByAttr(Argument *Arg)
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
bool hasPointeeTypeAttr(Argument *Arg)
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructionsPermissive(SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow instructions that are not...
constexpr unsigned BitWidth
bool isEquivalentTypes(Type *Ty1, Type *Ty2)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
bool hasInitializer(const GlobalVariable *GV)
bool isPointerTyOrWrapper(const Type *Ty)
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID)
PoisonValue * getNormalizedPoisonValue(Type *Ty, bool CanUseAnyVectorRank)
bool isUntypedPointerTy(const Type *T)
Type * reconstitutePeeledArrayType(Type *Ty)
bool spirvPreserveAuxData(const SPIRVOptions &CLOpts, const Triple &TT)
SPIRV::MemorySemantics::MemorySemantics getMemSemantics(AtomicOrdering Ord)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
static size_t computeFPFastMathDefaultInfoVecIndex(size_t BitWidth)