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 (User *U :
II->users()) {
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++) {
2650 Type *ExpectedType =
2651 OpIdx < CalledArgTys.
size() ? CalledArgTys[OpIdx] :
nullptr;
2652 if (!ExpectedType && ParseBuiltinTypes)
2653 ExpectedType = SPIRV::parseBuiltinCallArgumentBaseType(
2654 DemangledName, OpIdx,
I->getContext());
2655 if (!ExpectedType || ExpectedType->
isVoidTy())
2663 replacePointerOperandWithPtrCast(CI, ArgOperand, ExpectedType, OpIdx,
B);
2668SPIRVEmitIntrinsicsImpl::visitInsertElementInst(InsertElementInst &
I) {
2671 if (
isVector1(
I.getType()) && !CanUseAnyVectorRank)
2675 I.getOperand(1)->getType(),
2676 I.getOperand(2)->getType()};
2678 B.SetInsertPoint(&
I);
2680 Instruction *NewI =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertelt,
2682 replaceAllUsesWithAndErase(
B, &
I, NewI);
2687SPIRVEmitIntrinsicsImpl::visitExtractElementInst(ExtractElementInst &
I) {
2690 if (
isVector1(
I.getVectorOperandType()) && !CanUseAnyVectorRank)
2694 B.SetInsertPoint(&
I);
2696 I.getIndexOperand()->getType()};
2697 SmallVector<Value *, 2>
Args = {
I.getVectorOperand(),
I.getIndexOperand()};
2698 Instruction *NewI =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractelt,
2700 replaceAllUsesWithAndErase(
B, &
I, NewI);
2708void SPIRVEmitIntrinsicsImpl::scalarizeVectorPtrCasts(
Function &
F) {
2712 if (
ST.canUseExtension(SPIRV::Extension::SPV_INTEL_masked_gather_scatter))
2715 SmallVector<Instruction *, 8> ToErase;
2720 if (!VecTy || !VecTy->getElementType()->isPointerTy())
2724 unsigned NumElems = VecTy->getNumElements();
2728 for (
unsigned Idx = 0;
Idx < NumElems; ++
Idx) {
2731 ElemPtr =
B.CreateExtractElement(PTI->getOperand(0),
B.getInt32(Idx));
2732 Value *Conv =
B.CreatePtrToInt(ElemPtr, ElemIntTy);
2733 Result =
B.CreateInsertElement(Result, Conv,
B.getInt32(Idx));
2736 PTI->replaceAllUsesWith(Result);
2740 if (!VecTy || !VecTy->getElementType()->isPointerTy())
2746 bool AllUsersExtract =
llvm::all_of(ITP->users(), [&](User *U) {
2747 auto *EE = dyn_cast<ExtractElementInst>(U);
2748 return EE && isa<ConstantInt>(EE->getIndexOperand());
2750 if (!AllUsersExtract)
2754 Type *ElemPtrTy = VecTy->getElementType();
2760 B.SetInsertPoint(EE);
2762 B.CreateExtractElement(ITP->getOperand(0),
B.getInt32(Idx));
2763 Value *Conv =
B.CreateIntToPtr(Elem, ElemPtrTy);
2772 if (ToErase.
empty())
2775 for (Instruction *
I : ToErase) {
2776 for (
Value *
Op :
I->operand_values())
2778 I->eraseFromParent();
2783Instruction *SPIRVEmitIntrinsicsImpl::visitInsertValueInst(InsertValueInst &
I) {
2785 B.SetInsertPoint(&
I);
2788 Value *AggregateOp =
I.getAggregateOperand();
2792 Args.push_back(AggregateOp);
2793 Args.push_back(
I.getInsertedValueOperand());
2794 for (
auto &
Op :
I.indices())
2795 Args.push_back(
B.getInt32(
Op));
2797 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertv, {
Types}, {
Args});
2798 replaceMemInstrUses(&
I, NewI,
B);
2803SPIRVEmitIntrinsicsImpl::visitExtractValueInst(ExtractValueInst &
I) {
2805 B.SetInsertPoint(&
I);
2806 if (
I.getAggregateOperand()->getType()->isAggregateType()) {
2815 for (
auto &
Op :
I.indices())
2816 Args.push_back(
B.getInt32(
Op));
2817 Instruction *NewI =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractv,
2818 {
I.getType()}, {
Args});
2823 Type *AggrTy =
I.getType();
2824 AggrConstTypes[NewI] = AggrTy;
2826 replaceMemInstrUses(&
I, NewI,
B);
2833 replaceAllUsesWithAndErase(
B, &
I, NewI);
2837Instruction *SPIRVEmitIntrinsicsImpl::visitLoadInst(LoadInst &
I) {
2838 if (!
I.getType()->isAggregateType())
2841 B.SetInsertPoint(&
I);
2842 TrackConstants =
false;
2847 unsigned IntrinsicId;
2848 SmallVector<Value *, 4>
Args = {
I.getPointerOperand(),
B.getInt16(Flags)};
2849 if (!
I.isAtomic()) {
2850 IntrinsicId = Intrinsic::spv_load;
2851 Args.push_back(
B.getInt32(
I.getAlign().value()));
2853 IntrinsicId = Intrinsic::spv_atomic_load;
2854 Args.push_back(
B.getInt8(
static_cast<uint8_t
>(
I.getOrdering())));
2856 CallInst *NewI =
B.CreateIntrinsicWithoutFolding(
2857 IntrinsicId, {
I.getOperand(0)->getType()},
Args);
2859 replaceMemInstrUses(&
I, NewI,
B);
2863Instruction *SPIRVEmitIntrinsicsImpl::visitStoreInst(StoreInst &
I) {
2867 B.SetInsertPoint(&
I);
2868 TrackConstants =
false;
2872 auto *PtrOp =
I.getPointerOperand();
2874 if (
I.getValueOperand()->getType()->isAggregateType()) {
2882 "Unexpected argument of aggregate type, should be spv_extractv!");
2886 unsigned IntrinsicId;
2887 SmallVector<Value *, 4>
Args = {
I.getValueOperand(), PtrOp,
2889 if (!
I.isAtomic()) {
2890 IntrinsicId = Intrinsic::spv_store;
2891 Args.push_back(
B.getInt32(
I.getAlign().value()));
2893 IntrinsicId = Intrinsic::spv_atomic_store;
2894 Args.push_back(
B.getInt8(
static_cast<uint8_t
>(
I.getOrdering())));
2897 IntrinsicId, {
I.getValueOperand()->getType(), PtrOp->
getType()},
Args);
2899 I.eraseFromParent();
2903Instruction *SPIRVEmitIntrinsicsImpl::visitAllocaInst(AllocaInst &
I) {
2904 Value *ArraySize =
nullptr;
2905 if (
I.isArrayAllocation()) {
2908 SPIRV::Extension::SPV_INTEL_variable_length_array))
2910 "array allocation: this instruction requires the following "
2911 "SPIR-V extension: SPV_INTEL_variable_length_array",
2913 ArraySize =
I.getArraySize();
2916 B.SetInsertPoint(&
I);
2917 TrackConstants =
false;
2918 Type *PtrTy =
I.getType();
2921 ?
B.CreateIntrinsicWithoutFolding(
2922 Intrinsic::spv_alloca_array, {PtrTy, ArraySize->
getType()},
2923 {ArraySize,
B.getInt32(
I.getAlign().value())})
2924 :
B.CreateIntrinsicWithoutFolding(
Intrinsic::spv_alloca, {PtrTy},
2925 {
B.getInt32(
I.getAlign().value())});
2926 replaceAllUsesWithAndErase(
B, &
I, NewI);
2931SPIRVEmitIntrinsicsImpl::visitAtomicCmpXchgInst(AtomicCmpXchgInst &
I) {
2932 assert(
I.getType()->isAggregateType() &&
"Aggregate result is expected");
2934 B.SetInsertPoint(&
I);
2937 Args.push_back(
B.getInt32(
static_cast<uint32_t
>(
2941 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*
I.getFunction());
2942 unsigned AS =
I.getPointerOperand()->getType()->getPointerAddressSpace();
2943 uint32_t ScSem =
static_cast<uint32_t
>(
2952 Intrinsic::spv_cmpxchg, {
I.getPointerOperand()->getType()}, {
Args});
2953 replaceMemInstrUses(&
I, NewI,
B);
2957Instruction *SPIRVEmitIntrinsicsImpl::visitAtomicRMWInst(AtomicRMWInst &
I) {
2958 auto Op =
I.getOperation();
2969 B.SetInsertPoint(&
I);
2971 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*
I.getFunction());
2972 unsigned AS =
I.getPointerOperand()->getType()->getPointerAddressSpace();
2974 uint32_t
Scope =
static_cast<uint32_t
>(
2975 getMemScope(
M->getTargetTriple(),
I.getContext(),
I.getSyncScopeID()));
2976 uint32_t ScSem =
static_cast<uint32_t
>(
2979 M->getTargetTriple(),
2983 ?
"__translate_spirv_atomic_uinc_wrap"
2984 :
"__translate_spirv_atomic_udec_wrap");
2986 Type *ValTy =
I.getValOperand()->getType();
2987 Type *PtrTy =
I.getPointerOperand()->getType();
2989 raw_svector_ostream OS(FuncName);
2990 OS <<
"_p" << AS <<
"_";
2992 OS <<
"v" << VecTy->getNumElements();
2995 Type *Int32Ty =
B.getInt32Ty();
2996 Type *BoolTy =
B.getInt1Ty();
2998 ValTy, BoolTy, BoolTy};
2999 FunctionType *FT = FunctionType::get(ValTy, ArgTys,
false);
3000 FunctionCallee
FC =
M->getOrInsertFunction(FuncName, FT);
3004 I.getPointerOperand(),
B.getInt32(Scope),
3005 B.getInt32(MemSem),
I.getValOperand(),
3006 B.getInt1(
I.isVolatile()),
B.getInt1(
I.isElementwise())};
3007 CallInst *CI =
B.CreateCall(FC, Args);
3013 replaceAllUsesWithAndErase(
B, &
I, CI);
3022 case Intrinsic::spv_abort:
3024 case Intrinsic::trap:
3025 case Intrinsic::ubsantrap:
3027 return ST.canUseExtension(SPIRV::Extension::SPV_KHR_abort);
3043 [&ST](
const Instruction &
II) { return isAbortCall(II, ST); }) &&
3044 "abort-like call must be the last non-debug instruction before its "
3045 "block's terminator");
3049Instruction *SPIRVEmitIntrinsicsImpl::visitUnreachableInst(UnreachableInst &
I) {
3050 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*
I.getFunction());
3054 B.CreateIntrinsic(Intrinsic::spv_unreachable, {});
3061 return Name ==
"llvm.compiler.used" || Name ==
"llvm.used";
3075 while (!Stack.empty()) {
3076 const Value *
V = Stack.pop_back_val();
3077 if (!Visited.
insert(
V).second)
3085 Stack.append(
C->user_begin(),
C->user_end());
3101 auto &UserFunctions = GVUsers.getTransitiveUserFunctions(GV);
3102 if (UserFunctions.contains(
F))
3107 if (!UserFunctions.empty())
3112 const Module &M = *
F->getParent();
3113 const Function &FirstDefinition = *M.getFunctionDefs().
begin();
3114 return F == &FirstDefinition;
3117Value *SPIRVEmitIntrinsicsImpl::buildSpvUndefComposite(
Type *AggrTy,
3119 auto MakeLeaf = [&](
Type *ElemTy) -> Instruction * {
3120 CallInst *Leaf =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_undef, {});
3122 AggrConstTypes[Leaf] = ElemTy;
3125 SmallVector<Value *, 4> Elems;
3127 Elems.
assign(ArrTy->getNumElements(), MakeLeaf(ArrTy->getElementType()));
3130 DenseMap<Type *, Instruction *> LeafByType;
3131 for (
unsigned I = 0;
I < StructTy->getNumElements(); ++
I) {
3133 auto &
Entry = LeafByType[ElemTy];
3135 Entry = MakeLeaf(ElemTy);
3139 CallInst *Composite =
B.CreateIntrinsicWithoutFolding(
3140 Intrinsic::spv_const_composite, {
B.getInt32Ty()}, Elems);
3142 AggrConstTypes[Composite] = AggrTy;
3151void SPIRVEmitIntrinsicsImpl::reconstructAggregateReturns(
Function &Func,
3156 for (BasicBlock &BB : Func) {
3160 Value *RetVal = RI->getReturnValue();
3167 B.SetInsertPoint(RI);
3170 Value *Elt =
B.CreateExtractValue(RetVal,
I);
3171 Rebuilt =
B.CreateInsertValue(Rebuilt, Elt,
I);
3173 RI->setOperand(0, Rebuilt);
3177void SPIRVEmitIntrinsicsImpl::processGlobalValue(GlobalVariable &GV,
3187 deduceElementTypeHelper(&GV,
false);
3192 Value *InitOp = Init;
3199 CallInst *
Call =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_poison,
3200 {
B.getInt32Ty()}, {});
3205 InitOp = buildSpvUndefComposite(Init->
getType(),
B);
3210 CallInst *InitInst =
B.CreateIntrinsicWithoutFolding(
3211 Intrinsic::spv_init_global, {GV.
getType(), Ty}, {&GV,
Const});
3217 B.CreateIntrinsic(Intrinsic::spv_unref_global, GV.
getType(), &GV);
3223bool SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeIntrs(Instruction *
I,
3225 bool UnknownElemTypeI8) {
3231 if (
Type *ElemTy = deduceElementType(
I, UnknownElemTypeI8)) {
3238void SPIRVEmitIntrinsicsImpl::insertAssignTypeIntrs(Instruction *
I,
3241 static StringMap<unsigned> ResTypeWellKnown = {
3242 {
"async_work_group_copy", WellKnownTypes::Event},
3243 {
"async_work_group_strided_copy", WellKnownTypes::Event},
3244 {
"__spirv_GroupAsyncCopy", WellKnownTypes::Event}};
3248 bool IsKnown =
false;
3253 std::string DemangledName =
3256 if (DemangledName.length() > 0)
3258 SPIRV::lookupBuiltinNameHelper(DemangledName, &DecorationId);
3259 auto ResIt = ResTypeWellKnown.
find(DemangledName);
3260 if (ResIt != ResTypeWellKnown.
end()) {
3263 switch (ResIt->second) {
3264 case WellKnownTypes::Event:
3267 CanUseAnyVectorRank);
3272 switch (DecorationId) {
3275 case FPDecorationId::SAT:
3278 case FPDecorationId::RTE:
3280 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTE,
B);
3282 case FPDecorationId::RTZ:
3284 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTZ,
B);
3286 case FPDecorationId::RTP:
3288 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTP,
B);
3290 case FPDecorationId::RTN:
3292 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTN,
B);
3298 Type *Ty =
I->getType();
3301 Type *TypeToAssign = Ty;
3304 auto It = AggrConstTypes.
find(
II);
3305 if (It == AggrConstTypes.
end())
3307 TypeToAssign = It->second;
3308 }
else if (
II->getIntrinsicID() == Intrinsic::spv_poison) {
3309 if (
auto It = AggrConstTypes.
find(
II); It != AggrConstTypes.
end())
3310 TypeToAssign = It->second;
3312 }
else if (
auto It = AggrConstTypes.
find(
I); It != AggrConstTypes.
end())
3313 TypeToAssign = It->second;
3317 for (
const auto &
Op :
I->operands()) {
3325 Type *OpTy =
Op->getType();
3327 CallInst *AssignCI =
3332 Type *OpTy =
Op->getType();
3348 Intrinsic::spv_assign_type, {OpTy},
3358bool SPIRVEmitIntrinsicsImpl::shouldTryToAddMemAliasingDecoration(
3359 Instruction *Inst) {
3361 if (!STI->
canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing))
3371void SPIRVEmitIntrinsicsImpl::insertSpirvDecorations(Instruction *
I,
3373 if (MDNode *MD =
I->getMetadata(
"spirv.Decorations")) {
3375 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {
I->getType()},
3380 auto processMemAliasingDecoration = [&](
unsigned Kind) {
3381 if (MDNode *AliasListMD =
I->getMetadata(Kind)) {
3382 if (shouldTryToAddMemAliasingDecoration(
I)) {
3383 uint32_t Dec =
Kind == LLVMContext::MD_alias_scope
3384 ? SPIRV::Decoration::AliasScopeINTEL
3385 : SPIRV::Decoration::NoAliasINTEL;
3387 I, ConstantInt::get(
B.getInt32Ty(), Dec),
3390 B.CreateIntrinsic(Intrinsic::spv_assign_aliasing_decoration,
3391 {
I->getType()}, {
Args});
3395 processMemAliasingDecoration(LLVMContext::MD_alias_scope);
3396 processMemAliasingDecoration(LLVMContext::MD_noalias);
3399 if (MDNode *MD =
I->getMetadata(LLVMContext::MD_fpmath)) {
3401 bool AllowFPMaxError =
3403 if (!AllowFPMaxError)
3407 B.CreateIntrinsic(Intrinsic::spv_assign_fpmaxerror_decoration,
3413 LLVMContext &Ctx =
B.getContext();
3415 B.getInt32Ty(), SPIRV::Decoration::AuxDataInstructionMetadata));
3418 if (
I->hasMetadata(
"amdgpu.no.fine.grained.memory"))
3420 Ctx, {AuxMD,
MDString::get(Ctx,
"amdgpu.no.fine.grained.memory")}));
3421 if (
I->hasMetadata(
"amdgpu.no.remote.memory"))
3423 Ctx, {AuxMD,
MDString::get(Ctx,
"amdgpu.no.remote.memory")}));
3424 if (
I->hasMetadata(LLVMContext::MD_atomic_ignore_denormal_mode))
3426 Ctx, {AuxMD,
MDString::get(Ctx,
"atomic.ignore.denormal.mode")}));
3429 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {
I->getType()},
3438 &FPFastMathDefaultInfoMap,
3440 auto it = FPFastMathDefaultInfoMap.
find(
F);
3441 if (it != FPFastMathDefaultInfoMap.
end())
3449 SPIRV::FPFastMathMode::None);
3451 SPIRV::FPFastMathMode::None);
3453 SPIRV::FPFastMathMode::None);
3454 return FPFastMathDefaultInfoMap[
F] = std::move(FPFastMathDefaultInfoVec);
3460 size_t BitWidth = Ty->getScalarSizeInBits();
3464 assert(Index >= 0 && Index < 3 &&
3465 "Expected FPFastMathDefaultInfo for half, float, or double");
3466 assert(FPFastMathDefaultInfoVec.
size() == 3 &&
3467 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3468 return FPFastMathDefaultInfoVec[Index];
3471void SPIRVEmitIntrinsicsImpl::insertConstantsForFPFastMathDefault(
Module &M) {
3473 if (!
ST->canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2))
3482 auto Node =
M.getNamedMetadata(
"spirv.ExecutionMode");
3484 if (!
M.getNamedMetadata(
"opencl.enable.FP_CONTRACT")) {
3492 ConstantInt::get(Type::getInt32Ty(
M.getContext()), 0);
3495 [[maybe_unused]] GlobalVariable *GV =
3496 new GlobalVariable(M,
3497 Type::getInt32Ty(
M.getContext()),
3511 MapVector<Function *, SPIRV::FPFastMathDefaultInfoVector>
3512 FPFastMathDefaultInfoMap;
3514 for (
unsigned i = 0; i <
Node->getNumOperands(); i++) {
3523 if (EM == SPIRV::ExecutionMode::FPFastMathDefault) {
3525 "Expected 4 operands for FPFastMathDefault");
3531 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3533 SPIRV::FPFastMathDefaultInfo &
Info =
3536 Info.FPFastMathDefault =
true;
3537 }
else if (EM == SPIRV::ExecutionMode::ContractionOff) {
3539 "Expected no operands for ContractionOff");
3543 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3545 for (SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3546 Info.ContractionOff =
true;
3548 }
else if (EM == SPIRV::ExecutionMode::SignedZeroInfNanPreserve) {
3550 "Expected 1 operand for SignedZeroInfNanPreserve");
3551 unsigned TargetWidth =
3556 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3560 assert(Index >= 0 && Index < 3 &&
3561 "Expected FPFastMathDefaultInfo for half, float, or double");
3562 assert(FPFastMathDefaultInfoVec.
size() == 3 &&
3563 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3564 FPFastMathDefaultInfoVec[
Index].SignedZeroInfNanPreserve =
true;
3568 DenseMap<unsigned, GlobalVariable *> GlobalVars;
3569 for (
auto &[Func, FPFastMathDefaultInfoVec] : FPFastMathDefaultInfoMap) {
3570 if (FPFastMathDefaultInfoVec.
empty())
3573 for (
const SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3574 assert(
Info.Ty &&
"Expected target type for FPFastMathDefaultInfo");
3577 if (Flags == SPIRV::FPFastMathMode::None && !
Info.ContractionOff &&
3578 !
Info.SignedZeroInfNanPreserve && !
Info.FPFastMathDefault)
3582 if (
Info.ContractionOff && (Flags & SPIRV::FPFastMathMode::AllowContract))
3584 "and AllowContract");
3586 if (
Info.SignedZeroInfNanPreserve &&
3588 (SPIRV::FPFastMathMode::NotNaN | SPIRV::FPFastMathMode::NotInf |
3589 SPIRV::FPFastMathMode::NSZ))) {
3590 if (
Info.FPFastMathDefault)
3592 "SignedZeroInfNanPreserve but at least one of "
3593 "NotNaN/NotInf/NSZ is enabled.");
3596 if ((Flags & SPIRV::FPFastMathMode::AllowTransform) &&
3597 !((Flags & SPIRV::FPFastMathMode::AllowReassoc) &&
3598 (Flags & SPIRV::FPFastMathMode::AllowContract))) {
3600 "AllowTransform requires AllowReassoc and "
3601 "AllowContract to be set.");
3604 auto it = GlobalVars.
find(Flags);
3605 GlobalVariable *GV =
nullptr;
3606 if (it != GlobalVars.
end()) {
3612 ConstantInt::get(Type::getInt32Ty(
M.getContext()), Flags);
3615 GV =
new GlobalVariable(M,
3616 Type::getInt32Ty(
M.getContext()),
3621 GlobalVars[
Flags] = GV;
3627void SPIRVEmitIntrinsicsImpl::processInstrAfterVisit(Instruction *
I,
3630 bool IsConstComposite =
3631 II &&
II->getIntrinsicID() == Intrinsic::spv_const_composite;
3632 if (IsConstComposite && TrackConstants) {
3634 auto t = AggrConsts.
find(
I);
3638 {
II->getType(),
II->getType()}, t->second,
I, {},
B);
3640 NewOp->setArgOperand(0,
I);
3643 for (
const auto &
Op :
I->operands()) {
3647 unsigned OpNo =
Op.getOperandNo();
3648 if (
II && ((
II->getIntrinsicID() == Intrinsic::spv_gep && OpNo == 0) ||
3649 (!
II->isBundleOperand(OpNo) &&
3650 II->paramHasAttr(OpNo, Attribute::ImmArg))))
3654 IsPhi ?
B.SetInsertPointPastAllocas(
I->getParent()->getParent())
3655 :
B.SetInsertPoint(
I);
3658 Type *OpTy =
Op->getType();
3666 {OpTy, OpTyVal->
getType()},
Op, OpTyVal, {},
B);
3668 if (!IsConstComposite &&
isPointerTy(OpTy) && OpElemTy !=
nullptr &&
3669 OpElemTy != IntegerType::getInt8Ty(
I->getContext())) {
3671 SmallVector<Value *, 2>
Args = {
3675 CallInst *PtrCasted =
B.CreateIntrinsicWithoutFolding(
3681 I->setOperand(OpNo, NewOp);
3687Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(
Function *
F,
3689 SmallPtrSet<Function *, 0> FVisited;
3690 return deduceFunParamElementType(
F, OpIdx, FVisited);
3693Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(
3694 Function *
F,
unsigned OpIdx, SmallPtrSetImpl<Function *> &FVisited) {
3696 if (!FVisited.
insert(
F).second)
3699 SmallPtrSet<Value *, 0> Visited;
3702 for (User *U :
F->users()) {
3704 if (!CI || OpIdx >= CI->
arg_size())
3714 if (
Type *Ty = deduceElementTypeHelper(OpArg, Visited,
false))
3717 for (User *OpU : OpArg->
users()) {
3719 if (!Inst || Inst == CI)
3722 if (
Type *Ty = deduceElementTypeHelper(Inst, Visited,
false))
3729 if (FVisited.
find(OuterF) != FVisited.
end())
3731 for (
unsigned i = 0; i < OuterF->
arg_size(); ++i) {
3732 if (OuterF->
getArg(i) == OpArg) {
3733 Lookup.push_back(std::make_pair(OuterF, i));
3740 for (
auto &Pair :
Lookup) {
3741 if (
Type *Ty = deduceFunParamElementType(Pair.first, Pair.second, FVisited))
3748void SPIRVEmitIntrinsicsImpl::processParamTypesByFunHeader(
Function *
F,
3750 B.SetInsertPointPastAllocas(
F);
3751 for (
unsigned OpIdx = 0; OpIdx <
F->arg_size(); ++OpIdx) {
3757 for (User *U : Arg->
users()) {
3759 if (
GEP &&
GEP->getPointerOperand() == Arg) {
3777 for (User *U :
F->users()) {
3779 if (!CI || OpIdx >= CI->
arg_size())
3793 for (User *U : Arg->
users()) {
3797 CI->
getParent()->getParent() == CurrF) {
3799 deduceOperandElementTypeFunctionPointer(CI,
Ops, ElemTy,
false);
3811 B.SetInsertPointPastAllocas(
F);
3812 for (
unsigned OpIdx = 0; OpIdx <
F->arg_size(); ++OpIdx) {
3817 if (!ElemTy && (ElemTy = deduceFunParamElementType(
F, OpIdx)) !=
nullptr) {
3819 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
3823 propagateElemType(Arg, IntegerType::getInt8Ty(
F->getContext()),
3835 bool IsNewFTy =
false;
3851bool SPIRVEmitIntrinsicsImpl::processFunctionPointers(
Module &M) {
3854 if (
F.isIntrinsic())
3856 if (
F.isDeclaration()) {
3857 for (User *U :
F.users()) {
3860 UF &&
UF->hasPersonalityFn() &&
UF->getPersonalityFn() == &
F)
3874 for (User *U :
F.users()) {
3876 if (!
II ||
II->arg_size() != 3 ||
II->getOperand(0) != &
F)
3878 if (
II->getIntrinsicID() == Intrinsic::spv_assign_ptr_type ||
3879 II->getIntrinsicID() == Intrinsic::spv_ptrcast) {
3887 if (Worklist.
empty())
3890 LLVMContext &Ctx =
M.getContext();
3897 for (
const auto &Arg :
F->args())
3900 IRB.CreateCall(
F, Args)->setTailCall(
true);
3902 IRB.CreateRetVoid();
3908void SPIRVEmitIntrinsicsImpl::applyDemangledPtrArgTypes(
IRBuilder<> &
B) {
3909 DenseMap<Function *, CallInst *> Ptrcasts;
3910 for (
auto It : FDeclPtrTys) {
3912 for (
auto *U :
F->users()) {
3917 for (
auto [Idx, ElemTy] : It.second) {
3925 B.SetInsertPointPastAllocas(Arg->
getParent());
3932 replaceUsesOfWithSpvPtrcast(
3933 Param,
normalizeType(ElemTy, CanUseAnyVectorRank), CI, Ptrcasts);
3942 .getFirstNonPHIOrAlloca());
3960 FDeclPtrTys.
clear();
3963GetElementPtrInst *SPIRVEmitIntrinsicsImpl::simplifyZeroLengthArrayGepInst(
3964 GetElementPtrInst *
GEP) {
3971 Type *SrcTy =
GEP->getSourceElementType();
3972 SmallVector<Value *, 8> Indices(
GEP->indices());
3974 if (ArrTy && ArrTy->getNumElements() == 0 &&
match(Indices[0],
m_Zero())) {
3975 Indices.erase(Indices.begin());
3976 SrcTy = ArrTy->getElementType();
3978 GEP->getNoWrapFlags(),
"",
3979 GEP->getIterator());
3984void SPIRVEmitIntrinsicsImpl::emitUnstructuredLoopControls(
Function &
F,
3991 if (
ST->canUseExtension(
3992 SPIRV::Extension::SPV_INTEL_unstructured_loop_controls)) {
3993 for (BasicBlock &BB :
F) {
3995 MDNode *LoopMD =
Term->getMetadata(LLVMContext::MD_loop);
3999 SmallVector<unsigned, 1>
Ops =
4001 unsigned LC =
Ops[0];
4002 if (LC == SPIRV::LoopControl::None)
4006 B.SetInsertPoint(Term);
4007 SmallVector<Value *, 4> IntrArgs;
4008 for (
unsigned Op :
Ops)
4010 B.CreateIntrinsic(Intrinsic::spv_loop_control_intel, IntrArgs);
4022 SmallPtrSet<BasicBlock *, 8> UsedMergeBlocks;
4029 SmallVector<unsigned, 1> LoopControlOps =
4031 if (LoopControlOps[0] == SPIRV::LoopControl::None)
4044 for (BasicBlock *BB : {Latch, Header}) {
4048 if (!
L->contains(Succ) && !UsedMergeBlocks.
contains(Succ))
4051 if (!MergeBlock || !UsedMergeBlocks.
insert(MergeBlock).second)
4054 B.SetInsertPoint(Header->getTerminator());
4057 SmallVector<Value *, 4>
Args = {MergeAddress, ContinueAddress};
4058 for (
unsigned Imm : LoopControlOps)
4059 Args.emplace_back(
B.getInt32(
Imm));
4060 B.CreateIntrinsic(Intrinsic::spv_loop_merge, {
Args});
4064bool SPIRVEmitIntrinsicsImpl::runOnFunction(
Function &Func) {
4065 if (
Func.isDeclaration())
4074 GR =
ST.getSPIRVGlobalRegistry();
4078 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
4080 CanUseAnyVectorRank =
4081 ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector);
4085 AggrConstTypes.
clear();
4088 scalarizeVectorPtrCasts(Func);
4089 processParamTypesByFunHeader(CurrF,
B);
4091 if (
ST.isLogicalSPIRV())
4092 foldConstantOffsetIntoArrayIndex(Func);
4096 SmallPtrSet<Instruction *, 4> DeadInsts;
4099 Type *ElTy =
SI->getValueOperand()->getType();
4114 normalizeType(SGEP->getResultElementType(), CanUseAnyVectorRank));
4118 GetElementPtrInst *NewGEP = simplifyZeroLengthArrayGepInst(
GEP);
4120 GEP->replaceAllUsesWith(NewGEP);
4124 if (
Type *GepTy = getGEPType(
GEP))
4128 for (
auto *
I : DeadInsts) {
4129 assert(
I->use_empty() &&
"Dead instruction should not have any uses left");
4130 I->eraseFromParent();
4132 if (AccessChainErrors)
4135 B.SetInsertPoint(
Func.getEntryBlock().begin());
4136 for (
auto &GV :
Func.getParent()->globals())
4137 processGlobalValue(GV,
B);
4139 reconstructAggregateReturns(Func,
B);
4144 insertCompositeAggregateArms(&
I,
B);
4145 preprocessUndefsAndPoisons(
B);
4146 simplifyNullAddrSpaceCasts();
4147 preprocessCompositeConstants(
B);
4155 Type *I32Ty =
B.getInt32Ty();
4159 AggrConstTypes[&
I] =
I.getType();
4160 I.mutateType(I32Ty);
4163 preprocessBoolVectorBitcasts(Func);
4164 SmallVector<Instruction *> Worklist(
4167 applyDemangledPtrArgTypes(
B);
4170 for (
auto &
I : Worklist) {
4172 if (isConvergenceIntrinsic(
I))
4175 bool Postpone = insertAssignPtrTypeIntrs(
I,
B,
false);
4177 insertAssignTypeIntrs(
I,
B);
4178 insertPtrCastOrAssignTypeInstr(
I,
B);
4183 insertAssignPtrTypeIntrs(
I,
B,
true);
4186 useRoundingMode(FPI,
B);
4191 SmallPtrSet<Instruction *, 4> IncompleteRets;
4193 deduceOperandElementType(&
I, &IncompleteRets);
4197 for (BasicBlock &BB : Func)
4198 for (PHINode &Phi : BB.
phis())
4200 deduceOperandElementType(&Phi,
nullptr);
4202 for (
auto *
I : Worklist) {
4203 TrackConstants =
true;
4209 if (AccessChainErrors)
4215 if (isConvergenceIntrinsic(
I))
4219 processInstrAfterVisit(
I,
B);
4222 emitUnstructuredLoopControls(Func,
B);
4228bool SPIRVEmitIntrinsicsImpl::postprocessTypes(
Module &M) {
4229 if (!GR || TodoTypeSz == 0)
4232 unsigned SzTodo = TodoTypeSz;
4233 DenseMap<Value *, SmallPtrSet<Value *, 4>> ToProcess;
4240 if (!KnownTy || !AssignCI)
4246 SmallPtrSet<Value *, 0> Visited;
4247 if (
Type *ElemTy = deduceElementTypeHelper(
Op, Visited,
false,
true)) {
4248 if (ElemTy != KnownTy) {
4249 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
4250 propagateElemType(CI, ElemTy, VisitedSubst);
4257 if (
Op->hasUseList()) {
4258 for (User *U :
Op->users()) {
4265 if (TodoTypeSz == 0)
4270 SmallPtrSet<Instruction *, 4> IncompleteRets;
4272 auto It = ToProcess.
find(&
I);
4273 if (It == ToProcess.
end())
4275 It->second.remove_if([
this](
Value *
V) {
return !isTodoType(
V); });
4276 if (It->second.size() == 0)
4278 deduceOperandElementType(&
I, &IncompleteRets, &It->second,
true);
4279 if (TodoTypeSz == 0)
4284 return SzTodo > TodoTypeSz;
4298 .Cases({
"char",
"signed char",
"unsigned char",
"short",
4299 "unsigned short",
"int",
"unsigned int",
"_Float16",
"float",
4307 unsigned NumElts = 0;
4308 if (
Count.getAsInteger(10, NumElts) || NumElts == 0)
4315 TypeStr.
split(Quals,
' ', -1,
false);
4318 if (Qual !=
"const" && Qual !=
"volatile" && Qual !=
"restrict" &&
4319 !(Qual.consume_front(
"AS") && !Qual.getAsInteger(10, AS)))
4326void SPIRVEmitIntrinsicsImpl::parseFunDeclarations(
Module &M) {
4328 if (!
F.isDeclaration() ||
F.isIntrinsic())
4331 if (DemangledName.empty())
4334 auto Set =
ST.getPreferredInstructionSet();
4335 auto [Grp, Opcode, ExtNo] = SPIRV::mapBuiltinToOpcode(DemangledName, Set);
4337 const bool IsBuiltin = Grp >= 0 || SPIRV::isBuiltin(DemangledName, Set);
4338 if (IsBuiltin && Opcode != SPIRV::OpGroupAsyncCopy)
4340 SmallVector<unsigned> Idxs;
4341 for (Argument &Arg :
F.args())
4346 LLVMContext &Ctx =
F.getContext();
4348 SPIRV::parseBuiltinTypeStr(TypeStrs, DemangledName, Ctx);
4349 if (TypeStrs.
empty())
4352 if (!IsBuiltin && (!
F.getName().starts_with(
"_Z") ||
F.hasStructRetAttr() ||
4353 StringRef(DemangledName).
count(
'(') != 1 ||
4354 StringRef(DemangledName).
count(
')') != 1 ||
4355 StringRef(DemangledName).
contains(
'<') ||
4356 TypeStrs.
size() !=
F.arg_size()))
4358 bool AllowLongVectors =
4359 ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector);
4360 for (
unsigned Idx : Idxs) {
4361 if (Idx >= TypeStrs.
size())
4363 StringRef TypeStr = TypeStrs[
Idx].trim();
4364 Type *ElemTy = IsBuiltin
4365 ? SPIRV::parseBuiltinCallArgumentType(TypeStr, Ctx)
4375 FDeclPtrTys[&
F].emplace_back(Idx, ElemTy);
4377 ST.getSPIRVGlobalRegistry()->addDeducedElementType(
F.getArg(Idx),
4383bool SPIRVEmitIntrinsicsImpl::processMaskedMemIntrinsic(IntrinsicInst &
I) {
4384 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*
I.getFunction());
4386 if (
I.getIntrinsicID() == Intrinsic::masked_gather) {
4387 if (!
ST.canUseExtension(
4388 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
4389 I.getContext().emitError(
4390 &
I,
"llvm.masked.gather requires SPV_INTEL_masked_gather_scatter "
4394 I.eraseFromParent();
4400 Value *Ptrs =
I.getArgOperand(0);
4402 Value *Passthru =
I.getArgOperand(2);
4405 uint32_t
Alignment =
I.getParamAlign(0).valueOrOne().value();
4407 SmallVector<Value *, 4>
Args = {Ptrs,
B.getInt32(Alignment),
Mask,
4412 auto *NewI =
B.CreateIntrinsic(Intrinsic::spv_masked_gather, Types, Args);
4414 I.eraseFromParent();
4418 if (
I.getIntrinsicID() == Intrinsic::masked_scatter) {
4419 if (!
ST.canUseExtension(
4420 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
4421 I.getContext().emitError(
4422 &
I,
"llvm.masked.scatter requires SPV_INTEL_masked_gather_scatter "
4425 I.eraseFromParent();
4432 Value *Ptrs =
I.getArgOperand(1);
4437 uint32_t
Alignment =
I.getParamAlign(1).valueOrOne().value();
4439 SmallVector<Value *, 4>
Args = {
Values, Ptrs,
B.getInt32(Alignment),
Mask};
4443 B.CreateIntrinsic(Intrinsic::spv_masked_scatter, Types, Args);
4444 I.eraseFromParent();
4455void SPIRVEmitIntrinsicsImpl::preprocessBoolVectorBitcasts(
Function &
F) {
4456 struct BoolVecBitcast {
4458 FixedVectorType *BoolVecTy;
4462 auto getAsBoolVec = [](
Type *Ty) -> FixedVectorType * {
4464 return (VTy && VTy->getElementType()->
isIntegerTy(1)) ? VTy :
nullptr;
4472 if (
auto *BVTy = getAsBoolVec(BC->getSrcTy()))
4474 else if (
auto *BVTy = getAsBoolVec(BC->getDestTy()))
4478 for (
auto &[BC, BoolVecTy, SrcIsBoolVec] : ToReplace) {
4480 Value *Src = BC->getOperand(0);
4481 unsigned BoolVecN = BoolVecTy->getNumElements();
4484 Type *OtherTy = SrcIsBoolVec ? BC->getDestTy() : Src->getType();
4485 unsigned NumElts = 1;
4487 NumElts = VTy->getNumElements();
4493 if (!SrcIsBoolVec) {
4496 auto GetLane = [&](
unsigned I) {
4499 Elt =
B.CreateExtractElement(IntVal,
B.getInt32(
I / EltBits));
4503 return B.CreateICmpNE(
And, ConstantInt::get(EltTy, 0));
4511 if (!Idx ||
Idx->getValue().uge(BoolVecN))
4513 B.SetInsertPoint(EE);
4514 EE->replaceAllUsesWith(GetLane(
Idx->getZExtValue()));
4515 EE->eraseFromParent();
4517 if (BC->use_empty()) {
4518 BC->eraseFromParent();
4522 B.SetInsertPoint(BC);
4524 for (
unsigned I = 0;
I < BoolVecN; ++
I)
4525 Result =
B.CreateInsertElement(Result, GetLane(
I),
B.getInt32(
I));
4529 for (
unsigned J = 0; J < NumElts; ++J) {
4530 Value *Elt = ConstantInt::get(EltTy, 0);
4531 for (
unsigned Bit = 0;
Bit < EltBits; ++
Bit) {
4533 B.CreateExtractElement(Src,
B.getInt32(J * EltBits + Bit));
4534 Value *Ext =
B.CreateZExt(Lane, EltTy);
4536 Ext =
B.CreateShl(Ext, ConstantInt::get(EltTy, Bit));
4537 Elt =
B.CreateOr(Elt, Ext);
4539 IntVal = NumElts > 1 ?
B.CreateInsertElement(IntVal, Elt,
B.getInt32(J))
4542 Result =
B.CreateBitCast(IntVal, BC->getDestTy());
4545 BC->replaceAllUsesWith(Result);
4546 BC->eraseFromParent();
4550bool SPIRVEmitIntrinsicsImpl::convertMaskedMemIntrinsics(
Module &M) {
4554 if (!
F.isIntrinsic())
4557 if (IID != Intrinsic::masked_gather && IID != Intrinsic::masked_scatter)
4562 Changed |= processMaskedMemIntrinsic(*
II);
4566 F.eraseFromParent();
4572bool SPIRVEmitIntrinsicsImpl::preprocessModule(
Module &M) {
4576 Type *I32Ty = Type::getInt32Ty(
M.getContext());
4578 if (
F.isDeclaration())
4584 CE &&
CE->getOpcode() == Instruction::GetElementPtr)
4591 if (!AI || !AI->isStaticAlloca() || !AI->isArrayAllocation() ||
4592 AI->getAddressSpace() !=
4597 if (
Count->isZero() || !
Count->getValue().isIntN(32))
4599 AI->setAllocatedType(
4600 ArrayType::get(AI->getAllocatedType(),
Count->getZExtValue()));
4601 AI->setOperand(0, ConstantInt::get(I32Ty, 1));
4605 Changed |= convertMaskedMemIntrinsics(M);
4613 GEPs,
nullptr,
false,
true);
4618bool SPIRVEmitIntrinsicsImpl::runOnModule(
Module &M) {
4619 bool Changed = preprocessModule(M);
4621 parseFunDeclarations(M);
4622 insertConstantsForFPFastMathDefault(M);
4628 if (AccessChainErrors)
4635 if (!
F.isDeclaration() && !
F.isIntrinsic()) {
4637 processParamTypes(&
F,
B);
4641 CanTodoType =
false;
4642 Changed |= postprocessTypes(M);
4645 Changed |= processFunctionPointers(M);
4652 if (SPIRVEmitIntrinsicsImpl(TM).runOnModule(M))
4658 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[]
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)
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.
@ 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)