LLVM 24.0.0git
SPIRVEmitIntrinsics.cpp
Go to the documentation of this file.
1//===-- SPIRVEmitIntrinsics.cpp - emit SPIRV intrinsics ---------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// The pass emits SPIRV intrinsics keeping essential high-level information for
10// the translation of LLVM IR to SPIR-V.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SPIRV.h"
15#include "SPIRVAuxDataHandler.h"
16#include "SPIRVBuiltins.h"
17#include "SPIRVSubtarget.h"
18#include "SPIRVTargetMachine.h"
19#include "SPIRVUtils.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/DenseSet.h"
22#include "llvm/ADT/MapVector.h"
28#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InstVisitor.h"
31#include "llvm/IR/IntrinsicsSPIRV.h"
32#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Value.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/Error.h"
41
42#include <cassert>
43#include <optional>
44#include <queue>
45
46// This pass performs the following transformation on LLVM IR level required
47// for the following translation to SPIR-V:
48// - replaces direct usages of aggregate constants with target-specific
49// intrinsics;
50// - replaces aggregates-related instructions (extract/insert, ld/st, etc)
51// with a target-specific intrinsics;
52// - emits intrinsics for the global variable initializers since IRTranslator
53// doesn't handle them and it's not very convenient to translate them
54// ourselves;
55// - emits intrinsics to keep track of the string names assigned to the values;
56// - emits intrinsics to keep track of constants (this is necessary to have an
57// LLVM IR constant after the IRTranslation is completed) for their further
58// deduplication;
59// - emits intrinsics to keep track of original LLVM types of the values
60// to be able to emit proper SPIR-V types eventually.
61//
62// TODO: consider removing spv.track.constant in favor of spv.assign.type.
63
64using namespace llvm;
65using namespace llvm::PatternMatch;
66
67#define DEBUG_TYPE "spirv-emit-intrinsics"
68
69namespace llvm::SPIRV {
70#define GET_BuiltinGroup_DECL
71#include "SPIRVGenTables.inc"
72} // namespace llvm::SPIRV
73
74namespace {
75// This class keeps track of which functions reference which global variables.
76class GlobalVariableUsers {
77 template <typename T1, typename T2>
78 using OneToManyMapTy = DenseMap<T1, SmallPtrSet<T2, 4>>;
79
80 OneToManyMapTy<const GlobalVariable *, const Function *> GlobalIsUsedByFun;
81
82 void collectGlobalUsers(
83 const GlobalVariable *GV,
84 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
85 &GlobalIsUsedByGlobal) {
87 while (!Stack.empty()) {
88 const Value *V = Stack.pop_back_val();
89
90 if (const Instruction *I = dyn_cast<Instruction>(V)) {
91 GlobalIsUsedByFun[GV].insert(I->getFunction());
92 continue;
93 }
94
95 if (const GlobalVariable *UserGV = dyn_cast<GlobalVariable>(V)) {
96 GlobalIsUsedByGlobal[GV].insert(UserGV);
97 continue;
98 }
99
100 if (const Constant *C = dyn_cast<Constant>(V))
101 Stack.append(C->user_begin(), C->user_end());
102 }
103 }
104
105 bool propagateGlobalToGlobalUsers(
106 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
107 &GlobalIsUsedByGlobal) {
109 bool Changed = false;
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())
115 continue;
116 Changed |= set_union(UserGlobals, It->second);
117 }
118 }
119 return Changed;
120 }
121
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())
130 continue;
131 set_union(UserFunctions, It->second);
132 }
133 }
134 }
135
136public:
137 void init(Module &M) {
138 // Collect which global variables are referenced by which global variables
139 // and which functions reference each global variables.
140 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
141 GlobalIsUsedByGlobal;
142 GlobalIsUsedByFun.clear();
143 for (GlobalVariable &GV : M.globals())
144 collectGlobalUsers(&GV, GlobalIsUsedByGlobal);
145
146 // Compute indirect references by iterating until a fixed point is reached.
147 while (propagateGlobalToGlobalUsers(GlobalIsUsedByGlobal))
148 (void)0;
149
150 propagateGlobalToFunctionReferences(GlobalIsUsedByGlobal);
151 }
152
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())
158 return It->second;
159
160 static const FunctionSetType Empty{};
161 return Empty;
162 }
163};
164
165static bool isaGEP(const Value *V) {
167}
168
169// If Ty is a byte-addressing type, return the multiplier for the offset.
170// Otherwise return std::nullopt.
171static std::optional<uint64_t> getByteAddressingMultiplier(Type *Ty) {
172 if (Ty == IntegerType::getInt8Ty(Ty->getContext())) {
173 return 1;
174 }
175 if (auto *AT = dyn_cast<ArrayType>(Ty)) {
176 if (AT->getElementType() == IntegerType::getInt8Ty(Ty->getContext())) {
177 return AT->getNumElements();
178 }
179 }
180 return std::nullopt;
181}
182
183// InstCombine emits `P[I + K]` as a constant byte offset C from `P[I]`, which
184// can land past element I. Logical SPIR-V has no pointer arithmetic, and an
185// access chain based on `P[I]` can only index inside element I.
186//
187// To fix this, we split C into a count of array elements, which we add to the
188// array index, and the leftover bytes, fewer than one element, which stay a
189// byte offset inside the new element:
190//
191// gep i8, (gep [N x i8], P, I), C becomes
192// gep i8, (gep [N x i8], P, I + floor(C / N)), C mod N.
193static void foldConstantOffsetIntoArrayIndex(Function &F) {
196 if (!Outer || Outer->getNumIndices() != 1 ||
197 !Outer->getSourceElementType()->isIntegerTy(8))
198 continue;
199 auto *Offset = dyn_cast<ConstantInt>(Outer->getOperand(1));
200 auto *Inner = dyn_cast<GetElementPtrInst>(Outer->getPointerOperand());
201 if (!Offset || !Inner || Inner->getNumIndices() != 1)
202 continue;
203 Value *Index = Inner->getOperand(1);
204 std::optional<uint64_t> Stride =
205 getByteAddressingMultiplier(Inner->getSourceElementType());
206 if (isa<Constant>(Index) || !Stride || *Stride <= 1)
207 continue;
208
209 // Compute in the index type, as the GEP does.
210 Type *IdxTy = F.getDataLayout().getIndexType(Inner->getType());
211 int64_t Bytes = Offset->getValue()
212 .sextOrTrunc(IdxTy->getScalarSizeInBits())
213 .getSExtValue();
214 int64_t Size = *Stride;
215 int64_t Elements = divideFloorSigned(Bytes, Size);
216 if (Elements == 0)
217 continue;
218
219 GEPNoWrapFlags NW = Inner->isInBounds() && Outer->isInBounds()
221 : GEPNoWrapFlags::none();
222 IRBuilder<> B(Outer);
223 Value *NewIndex = B.CreateAdd(B.CreateSExtOrTrunc(Index, IdxTy),
224 ConstantInt::getSigned(IdxTy, Elements));
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),
229 "", NW);
230 Ptr->takeName(Outer);
231 Outer->replaceAllUsesWith(Ptr);
232 Outer->eraseFromParent();
233 if (Inner->use_empty())
234 Inner->eraseFromParent();
235 }
236}
237
238class SPIRVEmitIntrinsicsImpl
239 : public InstVisitor<SPIRVEmitIntrinsicsImpl, Instruction *> {
240 const SPIRVTargetMachine &TM;
241 SPIRVGlobalRegistry *GR = nullptr;
242 Function *CurrF = 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;
251 Error AccessChainErrors = Error::success();
252 SmallPtrSet<GetElementPtrInst *, 4> InvalidGEPs;
253
254 // map of function declarations to <pointer arg index => element type>
255 MapVector<Function *, SmallVector<std::pair<unsigned, Type *>>> FDeclPtrTys;
256
257 // a register of Instructions that don't have a complete type definition
258 bool CanTodoType = true;
259 unsigned TodoTypeSz = 0;
260 DenseMap<Value *, bool> TodoType;
261 void insertTodoType(Value *Op) {
262 // TODO: add isa<CallInst>(Op) to no-insert
263 if (CanTodoType && !isaGEP(Op)) {
264 auto It = TodoType.try_emplace(Op, true);
265 if (It.second)
266 ++TodoTypeSz;
267 }
268 }
269 void eraseTodoType(Value *Op) {
270 auto It = TodoType.find(Op);
271 if (It != TodoType.end() && It->second) {
272 It->second = false;
273 --TodoTypeSz;
274 }
275 }
276 bool isTodoType(Value *Op) {
277 if (isaGEP(Op))
278 return false;
279 auto It = TodoType.find(Op);
280 return It != TodoType.end() && It->second;
281 }
282 // a register of Instructions that were visited by deduceOperandElementType()
283 // to validate operand types with an instruction
284 SmallPtrSet<Instruction *, 0> TypeValidated;
285 // Type-validated PHIs and selects whose element type changed since, to be
286 // revalidated by the outermost deduceOperandElementType() call.
287 SmallVector<Instruction *> RetypedToRevalidate;
288 bool RevalidatingRetyped = false;
289
290 // well known result types of builtins
291 enum WellKnownTypes { Event };
292
293 // deduce element type of untyped pointers
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 = {});
305 Type *deduceElementTypeByUsersDeep(Value *Op,
306 SmallPtrSetImpl<Value *> &Visited,
307 bool UnknownElemTypeI8);
308 void maybeAssignPtrType(Type *&Ty, Value *I, Type *RefTy,
309 bool UnknownElemTypeI8);
310
311 // deduce nested types of composites
312 Type *deduceNestedTypeHelper(User *U, bool UnknownElemTypeI8);
313 Type *deduceNestedTypeHelper(User *U, Type *Ty,
314 SmallPtrSetImpl<Value *> &Visited,
315 bool UnknownElemTypeI8);
316
317 // deduce Types of operands of the Instruction if possible
318 void
319 deduceOperandElementType(Instruction *I,
320 SmallPtrSetImpl<Instruction *> *IncompleteRets,
321 const SmallPtrSetImpl<Value *> *AskOps = nullptr,
322 bool IsPostprocessing = false);
323
324 void preprocessCompositeConstants(IRBuilder<> &B);
325 Value *lowerUndefOrPoison(Value *Op, IRBuilder<> &B, bool HasPoisonExt);
326 void preprocessUndefsAndPoisons(IRBuilder<> &B);
327 void insertCompositeAggregateArms(Instruction *I, IRBuilder<> &B);
328 Value *lowerCompositeMember(Value *Op, IRBuilder<> &B, bool HasPoisonExt);
329 void simplifyNullAddrSpaceCasts();
330
331 Type *reconstructType(Value *Op, bool UnknownElemTypeI8,
332 bool IsPostprocessing);
333
334 void replaceMemInstrUses(Instruction *Old, Instruction *New, IRBuilder<> &B);
335 void processInstrAfterVisit(Instruction *I, IRBuilder<> &B);
336 bool insertAssignPtrTypeIntrs(Instruction *I, IRBuilder<> &B,
337 bool UnknownElemTypeI8);
338 void insertAssignTypeIntrs(Instruction *I, IRBuilder<> &B);
339 void insertAssignPtrTypeTargetExt(TargetExtType *AssignedType, Value *V,
340 IRBuilder<> &B);
341 void replacePointerOperandWithPtrCast(Instruction *I, Value *Pointer,
342 Type *ExpectedElementType,
343 unsigned OperandToReplace,
344 IRBuilder<> &B);
345 void insertPtrCastOrAssignTypeInstr(Instruction *I, IRBuilder<> &B);
346 bool shouldTryToAddMemAliasingDecoration(Instruction *Inst);
347 void insertSpirvDecorations(Instruction *I, IRBuilder<> &B);
348 void insertConstantsForFPFastMathDefault(Module &M);
349 Value *buildSpvUndefComposite(Type *AggrTy, IRBuilder<> &B);
350 void reconstructAggregateReturns(Function &Func, IRBuilder<> &B);
351 void processGlobalValue(GlobalVariable &GV, IRBuilder<> &B);
352 void processParamTypes(Function *F, IRBuilder<> &B);
353 void processParamTypesByFunHeader(Function *F, IRBuilder<> &B);
354 Type *deduceFunParamElementType(Function *F, unsigned OpIdx);
355 Type *deduceFunParamElementType(Function *F, unsigned OpIdx,
356 SmallPtrSetImpl<Function *> &FVisited);
357
358 bool deduceOperandElementTypeCalledFunction(
359 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
360 Type *&KnownElemTy, bool &Incomplete);
361 void deduceOperandElementTypeFunctionPointer(
362 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
363 Type *&KnownElemTy, bool IsPostprocessing);
364 bool deduceOperandElementTypeFunctionRet(
365 Instruction *I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
366 const SmallPtrSetImpl<Value *> *AskOps, bool IsPostprocessing,
367 Type *&KnownElemTy, Value *Op, Function *F);
368
369 CallInst *buildSpvPtrcast(Function *F, Value *Op, Type *ElemTy);
370 void replaceUsesOfWithSpvPtrcast(Value *Op, Type *ElemTy, Instruction *I,
371 DenseMap<Function *, CallInst *> Ptrcasts);
372 void propagateElemType(Value *Op, Type *ElemTy,
373 DenseSet<std::pair<Value *, Value *>> &VisitedSubst);
374 void
375 propagateElemTypeRec(Value *Op, Type *PtrElemTy, Type *CastElemTy,
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);
381
382 void replaceAllUsesWith(Value *Src, Value *Dest, bool DeleteOld = true);
383 void replaceAllUsesWithAndErase(IRBuilder<> &B, Instruction *Src,
384 Instruction *Dest, bool DeleteOld = true);
385
386 void applyDemangledPtrArgTypes(IRBuilder<> &B);
387
388 GetElementPtrInst *simplifyZeroLengthArrayGepInst(GetElementPtrInst *GEP);
389
390 bool runOnFunction(Function &F);
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);
400
401 void emitUnstructuredLoopControls(Function &F, IRBuilder<> &B);
402
403 // Tries to walk the type accessed by the given GEP instruction.
404 // For each nested type access, one of the 2 callbacks is called:
405 // - OnLiteralIndexing when the index is a known constant value.
406 // Parameters:
407 // PointedType: the pointed type resulting of this indexing.
408 // If the parent type is an array, this is the index in the array.
409 // If the parent type is a struct, this is the field index.
410 // Index: index of the element in the parent type.
411 // - OnDynamnicIndexing when the index is a non-constant value.
412 // This callback is only called when indexing into an array.
413 // Parameters:
414 // ElementType: the type of the elements stored in the parent array.
415 // Offset: the Value* containing the byte offset into the array.
416 // Multiplier: a scaling factor for the offset.
417 // Return true for a fallback, false for a complete walk, or an error.
418 Expected<bool> walkLogicalAccessChain(
419 GetElementPtrInst &GEP,
420 const std::function<void(Type *PointedType, uint64_t Index)>
421 &OnLiteralIndexing,
422 const std::function<void(Type *ElementType, Value *Offset,
423 uint64_t Multiplier)> &OnDynamicIndexing);
424
425 bool walkLogicalAccessChainDynamic(
426 Type *CurType, Value *Operand, uint64_t Multiplier,
427 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing,
428 const std::function<void(Type *, Value *, uint64_t)> &OnDynamicIndexing);
429
430 Expected<bool> walkLogicalAccessChainConstant(
431 Type *CurType, uint64_t Offset,
432 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing);
433
434 void recordAccessChainError(GetElementPtrInst &GEP, Error Err);
435
436 // Returns the type accessed using the given GEP instruction by relying
437 // on the GEP type.
438 // FIXME: GEP types are not supposed to be used to retrieve the pointed
439 // type. This must be fixed.
440 Type *getGEPType(GetElementPtrInst *GEP);
441
442 // Returns the type accessed using the given GEP instruction by walking
443 // the source type using the GEP indices.
444 // FIXME: without help from the frontend, this method cannot reliably retrieve
445 // the stored type, nor can robustly determine the depth of the type
446 // we are accessing.
447 Type *getGEPTypeLogical(GetElementPtrInst *GEP);
448
449 Instruction *buildLogicalAccessChainFromGEP(GetElementPtrInst &GEP);
450
451 Value *truncateGEPIndex(Value *Idx, Type *IdxTy, IRBuilder<> &B);
452
453public:
454 SPIRVEmitIntrinsicsImpl(const SPIRVTargetMachine &TM) : TM(TM) {}
455 Instruction *visitInstruction(Instruction &I) { return &I; }
456 Instruction *visitSwitchInst(SwitchInst &I);
457 Instruction *visitGetElementPtrInst(GetElementPtrInst &I);
458 Instruction *visitIntrinsicInst(IntrinsicInst &I);
459 Instruction *visitBitCastInst(BitCastInst &I);
460 Instruction *visitInsertElementInst(InsertElementInst &I);
461 Instruction *visitExtractElementInst(ExtractElementInst &I);
462 Instruction *visitInsertValueInst(InsertValueInst &I);
463 Instruction *visitExtractValueInst(ExtractValueInst &I);
464 Instruction *visitLoadInst(LoadInst &I);
465 Instruction *visitStoreInst(StoreInst &I);
466 Instruction *visitAllocaInst(AllocaInst &I);
467 Instruction *visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
468 Instruction *visitAtomicRMWInst(AtomicRMWInst &I);
469 Instruction *visitUnreachableInst(UnreachableInst &I);
470 Instruction *visitCallInst(CallInst &I);
471
472 bool runOnModule(Module &M);
473};
474
475class SPIRVEmitIntrinsicsLegacy : public ModulePass {
476 const SPIRVTargetMachine &TM;
477
478public:
479 static char ID;
480 SPIRVEmitIntrinsicsLegacy(const SPIRVTargetMachine &TM)
481 : ModulePass(ID), TM(TM) {}
482
483 StringRef getPassName() const override { return "SPIRV emit intrinsics"; }
484
485 bool runOnModule(Module &M) override {
486 return SPIRVEmitIntrinsicsImpl(TM).runOnModule(M);
487 }
488};
489
490bool isConvergenceIntrinsic(const Instruction *I) {
491 return match(I, m_AnyIntrinsic<Intrinsic::experimental_convergence_entry,
492 Intrinsic::experimental_convergence_loop,
493 Intrinsic::experimental_convergence_anchor>());
494}
495
496bool expectIgnoredInIRTranslation(const Instruction *I) {
497 return match(I,
498 m_AnyIntrinsic<Intrinsic::invariant_start,
499 Intrinsic::spv_resource_handlefrombinding_mdname,
500 Intrinsic::spv_resource_getbasepointer,
501 Intrinsic::spv_resource_getpointer>());
502}
503
504// Returns the source pointer from `I` ignoring intermediate ptrcast.
505Value *getPointerRoot(Value *I) {
506 Value *V;
508 return getPointerRoot(V);
509 return I;
510}
511
512} // namespace
513
514char SPIRVEmitIntrinsicsLegacy::ID = 0;
515
516INITIALIZE_PASS(SPIRVEmitIntrinsicsLegacy, "spirv-emit-intrinsics",
517 "SPIRV emit intrinsics", false, false)
518
519static inline bool isAssignTypeInstr(const Instruction *I) {
521}
522
527
528static bool isAggrConstForceInt32(const Value *V) {
529 bool IsAggrZero =
530 isa<ConstantAggregateZero>(V) && !V->getType()->isVectorTy();
531 bool IsUndefAggregate = isa<UndefValue>(V) && V->getType()->isAggregateType();
533 isa<ConstantDataArray>(V) || IsAggrZero || IsUndefAggregate;
534}
535
541
543 if (isa<PHINode>(I))
544 B.SetInsertPoint(I->getParent()->getFirstNonPHIOrAlloca());
545 else
546 B.SetInsertPoint(I);
547}
548
550 B.SetCurrentDebugLocation(I->getDebugLoc());
551 if (I->getType()->isVoidTy())
552 B.SetInsertPoint(I->getNextNode());
553 else
554 B.SetInsertPoint(*I->getInsertionPointAfterDef());
555}
556
562
563static inline void reportFatalOnTokenType(const Instruction *I) {
564 if (I->getType()->isTokenTy())
565 report_fatal_error("A token is encountered but SPIR-V without extensions "
566 "does not support token type",
567 false);
568}
569
570static void emitAssignName(const SPIRVOptions &CLOpts, Instruction *I,
571 IRBuilder<> &B) {
572 if (!I->hasName() || I->getType()->isAggregateType() ||
573 expectIgnoredInIRTranslation(I))
574 return;
575
576 // We want to be conservative when adding the names because they can interfere
577 // with later optimizations.
578 bool KeepName = CLOpts.emit_op_names;
579 if (!KeepName) {
580 if (isa<AllocaInst>(I)) {
581 KeepName = true;
582 } else if (auto *CI = dyn_cast<CallBase>(I)) {
583 Function *F = CI->getCalledFunction();
584 if (F && F->getName().starts_with("llvm.spv.alloca"))
585 KeepName = true;
586 }
587 }
588
589 if (!KeepName)
590 return;
591
594 LLVMContext &Ctx = I->getContext();
595 std::vector<Value *> Args = {
597 Ctx, MDNode::get(Ctx, MDString::get(Ctx, I->getName())))};
598 B.CreateIntrinsic(Intrinsic::spv_assign_name, {I->getType()}, Args);
599}
600
601void SPIRVEmitIntrinsicsImpl::replaceAllUsesWith(Value *Src, Value *Dest,
602 bool DeleteOld) {
603 GR->replaceAllUsesWith(Src, Dest, DeleteOld);
604 // Update uncomplete type records if any
605 if (isTodoType(Src)) {
606 if (DeleteOld)
607 eraseTodoType(Src);
608 insertTodoType(Dest);
609 }
610}
611
612void SPIRVEmitIntrinsicsImpl::replaceAllUsesWithAndErase(IRBuilder<> &B,
613 Instruction *Src,
614 Instruction *Dest,
615 bool DeleteOld) {
616 replaceAllUsesWith(Src, Dest, DeleteOld);
617 std::string Name = Src->hasName() ? Src->getName().str() : "";
618 Src->eraseFromParent();
619 if (!Name.empty()) {
620 Dest->setName(Name);
621 if (Named.insert(Dest).second)
622 emitAssignName(TM.getCLOpts(), Dest, B);
623 }
624}
625
627 return SI && F->getCallingConv() == CallingConv::SPIR_KERNEL &&
628 isPointerTy(SI->getValueOperand()->getType()) &&
629 isa<Argument>(SI->getValueOperand());
630}
631
632// A pointer-typed local holds a pointer, so its deduced pointee must stay a
633// pointer.
635 using namespace PatternMatch;
636 V = V->stripPointerCasts();
637 if (auto *AI = dyn_cast<AllocaInst>(V))
638 return isUntypedPointerTy(AI->getAllocatedType());
639 return match(
641}
642
643// Maybe restore original function return type.
645 Type *Ty) {
647 if (!CI || CI->isIndirectCall() || CI->isInlineAsm() ||
649 return Ty;
650 if (Type *OriginalTy = GR->findMutated(CI->getCalledFunction()))
651 return OriginalTy;
652 return Ty;
653}
654
655// Return the pointee type of the pointer member of AggrTy selected by Indices.
656// Untyped pointer members are lowered as pointers to i8.
658 Type *MemberTy = ExtractValueInst::getIndexedType(AggrTy, Indices);
659 if (Type *ElemTy = getPointeeType(MemberTy))
660 return ElemTy;
661 return IntegerType::getInt8Ty(AggrTy->getContext());
662}
663
664// Reconstruct type with nested element types according to deduced type info.
665// Return nullptr if no detailed type info is available.
666Type *SPIRVEmitIntrinsicsImpl::reconstructType(Value *Op,
667 bool UnknownElemTypeI8,
668 bool IsPostprocessing) {
669 Type *Ty = Op->getType();
670 if (auto *OpI = dyn_cast<Instruction>(Op)) {
671 Ty = restoreMutatedType(GR, OpI, Ty);
672 if (auto It = AggrConstTypes.find(OpI); It != AggrConstTypes.end())
673 Ty = It->second;
674 }
675 if (!isUntypedPointerTy(Ty))
676 return Ty;
677 // try to find the pointee type
678 if (Type *NestedTy = GR->findDeducedElementType(Op))
680 // not a pointer according to the type info (e.g., Event object)
681 CallInst *CI = GR->findAssignPtrTypeInstr(Op);
682 if (CI) {
683 MetadataAsValue *MD = cast<MetadataAsValue>(CI->getArgOperand(1));
684 return cast<ConstantAsMetadata>(MD->getMetadata())->getType();
685 }
686 if (UnknownElemTypeI8) {
687 if (!IsPostprocessing)
688 insertTodoType(Op);
689 return getTypedPointerWrapper(IntegerType::getInt8Ty(Op->getContext()),
691 }
692 return nullptr;
693}
694
695CallInst *SPIRVEmitIntrinsicsImpl::buildSpvPtrcast(Function *F, Value *Op,
696 Type *ElemTy) {
697 IRBuilder<> B(*F->getParent());
698 if (auto *OpI = dyn_cast<Instruction>(Op)) {
699 // spv_ptrcast's argument Op denotes an instruction that generates
700 // a value, and we may use getInsertionPointAfterDef()
702 } else if (auto *OpA = dyn_cast<Argument>(Op)) {
703 B.SetInsertPointPastAllocas(OpA->getParent());
704 B.SetCurrentDebugLocation(DebugLoc());
705 } else {
706 B.SetInsertPoint(F->getEntryBlock().getFirstNonPHIOrAlloca());
707 }
708 Type *OpTy = Op->getType();
709 SmallVector<Type *, 2> Types = {OpTy, OpTy};
710 SmallVector<Value *, 2> Args = {
711 Op, buildMD(getNormalizedPoisonValue(ElemTy, CanUseAnyVectorRank)),
712 B.getInt32(getPointerAddressSpace(OpTy))};
713 CallInst *PtrCasted =
714 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_ptrcast, {Types}, Args);
715 GR->buildAssignPtr(B, ElemTy, PtrCasted);
716 return PtrCasted;
717}
718
719void SPIRVEmitIntrinsicsImpl::replaceUsesOfWithSpvPtrcast(
720 Value *Op, Type *ElemTy, Instruction *I,
721 DenseMap<Function *, CallInst *> Ptrcasts) {
722 Function *F = I->getParent()->getParent();
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;
728 } else {
729 PtrCastedI = It->second;
730 }
731 I->replaceUsesOfWith(Op, PtrCastedI);
732}
733
734void SPIRVEmitIntrinsicsImpl::propagateElemType(
735 Value *Op, Type *ElemTy,
736 DenseSet<std::pair<Value *, Value *>> &VisitedSubst) {
737 DenseMap<Function *, CallInst *> Ptrcasts;
738 SmallVector<User *> Users(Op->users());
739 for (auto *U : Users) {
740 if (!isa<Instruction>(U) || isSpvIntrinsic(U))
741 continue;
742 if (!VisitedSubst.insert(std::make_pair(U, Op)).second)
743 continue;
745 // If the instruction was validated already, we need to keep it valid by
746 // keeping current Op type.
747 if (isaGEP(UI) || TypeValidated.find(UI) != TypeValidated.end())
748 replaceUsesOfWithSpvPtrcast(Op, ElemTy, UI, Ptrcasts);
749 }
750}
751
752void SPIRVEmitIntrinsicsImpl::propagateElemTypeRec(
753 Value *Op, Type *PtrElemTy, Type *CastElemTy,
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));
759}
760
761void SPIRVEmitIntrinsicsImpl::propagateElemTypeRec(
762 Value *Op, Type *PtrElemTy, Type *CastElemTy,
763 DenseSet<std::pair<Value *, Value *>> &VisitedSubst,
764 SmallPtrSetImpl<Value *> &Visited,
765 DenseMap<Function *, CallInst *> Ptrcasts) {
766 if (!Visited.insert(Op).second)
767 return;
768 SmallVector<User *> Users(Op->users());
769 for (auto *U : Users) {
770 if (!isa<Instruction>(U) || isSpvIntrinsic(U))
771 continue;
772 if (!VisitedSubst.insert(std::make_pair(U, Op)).second)
773 continue;
775 // If the instruction was validated already, we need to keep it valid by
776 // keeping current Op type.
777 if (isaGEP(UI) || TypeValidated.find(UI) != TypeValidated.end())
778 replaceUsesOfWithSpvPtrcast(Op, CastElemTy, UI, Ptrcasts);
779 }
780}
781
782// Set element pointer type to the given value of ValueTy and tries to
783// specify this type further (recursively) by Operand value, if needed.
784
785Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByValueDeep(
786 Type *ValueTy, Value *Operand, bool UnknownElemTypeI8) {
787 SmallPtrSet<Value *, 0> Visited;
788 return deduceElementTypeByValueDeep(ValueTy, Operand, Visited,
789 UnknownElemTypeI8);
790}
791
792Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByValueDeep(
793 Type *ValueTy, Value *Operand, SmallPtrSetImpl<Value *> &Visited,
794 bool UnknownElemTypeI8, std::optional<unsigned> AddrSpace) {
795 Type *Ty = ValueTy;
796 if (Operand) {
797 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
798 if (Type *NestedTy =
799 deduceElementTypeHelper(Operand, Visited, UnknownElemTypeI8))
801 NestedTy, AddrSpace.value_or(PtrTy->getAddressSpace()));
802 } else {
803 Ty = deduceNestedTypeHelper(dyn_cast<User>(Operand), Ty, Visited,
804 UnknownElemTypeI8);
805 }
806 }
807 return Ty;
808}
809
810// Traverse User instructions to deduce an element pointer type of the operand.
811Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByUsersDeep(
812 Value *Op, SmallPtrSetImpl<Value *> &Visited, bool UnknownElemTypeI8) {
813 if (!Op || !isPointerTy(Op->getType()) || isa<ConstantPointerNull>(Op) ||
815 return nullptr;
816
817 if (auto ElemTy = getPointeeType(Op->getType()))
818 return ElemTy;
819
820 // maybe we already know operand's element type
821 if (Type *KnownTy = GR->findDeducedElementType(Op))
822 return KnownTy;
823
824 for (User *OpU : Op->users()) {
825 if (Instruction *Inst = dyn_cast<Instruction>(OpU)) {
826 if (Type *Ty = deduceElementTypeHelper(Inst, Visited, UnknownElemTypeI8))
827 return Ty;
828 }
829 }
830 return nullptr;
831}
832
833// Implements what we know in advance about intrinsics and builtin calls
834// TODO: consider feasibility of this particular case to be generalized by
835// encoding knowledge about intrinsics and builtin calls by corresponding
836// specification rules
838 Function *CalledF, unsigned OpIdx) {
839 // OpenCL.std printf takes its format string as a pointer to i8. Match the
840 // bare builtin name, as lowering does, to also cover unmangled `printf`.
841 std::string Name = SPIRV::lookupBuiltinNameHelper(DemangledName);
842 // OpenCL get_fence only has void* overloads.
843 if (OpIdx == 0 && (Name == "printf" || Name == "get_fence"))
844 return IntegerType::getInt8Ty(CalledF->getContext());
845 // OpCaptureEventProfilingInfo requires Value to point to an 8-bit integer.
846 if (OpIdx == 2 && (Name == "capture_event_profiling_info" ||
847 Name == "__spirv_CaptureEventProfilingInfo"))
848 return IntegerType::getInt8Ty(CalledF->getContext());
849 return nullptr;
850}
851
852// Deduce and return a successfully deduced Type of the Instruction,
853// or nullptr otherwise.
854Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeHelper(Value *I,
855 bool UnknownElemTypeI8) {
856 SmallPtrSet<Value *, 0> Visited;
857 return deduceElementTypeHelper(I, Visited, UnknownElemTypeI8);
858}
859
860void SPIRVEmitIntrinsicsImpl::maybeAssignPtrType(Type *&Ty, Value *Op,
861 Type *RefTy,
862 bool UnknownElemTypeI8) {
863 if (isUntypedPointerTy(RefTy)) {
864 if (!UnknownElemTypeI8)
865 return;
866 insertTodoType(Op);
868 return;
869 }
870 Ty = RefTy;
871}
872
873bool SPIRVEmitIntrinsicsImpl::walkLogicalAccessChainDynamic(
874 Type *CurType, Value *Operand, uint64_t Multiplier,
875 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing,
876 const std::function<void(Type *, Value *, uint64_t)> &OnDynamicIndexing) {
877 // Dynamic indexing into a struct is not possible.
878 // We know that we must be accessing the first element
879 // of the struct if the current type is a struct.
880 // Try to find the first array type that is at offset 0 in the struct.
881 while (auto *ST = dyn_cast<StructType>(CurType)) {
882 if (ST->getNumElements() == 0)
883 break;
884 CurType = ST->getElementType(0);
885 OnLiteralIndexing(CurType, 0);
886 }
887
888 assert(CurType);
889 ArrayType *AT = dyn_cast<ArrayType>(CurType);
890 // Operand is not constant. Either we have an array and accept it, or we
891 // give up.
892 if (AT)
893 OnDynamicIndexing(AT->getElementType(), Operand, Multiplier);
894 return AT == nullptr;
895}
896
897Expected<bool> SPIRVEmitIntrinsicsImpl::walkLogicalAccessChainConstant(
898 Type *CurType, uint64_t Offset,
899 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing) {
900 auto &DL = CurrF->getDataLayout();
901 Type *BaseType = CurType;
902
903 do {
904 if (ArrayType *AT = dyn_cast<ArrayType>(CurType)) {
905 uint64_t EltTypeSize = DL.getTypeAllocSize(AT->getElementType());
906 assert(Offset < AT->getNumElements() * EltTypeSize);
907 uint64_t Index = Offset / EltTypeSize;
908 Offset = Offset - (Index * EltTypeSize);
909 CurType = AT->getElementType();
910 OnLiteralIndexing(CurType, Index);
911 } else if (StructType *ST = dyn_cast<StructType>(CurType)) {
912 uint32_t StructSize = DL.getTypeSizeInBits(ST) / 8;
913 assert(Offset < StructSize);
914 (void)StructSize;
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);
920 } else if (auto *VT = dyn_cast<FixedVectorType>(CurType)) {
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)
927 return createStringError(
928 "Cannot lower an access to vector padding for Logical SPIR-V");
929 uint64_t Index = Offset / EltTypeSize;
930 Offset -= Index * EltTypeSize;
931 CurType = EltTy;
932 OnLiteralIndexing(CurType, Index);
933 } else {
934 if (CurType == BaseType && Offset >= DL.getTypeAllocSize(CurType))
935 return true;
936 return createStringError(
937 "Cannot lower a byte offset within a scalar or padding for "
938 "Logical SPIR-V");
939 }
940 } while (Offset > 0);
941
942 return false;
943}
944
945Expected<bool> SPIRVEmitIntrinsicsImpl::walkLogicalAccessChain(
946 GetElementPtrInst &GEP,
947 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing,
948 const std::function<void(Type *, Value *, uint64_t)> &OnDynamicIndexing) {
949 // We only rewrite byte-addressing GEP. Other should be left as-is.
950 // Valid byte-addressing GEP must always have a single index.
951 std::optional<uint64_t> MultiplierOpt =
952 getByteAddressingMultiplier(GEP.getSourceElementType());
953 assert(MultiplierOpt && "We only rewrite byte-addressing GEP");
954 uint64_t Multiplier = *MultiplierOpt;
955 assert(GEP.getNumIndices() == 1);
956
957 Value *Src = getPointerRoot(GEP.getPointerOperand());
958 Type *CurType = deduceElementType(Src, true);
959 if (!CurType->isSized())
960 return createStringError(
961 "Cannot lower byte addressing with an unsized type for Logical SPIR-V");
962
963 Value *Operand = *GEP.idx_begin();
964 if (isa<ConstantInt>(Operand)) {
965 // The byte offset wraps at the width of the GEP index type.
966 const DataLayout &DL = CurrF->getDataLayout();
967 APInt Offset(DL.getIndexSizeInBits(GEP.getPointerAddressSpace()), 0);
968 [[maybe_unused]] bool IsConstant = GEP.accumulateConstantOffset(DL, Offset);
969 assert(IsConstant && "a constant index must give a constant offset");
970 return walkLogicalAccessChainConstant(CurType, Offset.getZExtValue(),
971 OnLiteralIndexing);
972 }
973
974 return walkLogicalAccessChainDynamic(CurType, Operand, Multiplier,
975 OnLiteralIndexing, OnDynamicIndexing);
976}
977
978void SPIRVEmitIntrinsicsImpl::recordAccessChainError(GetElementPtrInst &GEP,
979 Error Err) {
980 InvalidGEPs.insert(&GEP);
981 AccessChainErrors = joinErrors(
982 std::move(AccessChainErrors),
983 createStringError(Twine(toString(std::move(Err))) + " (in function '" +
984 GEP.getFunction()->getName() + "')"));
985}
986
987// Returns Idx truncated to IdxTy, the GEP index type, if Idx is wider. A GEP
988// uses only the low bits of a wider index, while an access chain uses all of
989// them. Both sign-extend a narrower index, so this returns Idx unchanged when
990// it is not wider.
991Value *SPIRVEmitIntrinsicsImpl::truncateGEPIndex(Value *Idx, Type *IdxTy,
992 IRBuilder<> &B) {
993 if (Idx->getType()->getScalarSizeInBits() <= IdxTy->getScalarSizeInBits())
994 return Idx;
995 Value *Trunc = B.CreateTrunc(Idx, IdxTy);
996 if (auto *TruncI = dyn_cast<Instruction>(Trunc))
997 insertAssignTypeIntrs(TruncI, B);
998 return Trunc;
999}
1000
1001Instruction *SPIRVEmitIntrinsicsImpl::buildLogicalAccessChainFromGEP(
1002 GetElementPtrInst &GEP) {
1003 if (InvalidGEPs.contains(&GEP))
1004 return nullptr;
1005
1006 auto &DL = CurrF->getDataLayout();
1007 IRBuilder<> B(GEP.getParent());
1008 B.SetInsertPoint(&GEP);
1009
1010 std::vector<Value *> Indices;
1011 Indices.push_back(ConstantInt::get(
1012 IntegerType::getInt32Ty(CurrF->getContext()), 0, /* Signed= */ false));
1013 Type *IdxTy = DL.getIndexType(GEP.getPointerOperandType());
1014 auto Result = walkLogicalAccessChain(
1015 GEP,
1016 [&Indices, IdxTy](Type *EltType, uint64_t Index) {
1017 Indices.push_back(ConstantInt::get(IdxTy, Index, /* Signed= */ false));
1018 },
1019 [&Indices, &B, &DL, IdxTy, this](Type *EltType, Value *Offset,
1020 uint64_t Multiplier) {
1021 Offset = truncateGEPIndex(Offset, IdxTy, B);
1022 Value *Index = nullptr;
1023 uint32_t EltTypeSize = DL.getTypeSizeInBits(EltType) / 8;
1024 assert(Multiplier != 0);
1025 if (Multiplier == EltTypeSize) {
1026 Index = Offset;
1027 } else if (EltTypeSize % Multiplier == 0) {
1028 Index =
1029 B.CreateUDiv(Offset, ConstantInt::get(Offset->getType(),
1030 EltTypeSize / Multiplier,
1031 /* Signed= */ false));
1032 } else {
1033 Index = B.CreateMul(Offset,
1034 ConstantInt::get(Offset->getType(), Multiplier,
1035 /* Signed= */ false));
1036 insertAssignTypeIntrs(cast<Instruction>(Index), B);
1037 Index = B.CreateUDiv(Index,
1038 ConstantInt::get(Offset->getType(), EltTypeSize,
1039 /* Signed= */ false));
1040 }
1041 insertAssignTypeIntrs(cast<Instruction>(Index), B);
1042 Indices.push_back(Index);
1043 });
1044 if (!Result) {
1045 recordAccessChainError(GEP, Result.takeError());
1046 return nullptr;
1047 }
1048
1049 B.SetInsertPoint(&GEP);
1050 SmallVector<Type *, 2> Types = {GEP.getType(), GEP.getOperand(0)->getType()};
1051 SmallVector<Value *, 4> Args;
1052 Args.push_back(B.getInt1(GEP.isInBounds()));
1053 Args.push_back(GEP.getOperand(0));
1054 llvm::append_range(Args, Indices);
1055 Instruction *NewI =
1056 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, {Types}, {Args});
1057 replaceAllUsesWithAndErase(B, &GEP, NewI);
1058 return NewI;
1059}
1060
1061Type *SPIRVEmitIntrinsicsImpl::getGEPTypeLogical(GetElementPtrInst *GEP) {
1062 if (InvalidGEPs.contains(GEP))
1063 return nullptr;
1064
1065 Type *CurType = GEP->getResultElementType();
1066
1067 auto Result = walkLogicalAccessChain(
1068 *GEP, [&CurType](Type *EltType, uint64_t Index) { CurType = EltType; },
1069 [&CurType](Type *EltType, Value *Index, uint64_t) { CurType = EltType; });
1070 if (!Result) {
1071 recordAccessChainError(*GEP, Result.takeError());
1072 return nullptr;
1073 }
1074
1075 return *Result ? GEP->getResultElementType() : CurType;
1076}
1077
1078Type *SPIRVEmitIntrinsicsImpl::getGEPType(GetElementPtrInst *Ref) {
1079 if (getByteAddressingMultiplier(Ref->getSourceElementType()) &&
1081 return getGEPTypeLogical(Ref);
1082 }
1083
1084 Type *Ty = nullptr;
1085 // TODO: not sure if GetElementPtrInst::getTypeAtIndex() does anything
1086 // useful here
1087 if (isNestedPointer(Ref->getSourceElementType())) {
1088 Ty = Ref->getSourceElementType();
1089 for (Use &U : drop_begin(Ref->indices()))
1090 Ty = GetElementPtrInst::getTypeAtIndex(Ty, U.get());
1091 } else {
1092 Ty = Ref->getResultElementType();
1093 }
1094 return Ty;
1095}
1096
1097Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeHelper(
1098 Value *I, SmallPtrSetImpl<Value *> &Visited, bool UnknownElemTypeI8,
1099 bool IgnoreKnownType) {
1100 // allow to pass nullptr as an argument
1101 if (!I)
1102 return nullptr;
1103
1104 // maybe already known
1105 if (!IgnoreKnownType)
1106 if (Type *KnownTy = GR->findDeducedElementType(I))
1107 return KnownTy;
1108
1109 // maybe a cycle
1110 if (!Visited.insert(I).second)
1111 return nullptr;
1112
1113 // fallback value in case when we fail to deduce a type
1114 Type *Ty = nullptr;
1115 // look for known basic patterns of type inference
1116 if (auto *Ref = dyn_cast<AllocaInst>(I)) {
1117 maybeAssignPtrType(Ty, I, Ref->getAllocatedType(), UnknownElemTypeI8);
1118 } else if (auto *Ref = dyn_cast<GetElementPtrInst>(I)) {
1119 Ty = getGEPType(Ref);
1120 } else if (auto *SGEP = dyn_cast<StructuredGEPInst>(I)) {
1121 Ty = SGEP->getResultElementType();
1122 } else if (auto *Ref = dyn_cast<LoadInst>(I)) {
1123 Value *Op = Ref->getPointerOperand();
1124 Type *KnownTy = GR->findDeducedElementType(Op);
1125 if (!KnownTy)
1126 KnownTy = Op->getType();
1127 if (Type *ElemTy = getPointeeType(KnownTy))
1128 maybeAssignPtrType(Ty, I, ElemTy, UnknownElemTypeI8);
1129 } else if (auto *Ref = dyn_cast<GlobalValue>(I)) {
1130 if (auto *Fn = dyn_cast<Function>(Ref)) {
1131 Ty = SPIRV::getOriginalFunctionType(*Fn);
1132 GR->addDeducedElementType(I, Ty);
1133 } else {
1134 Value *Op = Ref->getNumOperands() > 0 ? Ref->getOperand(0) : nullptr;
1135 // Code lives in the program address space, not in the address space of
1136 // the global. For known SPIR-V targets, program address space 0 maps
1137 // to Function/Private, which cannot hold code, so treat it as unset.
1138 std::optional<unsigned> ProgramAS;
1140 if (unsigned AS = CurrF->getDataLayout().getProgramAddressSpace())
1141 ProgramAS = AS;
1142 else if (TM.getSubtargetImpl()->canUseExtension(
1143 SPIRV::Extension::SPV_INTEL_function_pointers))
1144 ProgramAS =
1145 storageClassToAddressSpace(SPIRV::StorageClass::CodeSectionINTEL);
1146 }
1147 Ty = deduceElementTypeByValueDeep(Ref->getValueType(), Op, Visited,
1148 UnknownElemTypeI8, ProgramAS);
1149 }
1150 } else if (auto *Ref = dyn_cast<AddrSpaceCastInst>(I)) {
1151 Type *RefTy = deduceElementTypeHelper(Ref->getPointerOperand(), Visited,
1152 UnknownElemTypeI8);
1153 maybeAssignPtrType(Ty, I, RefTy, UnknownElemTypeI8);
1154 } else if (auto *Ref = dyn_cast<IntToPtrInst>(I)) {
1155 maybeAssignPtrType(Ty, I, Ref->getDestTy(), UnknownElemTypeI8);
1156 } else if (auto *Ref = dyn_cast<BitCastInst>(I)) {
1157 if (Type *Src = Ref->getSrcTy(), *Dest = Ref->getDestTy();
1158 isPointerTy(Src) && isPointerTy(Dest))
1159 Ty = deduceElementTypeHelper(Ref->getOperand(0), Visited,
1160 UnknownElemTypeI8);
1161 } else if (auto *Ref = dyn_cast<ExtractValueInst>(I)) {
1162 // An extracted pointer has the type of its aggregate member.
1163 if (isPointerTy(I->getType()))
1165 reconstructType(Ref->getAggregateOperand(), false, false),
1166 Ref->getIndices());
1167 } else if (auto *Ref = dyn_cast<AtomicCmpXchgInst>(I)) {
1168 Value *Op = Ref->getNewValOperand();
1169 if (isPointerTy(Op->getType()))
1170 Ty = deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8);
1171 } else if (auto *Ref = dyn_cast<AtomicRMWInst>(I)) {
1172 Value *Op = Ref->getValOperand();
1173 if (isPointerTy(Op->getType()))
1174 Ty = deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8);
1175 } else if (auto *Ref = dyn_cast<PHINode>(I)) {
1176 Type *BestTy = nullptr;
1177 unsigned MaxN = 1;
1178 DenseMap<Type *, unsigned> PhiTys;
1179 for (int i = Ref->getNumIncomingValues() - 1; i >= 0; --i) {
1180 Ty = deduceElementTypeByUsersDeep(Ref->getIncomingValue(i), Visited,
1181 UnknownElemTypeI8);
1182 if (!Ty)
1183 continue;
1184 auto It = PhiTys.try_emplace(Ty, 1);
1185 if (!It.second) {
1186 ++It.first->second;
1187 if (It.first->second > MaxN) {
1188 MaxN = It.first->second;
1189 BestTy = Ty;
1190 }
1191 }
1192 }
1193 if (BestTy)
1194 Ty = BestTy;
1195 } else if (auto *Ref = dyn_cast<SelectInst>(I)) {
1196 for (Value *Op : {Ref->getTrueValue(), Ref->getFalseValue()}) {
1197 // A function pointer operand carries its function type directly. Other
1198 // operands are deduced from their uses.
1199 Ty = isa<Function>(Op)
1200 ? deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8)
1201 : deduceElementTypeByUsersDeep(Op, Visited, UnknownElemTypeI8);
1202 if (Ty)
1203 break;
1204 }
1205 } else if (auto *CI = dyn_cast<CallInst>(I)) {
1206 static StringMap<unsigned> ResTypeByArg = {
1207 {"to_global", 0},
1208 {"to_local", 0},
1209 {"to_private", 0},
1210 {"__to_global", 0},
1211 {"__to_local", 0},
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}};
1219 // TODO: maybe improve performance by caching demangled names
1220
1221 auto *II = dyn_cast<IntrinsicInst>(I);
1222 if (II && (II->getIntrinsicID() == Intrinsic::spv_resource_getbasepointer ||
1223 II->getIntrinsicID() == Intrinsic::spv_resource_getpointer)) {
1224 auto *HandleType = cast<TargetExtType>(II->getOperand(0)->getType());
1225 if (HandleType->getTargetExtName() == "spirv.Image" ||
1226 HandleType->getTargetExtName() == "spirv.SignedImage") {
1227 for (Instruction *U : II->users()) {
1228 Ty = U->getAccessType();
1229 if (Ty)
1230 break;
1231 }
1232 } else if (HandleType->getTargetExtName() == "spirv.VulkanBuffer") {
1233 // This call is supposed to index into an array
1234 Ty = HandleType->getTypeParameter(0);
1235 if (II->getIntrinsicID() == Intrinsic::spv_resource_getpointer) {
1236 if (Ty->isArrayTy())
1237 Ty = Ty->getArrayElementType();
1238 else {
1239 assert(Ty && Ty->isStructTy());
1240 uint32_t Index =
1241 cast<ConstantInt>(II->getOperand(1))->getZExtValue();
1242 Ty = cast<StructType>(Ty)->getElementType(Index);
1243 }
1244 }
1246 } else {
1247 llvm_unreachable("Unknown handle type for spv_resource_getpointer.");
1248 }
1249 } else if (II && II->getIntrinsicID() ==
1250 Intrinsic::spv_generic_cast_to_ptr_explicit) {
1251 Ty = deduceElementTypeHelper(CI->getArgOperand(0), Visited,
1252 UnknownElemTypeI8);
1253 } else if (Function *CalledF = CI->getCalledFunction()) {
1254 std::string DemangledName =
1255 getOclOrSpirvBuiltinDemangledName(CalledF->getName());
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);
1262 else if (Type *KnownRetTy = GR->findDeducedElementType(CalledF))
1263 Ty = KnownRetTy;
1264 }
1265 }
1266
1267 // remember the found relationship
1268 if (Ty && !IgnoreKnownType) {
1269 // specify nested types if needed, otherwise return unchanged
1270 GR->addDeducedElementType(I, normalizeType(Ty, CanUseAnyVectorRank));
1271 }
1272
1273 return Ty;
1274}
1275
1276// Re-create a type of the value if it has untyped pointer fields, also nested.
1277// Return the original value type if no corrections of untyped pointer
1278// information is found or needed.
1279Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(User *U,
1280 bool UnknownElemTypeI8) {
1281 SmallPtrSet<Value *, 0> Visited;
1282 return deduceNestedTypeHelper(U, U->getType(), Visited, UnknownElemTypeI8);
1283}
1284
1285Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(
1286 User *U, Type *OrigTy, SmallPtrSetImpl<Value *> &Visited,
1287 bool UnknownElemTypeI8) {
1288 // Only constant aggregate operands map to aggregate elements.
1290 return OrigTy;
1291
1292 // maybe already known
1293 if (Type *KnownTy = GR->findDeducedCompositeType(U))
1294 return KnownTy;
1295
1296 // maybe a cycle
1297 if (!Visited.insert(U).second)
1298 return OrigTy;
1299
1300 auto DeduceOpTy = [&](Value *Op, Type *OpTy) -> Type * {
1301 auto *PtrTy = dyn_cast<PointerType>(OpTy);
1302 if (!PtrTy)
1303 return deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited,
1304 UnknownElemTypeI8);
1305 // A uniqued null carries the pointee an earlier user gave it.
1307 return OpTy;
1308 if (Type *NestedTy =
1309 deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8))
1310 return getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
1311 return OpTy;
1312 };
1313
1314 if (auto *OrigStructTy = dyn_cast<StructType>(OrigTy)) {
1316 bool Change = false;
1317 for (unsigned i = 0; i < U->getNumOperands(); ++i) {
1318 Value *Op = U->getOperand(i);
1319 assert(Op && "Operands should not be null.");
1320 Type *OpTy = Op->getType();
1321 Type *Ty = DeduceOpTy(Op, OpTy);
1322 Tys.push_back(Ty);
1323 Change |= Ty != OpTy;
1324 }
1325 if (Change) {
1326 Type *NewTy = StructType::create(
1327 Tys, OrigStructTy->isLiteral() ? "" : OrigStructTy->getName(),
1328 OrigStructTy->isPacked());
1329 GR->addDeducedCompositeType(U, NewTy);
1330 return NewTy;
1331 }
1332 } else if (auto *ArrTy = dyn_cast<ArrayType>(OrigTy)) {
1333 for (Value *Op : U->operands()) {
1334 Type *OpTy = ArrTy->getElementType();
1335 Type *Ty = DeduceOpTy(Op, OpTy);
1336 if (Ty != OpTy) {
1337 Type *NewTy = ArrayType::get(Ty, ArrTy->getNumElements());
1338 GR->addDeducedCompositeType(U, NewTy);
1339 return NewTy;
1340 }
1341 }
1342 } else if (auto *VecTy = dyn_cast<VectorType>(OrigTy)) {
1343 for (Value *Op : U->operands()) {
1344 Type *OpTy = VecTy->getElementType();
1345 Type *Ty = DeduceOpTy(Op, OpTy);
1346 if (Ty != OpTy) {
1347 Type *NewTy = VectorType::get(Ty, VecTy->getElementCount());
1349 normalizeType(NewTy, CanUseAnyVectorRank));
1350 return NewTy;
1351 }
1352 }
1353 }
1354
1355 return OrigTy;
1356}
1357
1358Type *SPIRVEmitIntrinsicsImpl::deduceElementType(Value *I,
1359 bool UnknownElemTypeI8) {
1360 if (Type *Ty = deduceElementTypeHelper(I, UnknownElemTypeI8))
1361 return Ty;
1362 if (!UnknownElemTypeI8)
1363 return nullptr;
1364 insertTodoType(I);
1365 return IntegerType::getInt8Ty(I->getContext());
1366}
1367
1369 Value *PointerOperand) {
1370 Type *PointeeTy = GR->findDeducedElementType(PointerOperand);
1371 if (PointeeTy && !isUntypedPointerTy(PointeeTy))
1372 return nullptr;
1373 auto *PtrTy = dyn_cast<PointerType>(I->getType());
1374 if (!PtrTy)
1375 return I->getType();
1376 if (Type *NestedTy = GR->findDeducedElementType(I))
1377 return getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
1378 return nullptr;
1379}
1380
1381// Try to deduce element type for a call base. Returns false if this is an
1382// indirect function invocation, and true otherwise.
1383bool SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeCalledFunction(
1384 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
1385 Type *&KnownElemTy, bool &Incomplete) {
1386 Function *CalledF = CI->getCalledFunction();
1387 if (!CalledF)
1388 return false;
1389 std::string DemangledName =
1391 if (DemangledName.length() > 0 &&
1392 !StringRef(DemangledName).starts_with("llvm.")) {
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) {
1398 Value *Op = CI->getArgOperand(i);
1399 if (!isPointerTy(Op->getType()))
1400 continue;
1401 ++PtrCnt;
1402 if (Type *ElemTy = GR->findDeducedElementType(Op))
1403 KnownElemTy = ElemTy; // src will rewrite dest if both are defined
1404 Ops.push_back(std::make_pair(Op, i));
1405 }
1406 } else if (Grp == SPIRV::Atomic || Grp == SPIRV::AtomicFloating) {
1407 if (CI->arg_size() == 0)
1408 return true;
1409 Value *Op = CI->getArgOperand(0);
1410 if (!isPointerTy(Op->getType()))
1411 return true;
1412 switch (Opcode) {
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: {
1429 KnownElemTy = isPointerTy(CI->getType()) ? getAtomicElemTy(GR, CI, Op)
1430 : CI->getType();
1431 if (!KnownElemTy)
1432 return true;
1433 Incomplete = isTodoType(Op);
1434 Ops.push_back(std::make_pair(Op, 0));
1435 } break;
1436 case SPIRV::OpAtomicStore: {
1437 if (CI->arg_size() < 4)
1438 return true;
1439 Value *ValOp = CI->getArgOperand(3);
1440 KnownElemTy = isPointerTy(ValOp->getType())
1441 ? getAtomicElemTy(GR, CI, Op)
1442 : ValOp->getType();
1443 if (!KnownElemTy)
1444 return true;
1445 Incomplete = isTodoType(Op);
1446 Ops.push_back(std::make_pair(Op, 0));
1447 } break;
1448 }
1449 }
1450 }
1451 return true;
1452}
1453
1454// Try to deduce element type for a function pointer.
1455void SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeFunctionPointer(
1456 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
1457 Type *&KnownElemTy, bool IsPostprocessing) {
1458 Value *Op = CI->getCalledOperand();
1459 if (!Op || !isPointerTy(Op->getType()))
1460 return;
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;
1465 for (auto &&[ParmIdx, Arg] : llvm::enumerate(CI->args())) {
1466 Type *ArgTy = Arg->getType();
1467 if (ArgTy->isPointerTy()) {
1468 if (Type *ElemTy = GR->findDeducedElementType(Arg)) {
1469 IsNewFTy = true;
1470 ArgTy = getTypedPointerWrapper(ElemTy, getPointerAddressSpace(ArgTy));
1471 if (isTodoType(Arg))
1472 IsIncomplete = true;
1473 } else {
1474 IsIncomplete = true;
1475 }
1476 } else {
1477 ArgTy = FTy->getFunctionParamType(ParmIdx);
1478 }
1479 ArgTys.push_back(ArgTy);
1480 }
1481 Type *RetTy = FTy->getReturnType();
1482 if (CI->getType()->isPointerTy()) {
1483 if (Type *ElemTy = GR->findDeducedElementType(CI)) {
1484 IsNewFTy = true;
1485 RetTy =
1487 if (isTodoType(CI))
1488 IsIncomplete = true;
1489 } else {
1490 IsIncomplete = true;
1491 }
1492 }
1493 if (!IsPostprocessing && IsIncomplete)
1494 insertTodoType(Op);
1495 KnownElemTy =
1496 IsNewFTy ? FunctionType::get(RetTy, ArgTys, FTy->isVarArg()) : FTy;
1497}
1498
1499bool SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeFunctionRet(
1500 Instruction *I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
1501 const SmallPtrSetImpl<Value *> *AskOps, bool IsPostprocessing,
1502 Type *&KnownElemTy, Value *Op, Function *F) {
1503 KnownElemTy = GR->findDeducedElementType(F);
1504 if (KnownElemTy)
1505 return false;
1506 if (Type *OpElemTy = GR->findDeducedElementType(Op)) {
1507 OpElemTy = normalizeType(OpElemTy, CanUseAnyVectorRank);
1508 GR->addDeducedElementType(F, OpElemTy);
1509 GR->addReturnType(
1510 F, TypedPointerType::get(OpElemTy,
1511 getPointerAddressSpace(F->getReturnType())));
1512 // non-recursive update of types in function uses
1513 DenseSet<std::pair<Value *, Value *>> VisitedSubst{std::make_pair(I, Op)};
1514 for (User *U : F->users()) {
1515 CallInst *CI = dyn_cast<CallInst>(U);
1516 if (!CI || CI->getCalledFunction() != F)
1517 continue;
1518 if (CallInst *AssignCI = GR->findAssignPtrTypeInstr(CI)) {
1519 if (Type *PrevElemTy = GR->findDeducedElementType(CI)) {
1520 GR->updateAssignType(
1521 AssignCI, CI,
1522 getNormalizedPoisonValue(OpElemTy, CanUseAnyVectorRank));
1523 propagateElemType(CI, PrevElemTy, VisitedSubst);
1524 }
1525 }
1526 }
1527 // Non-recursive update of types in the function uncomplete returns.
1528 // This may happen just once per a function, the latch is a pair of
1529 // findDeducedElementType(F) / addDeducedElementType(F, ...).
1530 // With or without the latch it is a non-recursive call due to
1531 // IncompleteRets set to nullptr in this call.
1532 if (IncompleteRets)
1533 for (Instruction *IncompleteRetI : *IncompleteRets)
1534 deduceOperandElementType(IncompleteRetI, nullptr, AskOps,
1535 IsPostprocessing);
1536 } else if (IncompleteRets) {
1537 IncompleteRets->insert(I);
1538 }
1539 TypeValidated.insert(I);
1540 return true;
1541}
1542
1543// If the Instruction has Pointer operands with unresolved types, this function
1544// tries to deduce them. If the Instruction has Pointer operands with known
1545// types which differ from expected, this function tries to insert a bitcast to
1546// resolve the issue.
1547void SPIRVEmitIntrinsicsImpl::deduceOperandElementType(
1548 Instruction *I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
1549 const SmallPtrSetImpl<Value *> *AskOps, bool IsPostprocessing) {
1551 Type *KnownElemTy = nullptr;
1552 bool Incomplete = false;
1553 // look for known basic patterns of type inference
1554 if (auto *Ref = dyn_cast<PHINode>(I)) {
1555 if (!isPointerTy(I->getType()) ||
1556 !(KnownElemTy = GR->findDeducedElementType(I)))
1557 return;
1558 Incomplete = isTodoType(I);
1559 for (unsigned i = 0; i < Ref->getNumIncomingValues(); i++) {
1560 Value *Op = Ref->getIncomingValue(i);
1561 if (isPointerTy(Op->getType()))
1562 Ops.push_back(std::make_pair(Op, i));
1563 }
1564 } else if (auto *Ref = dyn_cast<AddrSpaceCastInst>(I)) {
1565 KnownElemTy = GR->findDeducedElementType(I);
1566 if (!KnownElemTy)
1567 return;
1568 Incomplete = isTodoType(I);
1569 Ops.push_back(std::make_pair(Ref->getPointerOperand(), 0));
1570 } else if (auto *Ref = dyn_cast<BitCastInst>(I)) {
1571 if (!isPointerTy(I->getType()))
1572 return;
1573 KnownElemTy = GR->findDeducedElementType(I);
1574 if (!KnownElemTy)
1575 return;
1576 Incomplete = isTodoType(I);
1577 Ops.push_back(std::make_pair(Ref->getOperand(0), 0));
1578 } else if (auto *Ref = dyn_cast<GetElementPtrInst>(I)) {
1579 if (GR->findDeducedElementType(Ref->getPointerOperand()))
1580 return;
1581 KnownElemTy = Ref->getSourceElementType();
1582 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1584 } else if (auto *Ref = dyn_cast<StructuredGEPInst>(I)) {
1585 if (GR->findDeducedElementType(Ref->getPointerOperand()))
1586 return;
1587 KnownElemTy = Ref->getBaseType();
1588 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1590 } else if (auto *Ref = dyn_cast<LoadInst>(I)) {
1591 KnownElemTy = I->getType();
1592 if (isUntypedPointerTy(KnownElemTy)) {
1593 // A T** loaded back from its alloca comes out opaque, dropping type info.
1594 // When the load is a pointer-to-pointer, type the alloca as that pointer.
1595 Type *LoadedElemTy = GR->findDeducedElementType(I);
1596 if (!LoadedElemTy || !isPointerTyOrWrapper(LoadedElemTy))
1597 return;
1598 Value *Root = Ref->getPointerOperand()->stripPointerCasts();
1599 if (!isa<AllocaInst>(Root))
1600 return;
1601 KnownElemTy = getTypedPointerWrapper(LoadedElemTy,
1602 getPointerAddressSpace(KnownElemTy));
1603 }
1604 Type *PointeeTy = GR->findDeducedElementType(Ref->getPointerOperand());
1605 if (PointeeTy && !isUntypedPointerTy(PointeeTy))
1606 return;
1607 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1609 } else if (auto *Ref = dyn_cast<StoreInst>(I)) {
1610 if (!(KnownElemTy =
1611 reconstructType(Ref->getValueOperand(), false, IsPostprocessing)))
1612 return;
1613 Type *PointeeTy = GR->findDeducedElementType(Ref->getPointerOperand());
1614 if (PointeeTy && !isUntypedPointerTy(PointeeTy))
1615 return;
1616 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1618 } else if (auto *Ref = dyn_cast<AtomicCmpXchgInst>(I)) {
1619 KnownElemTy = isPointerTy(I->getType())
1620 ? getAtomicElemTy(GR, I, Ref->getPointerOperand())
1621 : I->getType();
1622 if (!KnownElemTy)
1623 return;
1624 Incomplete = isTodoType(Ref->getPointerOperand());
1625 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1627 } else if (auto *Ref = dyn_cast<AtomicRMWInst>(I)) {
1628 KnownElemTy = isPointerTy(I->getType())
1629 ? getAtomicElemTy(GR, I, Ref->getPointerOperand())
1630 : I->getType();
1631 if (!KnownElemTy)
1632 return;
1633 Incomplete = isTodoType(Ref->getPointerOperand());
1634 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1636 } else if (auto *Ref = dyn_cast<SelectInst>(I)) {
1637 if (!isPointerTy(I->getType()) ||
1638 !(KnownElemTy = GR->findDeducedElementType(I)))
1639 return;
1640 Incomplete = isTodoType(I);
1641 for (unsigned i = 0; i < Ref->getNumOperands(); i++) {
1642 Value *Op = Ref->getOperand(i);
1643 if (isPointerTy(Op->getType()))
1644 Ops.push_back(std::make_pair(Op, i));
1645 }
1646 } else if (auto *Ref = dyn_cast<ReturnInst>(I)) {
1647 if (!isPointerTy(CurrF->getReturnType()))
1648 return;
1649 Value *Op = Ref->getReturnValue();
1650 if (!Op)
1651 return;
1652 if (deduceOperandElementTypeFunctionRet(I, IncompleteRets, AskOps,
1653 IsPostprocessing, KnownElemTy, Op,
1654 CurrF))
1655 return;
1656 Incomplete = isTodoType(CurrF);
1657 Ops.push_back(std::make_pair(Op, 0));
1658 } else if (auto *Ref = dyn_cast<ICmpInst>(I)) {
1659 if (!isPointerTy(Ref->getOperand(0)->getType()))
1660 return;
1661 Value *Op0 = Ref->getOperand(0);
1662 Value *Op1 = Ref->getOperand(1);
1663 bool Incomplete0 = isTodoType(Op0);
1664 bool Incomplete1 = isTodoType(Op1);
1665 Type *ElemTy1 = GR->findDeducedElementType(Op1);
1666 Type *ElemTy0 = (Incomplete0 && !Incomplete1 && ElemTy1)
1667 ? nullptr
1668 : GR->findDeducedElementType(Op0);
1669 if (ElemTy0) {
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));
1677 }
1678 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1679 if (!CI->isIndirectCall())
1680 deduceOperandElementTypeCalledFunction(CI, Ops, KnownElemTy, Incomplete);
1681 else if (HaveFunPtrs)
1682 deduceOperandElementTypeFunctionPointer(CI, Ops, KnownElemTy,
1683 IsPostprocessing);
1684 }
1685
1686 // There is no enough info to deduce types or all is valid.
1687 if (!KnownElemTy || Ops.size() == 0)
1688 return;
1689
1690 IRBuilder<> B(*CurrF->getParent());
1691 for (auto &OpIt : Ops) {
1692 Value *Op = OpIt.first;
1693 if (AskOps && !AskOps->contains(Op))
1694 continue;
1695 Type *AskTy = nullptr;
1696 CallInst *AskCI = nullptr;
1697 if (IsPostprocessing && AskOps) {
1698 AskTy = GR->findDeducedElementType(Op);
1699 AskCI = GR->findAssignPtrTypeInstr(Op);
1700 assert(AskTy && AskCI);
1701 }
1702 Type *Ty = AskTy ? AskTy : GR->findDeducedElementType(Op);
1703 if (Ty == KnownElemTy)
1704 continue;
1705 Value *OpTyVal = getNormalizedPoisonValue(KnownElemTy, CanUseAnyVectorRank);
1706 Type *OpTy = Op->getType();
1707 // Do not let a non-pointer element type clobber an already-deduced pointer
1708 // element type for the same operand.
1709 bool WouldClobberPtrWithNonPtr = Ty && isPointerTyOrWrapper(Ty) &&
1710 !isPointerTyOrWrapper(KnownElemTy) &&
1712 if (Op->hasUseList() && !WouldClobberPtrWithNonPtr &&
1713 (!Ty || AskTy || isUntypedPointerTy(Ty) || isTodoType(Op))) {
1714 Type *PrevElemTy = GR->findDeducedElementType(Op);
1716 Op, normalizeType(KnownElemTy, CanUseAnyVectorRank));
1717 // check if KnownElemTy is complete
1718 if (!Incomplete)
1719 eraseTodoType(Op);
1720 else if (!IsPostprocessing)
1721 insertTodoType(Op);
1722 // check if there is existing Intrinsic::spv_assign_ptr_type instruction
1723 CallInst *AssignCI = AskCI ? AskCI : GR->findAssignPtrTypeInstr(Op);
1724 if (AssignCI == nullptr) {
1725 Instruction *User = dyn_cast<Instruction>(Op->use_begin()->get());
1726 setInsertPointSkippingPhis(B, User ? User->getNextNode() : I);
1727 CallInst *CI =
1728 buildIntrWithMD(Intrinsic::spv_assign_ptr_type, {OpTy}, OpTyVal, Op,
1729 {B.getInt32(getPointerAddressSpace(OpTy))}, B);
1730 GR->addAssignPtrTypeInstr(Op, CI);
1731 } else {
1732 GR->updateAssignType(AssignCI, Op, OpTyVal);
1733 DenseSet<std::pair<Value *, Value *>> VisitedSubst{
1734 std::make_pair(I, Op)};
1735 propagateElemTypeRec(Op, KnownElemTy, PrevElemTy, VisitedSubst);
1736 // A PHI or select validated its operands against its previous element
1737 // type. Null constants have no use list and are not revisited by
1738 // postprocessing, so validate the operands against the new type.
1739 if (auto *OpI = dyn_cast<Instruction>(Op);
1740 OpI && (isa<PHINode>(OpI) || isa<SelectInst>(OpI)) &&
1741 TypeValidated.contains(OpI))
1742 RetypedToRevalidate.push_back(OpI);
1743 }
1744 } else {
1745 eraseTodoType(Op);
1746 CallInst *PtrCastI =
1747 buildSpvPtrcast(I->getParent()->getParent(), Op, KnownElemTy);
1748 if (OpIt.second == std::numeric_limits<unsigned>::max())
1749 dyn_cast<CallInst>(I)->setCalledOperand(PtrCastI);
1750 else
1751 I->setOperand(OpIt.second, PtrCastI);
1752 }
1753 }
1754 TypeValidated.insert(I);
1755
1756 // Revalidating one PHI can retype the next one in a chain. Use a worklist
1757 // rather than recursion, as such chains can be long.
1758 if (RevalidatingRetyped)
1759 return;
1760 RevalidatingRetyped = true;
1761 while (!RetypedToRevalidate.empty())
1762 deduceOperandElementType(RetypedToRevalidate.pop_back_val(), nullptr,
1763 nullptr, IsPostprocessing);
1764 RevalidatingRetyped = false;
1765}
1766
1767void SPIRVEmitIntrinsicsImpl::replaceMemInstrUses(Instruction *Old,
1768 Instruction *New,
1769 IRBuilder<> &B) {
1770 while (!Old->user_empty()) {
1771 auto *U = Old->user_back();
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);
1777 GR->addAssignPtrTypeInstr(New, AssignCI);
1778 U->eraseFromParent();
1779 } else if (isMemInstrToReplace(U) || isa<ReturnInst>(U) ||
1780 isa<CallInst>(U)) {
1781 U->replaceUsesOfWith(Old, New);
1782 // For a `llvm.spv.abort` call whose composite message argument was
1783 // rewritten to a value-id (i32), also retarget the call to a matching
1784 // intrinsic declaration so the IR verifier is satisfied. The SPIR-V
1785 // type of the value is tracked via the GlobalRegistry, so the selector
1786 // still emits OpAbortKHR with the original composite type.
1787 if (auto *CI = dyn_cast<CallInst>(U);
1788 CI && CI->getIntrinsicID() == Intrinsic::spv_abort) {
1789 Type *NewArgTy = New->getType();
1790 Type *ExpectedArgTy = CI->getFunctionType()->getParamType(0);
1791 if (NewArgTy != ExpectedArgTy) {
1792 Module *M = CI->getModule();
1794 M, Intrinsic::spv_abort, {NewArgTy});
1795 CI->setCalledFunction(NewF);
1796 }
1797 }
1798 } else if (isa<PHINode>(U) || isa<SelectInst>(U) || isa<FreezeInst>(U)) {
1799 // Aggregate-typed PHIs, selects and freezes have already been mutated to
1800 // the i32 value-id type up front in runOnFunction, so only the operand
1801 // needs replacing here; their extractvalue users are lowered to
1802 // spv_extractv by visitExtractValueInst.
1803 assert(U->getType() == New->getType() &&
1804 "aggregate PHI/select/freeze should have been mutated to value-id "
1805 "type");
1806 U->replaceUsesOfWith(Old, New);
1807 } else {
1808 llvm_unreachable("illegal aggregate intrinsic user");
1809 }
1810 }
1811 New->copyMetadata(*Old);
1812 GR->removeAssignPtrTypeInstr(Old); // Old's address could be re-used.
1813 TypeValidated.erase(Old);
1814 Old->eraseFromParent();
1815}
1816
1817// Lower a poison or undef Op to its placeholder intrinsic.
1818Value *SPIRVEmitIntrinsicsImpl::lowerUndefOrPoison(Value *Op, IRBuilder<> &B,
1819 bool HasPoisonExt) {
1820 auto *UV = dyn_cast<UndefValue>(Op);
1821 if (!UV)
1822 return nullptr;
1823
1824 bool AsPoison = HasPoisonExt && isa<PoisonValue>(UV);
1825 if (isa<PoisonValue>(UV) && !HasPoisonExt)
1826 LLVM_DEBUG(dbgs() << "SPV_KHR_poison_freeze is not enabled. Poison is "
1827 "lowered as undef\n");
1828
1829 Intrinsic::ID IID = AsPoison ? Intrinsic::spv_poison : Intrinsic::spv_undef;
1830 Type *Ty = UV->getType();
1831
1832 // Aggregates use an i32-result placeholder with the real type kept in
1833 // AggrConstTypes and scalar poison uses a type-overloaded one.
1834 if (Ty->isAggregateType()) {
1835 auto *Call =
1836 AsPoison ? B.CreateIntrinsicWithoutFolding(IID, {B.getInt32Ty()}, {})
1837 : B.CreateIntrinsicWithoutFolding(IID, {});
1838 AggrConsts[Call] = UV;
1839 AggrConstTypes[Call] = Ty;
1840 return Call;
1841 }
1842
1843 if (AsPoison)
1844 return B.CreateIntrinsic(IID, {Ty}, {});
1845 return nullptr;
1846}
1847
1848// Replace aggregate undef or poison operands and extension-enabled scalar
1849// poison operands with placeholder intrinsics. Scalar undef is left as is. See
1850// lowerUndefOrPoison.
1851void SPIRVEmitIntrinsicsImpl::preprocessUndefsAndPoisons(IRBuilder<> &B) {
1852 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*CurrF);
1853 bool HasPoisonExt =
1854 STI->canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
1855
1856 SmallVector<Instruction *, 16> Insts;
1857 for (auto &I : instructions(CurrF))
1858 Insts.push_back(&I);
1859
1860 for (Instruction *I : Insts) {
1861 bool BPrepared = false;
1862 auto *Phi = dyn_cast<PHINode>(I);
1863 for (unsigned Idx = 0; Idx < I->getNumOperands(); ++Idx) {
1864 Value *Op = I->getOperand(Idx);
1865 if (!isa<UndefValue>(Op) || Op->getType()->isMetadataTy())
1866 continue;
1867 bool IsScalar = !Op->getType()->isAggregateType();
1868 bool AsPoison = HasPoisonExt && isa<PoisonValue>(Op);
1869 // Scalar undef or extensionless scalar poison is directly translatable.
1870 if (IsScalar && !AsPoison)
1871 continue;
1872 // Scalar poison in a phi materializes in the incoming block. Everything
1873 // else materializes right before I.
1874 if (IsScalar && Phi)
1875 B.SetInsertPoint(Phi->getIncomingBlock(Idx)->getTerminator());
1876 else if (!BPrepared) {
1878 BPrepared = true;
1879 }
1880 if (Value *Repl = lowerUndefOrPoison(Op, B, HasPoisonExt))
1881 I->setOperand(Idx, Repl);
1882 }
1883 }
1884}
1885
1886// Simplify addrspacecast(null) instructions to ConstantPointerNull of the
1887// target type. Casting null always yields null, and this avoids SPIR-V
1888// lowering issues where the null gets typed as an integer instead of a
1889// pointer.
1890void SPIRVEmitIntrinsicsImpl::simplifyNullAddrSpaceCasts() {
1891 for (Instruction &I : make_early_inc_range(instructions(CurrF)))
1892 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I))
1893 if (isa<ConstantPointerNull>(ASC->getPointerOperand())) {
1894 ASC->replaceAllUsesWith(
1896 ASC->eraseFromParent();
1897 }
1898}
1899
1900// True for an aggregate value the legalizer splits into a multi-result op
1901// (with.overflow -> G_UADDO, frexp/sincos/modf -> G_FFREXP/...). These keep a
1902// genuine multi-register result; all other aggregates become a single value-id.
1904 if (!V->getType()->isAggregateType())
1905 return false;
1906 return isa<IntrinsicInst>(V) && !isSpvIntrinsic(V);
1907}
1908
1909// True for an aggregate PHI/select/freeze, which is lowered to a single
1910// value-id.
1912 return (isa<PHINode>(I) || isa<SelectInst>(I) || isa<FreezeInst>(I)) &&
1913 I.getType()->isAggregateType();
1914}
1915
1916// Give each multi-register aggregate arm of an aggregate PHI/select/freeze a
1917// single value-id by reassembling it with extractvalue + insertvalue, so the
1918// arm matches the result once it is mutated to a value-id.
1919void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
1920 IRBuilder<> &B) {
1921 auto *Phi = dyn_cast<PHINode>(I);
1922 // A switch can list an incoming block twice, and both entries need the same
1923 // value, so build one chain per block.
1924 SmallDenseMap<BasicBlock *, Value *> PhiArms;
1925 for (Use &U : I->operands()) {
1926 Value *Op = U.get();
1928 continue;
1929 if (Value *Arm = Phi ? PhiArms.lookup(Phi->getIncomingBlock(U)) : nullptr) {
1930 U.set(Arm);
1931 continue;
1932 }
1933 // A PHI arm materializes in its incoming block, everything else after the
1934 // producer.
1935 if (Phi)
1936 B.SetInsertPoint(Phi->getIncomingBlock(U)->getTerminator());
1937 else
1939 auto *AggrTy = cast<StructType>(Op->getType());
1940 Value *Composite = PoisonValue::get(AggrTy);
1941 for (unsigned Idx = 0, E = AggrTy->getNumElements(); Idx != E; ++Idx) {
1942 Value *Field = B.CreateExtractValue(Op, Idx);
1943 Composite = B.CreateInsertValue(Composite, Field, Idx);
1944 }
1945 U.set(Composite);
1946 if (Phi)
1947 PhiArms[Phi->getIncomingBlock(U)] = Composite;
1948 }
1949}
1950
1951// Lower a constant aggregate member to null in the target address space
1952// if it's `addrspacecast(null)`, and nested `undef/poison` because they're
1953// missed in `preprocessUndefsAndPoisons()`.
1954Value *SPIRVEmitIntrinsicsImpl::lowerCompositeMember(Value *Op, IRBuilder<> &B,
1955 bool HasPoisonExt) {
1956 if (auto *CE = dyn_cast<ConstantExpr>(Op);
1957 CE && CE->getOpcode() == Instruction::AddrSpaceCast &&
1958 isa<ConstantPointerNull>(CE->getOperand(0)))
1959 return ConstantPointerNull::get(cast<PointerType>(CE->getType()));
1960 if (isa<UndefValue>(Op))
1961 if (Value *Repl = lowerUndefOrPoison(Op, B, HasPoisonExt))
1962 return Repl;
1963 return Op;
1964}
1965
1966void SPIRVEmitIntrinsicsImpl::preprocessCompositeConstants(IRBuilder<> &B) {
1967 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*CurrF);
1968 bool HasPoisonExt =
1969 STI->canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
1970 std::queue<Instruction *> Worklist;
1971 for (auto &I : instructions(CurrF))
1972 Worklist.push(&I);
1973
1974 while (!Worklist.empty()) {
1975 auto *I = Worklist.front();
1976 bool IsPhi = isa<PHINode>(I), BPrepared = false;
1977 assert(I);
1978 bool KeepInst = false;
1979 for (const auto &Op : I->operands()) {
1980 Constant *AggrConst = nullptr;
1981 Type *ResTy = nullptr;
1982 if (auto *COp = dyn_cast<ConstantVector>(Op)) {
1983 AggrConst = COp;
1984 ResTy = COp->getType();
1985 } else if (auto *COp = dyn_cast<ConstantArray>(Op)) {
1986 AggrConst = COp;
1987 ResTy = B.getInt32Ty();
1988 } else if (auto *COp = dyn_cast<ConstantStruct>(Op)) {
1989 AggrConst = COp;
1990 ResTy = B.getInt32Ty();
1991 } else if (auto *COp = dyn_cast<ConstantDataArray>(Op)) {
1992 AggrConst = COp;
1993 ResTy = B.getInt32Ty();
1994 } else if (auto *COp = dyn_cast<ConstantAggregateZero>(Op)) {
1995 AggrConst = COp;
1996 ResTy = Op->getType()->isVectorTy() ? COp->getType() : B.getInt32Ty();
1997 }
1998 if (AggrConst) {
1999 auto PrepareInsert = [&]() {
2000 if (BPrepared)
2001 return;
2002 IsPhi ? B.SetInsertPointPastAllocas(I->getParent()->getParent())
2003 : B.SetInsertPoint(I);
2004 BPrepared = true;
2005 };
2006 PrepareInsert();
2007 Type *DeducedTy = deduceNestedTypeHelper(AggrConst, false);
2008 // Users other than an intrinsic or extractvalue expect the LLVM type.
2009 // Rebuild the constant as an insert chain, which casts each member
2010 // to it.
2011 if (DeducedTy != AggrConst->getType() &&
2013 bool IsVector = AggrConst->getType()->isVectorTy();
2014 Value *Composite = PoisonValue::get(AggrConst->getType());
2015 for (unsigned Idx = 0, E = AggrConst->getNumOperands(); Idx != E;
2016 ++Idx) {
2017 Value *Member = AggrConst->getOperand(Idx);
2018 // Lowered undef/poison is an i32 placeholder, so it is set after
2019 // Create, which checks the types.
2020 Value *LoweredBase =
2021 lowerCompositeMember(Composite, B, HasPoisonExt);
2022 Value *LoweredMember =
2023 lowerCompositeMember(Member, B, HasPoisonExt);
2025 if (IsVector)
2027 Composite, Member, B.getInt32(Idx), "", B.GetInsertPoint());
2028 else
2029 Insert = InsertValueInst::Create(Composite, Member, Idx, "",
2030 B.GetInsertPoint());
2031 Insert->setOperand(0, LoweredBase);
2032 Insert->setOperand(1, LoweredMember);
2033 Worklist.push(Insert);
2034 Composite = Insert;
2035 }
2036 I->replaceUsesOfWith(Op, Composite);
2037 KeepInst = true;
2038 continue;
2039 }
2041 if (auto *COp = dyn_cast<ConstantDataSequential>(Op))
2042 for (unsigned i = 0; i < COp->getNumElements(); ++i)
2043 Args.push_back(COp->getElementAsConstant(i));
2044 else
2045 for (Value *Op : AggrConst->operands())
2046 Args.push_back(lowerCompositeMember(Op, B, HasPoisonExt));
2047 auto *CI = B.CreateIntrinsicWithoutFolding(
2048 Intrinsic::spv_const_composite, {ResTy}, {Args});
2049 Worklist.push(CI);
2050 I->replaceUsesOfWith(Op, CI);
2051 KeepInst = true;
2052 AggrConsts[CI] = AggrConst;
2053 AggrConstTypes[CI] = DeducedTy;
2054 }
2055 }
2056 if (!KeepInst)
2057 Worklist.pop();
2058 }
2059}
2060
2062 IRBuilder<> &B) {
2063 LLVMContext &Ctx = I->getContext();
2065 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {I->getType()},
2066 {I, MetadataAsValue::get(Ctx, MDNode::get(Ctx, {Node}))});
2067}
2068
2070 unsigned RoundingModeDeco,
2071 IRBuilder<> &B) {
2072 LLVMContext &Ctx = I->getContext();
2073 Type *Int32Ty = Type::getInt32Ty(Ctx);
2074 MDNode *RoundingModeNode = MDNode::get(
2075 Ctx,
2077 ConstantInt::get(Int32Ty, SPIRV::Decoration::FPRoundingMode)),
2078 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, RoundingModeDeco))});
2079 createDecorationIntrinsic(I, RoundingModeNode, B);
2080}
2081
2083 IRBuilder<> &B) {
2084 LLVMContext &Ctx = I->getContext();
2085 Type *Int32Ty = Type::getInt32Ty(Ctx);
2086 MDNode *SaturatedConversionNode =
2087 MDNode::get(Ctx, {ConstantAsMetadata::get(ConstantInt::get(
2088 Int32Ty, SPIRV::Decoration::SaturatedConversion))});
2089 createDecorationIntrinsic(I, SaturatedConversionNode, B);
2090}
2091
2096
2097Instruction *SPIRVEmitIntrinsicsImpl::visitCallInst(CallInst &Call) {
2098 if (!Call.isInlineAsm())
2099 return &Call;
2100
2101 LLVMContext &Ctx = CurrF->getContext();
2102 // TODO: this does not retain elementtype info for memory constraints, which
2103 // in turn means that we lower them into pointers to i8, rather than
2104 // pointers to elementtype; this can be fixed during reverse translation
2105 // but we should correct it here, possibly by tweaking the function
2106 // type to take TypedPointerType args.
2107 Constant *TyC = UndefValue::get(SPIRV::getOriginalFunctionType(Call));
2108 MDString *ConstraintString =
2109 MDString::get(Ctx, SPIRV::getOriginalAsmConstraints(Call));
2111 buildMD(TyC),
2112 MetadataAsValue::get(Ctx, MDNode::get(Ctx, ConstraintString))};
2113 for (unsigned OpIdx = 0; OpIdx < Call.arg_size(); OpIdx++)
2114 Args.push_back(Call.getArgOperand(OpIdx));
2115
2117 B.SetInsertPoint(&Call);
2118 B.CreateIntrinsic(Intrinsic::spv_inline_asm, {Args});
2119 return &Call;
2120}
2121
2122// Use a tip about rounding mode to create a decoration.
2123void SPIRVEmitIntrinsicsImpl::useRoundingMode(ConstrainedFPIntrinsic *FPI,
2124 IRBuilder<> &B) {
2125 std::optional<RoundingMode> RM = FPI->getRoundingMode();
2126 if (!RM.has_value())
2127 return;
2128 unsigned RoundingModeDeco = std::numeric_limits<unsigned>::max();
2129 switch (RM.value()) {
2130 default:
2131 // ignore unknown rounding modes
2132 break;
2133 case RoundingMode::NearestTiesToEven:
2134 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTE;
2135 break;
2136 case RoundingMode::TowardNegative:
2137 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTN;
2138 break;
2139 case RoundingMode::TowardPositive:
2140 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTP;
2141 break;
2142 case RoundingMode::TowardZero:
2143 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTZ;
2144 break;
2145 case RoundingMode::Dynamic:
2146 case RoundingMode::NearestTiesToAway:
2147 // TODO: check if supported
2148 break;
2149 }
2150 if (RoundingModeDeco == std::numeric_limits<unsigned>::max())
2151 return;
2152 // Convert the tip about rounding mode into a decoration record.
2153 createRoundingModeDecoration(FPI, RoundingModeDeco, B);
2154}
2155
2156Instruction *SPIRVEmitIntrinsicsImpl::visitSwitchInst(SwitchInst &I) {
2157 BasicBlock *ParentBB = I.getParent();
2158 Function *F = ParentBB->getParent();
2159 IRBuilder<> B(ParentBB);
2160 B.SetInsertPoint(&I);
2161 SmallVector<Value *, 4> Args;
2163 Args.push_back(I.getCondition());
2164 BBCases.push_back(I.getDefaultDest());
2165 Args.push_back(BlockAddress::get(F, I.getDefaultDest()));
2166 for (auto &Case : I.cases()) {
2167 Args.push_back(Case.getCaseValue());
2168 BBCases.push_back(Case.getCaseSuccessor());
2169 Args.push_back(BlockAddress::get(F, Case.getCaseSuccessor()));
2170 }
2171 CallInst *NewI = B.CreateIntrinsicWithoutFolding(
2172 Intrinsic::spv_switch, {I.getOperand(0)->getType()}, {Args});
2173 // remove switch to avoid its unneeded and undesirable unwrap into branches
2174 // and conditions
2175 replaceAllUsesWith(&I, NewI);
2176 I.eraseFromParent();
2177 // insert artificial and temporary instruction to preserve valid CFG,
2178 // it will be removed after IR translation pass
2179 B.SetInsertPoint(ParentBB);
2180 IndirectBrInst *BrI = B.CreateIndirectBr(
2181 Constant::getNullValue(PointerType::getUnqual(ParentBB->getContext())),
2182 BBCases.size());
2183 for (BasicBlock *BBCase : BBCases)
2184 BrI->addDestination(BBCase);
2185 return BrI;
2186}
2187
2189 return GEP->getNumIndices() > 0 && match(GEP->getOperand(1), m_Zero());
2190}
2191
2192Instruction *SPIRVEmitIntrinsicsImpl::visitIntrinsicInst(IntrinsicInst &I) {
2193 auto *SGEP = dyn_cast<StructuredGEPInst>(&I);
2194 if (!SGEP)
2195 return &I;
2196
2197 IRBuilder<> B(I.getParent());
2198 B.SetInsertPoint(&I);
2199 SmallVector<Type *, 2> Types = {I.getType(), I.getOperand(0)->getType()};
2200 SmallVector<Value *, 4> Args;
2201 Args.push_back(/* inBounds= */ B.getInt1(true));
2202 Args.push_back(I.getOperand(0));
2203 Args.push_back(/* zero index */ B.getInt32(0));
2204 for (unsigned J = 0; J < SGEP->getNumIndices(); ++J)
2205 Args.push_back(SGEP->getIndexOperand(J));
2206
2207 Instruction *NewI =
2208 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, Types, Args);
2209 replaceAllUsesWithAndErase(B, &I, NewI);
2210 return NewI;
2211}
2212
2214SPIRVEmitIntrinsicsImpl::visitGetElementPtrInst(GetElementPtrInst &I) {
2215 IRBuilder<> B(I.getParent());
2216 B.SetInsertPoint(&I);
2217
2218 // OpPtrAccessChain requires a scalar pointer result; scalarize per-lane
2219 // GEPs that return <N x ptr> and rebuild the vector via insertelement.
2220 if (auto *RetVTy = dyn_cast<FixedVectorType>(I.getType())) {
2221 unsigned N = RetVTy->getNumElements();
2222 Value *PtrOp = I.getPointerOperand();
2223 bool PtrIsVec = isa<VectorType>(PtrOp->getType());
2224 Type *ResultPtrTy = RetVTy->getElementType();
2225 Type *ScalarPtrTy = PtrOp->getType()->getScalarType();
2226 SmallVector<Type *, 2> GepTypes = {ResultPtrTy, ScalarPtrTy};
2227 Value *InBounds = B.getInt1(I.isInBounds());
2228 Type *LanePointeeTy = getGEPType(&I);
2229 if (!LanePointeeTy)
2230 return nullptr;
2231 Type *SrcElemTy = I.getSourceElementType();
2232
2233 // Pin the lane pointee type on the vector operand and on each extracted
2234 // lane so the prelegalizer wraps them as OpTypeVector/OpTypePointer of
2235 // the right element type instead of defaulting to i8.
2236 if (PtrIsVec)
2237 GR->buildAssignPtr(B, SrcElemTy, PtrOp);
2238
2239 Value *VecResult = PoisonValue::get(RetVTy);
2240 for (unsigned Lane = 0; Lane < N; ++Lane) {
2241 Value *LaneIdx = B.getInt32(Lane);
2242 Value *ScalarPtr = PtrOp;
2243 if (PtrIsVec) {
2244 SmallVector<Type *, 3> ExtractTypes = {ScalarPtrTy, PtrOp->getType(),
2245 LaneIdx->getType()};
2246 ScalarPtr = B.CreateIntrinsic(Intrinsic::spv_extractelt, {ExtractTypes},
2247 {PtrOp, LaneIdx});
2248 GR->buildAssignPtr(B, SrcElemTy, ScalarPtr);
2249 }
2250 SmallVector<Value *, 4> Args;
2251 Args.push_back(InBounds);
2252 Args.push_back(ScalarPtr);
2253 for (Value *Idx : I.indices()) {
2254 if (isa<VectorType>(Idx->getType())) {
2255 // We cannot use the builder here as for splat-ed / constant vectors
2256 // it will fold to the scalar, and then it becomes impossible to
2257 // retrieve / retain the vectorness.
2258 auto *EI =
2259 ExtractElementInst::Create(Idx, LaneIdx, "", B.GetInsertPoint());
2260 if (isVector1(Idx->getType())) // IRTranslator clobbers <1 x T>.
2261 Args.push_back(visitExtractElementInst(*EI));
2262 else
2263 Args.push_back(EI);
2264 } else {
2265 Args.push_back(Idx);
2266 }
2267 }
2268 Value *ScalarGep = B.CreateIntrinsic(Intrinsic::spv_gep, GepTypes, Args);
2269 GR->buildAssignPtr(B, LanePointeeTy, ScalarGep);
2270 VecResult = B.CreateInsertElement(VecResult, ScalarGep, LaneIdx);
2271 }
2272
2273 auto *NewI = cast<Instruction>(VecResult);
2274 replaceAllUsesWithAndErase(B, &I, NewI);
2275
2276 if (CallInst *Old = GR->findAssignPtrTypeInstr(NewI)) {
2277 Old->eraseFromParent();
2278 GR->addAssignPtrTypeInstr(NewI, nullptr);
2279 }
2281 GR->buildAssignPtr(B, LanePointeeTy, NewI);
2282
2283 return NewI;
2284 }
2285
2287 Type *IdxTy = CurrF->getDataLayout().getIndexType(I.getPointerOperandType());
2288 if (IsLogical && !isFirstIndexZero(&I)) {
2289 // Logical SPIR-V cannot use the OpPtrAccessChain instruction. If the first
2290 // index of the GEP is not 0, then we need to try to adjust it.
2291 //
2292 // If the GEP is doing byte addressing, try to rebuild the full access chain
2293 // from the type of the pointer.
2294 if (getByteAddressingMultiplier(I.getSourceElementType())) {
2295 return buildLogicalAccessChainFromGEP(I);
2296 }
2297
2298 // Look for the array-to-pointer decay. If this is the pattern
2299 // we can adjust the types, and prepend a 0 to the indices.
2300 Value *PtrOp = I.getPointerOperand();
2301 Type *SrcElemTy = I.getSourceElementType();
2302 Type *DeducedPointeeTy = deduceElementType(PtrOp, true);
2303
2304 if (auto *ArrTy = dyn_cast<ArrayType>(DeducedPointeeTy)) {
2305 if (ArrTy->getElementType() == SrcElemTy) {
2306 SmallVector<Value *> NewIndices;
2307 for (Value *Idx : I.indices())
2308 NewIndices.push_back(truncateGEPIndex(Idx, IdxTy, B));
2309 NewIndices.insert(NewIndices.begin(),
2310 ConstantInt::get(NewIndices.front()->getType(), 0));
2311
2312 SmallVector<Type *, 2> Types = {I.getType(), I.getPointerOperandType()};
2313 SmallVector<Value *, 4> Args;
2314 Args.push_back(B.getInt1(I.isInBounds()));
2315 Args.push_back(I.getPointerOperand());
2316 Args.append(NewIndices.begin(), NewIndices.end());
2317
2318 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep,
2319 {Types}, {Args});
2320 replaceAllUsesWithAndErase(B, &I, NewI);
2321 return NewI;
2322 }
2323 }
2324 }
2325
2326 SmallVector<Type *, 2> Types = {I.getType(), I.getOperand(0)->getType()};
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);
2332 Instruction *NewI =
2333 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, {Types}, {Args});
2334 replaceAllUsesWithAndErase(B, &I, NewI);
2335 return NewI;
2336}
2337
2338Instruction *SPIRVEmitIntrinsicsImpl::visitBitCastInst(BitCastInst &I) {
2339 IRBuilder<> B(I.getParent());
2340 B.SetInsertPoint(&I);
2341 Value *Source = I.getOperand(0);
2342
2343 // SPIR-V, contrary to LLVM 17+ IR, supports bitcasts between pointers of
2344 // varying element types. In case of IR coming from older versions of LLVM
2345 // such bitcasts do not provide sufficient information, should be just skipped
2346 // here, and handled in insertPtrCastOrAssignTypeInstr.
2347 if (isPointerTy(I.getType())) {
2348 replaceAllUsesWith(&I, Source);
2349 I.eraseFromParent();
2350 return nullptr;
2351 }
2352
2353 SmallVector<Type *, 2> Types = {I.getType(), Source->getType()};
2354 SmallVector<Value *> Args(I.op_begin(), I.op_end());
2355 Instruction *NewI =
2356 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_bitcast, {Types}, {Args});
2357 replaceAllUsesWithAndErase(B, &I, NewI);
2358 return NewI;
2359}
2360
2361void SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeTargetExt(
2362 TargetExtType *AssignedType, Value *V, IRBuilder<> &B) {
2363 Type *VTy = V->getType();
2364
2365 // A couple of sanity checks.
2366 assert((isPointerTy(VTy)) && "Expect a pointer type!");
2367 if (Type *ElemTy = getPointeeType(VTy))
2368 if (ElemTy != AssignedType)
2369 report_fatal_error("Unexpected pointer element type!");
2370
2371 CallInst *AssignCI = GR->findAssignPtrTypeInstr(V);
2372 if (!AssignCI) {
2373 GR->buildAssignType(B, AssignedType, V, CanUseAnyVectorRank);
2374 return;
2375 }
2376
2377 Type *CurrentType =
2379 cast<MetadataAsValue>(AssignCI->getOperand(1))->getMetadata())
2380 ->getType();
2381 if (CurrentType == AssignedType)
2382 return;
2383
2384 // Builtin types cannot be redeclared or casted.
2385 if (CurrentType->isTargetExtTy())
2386 report_fatal_error("Type mismatch " + CurrentType->getTargetExtName() +
2387 "/" + AssignedType->getTargetExtName() +
2388 " for value " + V->getName(),
2389 false);
2390
2391 // Our previous guess about the type seems to be wrong, let's update
2392 // inferred type according to a new, more precise type information.
2393 GR->updateAssignType(
2394 AssignCI, V, getNormalizedPoisonValue(AssignedType, CanUseAnyVectorRank));
2395}
2396
2397void SPIRVEmitIntrinsicsImpl::replacePointerOperandWithPtrCast(
2398 Instruction *I, Value *Pointer, Type *ExpectedElementType,
2399 unsigned OperandToReplace, IRBuilder<> &B) {
2400 TypeValidated.insert(I);
2401
2402 // Do not emit spv_ptrcast if Pointer's element type is ExpectedElementType
2403 Type *PointerElemTy = deduceElementTypeHelper(Pointer, false);
2404 if (PointerElemTy == ExpectedElementType ||
2405 isEquivalentTypes(PointerElemTy, ExpectedElementType))
2406 return;
2407
2409 Value *ExpectedElementVal =
2410 getNormalizedPoisonValue(ExpectedElementType, CanUseAnyVectorRank);
2411 MetadataAsValue *VMD = buildMD(ExpectedElementVal);
2412 unsigned AddressSpace = getPointerAddressSpace(Pointer->getType());
2413 bool FirstPtrCastOrAssignPtrType = true;
2414
2415 // Do not emit new spv_ptrcast if equivalent one already exists or when
2416 // spv_assign_ptr_type already targets this pointer with the same element
2417 // type.
2418 if (Pointer->hasUseList()) {
2419 for (auto User : Pointer->users()) {
2420 auto *II = dyn_cast<IntrinsicInst>(User);
2421 if (!II ||
2422 (II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type &&
2423 II->getIntrinsicID() != Intrinsic::spv_ptrcast) ||
2424 II->getOperand(0) != Pointer)
2425 continue;
2426
2427 // There is some spv_ptrcast/spv_assign_ptr_type already targeting this
2428 // pointer.
2429 FirstPtrCastOrAssignPtrType = false;
2430 if (II->getOperand(1) != VMD ||
2431 dyn_cast<ConstantInt>(II->getOperand(2))->getSExtValue() !=
2433 continue;
2434
2435 // The spv_ptrcast/spv_assign_ptr_type targeting this pointer is of the
2436 // same element type and address space.
2437 if (II->getIntrinsicID() != Intrinsic::spv_ptrcast)
2438 return;
2439
2440 // This must be a spv_ptrcast, do not emit new if this one has the same BB
2441 // as I. Otherwise, search for other spv_ptrcast/spv_assign_ptr_type.
2442 if (II->getParent() != I->getParent())
2443 continue;
2444
2445 I->setOperand(OperandToReplace, II);
2446 return;
2447 }
2448 }
2449
2450 // Never replace an already-deduced pointer element type with a non-pointer
2451 // one. The conflicting use comes from a mis-deduced expected type. Leave the
2452 // operand untouched rather than emitting a ptrcast that re-introduces the
2453 // collapsed type at the use site.
2454 if (PointerElemTy && isPointerTyOrWrapper(PointerElemTy) &&
2455 !isPointerTyOrWrapper(ExpectedElementType) &&
2456 tracesToPointerAlloca(Pointer))
2457 return;
2458
2459 if (isa<Instruction>(Pointer) || isa<Argument>(Pointer)) {
2460 if (FirstPtrCastOrAssignPtrType) {
2461 // If this would be the first spv_ptrcast, do not emit spv_ptrcast and
2462 // emit spv_assign_ptr_type instead.
2463 GR->buildAssignPtr(B, ExpectedElementType, Pointer);
2464 return;
2465 } else if (isTodoType(Pointer)) {
2466 eraseTodoType(Pointer);
2467 if (!isa<CallInst>(Pointer) && !isaGEP(Pointer) &&
2468 !isa<AllocaInst>(Pointer)) {
2469 // If this wouldn't be the first spv_ptrcast but existing type info is
2470 // uncomplete, update spv_assign_ptr_type arguments.
2471 if (CallInst *AssignCI = GR->findAssignPtrTypeInstr(Pointer)) {
2472 Type *PrevElemTy = GR->findDeducedElementType(Pointer);
2473 assert(PrevElemTy);
2474 DenseSet<std::pair<Value *, Value *>> VisitedSubst{
2475 std::make_pair(I, Pointer)};
2476 GR->updateAssignType(AssignCI, Pointer, ExpectedElementVal);
2477 propagateElemType(Pointer, PrevElemTy, VisitedSubst);
2478 } else {
2479 GR->buildAssignPtr(B, ExpectedElementType, Pointer);
2480 }
2481 return;
2482 }
2483 }
2484 }
2485
2486 // Emit spv_ptrcast
2487 SmallVector<Type *, 2> Types = {Pointer->getType(), Pointer->getType()};
2488 SmallVector<Value *, 2> Args = {Pointer, VMD, B.getInt32(AddressSpace)};
2489 auto *PtrCastI =
2490 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_ptrcast, {Types}, Args);
2491 I->setOperand(OperandToReplace, PtrCastI);
2492 // We need to set up a pointee type for the newly created spv_ptrcast.
2493 GR->buildAssignPtr(B, ExpectedElementType, PtrCastI);
2494}
2495
2496void SPIRVEmitIntrinsicsImpl::insertPtrCastOrAssignTypeInstr(Instruction *I,
2497 IRBuilder<> &B) {
2498 // Handle basic instructions:
2499 StoreInst *SI = dyn_cast<StoreInst>(I);
2500 if (IsKernelArgInt8(CurrF, SI)) {
2501 replacePointerOperandWithPtrCast(
2502 I, SI->getValueOperand(), IntegerType::getInt8Ty(CurrF->getContext()),
2503 0, B);
2504 }
2505 if (SI) {
2506 Value *Op = SI->getValueOperand();
2507 Value *Pointer = SI->getPointerOperand();
2508 Type *OpTy = Op->getType();
2509 if (auto *OpI = dyn_cast<Instruction>(Op)) {
2510 OpTy = restoreMutatedType(GR, OpI, OpTy);
2511 if (auto It = AggrConstTypes.find(OpI); It != AggrConstTypes.end())
2512 OpTy = It->second;
2513 }
2514 if (OpTy == Op->getType())
2515 OpTy = deduceElementTypeByValueDeep(OpTy, Op, false);
2516 replacePointerOperandWithPtrCast(I, Pointer, OpTy, 1, B);
2517 return;
2518 }
2519 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2520 Value *Pointer = LI->getPointerOperand();
2521 Type *OpTy = LI->getType();
2522 // If the loaded from pointer carries byref/byval, the dominant type is the
2523 // pointee type specified therein, and we should retain it.
2524 if (Argument *Arg;
2525 (Arg = dyn_cast<Argument>(Pointer)) && hasPointeeTypeAttr(Arg))
2526 OpTy = getPointeeTypeByAttr(Arg);
2527
2528 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
2529 if (Type *ElemTy = GR->findDeducedElementType(LI)) {
2530 OpTy = getTypedPointerWrapper(ElemTy, PtrTy->getAddressSpace());
2531 } else {
2532 Type *NewOpTy = OpTy;
2533 OpTy = deduceElementTypeByValueDeep(OpTy, LI, false);
2534 if (OpTy == NewOpTy)
2535 insertTodoType(Pointer);
2536 }
2537 }
2538 replacePointerOperandWithPtrCast(I, Pointer, OpTy, 0, B);
2539 return;
2540 }
2541 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2542 Value *Pointer = GEPI->getPointerOperand();
2543 Type *OpTy = nullptr;
2544
2545 // Logical SPIR-V is not allowed to use Op*PtrAccessChain instructions. If
2546 // the first index is 0, then we can trivially lower to OpAccessChain. If
2547 // not we need to try to rewrite the GEP. We avoid adding a pointer cast at
2548 // this time, and will rewrite the GEP when visiting it.
2549 if (TM.getSubtargetImpl()->isLogicalSPIRV() && !isFirstIndexZero(GEPI)) {
2550 return;
2551 }
2552
2553 // In all cases, fall back to the GEP type if type scavenging failed.
2554 if (!OpTy)
2555 OpTy = GEPI->getSourceElementType();
2556
2557 replacePointerOperandWithPtrCast(I, Pointer, OpTy, 0, B);
2558 if (isNestedPointer(OpTy))
2559 insertTodoType(Pointer);
2560 return;
2561 }
2562
2563 // An inserted pointer must have the type of its aggregate member.
2564 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
2565 Value *Op = IVI->getInsertedValueOperand();
2566 if (isPointerTy(Op->getType()))
2567 replacePointerOperandWithPtrCast(
2568 I, Op, getMemberPointeeType(IVI->getType(), IVI->getIndices()),
2570 return;
2571 }
2572 // So must a pointer inserted into a vector, whose elements are untyped
2573 // pointers and so pointers to i8.
2574 if (auto *IEI = dyn_cast<InsertElementInst>(I)) {
2575 Value *Op = IEI->getOperand(1);
2576 if (isPointerTy(Op->getType()))
2577 replacePointerOperandWithPtrCast(
2578 I, Op, IntegerType::getInt8Ty(I->getContext()), 1, B);
2579 return;
2580 }
2581
2582 // TODO: review and merge with existing logics:
2583 // Handle calls to builtins (non-intrinsics):
2584 CallInst *CI = dyn_cast<CallInst>(I);
2585 if (!CI || CI->isIndirectCall() || CI->isInlineAsm() ||
2587 return;
2588
2589 // collect information about formal parameter types
2590 std::string DemangledName =
2592 Function *CalledF = CI->getCalledFunction();
2593 SmallVector<Type *, 4> CalledArgTys;
2594 bool HaveTypes = false;
2595 for (unsigned OpIdx = 0; OpIdx < CalledF->arg_size(); ++OpIdx) {
2596 Argument *CalledArg = CalledF->getArg(OpIdx);
2597 Type *ArgType = CalledArg->getType();
2598 if (!isPointerTy(ArgType)) {
2599 CalledArgTys.push_back(nullptr);
2600 } else if (Type *ArgTypeElem = getPointeeType(ArgType)) {
2601 CalledArgTys.push_back(ArgTypeElem);
2602 HaveTypes = true;
2603 } else {
2604 Type *ElemTy = GR->findDeducedElementType(CalledArg);
2605 if (!ElemTy && hasPointeeTypeAttr(CalledArg))
2606 ElemTy = getPointeeTypeByAttr(CalledArg);
2607 if (!ElemTy) {
2608 ElemTy = getPointeeTypeByCallInst(DemangledName, CalledF, OpIdx);
2609 if (ElemTy) {
2610 GR->addDeducedElementType(CalledArg,
2611 normalizeType(ElemTy, CanUseAnyVectorRank));
2612 } else {
2613 for (User *U : CalledArg->users()) {
2614 if (Instruction *Inst = dyn_cast<Instruction>(U)) {
2615 if ((ElemTy = deduceElementTypeHelper(Inst, false)) != nullptr)
2616 break;
2617 }
2618 }
2619 }
2620 }
2621 HaveTypes |= ElemTy != nullptr;
2622 CalledArgTys.push_back(ElemTy);
2623 }
2624 }
2625
2626 if (DemangledName.empty() && !HaveTypes)
2627 return;
2628
2629 auto Set =
2630 TM.getSubtarget<SPIRVSubtarget>(*CalledF).getPreferredInstructionSet();
2631 // Do not reparse rejected declaration types with the builtin parser.
2632 bool ParseBuiltinTypes =
2633 !DemangledName.empty() &&
2634 (!CalledF->isDeclaration() || SPIRV::isBuiltin(DemangledName, Set));
2635 for (unsigned OpIdx = 0; OpIdx < CI->arg_size(); OpIdx++) {
2636 Value *ArgOperand = CI->getArgOperand(OpIdx);
2637 if (!isPointerTy(ArgOperand->getType()))
2638 continue;
2639
2640 // Constants (nulls/undefs) are handled in insertAssignPtrTypeIntrs()
2641 if (!isa<Instruction>(ArgOperand) && !isa<Argument>(ArgOperand)) {
2642 // However, we may have assumptions about the formal argument's type and
2643 // may have a need to insert a ptr cast for the actual parameter of this
2644 // call.
2645 if (OpIdx >= CalledF->arg_size())
2646 continue;
2647 Argument *CalledArg = CalledF->getArg(OpIdx);
2648 if (!GR->findDeducedElementType(CalledArg))
2649 continue;
2650 }
2651
2652 Type *ExpectedType =
2653 OpIdx < CalledArgTys.size() ? CalledArgTys[OpIdx] : nullptr;
2654 if (!ExpectedType && ParseBuiltinTypes)
2655 ExpectedType = SPIRV::parseBuiltinCallArgumentBaseType(
2656 DemangledName, OpIdx, I->getContext());
2657 if (!ExpectedType || ExpectedType->isVoidTy())
2658 continue;
2659
2660 if (ExpectedType->isTargetExtTy() &&
2662 insertAssignPtrTypeTargetExt(cast<TargetExtType>(ExpectedType),
2663 ArgOperand, B);
2664 else
2665 replacePointerOperandWithPtrCast(CI, ArgOperand, ExpectedType, OpIdx, B);
2666 }
2667}
2668
2670SPIRVEmitIntrinsicsImpl::visitInsertElementInst(InsertElementInst &I) {
2671 // If it's a <1 x Type> vector type, don't modify it. It's not a legal vector
2672 // type in LLT and IRTranslator will replace it by the scalar.
2673 if (isVector1(I.getType()) && !CanUseAnyVectorRank)
2674 return &I;
2675
2676 SmallVector<Type *, 4> Types = {I.getType(), I.getOperand(0)->getType(),
2677 I.getOperand(1)->getType(),
2678 I.getOperand(2)->getType()};
2679 IRBuilder<> B(I.getParent());
2680 B.SetInsertPoint(&I);
2681 SmallVector<Value *> Args(I.op_begin(), I.op_end());
2682 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertelt,
2683 {Types}, {Args});
2684 replaceAllUsesWithAndErase(B, &I, NewI);
2685 return NewI;
2686}
2687
2689SPIRVEmitIntrinsicsImpl::visitExtractElementInst(ExtractElementInst &I) {
2690 // If it's a <1 x Type> vector type, don't modify it. It's not a legal vector
2691 // type in LLT and IRTranslator will replace it by the scalar.
2692 if (isVector1(I.getVectorOperandType()) && !CanUseAnyVectorRank)
2693 return &I;
2694
2695 IRBuilder<> B(I.getParent());
2696 B.SetInsertPoint(&I);
2697 SmallVector<Type *, 3> Types = {I.getType(), I.getVectorOperandType(),
2698 I.getIndexOperand()->getType()};
2699 SmallVector<Value *, 2> Args = {I.getVectorOperand(), I.getIndexOperand()};
2700 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractelt,
2701 {Types}, {Args});
2702 replaceAllUsesWithAndErase(B, &I, NewI);
2703 return NewI;
2704}
2705
2706// Scalarize ptrtoint and inttoptr instructions operating on vectors of
2707// pointers, since SPIR-V does not support vectors of pointers without
2708// extensions. Run before preprocessCompositeConstants so that
2709// findScalarElement still sees constant vectors.
2710void SPIRVEmitIntrinsicsImpl::scalarizeVectorPtrCasts(Function &F) {
2711 // If the extension for vector-of-pointers is available, no scalarization
2712 // is needed - the backend can handle them natively.
2713 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(F);
2714 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_masked_gather_scatter))
2715 return;
2716
2717 SmallVector<Instruction *, 8> ToErase;
2718
2719 for (Instruction &I : make_early_inc_range(instructions(F))) {
2720 if (auto *PTI = dyn_cast<PtrToIntInst>(&I)) {
2721 auto *VecTy = dyn_cast<FixedVectorType>(PTI->getOperand(0)->getType());
2722 if (!VecTy || !VecTy->getElementType()->isPointerTy())
2723 continue;
2724
2725 IRBuilder<> B(PTI);
2726 unsigned NumElems = VecTy->getNumElements();
2727 Type *ElemIntTy = cast<VectorType>(PTI->getType())->getElementType();
2728 Value *Result = PoisonValue::get(PTI->getType());
2729
2730 for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
2731 Value *ElemPtr = findScalarElement(PTI->getOperand(0), Idx);
2732 if (!ElemPtr)
2733 ElemPtr = B.CreateExtractElement(PTI->getOperand(0), B.getInt32(Idx));
2734 Value *Conv = B.CreatePtrToInt(ElemPtr, ElemIntTy);
2735 Result = B.CreateInsertElement(Result, Conv, B.getInt32(Idx));
2736 }
2737
2738 PTI->replaceAllUsesWith(Result);
2739 ToErase.push_back(PTI);
2740 } else if (auto *ITP = dyn_cast<IntToPtrInst>(&I)) {
2741 auto *VecTy = dyn_cast<FixedVectorType>(ITP->getType());
2742 if (!VecTy || !VecTy->getElementType()->isPointerTy())
2743 continue;
2744
2745 // Only scalarize if all users are extractelement with constant index.
2746 // Other uses (e.g. masked.gather) need the vector-of-pointers and
2747 // should be handled by extension-specific lowering.
2748 bool AllUsersExtract = llvm::all_of(ITP->users(), [&](User *U) {
2749 auto *EE = dyn_cast<ExtractElementInst>(U);
2750 return EE && isa<ConstantInt>(EE->getIndexOperand());
2751 });
2752 if (!AllUsersExtract)
2753 continue;
2754
2755 IRBuilder<> B(ITP);
2756 Type *ElemPtrTy = VecTy->getElementType();
2757
2758 // Replace extractelement users with scalar inttoptr.
2759 for (User *U : make_early_inc_range(ITP->users())) {
2760 auto *EE = cast<ExtractElementInst>(U);
2761 unsigned Idx = cast<ConstantInt>(EE->getIndexOperand())->getZExtValue();
2762 B.SetInsertPoint(EE);
2763 Value *Elem =
2764 B.CreateExtractElement(ITP->getOperand(0), B.getInt32(Idx));
2765 Value *Conv = B.CreateIntToPtr(Elem, ElemPtrTy);
2766 EE->replaceAllUsesWith(Conv);
2767 ToErase.push_back(EE);
2768 }
2769
2770 ToErase.push_back(ITP);
2771 }
2772 }
2773
2774 if (ToErase.empty())
2775 return;
2777 for (Instruction *I : ToErase) {
2778 for (Value *Op : I->operand_values())
2779 MaybeDead.push_back(Op);
2780 I->eraseFromParent();
2781 }
2783}
2784
2785Instruction *SPIRVEmitIntrinsicsImpl::visitInsertValueInst(InsertValueInst &I) {
2786 IRBuilder<> B(I.getParent());
2787 B.SetInsertPoint(&I);
2788 SmallVector<Type *, 1> Types = {I.getInsertedValueOperand()->getType()};
2790 Value *AggregateOp = I.getAggregateOperand();
2791 if (isa<UndefValue>(AggregateOp))
2792 Args.push_back(UndefValue::get(B.getInt32Ty()));
2793 else
2794 Args.push_back(AggregateOp);
2795 Args.push_back(I.getInsertedValueOperand());
2796 for (auto &Op : I.indices())
2797 Args.push_back(B.getInt32(Op));
2798 Instruction *NewI =
2799 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertv, {Types}, {Args});
2800 replaceMemInstrUses(&I, NewI, B);
2801 return NewI;
2802}
2803
2805SPIRVEmitIntrinsicsImpl::visitExtractValueInst(ExtractValueInst &I) {
2806 IRBuilder<> B(I.getParent());
2807 B.SetInsertPoint(&I);
2808 if (I.getAggregateOperand()->getType()->isAggregateType()) {
2809 // Mutate an aggregate-returning spv_extractv producer to i32 so
2810 // IRTranslator does not see a multi-register value.
2811 CallBase *CB = dyn_cast<CallBase>(I.getAggregateOperand());
2812 if (!CB || CB->getIntrinsicID() != Intrinsic::spv_extractv)
2813 return &I;
2814 CB->mutateType(B.getInt32Ty());
2815 }
2816 SmallVector<Value *> Args(I.operands());
2817 for (auto &Op : I.indices())
2818 Args.push_back(B.getInt32(Op));
2819 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractv,
2820 {I.getType()}, {Args});
2821 // An aggregate extract is a SPIR-V value-id like an aggregate PHI, select or
2822 // freeze: keep the real aggregate type in metadata, but expose the value
2823 // itself as i32 so the intrinsic signature and its users stay valid.
2824 if (NewI->getType()->isAggregateType()) {
2825 Type *AggrTy = I.getType();
2826 AggrConstTypes[NewI] = AggrTy;
2827 NewI->mutateType(B.getInt32Ty());
2828 replaceMemInstrUses(&I, NewI, B);
2829 // The aggregate extractvalue only carried a name record; unlike a PHI, a
2830 // select or freeze does not pass its type down to an untyped operand.
2832 GR->buildAssignType(B, AggrTy, NewI, CanUseAnyVectorRank);
2833 return NewI;
2834 }
2835 replaceAllUsesWithAndErase(B, &I, NewI);
2836 return NewI;
2837}
2838
2839Instruction *SPIRVEmitIntrinsicsImpl::visitLoadInst(LoadInst &I) {
2840 if (!I.getType()->isAggregateType())
2841 return &I;
2842 IRBuilder<> B(I.getParent());
2843 B.SetInsertPoint(&I);
2844 TrackConstants = false;
2845 const auto *TLI = TM.getSubtargetImpl()->getTargetLowering();
2848
2849 unsigned IntrinsicId;
2850 SmallVector<Value *, 4> Args = {I.getPointerOperand(), B.getInt16(Flags)};
2851 if (!I.isAtomic()) {
2852 IntrinsicId = Intrinsic::spv_load;
2853 Args.push_back(B.getInt32(getMemoryAccessAlignment(I.getAlign())));
2854 } else {
2855 IntrinsicId = Intrinsic::spv_atomic_load;
2856 Args.push_back(B.getInt8(static_cast<uint8_t>(I.getOrdering())));
2857 }
2858 CallInst *NewI = B.CreateIntrinsicWithoutFolding(
2859 IntrinsicId, {I.getOperand(0)->getType()}, Args);
2860
2861 replaceMemInstrUses(&I, NewI, B);
2862 return NewI;
2863}
2864
2865Instruction *SPIRVEmitIntrinsicsImpl::visitStoreInst(StoreInst &I) {
2866 if (!AggrStores.contains(&I))
2867 return &I;
2868 IRBuilder<> B(I.getParent());
2869 B.SetInsertPoint(&I);
2870 TrackConstants = false;
2871 const auto *TLI = TM.getSubtargetImpl()->getTargetLowering();
2874 auto *PtrOp = I.getPointerOperand();
2875
2876 if (I.getValueOperand()->getType()->isAggregateType()) {
2877 // It is possible that what used to be an ExtractValueInst has been replaced
2878 // with a call to the spv_extractv intrinsic, and that said call hasn't
2879 // had its return type replaced with i32 during the dedicated pass (because
2880 // it was emitted later); we have to handle this here, because IRTranslator
2881 // cannot deal with multi-register types at the moment.
2882 CallBase *CB = dyn_cast<CallBase>(I.getValueOperand());
2883 assert(CB && CB->getIntrinsicID() == Intrinsic::spv_extractv &&
2884 "Unexpected argument of aggregate type, should be spv_extractv!");
2885 CB->mutateType(B.getInt32Ty());
2886 }
2887
2888 unsigned IntrinsicId;
2889 SmallVector<Value *, 4> Args = {I.getValueOperand(), PtrOp,
2890 B.getInt16(Flags)};
2891 if (!I.isAtomic()) {
2892 IntrinsicId = Intrinsic::spv_store;
2893 Args.push_back(B.getInt32(getMemoryAccessAlignment(I.getAlign())));
2894 } else {
2895 IntrinsicId = Intrinsic::spv_atomic_store;
2896 Args.push_back(B.getInt8(static_cast<uint8_t>(I.getOrdering())));
2897 }
2898 Instruction *NewI = B.CreateIntrinsicWithoutFolding(
2899 IntrinsicId, {I.getValueOperand()->getType(), PtrOp->getType()}, Args);
2900 NewI->copyMetadata(I);
2901 I.eraseFromParent();
2902 return NewI;
2903}
2904
2905Instruction *SPIRVEmitIntrinsicsImpl::visitAllocaInst(AllocaInst &I) {
2906 Value *ArraySize = nullptr;
2907 if (I.isArrayAllocation()) {
2908 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*I.getFunction());
2909 if (!STI->canUseExtension(
2910 SPIRV::Extension::SPV_INTEL_variable_length_array))
2912 "array allocation: this instruction requires the following "
2913 "SPIR-V extension: SPV_INTEL_variable_length_array",
2914 false);
2915 ArraySize = I.getArraySize();
2916 }
2917 IRBuilder<> B(I.getParent());
2918 B.SetInsertPoint(&I);
2919 TrackConstants = false;
2920 Type *PtrTy = I.getType();
2921 Instruction *NewI =
2922 ArraySize
2923 ? B.CreateIntrinsicWithoutFolding(
2924 Intrinsic::spv_alloca_array, {PtrTy, ArraySize->getType()},
2925 {ArraySize, B.getInt32(I.getAlign().value())})
2926 : B.CreateIntrinsicWithoutFolding(Intrinsic::spv_alloca, {PtrTy},
2927 {B.getInt32(I.getAlign().value())});
2928 replaceAllUsesWithAndErase(B, &I, NewI);
2929 return NewI;
2930}
2931
2933SPIRVEmitIntrinsicsImpl::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
2934 assert(I.getType()->isAggregateType() && "Aggregate result is expected");
2935 IRBuilder<> B(I.getParent());
2936 B.SetInsertPoint(&I);
2937 SmallVector<Value *> Args(I.operands());
2938 const Triple &TT = TM.getTargetTriple();
2939 Args.push_back(B.getInt32(static_cast<uint32_t>(
2940 getMemScope(TT, I.getContext(), I.getSyncScopeID()))));
2941 // Per SPIR-V spec atomic ops must combine the ordering bits with the
2942 // storage-class bit.
2943 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
2944 unsigned AS = I.getPointerOperand()->getType()->getPointerAddressSpace();
2945 uint32_t ScSem = static_cast<uint32_t>(
2947 Args.push_back(B.getInt32(getMemSemanticsWithStorageClass(
2948 TT, static_cast<uint32_t>(getMemSemantics(I.getSuccessOrdering())),
2949 ScSem)));
2950 Args.push_back(B.getInt32(getMemSemanticsWithStorageClass(
2951 TT, static_cast<uint32_t>(getMemSemantics(I.getFailureOrdering())),
2952 ScSem)));
2953 Instruction *NewI = B.CreateIntrinsicWithoutFolding(
2954 Intrinsic::spv_cmpxchg, {I.getPointerOperand()->getType()}, {Args});
2955 replaceMemInstrUses(&I, NewI, B);
2956 return NewI;
2957}
2958
2959Instruction *SPIRVEmitIntrinsicsImpl::visitAtomicRMWInst(AtomicRMWInst &I) {
2960 auto Op = I.getOperation();
2962 return &I;
2963
2964 // No SPIR-V opcode exists for these, so lowering to an imported helper is an
2965 // AMD extension. Other targets keep the generic expansion.
2967 return &I;
2968
2969 Module *M = I.getModule();
2970 IRBuilder<> B(I.getParent());
2971 B.SetInsertPoint(&I);
2972
2973 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
2974 unsigned AS = I.getPointerOperand()->getType()->getPointerAddressSpace();
2975
2976 uint32_t Scope = static_cast<uint32_t>(
2977 getMemScope(M->getTargetTriple(), I.getContext(), I.getSyncScopeID()));
2978 uint32_t ScSem = static_cast<uint32_t>(
2980 uint32_t MemSem = getMemSemanticsWithStorageClass(
2981 M->getTargetTriple(),
2982 static_cast<uint32_t>(getMemSemantics(I.getOrdering())), ScSem);
2983
2984 SmallString<64> FuncName(Op == AtomicRMWInst::UIncWrap
2985 ? "__translate_spirv_atomic_uinc_wrap"
2986 : "__translate_spirv_atomic_udec_wrap");
2987
2988 Type *ValTy = I.getValOperand()->getType();
2989 Type *PtrTy = I.getPointerOperand()->getType();
2990 // Encode the address space and value type in the name for overload.
2991 raw_svector_ostream OS(FuncName);
2992 OS << "_p" << AS << "_";
2993 if (auto *VecTy = dyn_cast<FixedVectorType>(ValTy))
2994 OS << "v" << VecTy->getNumElements();
2995 OS << "i" << ValTy->getScalarSizeInBits();
2996
2997 Type *Int32Ty = B.getInt32Ty();
2998 Type *BoolTy = B.getInt1Ty();
2999 SmallVector<Type *, 6> ArgTys = {PtrTy, Int32Ty, Int32Ty,
3000 ValTy, BoolTy, BoolTy};
3001 FunctionType *FT = FunctionType::get(ValTy, ArgTys, false);
3002 FunctionCallee FC = M->getOrInsertFunction(FuncName, FT);
3003 cast<Function>(FC.getCallee())->setCallingConv(CallingConv::SPIR_FUNC);
3004
3006 I.getPointerOperand(), B.getInt32(Scope),
3007 B.getInt32(MemSem), I.getValOperand(),
3008 B.getInt1(I.isVolatile()), B.getInt1(I.isElementwise())};
3009 CallInst *CI = B.CreateCall(FC, Args);
3010 CI->setCallingConv(CallingConv::SPIR_FUNC);
3011 // SPIRVCallLowering reads alias.scope/noalias off the call to build the
3012 // aliasing decorations and runs after this pass, so preserve the metadata.
3013 CI->copyMetadata(I);
3014
3015 replaceAllUsesWithAndErase(B, &I, CI);
3016 return CI;
3017}
3018
3019static bool isAbortCall(const Instruction &I, const SPIRVSubtarget &ST) {
3020 auto *CI = dyn_cast<CallInst>(&I);
3021 if (!CI)
3022 return false;
3023 switch (CI->getIntrinsicID()) {
3024 case Intrinsic::spv_abort:
3025 return true;
3026 case Intrinsic::trap:
3027 case Intrinsic::ubsantrap:
3028 // When the extension is enabled, selection lowers these to OpAbortKHR.
3029 return ST.canUseExtension(SPIRV::Extension::SPV_KHR_abort);
3030 default:
3031 return false;
3032 }
3033}
3034
3035// The OpAbortKHR instruction itself is a block terminator, so we don't need to
3036// emit an extra OpUnreachable instruction.
3038 const SPIRVSubtarget &ST) {
3039 const Instruction *Prev = I.getPrevNode();
3040 if (Prev && isAbortCall(*Prev, ST))
3041 return true;
3042
3044 *I.getParent(),
3045 [&ST](const Instruction &II) { return isAbortCall(II, ST); }) &&
3046 "abort-like call must be the last non-debug instruction before its "
3047 "block's terminator");
3048 return false;
3049}
3050
3051Instruction *SPIRVEmitIntrinsicsImpl::visitUnreachableInst(UnreachableInst &I) {
3052 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
3053 if (precededByAbortIntrinsic(I, ST))
3054 return &I;
3055 IRBuilder<> B(&I);
3056 B.CreateIntrinsic(Intrinsic::spv_unreachable, {});
3057 return &I;
3058}
3059
3060// llvm.compiler.used and llvm.used hold use-list entries that protect their
3061// referenced globals from DCE without participating in code generation.
3062static bool isUseListGlobal(StringRef Name) {
3063 return Name == "llvm.compiler.used" || Name == "llvm.used";
3064}
3065
3066// Returns true for module-level globals that should not have SPIR-V intrinsics
3067// emitted (use-list globals plus llvm.global.annotations).
3069 return isUseListGlobal(Name) || Name == "llvm.global.annotations";
3070}
3071
3072// Returns true if every use of GV traces back to llvm.compiler.used or
3073// llvm.used.
3077 while (!Stack.empty()) {
3078 const Value *V = Stack.pop_back_val();
3079 if (!Visited.insert(V).second)
3080 continue;
3081 if (const auto *GVUser = dyn_cast<GlobalVariable>(V)) {
3082 if (!isUseListGlobal(GVUser->getName()))
3083 return false;
3084 continue;
3085 }
3086 if (const auto *C = dyn_cast<Constant>(V)) {
3087 Stack.append(C->user_begin(), C->user_end());
3088 continue;
3089 }
3090 return false;
3091 }
3092 return true;
3093}
3094
3095static bool
3096shouldEmitIntrinsicsForGlobalValue(const GlobalVariableUsers &GVUsers,
3097 const GlobalVariable &GV,
3098 const Function *F) {
3099 // Skip special artificial variables.
3100 if (isArtificialGlobal(GV.getName()))
3101 return false;
3102
3103 auto &UserFunctions = GVUsers.getTransitiveUserFunctions(GV);
3104 if (UserFunctions.contains(F))
3105 return true;
3106
3107 // Do not emit the intrinsics in this function, it's going to be emitted on
3108 // the functions that reference it.
3109 if (!UserFunctions.empty())
3110 return false;
3111
3112 // Emit definitions for globals that are not referenced by any function on the
3113 // first function definition.
3114 const Module &M = *F->getParent();
3115 const Function &FirstDefinition = *M.getFunctionDefs().begin();
3116 return F == &FirstDefinition;
3117}
3118
3119Value *SPIRVEmitIntrinsicsImpl::buildSpvUndefComposite(Type *AggrTy,
3120 IRBuilder<> &B) {
3121 auto MakeLeaf = [&](Type *ElemTy) -> Instruction * {
3122 CallInst *Leaf = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_undef, {});
3123 AggrConsts[Leaf] = PoisonValue::get(ElemTy);
3124 AggrConstTypes[Leaf] = ElemTy;
3125 return Leaf;
3126 };
3127 SmallVector<Value *, 4> Elems;
3128 if (auto *ArrTy = dyn_cast<ArrayType>(AggrTy)) {
3129 Elems.assign(ArrTy->getNumElements(), MakeLeaf(ArrTy->getElementType()));
3130 } else {
3131 auto *StructTy = cast<StructType>(AggrTy);
3132 DenseMap<Type *, Instruction *> LeafByType;
3133 for (unsigned I = 0; I < StructTy->getNumElements(); ++I) {
3134 Type *ElemTy = StructTy->getContainedType(I);
3135 auto &Entry = LeafByType[ElemTy];
3136 if (!Entry)
3137 Entry = MakeLeaf(ElemTy);
3138 Elems.push_back(Entry);
3139 }
3140 }
3141 CallInst *Composite = B.CreateIntrinsicWithoutFolding(
3142 Intrinsic::spv_const_composite, {B.getInt32Ty()}, Elems);
3143 AggrConsts[Composite] = PoisonValue::get(AggrTy);
3144 AggrConstTypes[Composite] = AggrTy;
3145 return Composite;
3146}
3147
3148// If a function directly returns an aggregate-typed call result,
3149// the ReturnInst carries an aggregate while the function signature
3150// was rewritten to i32 by SPIRVPrepareFunctions. Rebuild the return value
3151// via extractvalue/insertvalue so the regular spv_extractv/spv_insertv
3152// lowering produces a valid OpReturnValue.
3153void SPIRVEmitIntrinsicsImpl::reconstructAggregateReturns(Function &Func,
3154 IRBuilder<> &B) {
3155 Type *OrigRetTy = GR->findMutated(&Func);
3156 if (!OrigRetTy || !OrigRetTy->isAggregateType())
3157 return;
3158 for (BasicBlock &BB : Func) {
3159 auto *RI = dyn_cast<ReturnInst>(BB.getTerminator());
3160 if (!RI)
3161 continue;
3162 Value *RetVal = RI->getReturnValue();
3163 if (!RetVal || RetVal->getType() != OrigRetTy || !isa<CallBase>(RetVal))
3164 continue;
3165 Type *AggrTy = RetVal->getType();
3166 uint64_t NumElts = isa<StructType>(AggrTy)
3167 ? cast<StructType>(AggrTy)->getNumElements()
3168 : cast<ArrayType>(AggrTy)->getNumElements();
3169 B.SetInsertPoint(RI);
3170 Value *Rebuilt = PoisonValue::get(AggrTy);
3171 for (uint64_t I = 0; I < NumElts; ++I) {
3172 Value *Elt = B.CreateExtractValue(RetVal, I);
3173 Rebuilt = B.CreateInsertValue(Rebuilt, Elt, I);
3174 }
3175 RI->setOperand(0, Rebuilt);
3176 }
3177}
3178
3179void SPIRVEmitIntrinsicsImpl::processGlobalValue(GlobalVariable &GV,
3180 IRBuilder<> &B) {
3181
3182 if (!shouldEmitIntrinsicsForGlobalValue(GVUsers, GV, CurrF))
3183 return;
3184
3185 // Record the pointee type for every global, not only initialized ones, so an
3186 // undef non-constant aggregate global is not later collapsed to its element
3187 // type. Result is ignored, because TypedPointerType is not supported
3188 // by llvm IR general logic.
3189 deduceElementTypeHelper(&GV, false);
3190
3191 Constant *Init = nullptr;
3192 if (hasInitializer(&GV)) {
3193 Init = GV.getInitializer();
3194 Value *InitOp = Init;
3195 if (isa<UndefValue>(Init) && Init->getType()->isAggregateType()) {
3196 const SPIRVSubtarget *STI = TM.getSubtargetImpl();
3197 bool UsePoison =
3198 isa<PoisonValue>(Init) &&
3199 STI->canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
3200 if (UsePoison) {
3201 CallInst *Call = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_poison,
3202 {B.getInt32Ty()}, {});
3203 AggrConsts[Call] = cast<PoisonValue>(Init);
3204 AggrConstTypes[Call] = Init->getType();
3205 InitOp = Call;
3206 } else {
3207 InitOp = buildSpvUndefComposite(Init->getType(), B);
3208 }
3209 }
3210 Type *Ty = isAggrConstForceInt32(Init) ? B.getInt32Ty() : Init->getType();
3211 Constant *Const = isAggrConstForceInt32(Init) ? B.getInt32(1) : Init;
3212 CallInst *InitInst = B.CreateIntrinsicWithoutFolding(
3213 Intrinsic::spv_init_global, {GV.getType(), Ty}, {&GV, Const});
3214 InitInst->setArgOperand(1, InitOp);
3215 }
3216 // Globals with only use-list references have no real function uses. Emit
3217 // spv_unref_global so buildGlobalVariable is called for them.
3218 if (!Init && hasOnlyArtificialUses(GV))
3219 B.CreateIntrinsic(Intrinsic::spv_unref_global, GV.getType(), &GV);
3220}
3221
3222// Return true, if we can't decide what is the pointee type now and will get
3223// back to the question later. Return false is spv_assign_ptr_type is not needed
3224// or can be inserted immediately.
3225bool SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeIntrs(Instruction *I,
3226 IRBuilder<> &B,
3227 bool UnknownElemTypeI8) {
3229 if (!isPointerTy(I->getType()) || !requireAssignType(I))
3230 return false;
3231
3233 if (Type *ElemTy = deduceElementType(I, UnknownElemTypeI8)) {
3234 GR->buildAssignPtr(B, ElemTy, I);
3235 return false;
3236 }
3237 return true;
3238}
3239
3240void SPIRVEmitIntrinsicsImpl::insertAssignTypeIntrs(Instruction *I,
3241 IRBuilder<> &B) {
3242 // TODO: extend the list of functions with known result types
3243 static StringMap<unsigned> ResTypeWellKnown = {
3244 {"async_work_group_copy", WellKnownTypes::Event},
3245 {"async_work_group_strided_copy", WellKnownTypes::Event},
3246 {"__spirv_GroupAsyncCopy", WellKnownTypes::Event}};
3247
3249
3250 bool IsKnown = false;
3251 if (auto *CI = dyn_cast<CallInst>(I)) {
3252 if (!CI->isIndirectCall() && !CI->isInlineAsm() &&
3253 CI->getCalledFunction() && !CI->getCalledFunction()->isIntrinsic()) {
3254 Function *CalledF = CI->getCalledFunction();
3255 std::string DemangledName =
3257 FPDecorationId DecorationId = FPDecorationId::NONE;
3258 if (DemangledName.length() > 0)
3259 DemangledName =
3260 SPIRV::lookupBuiltinNameHelper(DemangledName, &DecorationId);
3261 auto ResIt = ResTypeWellKnown.find(DemangledName);
3262 if (ResIt != ResTypeWellKnown.end()) {
3263 IsKnown = true;
3265 switch (ResIt->second) {
3266 case WellKnownTypes::Event:
3267 GR->buildAssignType(
3268 B, TargetExtType::get(I->getContext(), "spirv.Event"), I,
3269 CanUseAnyVectorRank);
3270 break;
3271 }
3272 }
3273 // check if a floating rounding mode or saturation info is present
3274 switch (DecorationId) {
3275 default:
3276 break;
3277 case FPDecorationId::SAT:
3279 break;
3280 case FPDecorationId::RTE:
3282 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTE, B);
3283 break;
3284 case FPDecorationId::RTZ:
3286 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTZ, B);
3287 break;
3288 case FPDecorationId::RTP:
3290 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTP, B);
3291 break;
3292 case FPDecorationId::RTN:
3294 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTN, B);
3295 break;
3296 }
3297 }
3298 }
3299
3300 Type *Ty = I->getType();
3301 if (!IsKnown && !Ty->isVoidTy() && !isPointerTy(Ty) && requireAssignType(I)) {
3303 Type *TypeToAssign = Ty;
3304 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3305 if (isSpvAggrPlaceholder(II)) {
3306 auto It = AggrConstTypes.find(II);
3307 if (It == AggrConstTypes.end())
3308 report_fatal_error("Unknown composite intrinsic type");
3309 TypeToAssign = It->second;
3310 } else if (II->getIntrinsicID() == Intrinsic::spv_poison) {
3311 if (auto It = AggrConstTypes.find(II); It != AggrConstTypes.end())
3312 TypeToAssign = It->second;
3313 }
3314 } else if (auto It = AggrConstTypes.find(I); It != AggrConstTypes.end())
3315 TypeToAssign = It->second;
3316 TypeToAssign = restoreMutatedType(GR, I, TypeToAssign);
3317 GR->buildAssignType(B, TypeToAssign, I, CanUseAnyVectorRank);
3318 }
3319 for (const auto &Op : I->operands()) {
3321 isVector1(Op->getType()) || // <1 x T> gets clobbered ty IRTranslator.
3322 // Check GetElementPtrConstantExpr case.
3324 (isa<GEPOperator>(Op) ||
3325 (cast<ConstantExpr>(Op)->getOpcode() == CastInst::IntToPtr)))) {
3327 Type *OpTy = Op->getType();
3328 if (isa<UndefValue>(Op) && OpTy->isAggregateType()) {
3329 CallInst *AssignCI =
3330 buildIntrWithMD(Intrinsic::spv_assign_type, {B.getInt32Ty()}, Op,
3331 UndefValue::get(B.getInt32Ty()), {}, B);
3332 GR->addAssignPtrTypeInstr(Op, AssignCI);
3333 } else if (!isa<Instruction>(Op)) {
3334 Type *OpTy = Op->getType();
3335 Type *OpTyElem = getPointeeType(OpTy);
3336 if (OpTyElem) {
3337 GR->buildAssignPtr(B, OpTyElem, Op);
3338 } else if (isPointerTy(OpTy)) {
3339 Type *ElemTy = GR->findDeducedElementType(Op);
3340 GR->buildAssignPtr(B, ElemTy ? ElemTy : deduceElementType(Op, true),
3341 Op);
3342 } else {
3343 Value *OpTyVal = Op;
3344 if (OpTy->isTargetExtTy()) {
3345 // We need to do this in order to be consistent with how target ext
3346 // types are handled in `processInstrAfterVisit`
3347 OpTyVal = getNormalizedPoisonValue(OpTy, CanUseAnyVectorRank);
3348 }
3349 CallInst *AssignCI = buildIntrWithMD(
3350 Intrinsic::spv_assign_type, {OpTy},
3351 getNormalizedPoisonValue(OpTy, CanUseAnyVectorRank), OpTyVal, {},
3352 B);
3353 GR->addAssignPtrTypeInstr(OpTyVal, AssignCI);
3354 }
3355 }
3356 }
3357 }
3358}
3359
3360bool SPIRVEmitIntrinsicsImpl::shouldTryToAddMemAliasingDecoration(
3361 Instruction *Inst) {
3362 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*Inst->getFunction());
3363 if (!STI->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing))
3364 return false;
3365 // Add aliasing decorations to internal load and store intrinsics.
3366 // Do not attach them to store atomic or load atomic intrinsics / instructions
3367 // since the extension is inconsistent at the moment (we cannot add the
3368 // decoration to atomic stores because they do not have an id).
3369 return match(Inst,
3371}
3372
3373void SPIRVEmitIntrinsicsImpl::insertSpirvDecorations(Instruction *I,
3374 IRBuilder<> &B) {
3375 if (MDNode *MD = I->getMetadata("spirv.Decorations")) {
3377 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {I->getType()},
3378 {I, MetadataAsValue::get(I->getContext(), MD)});
3379 }
3380 // Lower alias.scope/noalias metadata
3381 {
3382 auto processMemAliasingDecoration = [&](unsigned Kind) {
3383 if (MDNode *AliasListMD = I->getMetadata(Kind)) {
3384 if (shouldTryToAddMemAliasingDecoration(I)) {
3385 uint32_t Dec = Kind == LLVMContext::MD_alias_scope
3386 ? SPIRV::Decoration::AliasScopeINTEL
3387 : SPIRV::Decoration::NoAliasINTEL;
3389 I, ConstantInt::get(B.getInt32Ty(), Dec),
3390 MetadataAsValue::get(I->getContext(), AliasListMD)};
3392 B.CreateIntrinsic(Intrinsic::spv_assign_aliasing_decoration,
3393 {I->getType()}, {Args});
3394 }
3395 }
3396 };
3397 processMemAliasingDecoration(LLVMContext::MD_alias_scope);
3398 processMemAliasingDecoration(LLVMContext::MD_noalias);
3399 }
3400 // MD_fpmath
3401 if (MDNode *MD = I->getMetadata(LLVMContext::MD_fpmath)) {
3402 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*I->getFunction());
3403 bool AllowFPMaxError =
3404 STI->canUseExtension(SPIRV::Extension::SPV_INTEL_fp_max_error);
3405 if (!AllowFPMaxError)
3406 return;
3407
3409 B.CreateIntrinsic(Intrinsic::spv_assign_fpmaxerror_decoration,
3410 {I->getType()},
3411 {I, MetadataAsValue::get(I->getContext(), MD)});
3412 }
3413 if (spirvPreserveAuxData(TM.getCLOpts(), I->getModule()->getTargetTriple()) &&
3415 LLVMContext &Ctx = B.getContext();
3416 auto *AuxMD = ConstantAsMetadata::get(ConstantInt::get(
3417 B.getInt32Ty(), SPIRV::Decoration::AuxDataInstructionMetadata));
3418
3420 if (I->hasMetadata("amdgpu.no.fine.grained.memory"))
3422 Ctx, {AuxMD, MDString::get(Ctx, "amdgpu.no.fine.grained.memory")}));
3423 if (I->hasMetadata("amdgpu.no.remote.memory"))
3425 Ctx, {AuxMD, MDString::get(Ctx, "amdgpu.no.remote.memory")}));
3426 if (I->hasMetadata(LLVMContext::MD_atomic_ignore_denormal_mode))
3428 Ctx, {AuxMD, MDString::get(Ctx, "atomic.ignore.denormal.mode")}));
3429 if (!MDs.empty()) {
3431 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {I->getType()},
3432 {I, MetadataAsValue::get(Ctx, MDNode::get(Ctx, MDs))});
3433 }
3434 }
3435}
3436
3438 const Module &M,
3440 &FPFastMathDefaultInfoMap,
3441 Function *F) {
3442 auto it = FPFastMathDefaultInfoMap.find(F);
3443 if (it != FPFastMathDefaultInfoMap.end())
3444 return it->second;
3445
3446 // If the map does not contain the entry, create a new one. Initialize it to
3447 // contain all 3 elements sorted by bit width of target type: {half, float,
3448 // double}.
3449 SPIRV::FPFastMathDefaultInfoVector FPFastMathDefaultInfoVec;
3450 FPFastMathDefaultInfoVec.emplace_back(Type::getHalfTy(M.getContext()),
3451 SPIRV::FPFastMathMode::None);
3452 FPFastMathDefaultInfoVec.emplace_back(Type::getFloatTy(M.getContext()),
3453 SPIRV::FPFastMathMode::None);
3454 FPFastMathDefaultInfoVec.emplace_back(Type::getDoubleTy(M.getContext()),
3455 SPIRV::FPFastMathMode::None);
3456 return FPFastMathDefaultInfoMap[F] = std::move(FPFastMathDefaultInfoVec);
3457}
3458
3460 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec,
3461 const Type *Ty) {
3462 size_t BitWidth = Ty->getScalarSizeInBits();
3463 int Index =
3465 BitWidth);
3466 assert(Index >= 0 && Index < 3 &&
3467 "Expected FPFastMathDefaultInfo for half, float, or double");
3468 assert(FPFastMathDefaultInfoVec.size() == 3 &&
3469 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3470 return FPFastMathDefaultInfoVec[Index];
3471}
3472
3473void SPIRVEmitIntrinsicsImpl::insertConstantsForFPFastMathDefault(Module &M) {
3474 const SPIRVSubtarget *ST = TM.getSubtargetImpl();
3475 if (!ST->canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2))
3476 return;
3477
3478 // Store the FPFastMathDefaultInfo in the FPFastMathDefaultInfoMap.
3479 // We need the entry point (function) as the key, and the target
3480 // type and flags as the value.
3481 // We also need to check ContractionOff and SignedZeroInfNanPreserve
3482 // execution modes, as they are now deprecated and must be replaced
3483 // with FPFastMathDefaultInfo.
3484 auto Node = M.getNamedMetadata("spirv.ExecutionMode");
3485 if (!Node) {
3486 if (!M.getNamedMetadata("opencl.enable.FP_CONTRACT")) {
3487 // This requires emitting ContractionOff. However, because
3488 // ContractionOff is now deprecated, we need to replace it with
3489 // FPFastMathDefaultInfo with FP Fast Math Mode bitmask set to all 0.
3490 // We need to create the constant for that.
3491
3492 // Create constant instruction with the bitmask flags.
3493 Constant *InitValue =
3494 ConstantInt::get(Type::getInt32Ty(M.getContext()), 0);
3495 // TODO: Reuse constant if there is one already with the required
3496 // value.
3497 [[maybe_unused]] GlobalVariable *GV =
3498 new GlobalVariable(M, // Module
3499 Type::getInt32Ty(M.getContext()), // Type
3500 true, // isConstant
3502 InitValue // Initializer
3503 );
3504 }
3505 return;
3506 }
3507
3508 // The table maps function pointers to their default FP fast math info. It
3509 // can be assumed that the SmallVector is sorted by the bit width of the
3510 // type. The first element is the smallest bit width, and the last element
3511 // is the largest bit width, therefore, we will have {half, float, double}
3512 // in the order of their bit widths.
3513 MapVector<Function *, SPIRV::FPFastMathDefaultInfoVector>
3514 FPFastMathDefaultInfoMap;
3515
3516 for (unsigned i = 0; i < Node->getNumOperands(); i++) {
3517 MDNode *MDN = cast<MDNode>(Node->getOperand(i));
3518 assert(MDN->getNumOperands() >= 2 && "Expected at least 2 operands");
3520 cast<ConstantAsMetadata>(MDN->getOperand(0))->getValue());
3521 const auto EM =
3523 cast<ConstantAsMetadata>(MDN->getOperand(1))->getValue())
3524 ->getZExtValue();
3525 if (EM == SPIRV::ExecutionMode::FPFastMathDefault) {
3526 assert(MDN->getNumOperands() == 4 &&
3527 "Expected 4 operands for FPFastMathDefault");
3528 const Type *T = cast<ValueAsMetadata>(MDN->getOperand(2))->getType();
3529 unsigned Flags =
3531 cast<ConstantAsMetadata>(MDN->getOperand(3))->getValue())
3532 ->getZExtValue();
3533 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3534 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3535 SPIRV::FPFastMathDefaultInfo &Info =
3536 getFPFastMathDefaultInfo(FPFastMathDefaultInfoVec, T);
3537 Info.FastMathFlags = Flags;
3538 Info.FPFastMathDefault = true;
3539 } else if (EM == SPIRV::ExecutionMode::ContractionOff) {
3540 assert(MDN->getNumOperands() == 2 &&
3541 "Expected no operands for ContractionOff");
3542
3543 // We need to save this info for every possible FP type, i.e. {half,
3544 // float, double, fp128}.
3545 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3546 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3547 for (SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3548 Info.ContractionOff = true;
3549 }
3550 } else if (EM == SPIRV::ExecutionMode::SignedZeroInfNanPreserve) {
3551 assert(MDN->getNumOperands() == 3 &&
3552 "Expected 1 operand for SignedZeroInfNanPreserve");
3553 unsigned TargetWidth =
3555 cast<ConstantAsMetadata>(MDN->getOperand(2))->getValue())
3556 ->getZExtValue();
3557 // We need to save this info only for the FP type with TargetWidth.
3558 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3559 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3562 assert(Index >= 0 && Index < 3 &&
3563 "Expected FPFastMathDefaultInfo for half, float, or double");
3564 assert(FPFastMathDefaultInfoVec.size() == 3 &&
3565 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3566 FPFastMathDefaultInfoVec[Index].SignedZeroInfNanPreserve = true;
3567 }
3568 }
3569
3570 DenseMap<unsigned, GlobalVariable *> GlobalVars;
3571 for (auto &[Func, FPFastMathDefaultInfoVec] : FPFastMathDefaultInfoMap) {
3572 if (FPFastMathDefaultInfoVec.empty())
3573 continue;
3574
3575 for (const SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3576 assert(Info.Ty && "Expected target type for FPFastMathDefaultInfo");
3577 // Skip if none of the execution modes was used.
3578 unsigned Flags = Info.FastMathFlags;
3579 if (Flags == SPIRV::FPFastMathMode::None && !Info.ContractionOff &&
3580 !Info.SignedZeroInfNanPreserve && !Info.FPFastMathDefault)
3581 continue;
3582
3583 // Check if flags are compatible.
3584 if (Info.ContractionOff && (Flags & SPIRV::FPFastMathMode::AllowContract))
3585 report_fatal_error("Conflicting FPFastMathFlags: ContractionOff "
3586 "and AllowContract");
3587
3588 if (Info.SignedZeroInfNanPreserve &&
3589 !(Flags &
3590 (SPIRV::FPFastMathMode::NotNaN | SPIRV::FPFastMathMode::NotInf |
3591 SPIRV::FPFastMathMode::NSZ))) {
3592 if (Info.FPFastMathDefault)
3593 report_fatal_error("Conflicting FPFastMathFlags: "
3594 "SignedZeroInfNanPreserve but at least one of "
3595 "NotNaN/NotInf/NSZ is enabled.");
3596 }
3597
3598 if ((Flags & SPIRV::FPFastMathMode::AllowTransform) &&
3599 !((Flags & SPIRV::FPFastMathMode::AllowReassoc) &&
3600 (Flags & SPIRV::FPFastMathMode::AllowContract))) {
3601 report_fatal_error("Conflicting FPFastMathFlags: "
3602 "AllowTransform requires AllowReassoc and "
3603 "AllowContract to be set.");
3604 }
3605
3606 auto it = GlobalVars.find(Flags);
3607 GlobalVariable *GV = nullptr;
3608 if (it != GlobalVars.end()) {
3609 // Reuse existing global variable.
3610 GV = it->second;
3611 } else {
3612 // Create constant instruction with the bitmask flags.
3613 Constant *InitValue =
3614 ConstantInt::get(Type::getInt32Ty(M.getContext()), Flags);
3615 // TODO: Reuse constant if there is one already with the required
3616 // value.
3617 GV = new GlobalVariable(M, // Module
3618 Type::getInt32Ty(M.getContext()), // Type
3619 true, // isConstant
3621 InitValue // Initializer
3622 );
3623 GlobalVars[Flags] = GV;
3624 }
3625 }
3626 }
3627}
3628
3629void SPIRVEmitIntrinsicsImpl::processInstrAfterVisit(Instruction *I,
3630 IRBuilder<> &B) {
3631 auto *II = dyn_cast<IntrinsicInst>(I);
3632 bool IsConstComposite =
3633 II && II->getIntrinsicID() == Intrinsic::spv_const_composite;
3634 if (IsConstComposite && TrackConstants) {
3636 auto t = AggrConsts.find(I);
3637 assert(t != AggrConsts.end());
3638 auto *NewOp =
3639 buildIntrWithMD(Intrinsic::spv_track_constant,
3640 {II->getType(), II->getType()}, t->second, I, {}, B);
3641 replaceAllUsesWith(I, NewOp, false);
3642 NewOp->setArgOperand(0, I);
3643 }
3644 bool IsPhi = isa<PHINode>(I), BPrepared = false;
3645 for (const auto &Op : I->operands()) {
3646 if (isa<PHINode>(I) || isa<SwitchInst>(I) ||
3648 continue;
3649 unsigned OpNo = Op.getOperandNo();
3650 if (II && ((II->getIntrinsicID() == Intrinsic::spv_gep && OpNo == 0) ||
3651 (!II->isBundleOperand(OpNo) &&
3652 II->paramHasAttr(OpNo, Attribute::ImmArg))))
3653 continue;
3654
3655 if (!BPrepared) {
3656 IsPhi ? B.SetInsertPointPastAllocas(I->getParent()->getParent())
3657 : B.SetInsertPoint(I);
3658 BPrepared = true;
3659 }
3660 Type *OpTy = Op->getType();
3661 Type *OpElemTy = GR->findDeducedElementType(Op);
3662 Value *NewOp = Op;
3663 if (OpTy->isTargetExtTy()) {
3664 // Since this value is replaced by poison, we need to do the same in
3665 // `insertAssignTypeIntrs`.
3666 Value *OpTyVal = getNormalizedPoisonValue(OpTy, CanUseAnyVectorRank);
3667 NewOp = buildIntrWithMD(Intrinsic::spv_track_constant,
3668 {OpTy, OpTyVal->getType()}, Op, OpTyVal, {}, B);
3669 }
3670 if (!IsConstComposite && isPointerTy(OpTy) && OpElemTy != nullptr &&
3671 OpElemTy != IntegerType::getInt8Ty(I->getContext())) {
3672 SmallVector<Type *, 2> Types = {OpTy, OpTy};
3673 SmallVector<Value *, 2> Args = {
3674 NewOp,
3675 buildMD(getNormalizedPoisonValue(OpElemTy, CanUseAnyVectorRank)),
3676 B.getInt32(getPointerAddressSpace(OpTy))};
3677 CallInst *PtrCasted = B.CreateIntrinsicWithoutFolding(
3678 Intrinsic::spv_ptrcast, {Types}, Args);
3679 GR->buildAssignPtr(B, OpElemTy, PtrCasted);
3680 NewOp = PtrCasted;
3681 }
3682 if (NewOp != Op)
3683 I->setOperand(OpNo, NewOp);
3684 }
3685 if (Named.insert(I).second)
3686 emitAssignName(TM.getCLOpts(), I, B);
3687}
3688
3689Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(Function *F,
3690 unsigned OpIdx) {
3691 SmallPtrSet<Function *, 0> FVisited;
3692 return deduceFunParamElementType(F, OpIdx, FVisited);
3693}
3694
3695Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(
3696 Function *F, unsigned OpIdx, SmallPtrSetImpl<Function *> &FVisited) {
3697 // maybe a cycle
3698 if (!FVisited.insert(F).second)
3699 return nullptr;
3700
3701 SmallPtrSet<Value *, 0> Visited;
3703 // search in function's call sites
3704 for (User *U : F->users()) {
3705 CallInst *CI = dyn_cast<CallInst>(U);
3706 if (!CI || OpIdx >= CI->arg_size())
3707 continue;
3708 Value *OpArg = CI->getArgOperand(OpIdx);
3709 if (!isPointerTy(OpArg->getType()))
3710 continue;
3711 // maybe we already know operand's element type
3712 if (Type *KnownTy = GR->findDeducedElementType(OpArg))
3713 return KnownTy;
3714 // try to deduce from the operand itself
3715 Visited.clear();
3716 if (Type *Ty = deduceElementTypeHelper(OpArg, Visited, false))
3717 return Ty;
3718 // search in actual parameter's users
3719 for (User *OpU : OpArg->users()) {
3721 if (!Inst || Inst == CI)
3722 continue;
3723 Visited.clear();
3724 if (Type *Ty = deduceElementTypeHelper(Inst, Visited, false))
3725 return Ty;
3726 }
3727 // check if it's a formal parameter of the outer function
3728 if (!CI->getParent() || !CI->getParent()->getParent())
3729 continue;
3730 Function *OuterF = CI->getParent()->getParent();
3731 if (FVisited.find(OuterF) != FVisited.end())
3732 continue;
3733 for (unsigned i = 0; i < OuterF->arg_size(); ++i) {
3734 if (OuterF->getArg(i) == OpArg) {
3735 Lookup.push_back(std::make_pair(OuterF, i));
3736 break;
3737 }
3738 }
3739 }
3740
3741 // search in function parameters
3742 for (auto &Pair : Lookup) {
3743 if (Type *Ty = deduceFunParamElementType(Pair.first, Pair.second, FVisited))
3744 return Ty;
3745 }
3746
3747 return nullptr;
3748}
3749
3750void SPIRVEmitIntrinsicsImpl::processParamTypesByFunHeader(Function *F,
3751 IRBuilder<> &B) {
3752 B.SetInsertPointPastAllocas(F);
3753 for (unsigned OpIdx = 0; OpIdx < F->arg_size(); ++OpIdx) {
3754 Argument *Arg = F->getArg(OpIdx);
3755 // Vector-of-pointers arg: deduce pointee from a GEP user so the function
3756 // type isn't emitted with the default i8 pointee.
3757 if (isUntypedPointerVectorTy(Arg->getType()) &&
3758 !GR->findDeducedElementType(Arg)) {
3759 for (User *U : Arg->users()) {
3761 if (GEP && GEP->getPointerOperand() == Arg) {
3762 GR->buildAssignPtr(B, GEP->getSourceElementType(), Arg);
3763 break;
3764 }
3765 }
3766 continue;
3767 }
3768 if (!isUntypedPointerTy(Arg->getType()))
3769 continue;
3770 Type *ElemTy = GR->findDeducedElementType(Arg);
3771 if (ElemTy)
3772 continue;
3773 if (hasPointeeTypeAttr(Arg) &&
3774 (ElemTy = getPointeeTypeByAttr(Arg)) != nullptr) {
3775 GR->buildAssignPtr(B, ElemTy, Arg);
3776 continue;
3777 }
3778 // search in function's call sites
3779 for (User *U : F->users()) {
3780 CallInst *CI = dyn_cast<CallInst>(U);
3781 if (!CI || OpIdx >= CI->arg_size())
3782 continue;
3783 Value *OpArg = CI->getArgOperand(OpIdx);
3784 if (!isPointerTy(OpArg->getType()))
3785 continue;
3786 // maybe we already know operand's element type
3787 if ((ElemTy = GR->findDeducedElementType(OpArg)) != nullptr)
3788 break;
3789 }
3790 if (ElemTy) {
3791 GR->buildAssignPtr(B, ElemTy, Arg);
3792 continue;
3793 }
3794 if (HaveFunPtrs) {
3795 for (User *U : Arg->users()) {
3796 CallInst *CI = dyn_cast<CallInst>(U);
3797 if (CI && !isa<IntrinsicInst>(CI) && CI->isIndirectCall() &&
3798 CI->getCalledOperand() == Arg &&
3799 CI->getParent()->getParent() == CurrF) {
3801 deduceOperandElementTypeFunctionPointer(CI, Ops, ElemTy, false);
3802 if (ElemTy) {
3803 GR->buildAssignPtr(B, ElemTy, Arg);
3804 break;
3805 }
3806 }
3807 }
3808 }
3809 }
3810}
3811
3812void SPIRVEmitIntrinsicsImpl::processParamTypes(Function *F, IRBuilder<> &B) {
3813 B.SetInsertPointPastAllocas(F);
3814 for (unsigned OpIdx = 0; OpIdx < F->arg_size(); ++OpIdx) {
3815 Argument *Arg = F->getArg(OpIdx);
3816 if (!isUntypedPointerTy(Arg->getType()))
3817 continue;
3818 Type *ElemTy = GR->findDeducedElementType(Arg);
3819 if (!ElemTy && (ElemTy = deduceFunParamElementType(F, OpIdx)) != nullptr) {
3820 if (CallInst *AssignCI = GR->findAssignPtrTypeInstr(Arg)) {
3821 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
3822 GR->updateAssignType(
3823 AssignCI, Arg,
3824 getNormalizedPoisonValue(ElemTy, CanUseAnyVectorRank));
3825 propagateElemType(Arg, IntegerType::getInt8Ty(F->getContext()),
3826 VisitedSubst);
3827 } else {
3828 GR->buildAssignPtr(B, ElemTy, Arg);
3829 }
3830 }
3831 }
3832}
3833
3835 SPIRVGlobalRegistry *GR) {
3836 FunctionType *FTy = F->getFunctionType();
3837 bool IsNewFTy = false;
3839 for (Argument &Arg : F->args()) {
3840 Type *ArgTy = Arg.getType();
3841 if (ArgTy->isPointerTy())
3842 if (Type *ElemTy = GR->findDeducedElementType(&Arg)) {
3843 IsNewFTy = true;
3845 }
3846 ArgTys.push_back(ArgTy);
3847 }
3848 return IsNewFTy
3849 ? FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg())
3850 : FTy;
3851}
3852
3853bool SPIRVEmitIntrinsicsImpl::processFunctionPointers(Module &M) {
3854 SmallVector<Function *> Worklist;
3855 for (auto &F : M) {
3856 if (F.isIntrinsic())
3857 continue;
3858 if (F.isDeclaration()) {
3859 for (User *U : F.users()) {
3860 // SPIR-V has no personality, so it is not a function pointer use.
3861 if (auto *UF = dyn_cast<Function>(U);
3862 UF && UF->hasPersonalityFn() && UF->getPersonalityFn() == &F)
3863 continue;
3864 CallInst *CI = dyn_cast<CallInst>(U);
3865 if (!CI || CI->getCalledFunction() != &F) {
3866 Worklist.push_back(&F);
3867 break;
3868 }
3869 }
3870 } else {
3871 if (F.user_empty())
3872 continue;
3873 Type *FPElemTy = GR->findDeducedElementType(&F);
3874 if (!FPElemTy)
3875 FPElemTy = getFunctionPointerElemType(&F, GR);
3876 for (User *U : F.users()) {
3877 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3878 if (!II || II->arg_size() != 3 || II->getOperand(0) != &F)
3879 continue;
3880 if (II->getIntrinsicID() == Intrinsic::spv_assign_ptr_type ||
3881 II->getIntrinsicID() == Intrinsic::spv_ptrcast) {
3882 GR->updateAssignType(
3883 II, &F, getNormalizedPoisonValue(FPElemTy, CanUseAnyVectorRank));
3884 break;
3885 }
3886 }
3887 }
3888 }
3889 if (Worklist.empty())
3890 return false;
3891
3892 LLVMContext &Ctx = M.getContext();
3894 BasicBlock *BB = BasicBlock::Create(Ctx, "entry", SF);
3895 IRBuilder<> IRB(BB);
3896
3897 for (Function *F : Worklist) {
3899 for (const auto &Arg : F->args())
3900 Args.push_back(
3901 getNormalizedPoisonValue(Arg.getType(), CanUseAnyVectorRank));
3902 IRB.CreateCall(F, Args)->setTailCall(true);
3903 }
3904 IRB.CreateRetVoid();
3905
3906 return true;
3907}
3908
3909// Apply types parsed from demangled function declarations.
3910void SPIRVEmitIntrinsicsImpl::applyDemangledPtrArgTypes(IRBuilder<> &B) {
3911 DenseMap<Function *, CallInst *> Ptrcasts;
3912 for (auto It : FDeclPtrTys) {
3913 Function *F = It.first;
3914 for (auto *U : F->users()) {
3915 CallInst *CI = dyn_cast<CallInst>(U);
3916 if (!CI || CI->getCalledFunction() != F)
3917 continue;
3918 unsigned Sz = CI->arg_size();
3919 for (auto [Idx, ElemTy] : It.second) {
3920 if (Idx >= Sz)
3921 continue;
3922 Value *Param = CI->getArgOperand(Idx);
3923 if (GR->findDeducedElementType(Param) || isa<GlobalValue>(Param))
3924 continue;
3925 if (Argument *Arg = dyn_cast<Argument>(Param)) {
3926 if (!hasPointeeTypeAttr(Arg)) {
3927 B.SetInsertPointPastAllocas(Arg->getParent());
3928 B.SetCurrentDebugLocation(DebugLoc());
3929 GR->buildAssignPtr(B, ElemTy, Arg);
3930 }
3931 } else if (isaGEP(Param) || isa<AllocaInst>(Param)) {
3932 // The allocated type defines the size of an alloca, so cast at the
3933 // call instead of overriding its pointee type.
3934 replaceUsesOfWithSpvPtrcast(
3935 Param, normalizeType(ElemTy, CanUseAnyVectorRank), CI, Ptrcasts);
3936 } else if (isa<Instruction>(Param)) {
3937 GR->addDeducedElementType(Param,
3938 normalizeType(ElemTy, CanUseAnyVectorRank));
3939 // insertAssignTypeIntrs() will complete buildAssignPtr()
3940 } else {
3941 B.SetInsertPoint(CI->getParent()
3942 ->getParent()
3943 ->getEntryBlock()
3944 .getFirstNonPHIOrAlloca());
3945 GR->buildAssignPtr(B, ElemTy, Param);
3946 }
3947 CallInst *Ref = dyn_cast<CallInst>(Param);
3948 if (!Ref)
3949 continue;
3950 Function *RefF = Ref->getCalledFunction();
3951 if (!RefF || !isPointerTy(RefF->getReturnType()) ||
3952 GR->findDeducedElementType(RefF))
3953 continue;
3954 ElemTy = normalizeType(ElemTy, CanUseAnyVectorRank);
3955 GR->addDeducedElementType(RefF, ElemTy);
3956 GR->addReturnType(
3958 ElemTy, getPointerAddressSpace(RefF->getReturnType())));
3959 }
3960 }
3961 }
3962 FDeclPtrTys.clear();
3963}
3964
3965GetElementPtrInst *SPIRVEmitIntrinsicsImpl::simplifyZeroLengthArrayGepInst(
3966 GetElementPtrInst *GEP) {
3967 // getelementptr [0 x T], P, 0 (zero), I -> getelementptr T, P, I.
3968 // If type is 0-length array and first index is 0 (zero), drop both the
3969 // 0-length array type and the first index. This is a common pattern in
3970 // the IR, e.g. when using a zero-length array as a placeholder for a
3971 // flexible array such as unbound arrays.
3972 assert(GEP && "GEP is null");
3973 Type *SrcTy = GEP->getSourceElementType();
3974 SmallVector<Value *, 8> Indices(GEP->indices());
3975 ArrayType *ArrTy = dyn_cast<ArrayType>(SrcTy);
3976 if (ArrTy && ArrTy->getNumElements() == 0 && match(Indices[0], m_Zero())) {
3977 Indices.erase(Indices.begin());
3978 SrcTy = ArrTy->getElementType();
3979 return GetElementPtrInst::Create(SrcTy, GEP->getPointerOperand(), Indices,
3980 GEP->getNoWrapFlags(), "",
3981 GEP->getIterator());
3982 }
3983 return nullptr;
3984}
3985
3986void SPIRVEmitIntrinsicsImpl::emitUnstructuredLoopControls(Function &F,
3987 IRBuilder<> &B) {
3988 const SPIRVSubtarget *ST = TM.getSubtargetImpl(F);
3989 // Shaders use SPIRVStructurizer which emits OpLoopMerge via spv_loop_merge.
3990 if (ST->isShader())
3991 return;
3992
3993 if (ST->canUseExtension(
3994 SPIRV::Extension::SPV_INTEL_unstructured_loop_controls)) {
3995 for (BasicBlock &BB : F) {
3997 MDNode *LoopMD = Term->getMetadata(LLVMContext::MD_loop);
3998 if (!LoopMD)
3999 continue;
4000
4001 SmallVector<unsigned, 1> Ops =
4003 unsigned LC = Ops[0];
4004 if (LC == SPIRV::LoopControl::None)
4005 continue;
4006
4007 // Emit intrinsic: loop control mask + optional parameters.
4008 B.SetInsertPoint(Term);
4009 SmallVector<Value *, 4> IntrArgs;
4010 for (unsigned Op : Ops)
4011 IntrArgs.push_back(B.getInt32(Op));
4012 B.CreateIntrinsic(Intrinsic::spv_loop_control_intel, IntrArgs);
4013 }
4014 return;
4015 }
4016
4017 // For non-shader targets without the Intel extension, emit OpLoopMerge
4018 // using spv_loop_merge intrinsics, mirroring the structurizer approach.
4019 LoopInfo LI;
4020 LI.analyze(&F);
4021 if (LI.empty())
4022 return;
4023
4024 SmallPtrSet<BasicBlock *, 8> UsedMergeBlocks;
4025 for (Loop *L : LI.getLoopsInPreorder()) {
4026 BasicBlock *Latch = L->getLoopLatch();
4027 if (!Latch)
4028 continue;
4029
4030 // Check for loop unroll metadata on the latch terminator.
4031 SmallVector<unsigned, 1> LoopControlOps =
4033 if (LoopControlOps[0] == SPIRV::LoopControl::None)
4034 continue;
4035
4036 BasicBlock *Header = L->getHeader();
4037 // OpLoopMerge must immediately precede an OpBranch or OpBranchConditional.
4038 // Switches are already lowered to spv_switch + indirectbr at this point.
4039 if (!isa<UncondBrInst, CondBrInst>(Header->getTerminator()))
4040 continue;
4041
4042 BasicBlock *MergeBlock = L->getUniqueExitBlock();
4043 // LoopSimplify does not guarantee a unique exit block. Try the normal exit
4044 // of a rotated loop (from the latch), then an unrotated loop (from the
4045 // header). A merge block cannot be shared by multiple loop headers.
4046 for (BasicBlock *BB : {Latch, Header}) {
4047 if (MergeBlock || !isa<CondBrInst>(BB->getTerminator()))
4048 continue;
4049 for (BasicBlock *Succ : successors(BB))
4050 if (!L->contains(Succ) && !UsedMergeBlocks.contains(Succ))
4051 MergeBlock = Succ;
4052 }
4053 if (!MergeBlock || !UsedMergeBlocks.insert(MergeBlock).second)
4054 continue;
4055
4056 B.SetInsertPoint(Header->getTerminator());
4057 auto *MergeAddress = BlockAddress::get(&F, MergeBlock);
4058 auto *ContinueAddress = BlockAddress::get(&F, Latch);
4059 SmallVector<Value *, 4> Args = {MergeAddress, ContinueAddress};
4060 for (unsigned Imm : LoopControlOps)
4061 Args.emplace_back(B.getInt32(Imm));
4062 B.CreateIntrinsic(Intrinsic::spv_loop_merge, {Args});
4063 }
4064}
4065
4066bool SPIRVEmitIntrinsicsImpl::runOnFunction(Function &Func) {
4067 if (Func.isDeclaration())
4068 return false;
4069
4070 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(Func);
4071 // LoopSimplify runs after SPIRVPrepareFunctions sorted the blocks, and the
4072 // preheaders/dedicated exits it creates can end up before their dominator,
4073 // which SPIR-V forbids.
4074 if (!ST.isShader())
4075 sortBlocks(Func);
4076 GR = ST.getSPIRVGlobalRegistry();
4077
4078 if (!CurrF)
4079 HaveFunPtrs =
4080 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
4081
4082 CanUseAnyVectorRank =
4083 ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector);
4084 CurrF = &Func;
4085 IRBuilder<> B(*Func.getParent());
4086 AggrConsts.clear();
4087 AggrConstTypes.clear();
4088 AggrStores.clear();
4089
4090 scalarizeVectorPtrCasts(Func);
4091 processParamTypesByFunHeader(CurrF, B);
4092
4093 if (ST.isLogicalSPIRV())
4094 foldConstantOffsetIntoArrayIndex(Func);
4095
4096 // Fix GEP result types ahead of inference, and simplify if possible.
4097 // Data structure for dead instructions that were simplified and replaced.
4098 SmallPtrSet<Instruction *, 4> DeadInsts;
4099 for (auto &I : instructions(Func)) {
4100 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
4101 Type *ElTy = SI->getValueOperand()->getType();
4102 if (ElTy->isAggregateType() || ElTy->isVectorTy())
4103 AggrStores.insert(&I);
4104 continue;
4105 }
4106
4108 auto *SGEP = dyn_cast<StructuredGEPInst>(&I);
4109
4110 if ((!GEP && !SGEP) || GR->findDeducedElementType(&I))
4111 continue;
4112
4113 if (SGEP) {
4115 SGEP,
4116 normalizeType(SGEP->getResultElementType(), CanUseAnyVectorRank));
4117 continue;
4118 }
4119
4120 GetElementPtrInst *NewGEP = simplifyZeroLengthArrayGepInst(GEP);
4121 if (NewGEP) {
4122 GEP->replaceAllUsesWith(NewGEP);
4123 DeadInsts.insert(GEP);
4124 GEP = NewGEP;
4125 }
4126 if (Type *GepTy = getGEPType(GEP))
4127 GR->addDeducedElementType(GEP, normalizeType(GepTy, CanUseAnyVectorRank));
4128 }
4129 // Remove dead instructions that were simplified and replaced.
4130 for (auto *I : DeadInsts) {
4131 assert(I->use_empty() && "Dead instruction should not have any uses left");
4132 I->eraseFromParent();
4133 }
4134 if (AccessChainErrors)
4135 return true;
4136
4137 B.SetInsertPoint(Func.getEntryBlock().begin());
4138 for (auto &GV : Func.getParent()->globals())
4139 processGlobalValue(GV, B);
4140
4141 reconstructAggregateReturns(Func, B);
4142 // Before preprocessUndefsAndPoisons, which gives the poison starting each
4143 // chain a typed placeholder.
4144 for (Instruction &I : instructions(Func))
4146 insertCompositeAggregateArms(&I, B);
4147 preprocessUndefsAndPoisons(B);
4148 simplifyNullAddrSpaceCasts();
4149 preprocessCompositeConstants(B);
4150
4151 // A PHINode, SelectInst or FreezeInst takes its result type from its
4152 // operands. Aggregate arms are lowered to i32 value-ids (composite constants
4153 // here, loads and other producers during the visitor pass below), so mutate
4154 // an aggregate PHI, select or freeze to match. The original type is tracked
4155 // in AggrConstTypes (used to assign the SPIR-V type) and its extractvalue
4156 // users are lowered to spv_extractv.
4157 Type *I32Ty = B.getInt32Ty();
4158 for (Instruction &I : instructions(Func)) {
4160 continue;
4161 AggrConstTypes[&I] = I.getType();
4162 I.mutateType(I32Ty);
4163 }
4164
4165 preprocessBoolVectorBitcasts(Func);
4166 SmallVector<Instruction *> Worklist(
4168
4169 applyDemangledPtrArgTypes(B);
4170
4171 // Pass forward: use operand to deduce instructions result.
4172 for (auto &I : Worklist) {
4173 // Don't emit intrinsincs for convergence intrinsics.
4174 if (isConvergenceIntrinsic(I))
4175 continue;
4176
4177 bool Postpone = insertAssignPtrTypeIntrs(I, B, false);
4178 // if Postpone is true, we can't decide on pointee type yet
4179 insertAssignTypeIntrs(I, B);
4180 insertPtrCastOrAssignTypeInstr(I, B);
4182 // if instruction requires a pointee type set, let's check if we know it
4183 // already, and force it to be i8 if not
4184 if (Postpone && !GR->findAssignPtrTypeInstr(I))
4185 insertAssignPtrTypeIntrs(I, B, true);
4186
4187 if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(I))
4188 useRoundingMode(FPI, B);
4189 }
4190
4191 // Pass backward: use instructions results to specify/update/cast operands
4192 // where needed.
4193 SmallPtrSet<Instruction *, 4> IncompleteRets;
4194 for (auto &I : llvm::reverse(instructions(Func)))
4195 deduceOperandElementType(&I, &IncompleteRets);
4196
4197 // Pass forward for PHIs only, their operands are not preceed the
4198 // instruction in meaning of `instructions(Func)`.
4199 for (BasicBlock &BB : Func)
4200 for (PHINode &Phi : BB.phis())
4201 if (isPointerTy(Phi.getType()))
4202 deduceOperandElementType(&Phi, nullptr);
4203
4204 for (auto *I : Worklist) {
4205 TrackConstants = true;
4206 if (!I->getType()->isVoidTy() || isa<StoreInst>(I))
4208 // Visitors return either the original/newly created instruction for
4209 // further processing, nullptr otherwise.
4210 I = visit(*I);
4211 if (AccessChainErrors)
4212 return true;
4213 if (!I)
4214 continue;
4215
4216 // Don't emit intrinsics for convergence operations.
4217 if (isConvergenceIntrinsic(I))
4218 continue;
4219
4221 processInstrAfterVisit(I, B);
4222 }
4223
4224 emitUnstructuredLoopControls(Func, B);
4225
4226 return true;
4227}
4228
4229// Try to deduce a better type for pointers to untyped ptr.
4230bool SPIRVEmitIntrinsicsImpl::postprocessTypes(Module &M) {
4231 if (!GR || TodoTypeSz == 0)
4232 return false;
4233
4234 unsigned SzTodo = TodoTypeSz;
4235 DenseMap<Value *, SmallPtrSet<Value *, 4>> ToProcess;
4236 for (auto [Op, Enabled] : TodoType) {
4237 // TODO: add isa<CallInst>(Op) to continue
4238 if (!Enabled || isaGEP(Op))
4239 continue;
4240 CallInst *AssignCI = GR->findAssignPtrTypeInstr(Op);
4241 Type *KnownTy = GR->findDeducedElementType(Op);
4242 if (!KnownTy || !AssignCI)
4243 continue;
4244 assert(Op == AssignCI->getArgOperand(0));
4245 // Try to improve the type deduced after all Functions are processed.
4246 if (auto *CI = dyn_cast<Instruction>(Op)) {
4247 CurrF = CI->getParent()->getParent();
4248 SmallPtrSet<Value *, 0> Visited;
4249 if (Type *ElemTy = deduceElementTypeHelper(Op, Visited, false, true)) {
4250 if (ElemTy != KnownTy) {
4251 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
4252 propagateElemType(CI, ElemTy, VisitedSubst);
4253 eraseTodoType(Op);
4254 continue;
4255 }
4256 }
4257 }
4258
4259 if (Op->hasUseList()) {
4260 for (User *U : Op->users()) {
4262 if (Inst && !isa<IntrinsicInst>(Inst))
4263 ToProcess[Inst].insert(Op);
4264 }
4265 }
4266 }
4267 if (TodoTypeSz == 0)
4268 return true;
4269
4270 for (auto &F : M) {
4271 CurrF = &F;
4272 SmallPtrSet<Instruction *, 4> IncompleteRets;
4273 for (auto &I : llvm::reverse(instructions(F))) {
4274 auto It = ToProcess.find(&I);
4275 if (It == ToProcess.end())
4276 continue;
4277 It->second.remove_if([this](Value *V) { return !isTodoType(V); });
4278 if (It->second.size() == 0)
4279 continue;
4280 deduceOperandElementType(&I, &IncompleteRets, &It->second, true);
4281 if (TodoTypeSz == 0)
4282 return true;
4283 }
4284 }
4285
4286 return SzTodo > TodoTypeSz;
4287}
4288
4289// Parse unambiguous scalar/vector pointees, e.g. "float vector[4] const*".
4291 if (!TypeStr.consume_back("*") && !TypeStr.consume_back("&"))
4292 return nullptr;
4293 StringRef ScalarName = TypeStr;
4294 Type *ElemTy = parseBasicTypeName(TypeStr, Ctx);
4295 if (!ElemTy || ElemTy->isVoidTy() || ElemTy->isIntegerTy(1))
4296 return nullptr;
4297 ScalarName = ScalarName.drop_back(TypeStr.size());
4298 // OpenCL aliases such as uint can also name C++ classes.
4299 if (!StringSwitch<bool>(ScalarName)
4300 .Cases({"char", "signed char", "unsigned char", "short",
4301 "unsigned short", "int", "unsigned int", "_Float16", "float",
4302 "double"},
4303 true)
4304 .Default(false) ||
4305 (!TypeStr.empty() && !TypeStr.starts_with(" ")))
4306 return nullptr;
4307 if (TypeStr.consume_front(" vector[")) {
4308 auto [Count, Rest] = TypeStr.split(']');
4309 unsigned NumElts = 0;
4310 if (Count.getAsInteger(10, NumElts) || NumElts == 0)
4311 return nullptr;
4313 TypeStr = Rest;
4314 }
4315 // Only cv and address space qualifiers may follow.
4317 TypeStr.split(Quals, ' ', -1, /*KeepEmpty=*/false);
4318 for (StringRef Qual : Quals) {
4319 unsigned AS;
4320 if (Qual != "const" && Qual != "volatile" && Qual != "restrict" &&
4321 !(Qual.consume_front("AS") && !Qual.getAsInteger(10, AS)))
4322 return nullptr;
4323 }
4324 return ElemTy;
4325}
4326
4327// Parse and store argument types of function declarations where needed.
4328void SPIRVEmitIntrinsicsImpl::parseFunDeclarations(Module &M) {
4329 for (auto &F : M) {
4330 if (!F.isDeclaration() || F.isIntrinsic())
4331 continue;
4332 std::string DemangledName = getOclOrSpirvBuiltinDemangledName(F.getName());
4333 if (DemangledName.empty())
4334 continue;
4335 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(F);
4336 auto Set = ST.getPreferredInstructionSet();
4337 auto [Grp, Opcode, ExtNo] = SPIRV::mapBuiltinToOpcode(DemangledName, Set);
4338 // Some builtins have no opcode mapping.
4339 const bool IsBuiltin = Grp >= 0 || SPIRV::isBuiltin(DemangledName, Set);
4340 if (IsBuiltin && Opcode != SPIRV::OpGroupAsyncCopy)
4341 continue;
4342 SmallVector<unsigned> Idxs;
4343 for (Argument &Arg : F.args())
4344 if (isPointerTy(Arg.getType()) && !hasPointeeTypeAttr(&Arg))
4345 Idxs.push_back(Arg.getArgNo());
4346 if (Idxs.empty())
4347 continue;
4348 LLVMContext &Ctx = F.getContext();
4350 SPIRV::parseBuiltinTypeStr(TypeStrs, DemangledName, Ctx);
4351 if (TypeStrs.empty())
4352 continue;
4353 // Avoid nested signatures and hidden ABI arguments such as this and sret.
4354 if (!IsBuiltin && (!F.getName().starts_with("_Z") || F.hasStructRetAttr() ||
4355 StringRef(DemangledName).count('(') != 1 ||
4356 StringRef(DemangledName).count(')') != 1 ||
4357 StringRef(DemangledName).contains('<') ||
4358 TypeStrs.size() != F.arg_size()))
4359 continue;
4360 bool AllowLongVectors =
4361 ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector);
4362 for (unsigned Idx : Idxs) {
4363 if (Idx >= TypeStrs.size())
4364 continue;
4365 StringRef TypeStr = TypeStrs[Idx].trim();
4366 Type *ElemTy = IsBuiltin
4367 ? SPIRV::parseBuiltinCallArgumentType(TypeStr, Ctx)
4368 : parseDeclPtrElemType(TypeStr, Ctx);
4369 if (!ElemTy || !TypedPointerType::isValidElementType(ElemTy) ||
4370 ElemTy->isTargetExtTy())
4371 continue;
4372 if (!IsBuiltin) {
4373 ElemTy = normalizeType(ElemTy, AllowLongVectors);
4374 if (!AllowLongVectors && isLongVectorEXT(ElemTy))
4375 continue;
4376 }
4377 FDeclPtrTys[&F].emplace_back(Idx, ElemTy);
4378 if (!IsBuiltin)
4379 ST.getSPIRVGlobalRegistry()->addDeducedElementType(F.getArg(Idx),
4380 ElemTy);
4381 }
4382 }
4383}
4384
4385bool SPIRVEmitIntrinsicsImpl::processMaskedMemIntrinsic(IntrinsicInst &I) {
4386 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
4387
4388 if (I.getIntrinsicID() == Intrinsic::masked_gather) {
4389 if (!ST.canUseExtension(
4390 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
4391 I.getContext().emitError(
4392 &I, "llvm.masked.gather requires SPV_INTEL_masked_gather_scatter "
4393 "extension");
4394 // Replace with poison to allow compilation to continue and report error.
4395 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
4396 I.eraseFromParent();
4397 return true;
4398 }
4399
4400 IRBuilder<> B(&I);
4401
4402 Value *Ptrs = I.getArgOperand(0);
4403 Value *Mask = I.getArgOperand(1);
4404 Value *Passthru = I.getArgOperand(2);
4405
4406 // Alignment is stored as a parameter attribute, not as a regular parameter.
4407 uint32_t Alignment = I.getParamAlign(0).valueOrOne().value();
4408
4409 SmallVector<Value *, 4> Args = {Ptrs, B.getInt32(Alignment), Mask,
4410 Passthru};
4411 SmallVector<Type *, 4> Types = {I.getType(), Ptrs->getType(),
4412 Mask->getType(), Passthru->getType()};
4413
4414 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_masked_gather, Types, Args);
4415 I.replaceAllUsesWith(NewI);
4416 I.eraseFromParent();
4417 return true;
4418 }
4419
4420 if (I.getIntrinsicID() == Intrinsic::masked_scatter) {
4421 if (!ST.canUseExtension(
4422 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
4423 I.getContext().emitError(
4424 &I, "llvm.masked.scatter requires SPV_INTEL_masked_gather_scatter "
4425 "extension");
4426 // Erase the intrinsic to allow compilation to continue and report error.
4427 I.eraseFromParent();
4428 return true;
4429 }
4430
4431 IRBuilder<> B(&I);
4432
4433 Value *Values = I.getArgOperand(0);
4434 Value *Ptrs = I.getArgOperand(1);
4435 Value *Mask = I.getArgOperand(2);
4436
4437 // Alignment is stored as a parameter attribute on the ptrs parameter (arg
4438 // 1).
4439 uint32_t Alignment = I.getParamAlign(1).valueOrOne().value();
4440
4441 SmallVector<Value *, 4> Args = {Values, Ptrs, B.getInt32(Alignment), Mask};
4442 SmallVector<Type *, 3> Types = {Values->getType(), Ptrs->getType(),
4443 Mask->getType()};
4444
4445 B.CreateIntrinsic(Intrinsic::spv_masked_scatter, Types, Args);
4446 I.eraseFromParent();
4447 return true;
4448 }
4449
4450 return false;
4451}
4452
4453// SPIR-V doesn't support bitcasts involving vector boolean type. Decompose such
4454// bitcasts into element-wise operations before building instructions
4455// worklist, so new instructions are properly visited and converted to
4456// SPIR-V intrinsics.
4457void SPIRVEmitIntrinsicsImpl::preprocessBoolVectorBitcasts(Function &F) {
4458 struct BoolVecBitcast {
4459 BitCastInst *BC;
4460 FixedVectorType *BoolVecTy;
4461 bool SrcIsBoolVec;
4462 };
4463
4464 auto getAsBoolVec = [](Type *Ty) -> FixedVectorType * {
4465 auto *VTy = dyn_cast<FixedVectorType>(Ty);
4466 return (VTy && VTy->getElementType()->isIntegerTy(1)) ? VTy : nullptr;
4467 };
4468
4470 for (auto &I : instructions(F)) {
4471 auto *BC = dyn_cast<BitCastInst>(&I);
4472 if (!BC)
4473 continue;
4474 if (auto *BVTy = getAsBoolVec(BC->getSrcTy()))
4475 ToReplace.push_back({BC, BVTy, true});
4476 else if (auto *BVTy = getAsBoolVec(BC->getDestTy()))
4477 ToReplace.push_back({BC, BVTy, false});
4478 }
4479
4480 for (auto &[BC, BoolVecTy, SrcIsBoolVec] : ToReplace) {
4481 IRBuilder<> B(BC);
4482 Value *Src = BC->getOperand(0);
4483 unsigned BoolVecN = BoolVecTy->getNumElements();
4484 // Convert per element of the other side, as iN can exceed the maximum
4485 // SPIR-V integer width.
4486 Type *OtherTy = SrcIsBoolVec ? BC->getDestTy() : Src->getType();
4487 unsigned NumElts = 1;
4488 if (auto *VTy = dyn_cast<FixedVectorType>(OtherTy))
4489 NumElts = VTy->getNumElements();
4490 unsigned EltBits = OtherTy->getScalarSizeInBits();
4491 Type *EltTy = B.getIntNTy(EltBits);
4492 Type *IntTy = NumElts > 1 ? FixedVectorType::get(EltTy, NumElts) : EltTy;
4493
4494 Value *Result;
4495 if (!SrcIsBoolVec) {
4496 Value *IntVal = B.CreateBitCast(Src, IntTy);
4497 // Lane I is bit I % EltBits of element I / EltBits.
4498 auto GetLane = [&](unsigned I) {
4499 Value *Elt = IntVal;
4500 if (NumElts > 1)
4501 Elt = B.CreateExtractElement(IntVal, B.getInt32(I / EltBits));
4502 Value *Mask =
4503 ConstantInt::get(EltTy, APInt::getOneBitSet(EltBits, I % EltBits));
4504 Value *And = B.CreateAnd(Elt, Mask);
4505 return B.CreateICmpNE(And, ConstantInt::get(EltTy, 0));
4506 };
4507
4508 // Compute constant-index extracts directly, as no later pass removes
4509 // the unused lanes.
4510 for (User *U : make_early_inc_range(BC->users())) {
4511 auto *EE = dyn_cast<ExtractElementInst>(U);
4512 auto *Idx = EE ? dyn_cast<ConstantInt>(EE->getIndexOperand()) : nullptr;
4513 if (!Idx || Idx->getValue().uge(BoolVecN))
4514 continue;
4515 B.SetInsertPoint(EE);
4516 EE->replaceAllUsesWith(GetLane(Idx->getZExtValue()));
4517 EE->eraseFromParent();
4518 }
4519 if (BC->use_empty()) {
4520 BC->eraseFromParent();
4521 continue;
4522 }
4523
4524 B.SetInsertPoint(BC);
4525 Result = PoisonValue::get(BoolVecTy);
4526 for (unsigned I = 0; I < BoolVecN; ++I)
4527 Result = B.CreateInsertElement(Result, GetLane(I), B.getInt32(I));
4528 } else {
4529 // Build each element from its lanes.
4530 Value *IntVal = PoisonValue::get(IntTy);
4531 for (unsigned J = 0; J < NumElts; ++J) {
4532 Value *Elt = ConstantInt::get(EltTy, 0);
4533 for (unsigned Bit = 0; Bit < EltBits; ++Bit) {
4534 Value *Lane =
4535 B.CreateExtractElement(Src, B.getInt32(J * EltBits + Bit));
4536 Value *Ext = B.CreateZExt(Lane, EltTy);
4537 if (Bit > 0)
4538 Ext = B.CreateShl(Ext, ConstantInt::get(EltTy, Bit));
4539 Elt = B.CreateOr(Elt, Ext);
4540 }
4541 IntVal = NumElts > 1 ? B.CreateInsertElement(IntVal, Elt, B.getInt32(J))
4542 : Elt;
4543 }
4544 Result = B.CreateBitCast(IntVal, BC->getDestTy());
4545 }
4546
4547 BC->replaceAllUsesWith(Result);
4548 BC->eraseFromParent();
4549 }
4550}
4551
4552bool SPIRVEmitIntrinsicsImpl::convertMaskedMemIntrinsics(Module &M) {
4553 bool Changed = false;
4554
4555 for (Function &F : make_early_inc_range(M)) {
4556 if (!F.isIntrinsic())
4557 continue;
4558 Intrinsic::ID IID = F.getIntrinsicID();
4559 if (IID != Intrinsic::masked_gather && IID != Intrinsic::masked_scatter)
4560 continue;
4561
4562 for (User *U : make_early_inc_range(F.users())) {
4563 if (auto *II = dyn_cast<IntrinsicInst>(U))
4564 Changed |= processMaskedMemIntrinsic(*II);
4565 }
4566
4567 if (F.use_empty())
4568 F.eraseFromParent();
4569 }
4570
4571 return Changed;
4572}
4573
4574bool SPIRVEmitIntrinsicsImpl::preprocessModule(Module &M) {
4575 bool Changed = false;
4578 Type *I32Ty = Type::getInt32Ty(M.getContext());
4579 for (Function &F : M) {
4580 if (F.isDeclaration())
4581 continue;
4582 for (Instruction &I : instructions(F)) {
4583 if (IsLogical)
4584 for (Value *Op : I.operands())
4585 if (auto *CE = dyn_cast<ConstantExpr>(Op);
4586 CE && CE->getOpcode() == Instruction::GetElementPtr)
4587 GEPs.push_back(CE);
4588
4589 // Only entry-block allocations execute once per call, so a single array
4590 // object has the same meaning as the counted allocation. Allocations in
4591 // other blocks keep their lowering.
4592 auto *AI = dyn_cast<AllocaInst>(&I);
4593 if (!AI || !AI->isStaticAlloca() || !AI->isArrayAllocation() ||
4594 AI->getAddressSpace() !=
4595 storageClassToAddressSpace(SPIRV::StorageClass::Function))
4596 continue;
4597 auto *Count = cast<ConstantInt>(AI->getArraySize());
4598 // Zero sizes are legalized earlier; array lengths must fit in 32 bits.
4599 if (Count->isZero() || !Count->getValue().isIntN(32))
4600 continue;
4601 AI->setAllocatedType(
4602 ArrayType::get(AI->getAllocatedType(), Count->getZExtValue()));
4603 AI->setOperand(0, ConstantInt::get(I32Ty, 1));
4604 Changed = true;
4605 }
4606 }
4607 Changed |= convertMaskedMemIntrinsics(M);
4608
4609 // Materialize GEPs before pointer type inference so logical targets use
4610 // the typed access-chain lowering. Physical targets keep the existing
4611 // constant-expression handling.
4612 if (IsLogical) {
4613 // The list can contain both a constant and its users.
4615 GEPs, nullptr, /*RemoveDeadConstants=*/false, /*IncludeSelf=*/true);
4616 }
4617 return Changed;
4618}
4619
4620bool SPIRVEmitIntrinsicsImpl::runOnModule(Module &M) {
4621 bool Changed = preprocessModule(M);
4622
4623 parseFunDeclarations(M);
4624 insertConstantsForFPFastMathDefault(M);
4625 GVUsers.init(M);
4626
4627 TodoType.clear();
4628 for (auto &F : M)
4630 if (AccessChainErrors)
4631 report_fatal_error(Twine(toString(std::move(AccessChainErrors))), false);
4632
4633 // Specify function parameters after all functions were processed.
4634 for (auto &F : M) {
4635 // check if function parameter types are set
4636 CurrF = &F;
4637 if (!F.isDeclaration() && !F.isIntrinsic()) {
4638 IRBuilder<> B(M);
4639 processParamTypes(&F, B);
4640 }
4641 }
4642
4643 CanTodoType = false;
4644 Changed |= postprocessTypes(M);
4645
4646 if (HaveFunPtrs)
4647 Changed |= processFunctionPointers(M);
4648
4649 return Changed;
4650}
4651
4652PreservedAnalyses
4654 if (SPIRVEmitIntrinsicsImpl(TM).runOnModule(M))
4655 return PreservedAnalyses::none();
4656 return PreservedAnalyses::all();
4657}
4658
4660 return new SPIRVEmitIntrinsicsLegacy(TM);
4661}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
uint64_t Imm
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
always inline
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)
Hexagon Common GEP
iv Induction Variable Users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
if(!TBB||Cond.size()< 1) return false
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
#define T
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
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)
Definition Value.cpp:479
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...
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
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.
Definition APInt.h:235
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
const Function * getParent() const
Definition Argument.h:44
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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.
Definition BasicBlock.h:508
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
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.
Definition BasicBlock.h:236
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 ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
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
unsigned getProgramAddressSpace() const
Definition DataLayout.h:271
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)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
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.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
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.
Definition Function.cpp:356
iterator begin()
Definition Function.h:847
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:252
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
size_t arg_size() const
Definition Function.h:895
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
Argument * getArg(unsigned i) const
Definition Function.h:880
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
bool isInBounds() const
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...
Definition Globals.cpp:408
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).
Definition GlobalValue.h:60
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...
Definition IRBuilder.h:2990
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.
Definition InstVisitor.h:78
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.
Definition LLVMContext.h:76
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.
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
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.
Definition MapVector.h:39
iterator find(const KeyT &Key)
Definition MapVector.h:157
iterator end()
Definition MapVector.h:70
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:105
Metadata * getMetadata() const
Definition Metadata.h:203
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
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
iterator end() 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 end()
Definition StringMap.h:214
iterator find(StringRef Key)
Definition StringMap.h:227
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:728
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
Definition StringRef.h:683
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:653
StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
Definition StringRef.h:634
A switch()-like statement whose cases are string literals.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:657
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.
Definition Type.cpp:931
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.
Definition Triple.h:523
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:274
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
Type * getArrayElementType() const
Definition Type.h:427
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
LLVM_ABI StringRef getTargetExtName() const
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
bool isTargetExtTy() const
Return true if this is a target extension type.
Definition Type.h:205
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:314
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:272
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
Definition Type.h:399
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:271
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
Definition Type.cpp:269
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
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.
op_range operands()
Definition User.h:267
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:21
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator user_begin()
Definition Value.h:404
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
iterator_range< user_iterator > users()
Definition Value.h:428
user_iterator user_end()
Definition Value.h:412
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:809
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
bool user_empty() const
Definition Value.h:391
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#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.
@ Entry
Definition COFF.h:862
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
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)
Definition MCAsmInfo.h:51
initializer< Ty > init(const Ty &Val)
@ Init
Initialization function, sets up the coroutine frame.
Definition CodeView.h:644
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:118
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.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
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)
Definition SPIRVUtils.h:417
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
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,...
Definition STLExtras.h:2575
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:388
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
constexpr T divideFloorSigned(U Numerator, V Denominator)
Returns the integer floor(Numerator / Denominator).
Definition MathExtras.h:428
CallInst * buildIntrWithMD(Intrinsic::ID IntrID, ArrayRef< Type * > Types, Value *Arg, Value *Arg2, ArrayRef< Constant * > Imms, IRBuilder<> &B)
bool isUntypedPointerVectorTy(const Type *T)
Definition SPIRVUtils.h:381
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
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...
Definition STLExtras.h:649
bool sortBlocks(Function &F)
FPDecorationId
Definition SPIRVUtils.h:583
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
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.
Definition Error.h:1321
SPIRV::MemorySemantics::MemorySemantics getMemSemanticsForStorageClass(SPIRV::StorageClass::StorageClass SC)
constexpr unsigned storageClassToAddressSpace(SPIRV::StorageClass::StorageClass SC)
Definition SPIRVUtils.h:234
bool isNestedPointer(const Type *Ty)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
Function * getOrCreateBackendServiceFunction(Module &M)
MetadataAsValue * buildMD(Value *Arg)
Definition SPIRVUtils.h:549
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)
Definition SPIRVUtils.h:531
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
Type * getTypedPointerWrapper(Type *ElemTy, unsigned AS)
Definition SPIRVUtils.h:412
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
bool isVector1(Type *Ty)
Definition SPIRVUtils.h:505
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:376
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
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...
Definition Casting.h:547
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
uint32_t getMemoryAccessAlignment(Align A)
Definition SPIRVUtils.h:353
@ And
Bitwise or logical AND of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
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...
Definition STLExtras.h:2028
bool isLongVectorEXT(const Type *Ty, bool CanUseVector16=true)
Definition SPIRVUtils.h:522
Type * parseBasicTypeName(StringRef &TypeName, LLVMContext &Ctx)
DWARFExpression::Operation Op
Type * getPointeeTypeByAttr(Argument *Arg)
Definition SPIRVUtils.h:401
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
bool hasPointeeTypeAttr(Argument *Arg)
Definition SPIRVUtils.h:396
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...
Definition Local.cpp:537
constexpr unsigned BitWidth
bool isEquivalentTypes(Type *Ty1, Type *Ty2)
Definition SPIRVUtils.h:467
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool hasInitializer(const GlobalVariable *GV)
Definition SPIRVUtils.h:357
bool isPointerTyOrWrapper(const Type *Ty)
Definition SPIRVUtils.h:424
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:31
bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID)
PoisonValue * getNormalizedPoisonValue(Type *Ty, bool CanUseAnyVectorRank)
Definition SPIRVUtils.h:544
bool isUntypedPointerTy(const Type *T)
Definition SPIRVUtils.h:371
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.
Definition MIRParser.h:39
#define N
static size_t computeFPFastMathDefaultInfoVecIndex(size_t BitWidth)
Definition SPIRVUtils.h:149