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 "SPIRVEmitIntrinsics.h"
15#include "SPIRV.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"
23#include "llvm/ADT/StringSet.h"
25#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/InstVisitor.h"
28#include "llvm/IR/IntrinsicsSPIRV.h"
31#include "llvm/IR/Value.h"
33#include "llvm/Support/Debug.h"
35
36#include <cassert>
37#include <optional>
38#include <queue>
39
40// This pass performs the following transformation on LLVM IR level required
41// for the following translation to SPIR-V:
42// - replaces direct usages of aggregate constants with target-specific
43// intrinsics;
44// - replaces aggregates-related instructions (extract/insert, ld/st, etc)
45// with a target-specific intrinsics;
46// - emits intrinsics for the global variable initializers since IRTranslator
47// doesn't handle them and it's not very convenient to translate them
48// ourselves;
49// - emits intrinsics to keep track of the string names assigned to the values;
50// - emits intrinsics to keep track of constants (this is necessary to have an
51// LLVM IR constant after the IRTranslation is completed) for their further
52// deduplication;
53// - emits intrinsics to keep track of original LLVM types of the values
54// to be able to emit proper SPIR-V types eventually.
55//
56// TODO: consider removing spv.track.constant in favor of spv.assign.type.
57
58using namespace llvm;
59using namespace llvm::PatternMatch;
60
61#define DEBUG_TYPE "spirv-emit-intrinsics"
62
63static cl::opt<bool>
64 SpirvEmitOpNames("spirv-emit-op-names",
65 cl::desc("Emit OpName for all instructions"),
66 cl::init(false));
67
68namespace llvm::SPIRV {
69#define GET_BuiltinGroup_DECL
70#include "SPIRVGenTables.inc"
71} // namespace llvm::SPIRV
72
73namespace {
74// This class keeps track of which functions reference which global variables.
75class GlobalVariableUsers {
76 template <typename T1, typename T2>
77 using OneToManyMapTy = DenseMap<T1, SmallPtrSet<T2, 4>>;
78
79 OneToManyMapTy<const GlobalVariable *, const Function *> GlobalIsUsedByFun;
80
81 void collectGlobalUsers(
82 const GlobalVariable *GV,
83 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
84 &GlobalIsUsedByGlobal) {
86 while (!Stack.empty()) {
87 const Value *V = Stack.pop_back_val();
88
89 if (const Instruction *I = dyn_cast<Instruction>(V)) {
90 GlobalIsUsedByFun[GV].insert(I->getFunction());
91 continue;
92 }
93
94 if (const GlobalVariable *UserGV = dyn_cast<GlobalVariable>(V)) {
95 GlobalIsUsedByGlobal[GV].insert(UserGV);
96 continue;
97 }
98
99 if (const Constant *C = dyn_cast<Constant>(V))
100 Stack.append(C->user_begin(), C->user_end());
101 }
102 }
103
104 bool propagateGlobalToGlobalUsers(
105 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
106 &GlobalIsUsedByGlobal) {
108 bool Changed = false;
109 for (auto &[GV, UserGlobals] : GlobalIsUsedByGlobal) {
110 OldUsersGlobals.assign(UserGlobals.begin(), UserGlobals.end());
111 for (const GlobalVariable *UserGV : OldUsersGlobals) {
112 auto It = GlobalIsUsedByGlobal.find(UserGV);
113 if (It == GlobalIsUsedByGlobal.end())
114 continue;
115 Changed |= set_union(UserGlobals, It->second);
116 }
117 }
118 return Changed;
119 }
120
121 void propagateGlobalToFunctionReferences(
122 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
123 &GlobalIsUsedByGlobal) {
124 for (auto &[GV, UserGlobals] : GlobalIsUsedByGlobal) {
125 auto &UserFunctions = GlobalIsUsedByFun[GV];
126 for (const GlobalVariable *UserGV : UserGlobals) {
127 auto It = GlobalIsUsedByFun.find(UserGV);
128 if (It == GlobalIsUsedByFun.end())
129 continue;
130 set_union(UserFunctions, It->second);
131 }
132 }
133 }
134
135public:
136 void init(Module &M) {
137 // Collect which global variables are referenced by which global variables
138 // and which functions reference each global variables.
139 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
140 GlobalIsUsedByGlobal;
141 GlobalIsUsedByFun.clear();
142 for (GlobalVariable &GV : M.globals())
143 collectGlobalUsers(&GV, GlobalIsUsedByGlobal);
144
145 // Compute indirect references by iterating until a fixed point is reached.
146 while (propagateGlobalToGlobalUsers(GlobalIsUsedByGlobal))
147 (void)0;
148
149 propagateGlobalToFunctionReferences(GlobalIsUsedByGlobal);
150 }
151
152 using FunctionSetType = typename decltype(GlobalIsUsedByFun)::mapped_type;
153 const FunctionSetType &
154 getTransitiveUserFunctions(const GlobalVariable &GV) const {
155 auto It = GlobalIsUsedByFun.find(&GV);
156 if (It != GlobalIsUsedByFun.end())
157 return It->second;
158
159 static const FunctionSetType Empty{};
160 return Empty;
161 }
162};
163
164static bool isaGEP(const Value *V) {
166}
167
168// If Ty is a byte-addressing type, return the multiplier for the offset.
169// Otherwise return std::nullopt.
170static std::optional<uint64_t> getByteAddressingMultiplier(Type *Ty) {
171 if (Ty == IntegerType::getInt8Ty(Ty->getContext())) {
172 return 1;
173 }
174 if (auto *AT = dyn_cast<ArrayType>(Ty)) {
175 if (AT->getElementType() == IntegerType::getInt8Ty(Ty->getContext())) {
176 return AT->getNumElements();
177 }
178 }
179 return std::nullopt;
180}
181
182class SPIRVEmitIntrinsicsImpl
183 : public InstVisitor<SPIRVEmitIntrinsicsImpl, Instruction *> {
184 const SPIRVTargetMachine &TM;
185 SPIRVGlobalRegistry *GR = nullptr;
186 Function *CurrF = nullptr;
187 bool TrackConstants = true;
188 bool HaveFunPtrs = false;
189 DenseMap<Instruction *, Constant *> AggrConsts;
190 DenseMap<Instruction *, Type *> AggrConstTypes;
191 SmallPtrSet<Instruction *, 0> AggrStores;
192 GlobalVariableUsers GVUsers;
193 SmallPtrSet<Value *, 0> Named;
194
195 // map of function declarations to <pointer arg index => element type>
196 DenseMap<Function *, SmallVector<std::pair<unsigned, Type *>>> FDeclPtrTys;
197
198 // a register of Instructions that don't have a complete type definition
199 bool CanTodoType = true;
200 unsigned TodoTypeSz = 0;
201 DenseMap<Value *, bool> TodoType;
202 void insertTodoType(Value *Op) {
203 // TODO: add isa<CallInst>(Op) to no-insert
204 if (CanTodoType && !isaGEP(Op)) {
205 auto It = TodoType.try_emplace(Op, true);
206 if (It.second)
207 ++TodoTypeSz;
208 }
209 }
210 void eraseTodoType(Value *Op) {
211 auto It = TodoType.find(Op);
212 if (It != TodoType.end() && It->second) {
213 It->second = false;
214 --TodoTypeSz;
215 }
216 }
217 bool isTodoType(Value *Op) {
218 if (isaGEP(Op))
219 return false;
220 auto It = TodoType.find(Op);
221 return It != TodoType.end() && It->second;
222 }
223 // a register of Instructions that were visited by deduceOperandElementType()
224 // to validate operand types with an instruction
225 SmallPtrSet<Instruction *, 0> TypeValidated;
226
227 // well known result types of builtins
228 enum WellKnownTypes { Event };
229
230 // deduce element type of untyped pointers
231 Type *deduceElementType(Value *I, bool UnknownElemTypeI8);
232 Type *deduceElementTypeHelper(Value *I, bool UnknownElemTypeI8);
233 Type *deduceElementTypeHelper(Value *I, SmallPtrSetImpl<Value *> &Visited,
234 bool UnknownElemTypeI8,
235 bool IgnoreKnownType = false);
236 Type *deduceElementTypeByValueDeep(Type *ValueTy, Value *Operand,
237 bool UnknownElemTypeI8);
238 Type *deduceElementTypeByValueDeep(Type *ValueTy, Value *Operand,
239 SmallPtrSetImpl<Value *> &Visited,
240 bool UnknownElemTypeI8);
241 Type *deduceElementTypeByUsersDeep(Value *Op,
242 SmallPtrSetImpl<Value *> &Visited,
243 bool UnknownElemTypeI8);
244 void maybeAssignPtrType(Type *&Ty, Value *I, Type *RefTy,
245 bool UnknownElemTypeI8);
246
247 // deduce nested types of composites
248 Type *deduceNestedTypeHelper(User *U, bool UnknownElemTypeI8);
249 Type *deduceNestedTypeHelper(User *U, Type *Ty,
250 SmallPtrSetImpl<Value *> &Visited,
251 bool UnknownElemTypeI8);
252
253 // deduce Types of operands of the Instruction if possible
254 void
255 deduceOperandElementType(Instruction *I,
256 SmallPtrSetImpl<Instruction *> *IncompleteRets,
257 const SmallPtrSetImpl<Value *> *AskOps = nullptr,
258 bool IsPostprocessing = false);
259
260 void preprocessCompositeConstants(IRBuilder<> &B);
261 Value *lowerUndefOrPoison(Value *Op, IRBuilder<> &B, bool HasPoisonExt);
262 void preprocessUndefsAndPoisons(IRBuilder<> &B);
263 void insertCompositeAggregateArms(Instruction *I, IRBuilder<> &B);
264 void simplifyNullAddrSpaceCasts();
265
266 Type *reconstructType(Value *Op, bool UnknownElemTypeI8,
267 bool IsPostprocessing);
268
269 void replaceMemInstrUses(Instruction *Old, Instruction *New, IRBuilder<> &B);
270 void processInstrAfterVisit(Instruction *I, IRBuilder<> &B);
271 bool insertAssignPtrTypeIntrs(Instruction *I, IRBuilder<> &B,
272 bool UnknownElemTypeI8);
273 void insertAssignTypeIntrs(Instruction *I, IRBuilder<> &B);
274 void insertAssignPtrTypeTargetExt(TargetExtType *AssignedType, Value *V,
275 IRBuilder<> &B);
276 void replacePointerOperandWithPtrCast(Instruction *I, Value *Pointer,
277 Type *ExpectedElementType,
278 unsigned OperandToReplace,
279 IRBuilder<> &B);
280 void insertPtrCastOrAssignTypeInstr(Instruction *I, IRBuilder<> &B);
281 bool shouldTryToAddMemAliasingDecoration(Instruction *Inst);
282 void insertSpirvDecorations(Instruction *I, IRBuilder<> &B);
283 void insertConstantsForFPFastMathDefault(Module &M);
284 Value *buildSpvUndefComposite(Type *AggrTy, IRBuilder<> &B);
285 void reconstructAggregateReturns(Function &Func, IRBuilder<> &B);
286 void processGlobalValue(GlobalVariable &GV, IRBuilder<> &B);
287 void processParamTypes(Function *F, IRBuilder<> &B);
288 void processParamTypesByFunHeader(Function *F, IRBuilder<> &B);
289 Type *deduceFunParamElementType(Function *F, unsigned OpIdx);
290 Type *deduceFunParamElementType(Function *F, unsigned OpIdx,
291 SmallPtrSetImpl<Function *> &FVisited);
292
293 bool deduceOperandElementTypeCalledFunction(
294 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
295 Type *&KnownElemTy, bool &Incomplete);
296 void deduceOperandElementTypeFunctionPointer(
297 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
298 Type *&KnownElemTy, bool IsPostprocessing);
299 bool deduceOperandElementTypeFunctionRet(
300 Instruction *I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
301 const SmallPtrSetImpl<Value *> *AskOps, bool IsPostprocessing,
302 Type *&KnownElemTy, Value *Op, Function *F);
303
304 CallInst *buildSpvPtrcast(Function *F, Value *Op, Type *ElemTy);
305 void replaceUsesOfWithSpvPtrcast(Value *Op, Type *ElemTy, Instruction *I,
306 DenseMap<Function *, CallInst *> Ptrcasts);
307 void propagateElemType(Value *Op, Type *ElemTy,
308 DenseSet<std::pair<Value *, Value *>> &VisitedSubst);
309 void
310 propagateElemTypeRec(Value *Op, Type *PtrElemTy, Type *CastElemTy,
311 DenseSet<std::pair<Value *, Value *>> &VisitedSubst);
312 void propagateElemTypeRec(Value *Op, Type *PtrElemTy, Type *CastElemTy,
313 DenseSet<std::pair<Value *, Value *>> &VisitedSubst,
314 SmallPtrSetImpl<Value *> &Visited,
315 DenseMap<Function *, CallInst *> Ptrcasts);
316
317 void replaceAllUsesWith(Value *Src, Value *Dest, bool DeleteOld = true);
318 void replaceAllUsesWithAndErase(IRBuilder<> &B, Instruction *Src,
319 Instruction *Dest, bool DeleteOld = true);
320
321 void applyDemangledPtrArgTypes(IRBuilder<> &B);
322
323 GetElementPtrInst *simplifyZeroLengthArrayGepInst(GetElementPtrInst *GEP);
324
325 bool runOnFunction(Function &F);
326 bool postprocessTypes(Module &M);
327 bool processFunctionPointers(Module &M);
328 void parseFunDeclarations(Module &M);
329 void useRoundingMode(ConstrainedFPIntrinsic *FPI, IRBuilder<> &B);
330 bool processMaskedMemIntrinsic(IntrinsicInst &I);
331 bool convertMaskedMemIntrinsics(Module &M);
332 void preprocessBoolVectorBitcasts(Function &F);
333
334 void emitUnstructuredLoopControls(Function &F, IRBuilder<> &B);
335
336 // Tries to walk the type accessed by the given GEP instruction.
337 // For each nested type access, one of the 2 callbacks is called:
338 // - OnLiteralIndexing when the index is a known constant value.
339 // Parameters:
340 // PointedType: the pointed type resulting of this indexing.
341 // If the parent type is an array, this is the index in the array.
342 // If the parent type is a struct, this is the field index.
343 // Index: index of the element in the parent type.
344 // - OnDynamnicIndexing when the index is a non-constant value.
345 // This callback is only called when indexing into an array.
346 // Parameters:
347 // ElementType: the type of the elements stored in the parent array.
348 // Offset: the Value* containing the byte offset into the array.
349 // Multiplier: a scaling factor for the offset.
350 // Return true if an error occurred during the walk, false otherwise.
351 bool walkLogicalAccessChain(
352 GetElementPtrInst &GEP,
353 const std::function<void(Type *PointedType, uint64_t Index)>
354 &OnLiteralIndexing,
355 const std::function<void(Type *ElementType, Value *Offset,
356 uint64_t Multiplier)> &OnDynamicIndexing);
357
358 bool walkLogicalAccessChainDynamic(
359 Type *CurType, Value *Operand, uint64_t Multiplier,
360 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing,
361 const std::function<void(Type *, Value *, uint64_t)> &OnDynamicIndexing);
362
363 bool walkLogicalAccessChainConstant(
364 Type *CurType, uint64_t Offset,
365 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing);
366
367 // Returns the type accessed using the given GEP instruction by relying
368 // on the GEP type.
369 // FIXME: GEP types are not supposed to be used to retrieve the pointed
370 // type. This must be fixed.
371 Type *getGEPType(GetElementPtrInst *GEP);
372
373 // Returns the type accessed using the given GEP instruction by walking
374 // the source type using the GEP indices.
375 // FIXME: without help from the frontend, this method cannot reliably retrieve
376 // the stored type, nor can robustly determine the depth of the type
377 // we are accessing.
378 Type *getGEPTypeLogical(GetElementPtrInst *GEP);
379
380 Instruction *buildLogicalAccessChainFromGEP(GetElementPtrInst &GEP);
381
382public:
383 SPIRVEmitIntrinsicsImpl(const SPIRVTargetMachine &TM) : TM(TM) {}
384 Instruction *visitInstruction(Instruction &I) { return &I; }
385 Instruction *visitSwitchInst(SwitchInst &I);
386 Instruction *visitGetElementPtrInst(GetElementPtrInst &I);
387 Instruction *visitIntrinsicInst(IntrinsicInst &I);
388 Instruction *visitBitCastInst(BitCastInst &I);
389 Instruction *visitInsertElementInst(InsertElementInst &I);
390 Instruction *visitExtractElementInst(ExtractElementInst &I);
391 Instruction *visitInsertValueInst(InsertValueInst &I);
392 Instruction *visitExtractValueInst(ExtractValueInst &I);
393 Instruction *visitLoadInst(LoadInst &I);
394 Instruction *visitStoreInst(StoreInst &I);
395 Instruction *visitAllocaInst(AllocaInst &I);
396 Instruction *visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
397 Instruction *visitUnreachableInst(UnreachableInst &I);
398 Instruction *visitCallInst(CallInst &I);
399
400 bool runOnModule(Module &M);
401};
402
403class SPIRVEmitIntrinsicsLegacy : public ModulePass {
404 const SPIRVTargetMachine &TM;
405
406public:
407 static char ID;
408 SPIRVEmitIntrinsicsLegacy(const SPIRVTargetMachine &TM)
409 : ModulePass(ID), TM(TM) {}
410
411 StringRef getPassName() const override { return "SPIRV emit intrinsics"; }
412
413 bool runOnModule(Module &M) override {
414 return SPIRVEmitIntrinsicsImpl(TM).runOnModule(M);
415 }
416};
417
418bool isConvergenceIntrinsic(const Instruction *I) {
419 return match(I, m_AnyIntrinsic<Intrinsic::experimental_convergence_entry,
420 Intrinsic::experimental_convergence_loop,
421 Intrinsic::experimental_convergence_anchor>());
422}
423
424bool expectIgnoredInIRTranslation(const Instruction *I) {
425 return match(I, m_AnyIntrinsic<Intrinsic::invariant_start,
426 Intrinsic::spv_resource_handlefrombinding,
427 Intrinsic::spv_resource_getbasepointer,
428 Intrinsic::spv_resource_getpointer>());
429}
430
431// Returns the source pointer from `I` ignoring intermediate ptrcast.
432Value *getPointerRoot(Value *I) {
433 Value *V;
435 return getPointerRoot(V);
436 return I;
437}
438
439} // namespace
440
441char SPIRVEmitIntrinsicsLegacy::ID = 0;
442
443INITIALIZE_PASS(SPIRVEmitIntrinsicsLegacy, "spirv-emit-intrinsics",
444 "SPIRV emit intrinsics", false, false)
445
446static inline bool isAssignTypeInstr(const Instruction *I) {
448}
449
454
455static bool isAggrConstForceInt32(const Value *V) {
456 bool IsAggrZero =
457 isa<ConstantAggregateZero>(V) && !V->getType()->isVectorTy();
458 bool IsUndefAggregate = isa<UndefValue>(V) && V->getType()->isAggregateType();
459 return isa<ConstantArray>(V) || isa<ConstantStruct>(V) ||
460 isa<ConstantDataArray>(V) || IsAggrZero || IsUndefAggregate;
461}
462
468
470 if (isa<PHINode>(I))
471 B.SetInsertPoint(I->getParent()->getFirstNonPHIOrDbgOrAlloca());
472 else
473 B.SetInsertPoint(I);
474}
475
477 B.SetCurrentDebugLocation(I->getDebugLoc());
478 if (I->getType()->isVoidTy())
479 B.SetInsertPoint(I->getNextNode());
480 else
481 B.SetInsertPoint(*I->getInsertionPointAfterDef());
482}
483
489
490static inline void reportFatalOnTokenType(const Instruction *I) {
491 if (I->getType()->isTokenTy())
492 report_fatal_error("A token is encountered but SPIR-V without extensions "
493 "does not support token type",
494 false);
495}
496
498 if (!I->hasName() || I->getType()->isAggregateType() ||
499 expectIgnoredInIRTranslation(I))
500 return;
501
502 // We want to be conservative when adding the names because they can interfere
503 // with later optimizations.
504 bool KeepName = SpirvEmitOpNames;
505 if (!KeepName) {
506 if (isa<AllocaInst>(I)) {
507 KeepName = true;
508 } else if (auto *CI = dyn_cast<CallBase>(I)) {
509 Function *F = CI->getCalledFunction();
510 if (F && F->getName().starts_with("llvm.spv.alloca"))
511 KeepName = true;
512 }
513 }
514
515 if (!KeepName)
516 return;
517
520 LLVMContext &Ctx = I->getContext();
521 std::vector<Value *> Args = {
523 Ctx, MDNode::get(Ctx, MDString::get(Ctx, I->getName())))};
524 B.CreateIntrinsic(Intrinsic::spv_assign_name, {I->getType()}, Args);
525}
526
527void SPIRVEmitIntrinsicsImpl::replaceAllUsesWith(Value *Src, Value *Dest,
528 bool DeleteOld) {
529 GR->replaceAllUsesWith(Src, Dest, DeleteOld);
530 // Update uncomplete type records if any
531 if (isTodoType(Src)) {
532 if (DeleteOld)
533 eraseTodoType(Src);
534 insertTodoType(Dest);
535 }
536}
537
538void SPIRVEmitIntrinsicsImpl::replaceAllUsesWithAndErase(IRBuilder<> &B,
539 Instruction *Src,
540 Instruction *Dest,
541 bool DeleteOld) {
542 replaceAllUsesWith(Src, Dest, DeleteOld);
543 std::string Name = Src->hasName() ? Src->getName().str() : "";
544 Src->eraseFromParent();
545 if (!Name.empty()) {
546 Dest->setName(Name);
547 if (Named.insert(Dest).second)
548 emitAssignName(Dest, B);
549 }
550}
551
553 return SI && F->getCallingConv() == CallingConv::SPIR_KERNEL &&
554 isPointerTy(SI->getValueOperand()->getType()) &&
555 isa<Argument>(SI->getValueOperand());
556}
557
558// A pointer-typed local holds a pointer, so its deduced pointee must stay a
559// pointer.
561 using namespace PatternMatch;
562 V = V->stripPointerCasts();
563 if (auto *AI = dyn_cast<AllocaInst>(V))
564 return isUntypedPointerTy(AI->getAllocatedType());
565 return match(
567}
568
569// Maybe restore original function return type.
571 Type *Ty) {
573 if (!CI || CI->isIndirectCall() || CI->isInlineAsm() ||
575 return Ty;
576 if (Type *OriginalTy = GR->findMutated(CI->getCalledFunction()))
577 return OriginalTy;
578 return Ty;
579}
580
581// Reconstruct type with nested element types according to deduced type info.
582// Return nullptr if no detailed type info is available.
583Type *SPIRVEmitIntrinsicsImpl::reconstructType(Value *Op,
584 bool UnknownElemTypeI8,
585 bool IsPostprocessing) {
586 Type *Ty = Op->getType();
587 if (auto *OpI = dyn_cast<Instruction>(Op)) {
588 Ty = restoreMutatedType(GR, OpI, Ty);
589 if (auto It = AggrConstTypes.find(OpI); It != AggrConstTypes.end())
590 Ty = It->second;
591 }
592 if (!isUntypedPointerTy(Ty))
593 return Ty;
594 // try to find the pointee type
595 if (Type *NestedTy = GR->findDeducedElementType(Op))
597 // not a pointer according to the type info (e.g., Event object)
598 CallInst *CI = GR->findAssignPtrTypeInstr(Op);
599 if (CI) {
600 MetadataAsValue *MD = cast<MetadataAsValue>(CI->getArgOperand(1));
601 return cast<ConstantAsMetadata>(MD->getMetadata())->getType();
602 }
603 if (UnknownElemTypeI8) {
604 if (!IsPostprocessing)
605 insertTodoType(Op);
606 return getTypedPointerWrapper(IntegerType::getInt8Ty(Op->getContext()),
608 }
609 return nullptr;
610}
611
612CallInst *SPIRVEmitIntrinsicsImpl::buildSpvPtrcast(Function *F, Value *Op,
613 Type *ElemTy) {
614 IRBuilder<> B(Op->getContext());
615 if (auto *OpI = dyn_cast<Instruction>(Op)) {
616 // spv_ptrcast's argument Op denotes an instruction that generates
617 // a value, and we may use getInsertionPointAfterDef()
619 } else if (auto *OpA = dyn_cast<Argument>(Op)) {
620 B.SetInsertPointPastAllocas(OpA->getParent());
621 B.SetCurrentDebugLocation(DebugLoc());
622 } else {
623 B.SetInsertPoint(F->getEntryBlock().getFirstNonPHIOrDbgOrAlloca());
624 }
625 Type *OpTy = Op->getType();
626 SmallVector<Type *, 2> Types = {OpTy, OpTy};
627 SmallVector<Value *, 2> Args = {Op, buildMD(getNormalizedPoisonValue(ElemTy)),
628 B.getInt32(getPointerAddressSpace(OpTy))};
629 CallInst *PtrCasted =
630 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_ptrcast, {Types}, Args);
631 GR->buildAssignPtr(B, ElemTy, PtrCasted);
632 return PtrCasted;
633}
634
635void SPIRVEmitIntrinsicsImpl::replaceUsesOfWithSpvPtrcast(
636 Value *Op, Type *ElemTy, Instruction *I,
637 DenseMap<Function *, CallInst *> Ptrcasts) {
638 Function *F = I->getParent()->getParent();
639 CallInst *PtrCastedI = nullptr;
640 auto It = Ptrcasts.find(F);
641 if (It == Ptrcasts.end()) {
642 PtrCastedI = buildSpvPtrcast(F, Op, ElemTy);
643 Ptrcasts[F] = PtrCastedI;
644 } else {
645 PtrCastedI = It->second;
646 }
647 I->replaceUsesOfWith(Op, PtrCastedI);
648}
649
650void SPIRVEmitIntrinsicsImpl::propagateElemType(
651 Value *Op, Type *ElemTy,
652 DenseSet<std::pair<Value *, Value *>> &VisitedSubst) {
653 DenseMap<Function *, CallInst *> Ptrcasts;
654 SmallVector<User *> Users(Op->users());
655 for (auto *U : Users) {
656 if (!isa<Instruction>(U) || isSpvIntrinsic(U))
657 continue;
658 if (!VisitedSubst.insert(std::make_pair(U, Op)).second)
659 continue;
661 // If the instruction was validated already, we need to keep it valid by
662 // keeping current Op type.
663 if (isaGEP(UI) || TypeValidated.find(UI) != TypeValidated.end())
664 replaceUsesOfWithSpvPtrcast(Op, ElemTy, UI, Ptrcasts);
665 }
666}
667
668void SPIRVEmitIntrinsicsImpl::propagateElemTypeRec(
669 Value *Op, Type *PtrElemTy, Type *CastElemTy,
670 DenseSet<std::pair<Value *, Value *>> &VisitedSubst) {
671 SmallPtrSet<Value *, 0> Visited;
672 DenseMap<Function *, CallInst *> Ptrcasts;
673 propagateElemTypeRec(Op, PtrElemTy, CastElemTy, VisitedSubst, Visited,
674 std::move(Ptrcasts));
675}
676
677void SPIRVEmitIntrinsicsImpl::propagateElemTypeRec(
678 Value *Op, Type *PtrElemTy, Type *CastElemTy,
679 DenseSet<std::pair<Value *, Value *>> &VisitedSubst,
680 SmallPtrSetImpl<Value *> &Visited,
681 DenseMap<Function *, CallInst *> Ptrcasts) {
682 if (!Visited.insert(Op).second)
683 return;
684 SmallVector<User *> Users(Op->users());
685 for (auto *U : Users) {
686 if (!isa<Instruction>(U) || isSpvIntrinsic(U))
687 continue;
688 if (!VisitedSubst.insert(std::make_pair(U, Op)).second)
689 continue;
691 // If the instruction was validated already, we need to keep it valid by
692 // keeping current Op type.
693 if (isaGEP(UI) || TypeValidated.find(UI) != TypeValidated.end())
694 replaceUsesOfWithSpvPtrcast(Op, CastElemTy, UI, Ptrcasts);
695 }
696}
697
698// Set element pointer type to the given value of ValueTy and tries to
699// specify this type further (recursively) by Operand value, if needed.
700
701Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByValueDeep(
702 Type *ValueTy, Value *Operand, bool UnknownElemTypeI8) {
703 SmallPtrSet<Value *, 0> Visited;
704 return deduceElementTypeByValueDeep(ValueTy, Operand, Visited,
705 UnknownElemTypeI8);
706}
707
708Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByValueDeep(
709 Type *ValueTy, Value *Operand, SmallPtrSetImpl<Value *> &Visited,
710 bool UnknownElemTypeI8) {
711 Type *Ty = ValueTy;
712 if (Operand) {
713 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
714 if (Type *NestedTy =
715 deduceElementTypeHelper(Operand, Visited, UnknownElemTypeI8))
716 Ty = getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
717 } else {
718 Ty = deduceNestedTypeHelper(dyn_cast<User>(Operand), Ty, Visited,
719 UnknownElemTypeI8);
720 }
721 }
722 return Ty;
723}
724
725// Traverse User instructions to deduce an element pointer type of the operand.
726Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByUsersDeep(
727 Value *Op, SmallPtrSetImpl<Value *> &Visited, bool UnknownElemTypeI8) {
728 if (!Op || !isPointerTy(Op->getType()) || isa<ConstantPointerNull>(Op) ||
730 return nullptr;
731
732 if (auto ElemTy = getPointeeType(Op->getType()))
733 return ElemTy;
734
735 // maybe we already know operand's element type
736 if (Type *KnownTy = GR->findDeducedElementType(Op))
737 return KnownTy;
738
739 for (User *OpU : Op->users()) {
740 if (Instruction *Inst = dyn_cast<Instruction>(OpU)) {
741 if (Type *Ty = deduceElementTypeHelper(Inst, Visited, UnknownElemTypeI8))
742 return Ty;
743 }
744 }
745 return nullptr;
746}
747
748// Implements what we know in advance about intrinsics and builtin calls
749// TODO: consider feasibility of this particular case to be generalized by
750// encoding knowledge about intrinsics and builtin calls by corresponding
751// specification rules
753 Function *CalledF, unsigned OpIdx) {
754 if ((DemangledName.starts_with("__spirv_ocl_printf(") ||
755 DemangledName.starts_with("printf(")) &&
756 OpIdx == 0)
757 return IntegerType::getInt8Ty(CalledF->getContext());
758 return nullptr;
759}
760
761// Deduce and return a successfully deduced Type of the Instruction,
762// or nullptr otherwise.
763Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeHelper(Value *I,
764 bool UnknownElemTypeI8) {
765 SmallPtrSet<Value *, 0> Visited;
766 return deduceElementTypeHelper(I, Visited, UnknownElemTypeI8);
767}
768
769void SPIRVEmitIntrinsicsImpl::maybeAssignPtrType(Type *&Ty, Value *Op,
770 Type *RefTy,
771 bool UnknownElemTypeI8) {
772 if (isUntypedPointerTy(RefTy)) {
773 if (!UnknownElemTypeI8)
774 return;
775 insertTodoType(Op);
777 return;
778 }
779 Ty = RefTy;
780}
781
782bool SPIRVEmitIntrinsicsImpl::walkLogicalAccessChainDynamic(
783 Type *CurType, Value *Operand, uint64_t Multiplier,
784 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing,
785 const std::function<void(Type *, Value *, uint64_t)> &OnDynamicIndexing) {
786 // Dynamic indexing into a struct is not possible.
787 // We know that we must be accessing the first element
788 // of the struct if the current type is a struct.
789 // Try to find the first array type that is at offset 0 in the struct.
790 while (auto *ST = dyn_cast<StructType>(CurType)) {
791 if (ST->getNumElements() == 0)
792 break;
793 CurType = ST->getElementType(0);
794 OnLiteralIndexing(CurType, 0);
795 }
796
797 assert(CurType);
798 ArrayType *AT = dyn_cast<ArrayType>(CurType);
799 // Operand is not constant. Either we have an array and accept it, or we
800 // give up.
801 if (AT)
802 OnDynamicIndexing(AT->getElementType(), Operand, Multiplier);
803 return AT == nullptr;
804}
805
806bool SPIRVEmitIntrinsicsImpl::walkLogicalAccessChainConstant(
807 Type *CurType, uint64_t Offset,
808 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing) {
809 auto &DL = CurrF->getDataLayout();
810
811 do {
812 if (ArrayType *AT = dyn_cast<ArrayType>(CurType)) {
813 uint64_t EltTypeSize = DL.getTypeAllocSize(AT->getElementType());
814 assert(Offset < AT->getNumElements() * EltTypeSize);
815 uint64_t Index = Offset / EltTypeSize;
816 Offset = Offset - (Index * EltTypeSize);
817 CurType = AT->getElementType();
818 OnLiteralIndexing(CurType, Index);
819 } else if (StructType *ST = dyn_cast<StructType>(CurType)) {
820 uint32_t StructSize = DL.getTypeSizeInBits(ST) / 8;
821 assert(Offset < StructSize);
822 (void)StructSize;
823 const auto &STL = DL.getStructLayout(ST);
824 unsigned Element = STL->getElementContainingOffset(Offset);
825 Offset -= STL->getElementOffset(Element);
826 CurType = ST->getElementType(Element);
827 OnLiteralIndexing(CurType, Element);
828 } else if (auto *VT = dyn_cast<FixedVectorType>(CurType)) {
829 Type *EltTy = VT->getElementType();
830 TypeSize EltSizeBits = DL.getTypeSizeInBits(EltTy);
831 assert(EltSizeBits % 8 == 0 &&
832 "Element type size in bits must be a multiple of 8.");
833 uint32_t EltTypeSize = EltSizeBits / 8;
834 assert(Offset < VT->getNumElements() * EltTypeSize);
835 uint64_t Index = Offset / EltTypeSize;
836 Offset -= Index * EltTypeSize;
837 CurType = EltTy;
838 OnLiteralIndexing(CurType, Index);
839 } else {
840 // Unknown composite kind; give up.
841 return true;
842 }
843 } while (Offset > 0);
844
845 return false;
846}
847
848bool SPIRVEmitIntrinsicsImpl::walkLogicalAccessChain(
849 GetElementPtrInst &GEP,
850 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing,
851 const std::function<void(Type *, Value *, uint64_t)> &OnDynamicIndexing) {
852 // We only rewrite byte-addressing GEP. Other should be left as-is.
853 // Valid byte-addressing GEP must always have a single index.
854 std::optional<uint64_t> MultiplierOpt =
855 getByteAddressingMultiplier(GEP.getSourceElementType());
856 assert(MultiplierOpt && "We only rewrite byte-addressing GEP");
857 uint64_t Multiplier = *MultiplierOpt;
858 assert(GEP.getNumIndices() == 1);
859
860 Value *Src = getPointerRoot(GEP.getPointerOperand());
861 Type *CurType = deduceElementType(Src, true);
862
863 Value *Operand = *GEP.idx_begin();
864 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operand))
865 return walkLogicalAccessChainConstant(
866 CurType, CI->getZExtValue() * Multiplier, OnLiteralIndexing);
867
868 return walkLogicalAccessChainDynamic(CurType, Operand, Multiplier,
869 OnLiteralIndexing, OnDynamicIndexing);
870}
871
872Instruction *SPIRVEmitIntrinsicsImpl::buildLogicalAccessChainFromGEP(
873 GetElementPtrInst &GEP) {
874 auto &DL = CurrF->getDataLayout();
875 IRBuilder<> B(GEP.getParent());
876 B.SetInsertPoint(&GEP);
877
878 std::vector<Value *> Indices;
879 Indices.push_back(ConstantInt::get(
880 IntegerType::getInt32Ty(CurrF->getContext()), 0, /* Signed= */ false));
881 walkLogicalAccessChain(
882 GEP,
883 [&Indices, &B](Type *EltType, uint64_t Index) {
884 Indices.push_back(
885 ConstantInt::get(B.getInt64Ty(), Index, /* Signed= */ false));
886 },
887 [&Indices, &B, &DL, this](Type *EltType, Value *Offset,
888 uint64_t Multiplier) {
889 Value *Index = nullptr;
890 uint32_t EltTypeSize = DL.getTypeSizeInBits(EltType) / 8;
891 assert(Multiplier != 0);
892 if (Multiplier == EltTypeSize) {
893 Index = Offset;
894 } else if (EltTypeSize % Multiplier == 0) {
895 Index =
896 B.CreateUDiv(Offset, ConstantInt::get(Offset->getType(),
897 EltTypeSize / Multiplier,
898 /* Signed= */ false));
899 } else {
900 Index = B.CreateMul(Offset,
901 ConstantInt::get(Offset->getType(), Multiplier,
902 /* Signed= */ false));
903 insertAssignTypeIntrs(cast<Instruction>(Index), B);
904 Index = B.CreateUDiv(Index,
905 ConstantInt::get(Offset->getType(), EltTypeSize,
906 /* Signed= */ false));
907 }
908 insertAssignTypeIntrs(cast<Instruction>(Index), B);
909 Indices.push_back(Index);
910 });
911
912 SmallVector<Type *, 2> Types = {GEP.getType(), GEP.getOperand(0)->getType()};
913 SmallVector<Value *, 4> Args;
914 Args.push_back(B.getInt1(GEP.isInBounds()));
915 Args.push_back(GEP.getOperand(0));
916 llvm::append_range(Args, Indices);
917 Instruction *NewI =
918 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, {Types}, {Args});
919 replaceAllUsesWithAndErase(B, &GEP, NewI);
920 return NewI;
921}
922
923Type *SPIRVEmitIntrinsicsImpl::getGEPTypeLogical(GetElementPtrInst *GEP) {
924
925 Type *CurType = GEP->getResultElementType();
926
927 bool Interrupted = walkLogicalAccessChain(
928 *GEP, [&CurType](Type *EltType, uint64_t Index) { CurType = EltType; },
929 [&CurType](Type *EltType, Value *Index, uint64_t) { CurType = EltType; });
930
931 return Interrupted ? GEP->getResultElementType() : CurType;
932}
933
934Type *SPIRVEmitIntrinsicsImpl::getGEPType(GetElementPtrInst *Ref) {
935 if (getByteAddressingMultiplier(Ref->getSourceElementType()) &&
937 return getGEPTypeLogical(Ref);
938 }
939
940 Type *Ty = nullptr;
941 // TODO: not sure if GetElementPtrInst::getTypeAtIndex() does anything
942 // useful here
943 if (isNestedPointer(Ref->getSourceElementType())) {
944 Ty = Ref->getSourceElementType();
945 for (Use &U : drop_begin(Ref->indices()))
946 Ty = GetElementPtrInst::getTypeAtIndex(Ty, U.get());
947 } else {
948 Ty = Ref->getResultElementType();
949 }
950 return Ty;
951}
952
953Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeHelper(
954 Value *I, SmallPtrSetImpl<Value *> &Visited, bool UnknownElemTypeI8,
955 bool IgnoreKnownType) {
956 // allow to pass nullptr as an argument
957 if (!I)
958 return nullptr;
959
960 // maybe already known
961 if (!IgnoreKnownType)
962 if (Type *KnownTy = GR->findDeducedElementType(I))
963 return KnownTy;
964
965 // maybe a cycle
966 if (!Visited.insert(I).second)
967 return nullptr;
968
969 // fallback value in case when we fail to deduce a type
970 Type *Ty = nullptr;
971 // look for known basic patterns of type inference
972 if (auto *Ref = dyn_cast<AllocaInst>(I)) {
973 maybeAssignPtrType(Ty, I, Ref->getAllocatedType(), UnknownElemTypeI8);
974 } else if (auto *Ref = dyn_cast<GetElementPtrInst>(I)) {
975 Ty = getGEPType(Ref);
976 } else if (auto *SGEP = dyn_cast<StructuredGEPInst>(I)) {
977 Ty = SGEP->getResultElementType();
978 } else if (auto *Ref = dyn_cast<LoadInst>(I)) {
979 Value *Op = Ref->getPointerOperand();
980 Type *KnownTy = GR->findDeducedElementType(Op);
981 if (!KnownTy)
982 KnownTy = Op->getType();
983 if (Type *ElemTy = getPointeeType(KnownTy))
984 maybeAssignPtrType(Ty, I, ElemTy, UnknownElemTypeI8);
985 } else if (auto *Ref = dyn_cast<GlobalValue>(I)) {
986 if (auto *Fn = dyn_cast<Function>(Ref)) {
987 Ty = SPIRV::getOriginalFunctionType(*Fn);
988 GR->addDeducedElementType(I, Ty);
989 } else {
990 Ty = deduceElementTypeByValueDeep(
991 Ref->getValueType(),
992 Ref->getNumOperands() > 0 ? Ref->getOperand(0) : nullptr, Visited,
993 UnknownElemTypeI8);
994 }
995 } else if (auto *Ref = dyn_cast<AddrSpaceCastInst>(I)) {
996 Type *RefTy = deduceElementTypeHelper(Ref->getPointerOperand(), Visited,
997 UnknownElemTypeI8);
998 maybeAssignPtrType(Ty, I, RefTy, UnknownElemTypeI8);
999 } else if (auto *Ref = dyn_cast<IntToPtrInst>(I)) {
1000 maybeAssignPtrType(Ty, I, Ref->getDestTy(), UnknownElemTypeI8);
1001 } else if (auto *Ref = dyn_cast<BitCastInst>(I)) {
1002 if (Type *Src = Ref->getSrcTy(), *Dest = Ref->getDestTy();
1003 isPointerTy(Src) && isPointerTy(Dest))
1004 Ty = deduceElementTypeHelper(Ref->getOperand(0), Visited,
1005 UnknownElemTypeI8);
1006 } else if (auto *Ref = dyn_cast<AtomicCmpXchgInst>(I)) {
1007 Value *Op = Ref->getNewValOperand();
1008 if (isPointerTy(Op->getType()))
1009 Ty = deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8);
1010 } else if (auto *Ref = dyn_cast<AtomicRMWInst>(I)) {
1011 Value *Op = Ref->getValOperand();
1012 if (isPointerTy(Op->getType()))
1013 Ty = deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8);
1014 } else if (auto *Ref = dyn_cast<PHINode>(I)) {
1015 Type *BestTy = nullptr;
1016 unsigned MaxN = 1;
1017 DenseMap<Type *, unsigned> PhiTys;
1018 for (int i = Ref->getNumIncomingValues() - 1; i >= 0; --i) {
1019 Ty = deduceElementTypeByUsersDeep(Ref->getIncomingValue(i), Visited,
1020 UnknownElemTypeI8);
1021 if (!Ty)
1022 continue;
1023 auto It = PhiTys.try_emplace(Ty, 1);
1024 if (!It.second) {
1025 ++It.first->second;
1026 if (It.first->second > MaxN) {
1027 MaxN = It.first->second;
1028 BestTy = Ty;
1029 }
1030 }
1031 }
1032 if (BestTy)
1033 Ty = BestTy;
1034 } else if (auto *Ref = dyn_cast<SelectInst>(I)) {
1035 for (Value *Op : {Ref->getTrueValue(), Ref->getFalseValue()}) {
1036 // A function pointer operand carries its function type directly. Other
1037 // operands are deduced from their uses.
1038 Ty = isa<Function>(Op)
1039 ? deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8)
1040 : deduceElementTypeByUsersDeep(Op, Visited, UnknownElemTypeI8);
1041 if (Ty)
1042 break;
1043 }
1044 } else if (auto *CI = dyn_cast<CallInst>(I)) {
1045 static StringMap<unsigned> ResTypeByArg = {
1046 {"to_global", 0},
1047 {"to_local", 0},
1048 {"to_private", 0},
1049 {"__spirv_GenericCastToPtr_ToGlobal", 0},
1050 {"__spirv_GenericCastToPtr_ToLocal", 0},
1051 {"__spirv_GenericCastToPtr_ToPrivate", 0},
1052 {"__spirv_GenericCastToPtrExplicit_ToGlobal", 0},
1053 {"__spirv_GenericCastToPtrExplicit_ToLocal", 0},
1054 {"__spirv_GenericCastToPtrExplicit_ToPrivate", 0}};
1055 // TODO: maybe improve performance by caching demangled names
1056
1057 auto *II = dyn_cast<IntrinsicInst>(I);
1058 if (II && (II->getIntrinsicID() == Intrinsic::spv_resource_getbasepointer ||
1059 II->getIntrinsicID() == Intrinsic::spv_resource_getpointer)) {
1060 auto *HandleType = cast<TargetExtType>(II->getOperand(0)->getType());
1061 if (HandleType->getTargetExtName() == "spirv.Image" ||
1062 HandleType->getTargetExtName() == "spirv.SignedImage") {
1063 for (User *U : II->users()) {
1064 Ty = cast<Instruction>(U)->getAccessType();
1065 if (Ty)
1066 break;
1067 }
1068 } else if (HandleType->getTargetExtName() == "spirv.VulkanBuffer") {
1069 // This call is supposed to index into an array
1070 Ty = HandleType->getTypeParameter(0);
1071 if (II->getIntrinsicID() == Intrinsic::spv_resource_getpointer) {
1072 if (Ty->isArrayTy())
1073 Ty = Ty->getArrayElementType();
1074 else {
1075 assert(Ty && Ty->isStructTy());
1076 uint32_t Index =
1077 cast<ConstantInt>(II->getOperand(1))->getZExtValue();
1078 Ty = cast<StructType>(Ty)->getElementType(Index);
1079 }
1080 }
1082 } else {
1083 llvm_unreachable("Unknown handle type for spv_resource_getpointer.");
1084 }
1085 } else if (II && II->getIntrinsicID() ==
1086 Intrinsic::spv_generic_cast_to_ptr_explicit) {
1087 Ty = deduceElementTypeHelper(CI->getArgOperand(0), Visited,
1088 UnknownElemTypeI8);
1089 } else if (Function *CalledF = CI->getCalledFunction()) {
1090 std::string DemangledName =
1091 getOclOrSpirvBuiltinDemangledName(CalledF->getName());
1092 if (DemangledName.length() > 0)
1093 DemangledName = SPIRV::lookupBuiltinNameHelper(DemangledName);
1094 auto AsArgIt = ResTypeByArg.find(DemangledName);
1095 if (AsArgIt != ResTypeByArg.end())
1096 Ty = deduceElementTypeHelper(CI->getArgOperand(AsArgIt->second),
1097 Visited, UnknownElemTypeI8);
1098 else if (Type *KnownRetTy = GR->findDeducedElementType(CalledF))
1099 Ty = KnownRetTy;
1100 }
1101 }
1102
1103 // remember the found relationship
1104 if (Ty && !IgnoreKnownType) {
1105 // specify nested types if needed, otherwise return unchanged
1107 }
1108
1109 return Ty;
1110}
1111
1112// Re-create a type of the value if it has untyped pointer fields, also nested.
1113// Return the original value type if no corrections of untyped pointer
1114// information is found or needed.
1115Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(User *U,
1116 bool UnknownElemTypeI8) {
1117 SmallPtrSet<Value *, 0> Visited;
1118 return deduceNestedTypeHelper(U, U->getType(), Visited, UnknownElemTypeI8);
1119}
1120
1121Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(
1122 User *U, Type *OrigTy, SmallPtrSetImpl<Value *> &Visited,
1123 bool UnknownElemTypeI8) {
1124 if (!U)
1125 return OrigTy;
1126
1127 // maybe already known
1128 if (Type *KnownTy = GR->findDeducedCompositeType(U))
1129 return KnownTy;
1130
1131 // maybe a cycle
1132 if (!Visited.insert(U).second)
1133 return OrigTy;
1134
1135 if (isa<StructType>(OrigTy)) {
1137 bool Change = false;
1138 for (unsigned i = 0; i < U->getNumOperands(); ++i) {
1139 Value *Op = U->getOperand(i);
1140 assert(Op && "Operands should not be null.");
1141 Type *OpTy = Op->getType();
1142 Type *Ty = OpTy;
1143 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
1144 if (Type *NestedTy =
1145 deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8))
1146 Ty = getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
1147 } else {
1148 Ty = deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited,
1149 UnknownElemTypeI8);
1150 }
1151 Tys.push_back(Ty);
1152 Change |= Ty != OpTy;
1153 }
1154 if (Change) {
1155 Type *NewTy = StructType::create(Tys);
1156 GR->addDeducedCompositeType(U, NewTy);
1157 return NewTy;
1158 }
1159 } else if (auto *ArrTy = dyn_cast<ArrayType>(OrigTy)) {
1160 if (Value *Op = U->getNumOperands() > 0 ? U->getOperand(0) : nullptr) {
1161 Type *OpTy = ArrTy->getElementType();
1162 Type *Ty = OpTy;
1163 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
1164 if (Type *NestedTy =
1165 deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8))
1166 Ty = getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
1167 } else {
1168 Ty = deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited,
1169 UnknownElemTypeI8);
1170 }
1171 if (Ty != OpTy) {
1172 Type *NewTy = ArrayType::get(Ty, ArrTy->getNumElements());
1173 GR->addDeducedCompositeType(U, NewTy);
1174 return NewTy;
1175 }
1176 }
1177 } else if (auto *VecTy = dyn_cast<VectorType>(OrigTy)) {
1178 if (Value *Op = U->getNumOperands() > 0 ? U->getOperand(0) : nullptr) {
1179 Type *OpTy = VecTy->getElementType();
1180 Type *Ty = OpTy;
1181 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
1182 if (Type *NestedTy =
1183 deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8))
1184 Ty = getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
1185 } else {
1186 Ty = deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited,
1187 UnknownElemTypeI8);
1188 }
1189 if (Ty != OpTy) {
1190 Type *NewTy = VectorType::get(Ty, VecTy->getElementCount());
1192 return NewTy;
1193 }
1194 }
1195 }
1196
1197 return OrigTy;
1198}
1199
1200Type *SPIRVEmitIntrinsicsImpl::deduceElementType(Value *I,
1201 bool UnknownElemTypeI8) {
1202 if (Type *Ty = deduceElementTypeHelper(I, UnknownElemTypeI8))
1203 return Ty;
1204 if (!UnknownElemTypeI8)
1205 return nullptr;
1206 insertTodoType(I);
1207 return IntegerType::getInt8Ty(I->getContext());
1208}
1209
1211 Value *PointerOperand) {
1212 Type *PointeeTy = GR->findDeducedElementType(PointerOperand);
1213 if (PointeeTy && !isUntypedPointerTy(PointeeTy))
1214 return nullptr;
1215 auto *PtrTy = dyn_cast<PointerType>(I->getType());
1216 if (!PtrTy)
1217 return I->getType();
1218 if (Type *NestedTy = GR->findDeducedElementType(I))
1219 return getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
1220 return nullptr;
1221}
1222
1223// Try to deduce element type for a call base. Returns false if this is an
1224// indirect function invocation, and true otherwise.
1225bool SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeCalledFunction(
1226 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
1227 Type *&KnownElemTy, bool &Incomplete) {
1228 Function *CalledF = CI->getCalledFunction();
1229 if (!CalledF)
1230 return false;
1231 std::string DemangledName =
1233 if (DemangledName.length() > 0 &&
1234 !StringRef(DemangledName).starts_with("llvm.")) {
1235 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*CalledF);
1236 auto [Grp, Opcode, ExtNo] = SPIRV::mapBuiltinToOpcode(
1237 DemangledName, ST.getPreferredInstructionSet());
1238 if (Opcode == SPIRV::OpGroupAsyncCopy) {
1239 for (unsigned i = 0, PtrCnt = 0; i < CI->arg_size() && PtrCnt < 2; ++i) {
1240 Value *Op = CI->getArgOperand(i);
1241 if (!isPointerTy(Op->getType()))
1242 continue;
1243 ++PtrCnt;
1244 if (Type *ElemTy = GR->findDeducedElementType(Op))
1245 KnownElemTy = ElemTy; // src will rewrite dest if both are defined
1246 Ops.push_back(std::make_pair(Op, i));
1247 }
1248 } else if (Grp == SPIRV::Atomic || Grp == SPIRV::AtomicFloating) {
1249 if (CI->arg_size() == 0)
1250 return true;
1251 Value *Op = CI->getArgOperand(0);
1252 if (!isPointerTy(Op->getType()))
1253 return true;
1254 switch (Opcode) {
1255 case SPIRV::OpAtomicFAddEXT:
1256 case SPIRV::OpAtomicFMinEXT:
1257 case SPIRV::OpAtomicFMaxEXT:
1258 case SPIRV::OpAtomicLoad:
1259 case SPIRV::OpAtomicCompareExchangeWeak:
1260 case SPIRV::OpAtomicCompareExchange:
1261 case SPIRV::OpAtomicExchange:
1262 case SPIRV::OpAtomicIAdd:
1263 case SPIRV::OpAtomicISub:
1264 case SPIRV::OpAtomicOr:
1265 case SPIRV::OpAtomicXor:
1266 case SPIRV::OpAtomicAnd:
1267 case SPIRV::OpAtomicUMin:
1268 case SPIRV::OpAtomicUMax:
1269 case SPIRV::OpAtomicSMin:
1270 case SPIRV::OpAtomicSMax: {
1271 KnownElemTy = isPointerTy(CI->getType()) ? getAtomicElemTy(GR, CI, Op)
1272 : CI->getType();
1273 if (!KnownElemTy)
1274 return true;
1275 Incomplete = isTodoType(Op);
1276 Ops.push_back(std::make_pair(Op, 0));
1277 } break;
1278 case SPIRV::OpAtomicStore: {
1279 if (CI->arg_size() < 4)
1280 return true;
1281 Value *ValOp = CI->getArgOperand(3);
1282 KnownElemTy = isPointerTy(ValOp->getType())
1283 ? getAtomicElemTy(GR, CI, Op)
1284 : ValOp->getType();
1285 if (!KnownElemTy)
1286 return true;
1287 Incomplete = isTodoType(Op);
1288 Ops.push_back(std::make_pair(Op, 0));
1289 } break;
1290 }
1291 }
1292 }
1293 return true;
1294}
1295
1296// Try to deduce element type for a function pointer.
1297void SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeFunctionPointer(
1298 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
1299 Type *&KnownElemTy, bool IsPostprocessing) {
1300 Value *Op = CI->getCalledOperand();
1301 if (!Op || !isPointerTy(Op->getType()))
1302 return;
1303 Ops.push_back(std::make_pair(Op, std::numeric_limits<unsigned>::max()));
1304 FunctionType *FTy = SPIRV::getOriginalFunctionType(*CI);
1305 bool IsNewFTy = false, IsIncomplete = false;
1307 for (auto &&[ParmIdx, Arg] : llvm::enumerate(CI->args())) {
1308 Type *ArgTy = Arg->getType();
1309 if (ArgTy->isPointerTy()) {
1310 if (Type *ElemTy = GR->findDeducedElementType(Arg)) {
1311 IsNewFTy = true;
1312 ArgTy = getTypedPointerWrapper(ElemTy, getPointerAddressSpace(ArgTy));
1313 if (isTodoType(Arg))
1314 IsIncomplete = true;
1315 } else {
1316 IsIncomplete = true;
1317 }
1318 } else {
1319 ArgTy = FTy->getFunctionParamType(ParmIdx);
1320 }
1321 ArgTys.push_back(ArgTy);
1322 }
1323 Type *RetTy = FTy->getReturnType();
1324 if (CI->getType()->isPointerTy()) {
1325 if (Type *ElemTy = GR->findDeducedElementType(CI)) {
1326 IsNewFTy = true;
1327 RetTy =
1329 if (isTodoType(CI))
1330 IsIncomplete = true;
1331 } else {
1332 IsIncomplete = true;
1333 }
1334 }
1335 if (!IsPostprocessing && IsIncomplete)
1336 insertTodoType(Op);
1337 KnownElemTy =
1338 IsNewFTy ? FunctionType::get(RetTy, ArgTys, FTy->isVarArg()) : FTy;
1339}
1340
1341bool SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeFunctionRet(
1342 Instruction *I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
1343 const SmallPtrSetImpl<Value *> *AskOps, bool IsPostprocessing,
1344 Type *&KnownElemTy, Value *Op, Function *F) {
1345 KnownElemTy = GR->findDeducedElementType(F);
1346 if (KnownElemTy)
1347 return false;
1348 if (Type *OpElemTy = GR->findDeducedElementType(Op)) {
1349 OpElemTy = normalizeType(OpElemTy);
1350 GR->addDeducedElementType(F, OpElemTy);
1351 GR->addReturnType(
1352 F, TypedPointerType::get(OpElemTy,
1353 getPointerAddressSpace(F->getReturnType())));
1354 // non-recursive update of types in function uses
1355 DenseSet<std::pair<Value *, Value *>> VisitedSubst{std::make_pair(I, Op)};
1356 for (User *U : F->users()) {
1357 CallInst *CI = dyn_cast<CallInst>(U);
1358 if (!CI || CI->getCalledFunction() != F)
1359 continue;
1360 if (CallInst *AssignCI = GR->findAssignPtrTypeInstr(CI)) {
1361 if (Type *PrevElemTy = GR->findDeducedElementType(CI)) {
1362 GR->updateAssignType(AssignCI, CI,
1363 getNormalizedPoisonValue(OpElemTy));
1364 propagateElemType(CI, PrevElemTy, VisitedSubst);
1365 }
1366 }
1367 }
1368 // Non-recursive update of types in the function uncomplete returns.
1369 // This may happen just once per a function, the latch is a pair of
1370 // findDeducedElementType(F) / addDeducedElementType(F, ...).
1371 // With or without the latch it is a non-recursive call due to
1372 // IncompleteRets set to nullptr in this call.
1373 if (IncompleteRets)
1374 for (Instruction *IncompleteRetI : *IncompleteRets)
1375 deduceOperandElementType(IncompleteRetI, nullptr, AskOps,
1376 IsPostprocessing);
1377 } else if (IncompleteRets) {
1378 IncompleteRets->insert(I);
1379 }
1380 TypeValidated.insert(I);
1381 return true;
1382}
1383
1384// If the Instruction has Pointer operands with unresolved types, this function
1385// tries to deduce them. If the Instruction has Pointer operands with known
1386// types which differ from expected, this function tries to insert a bitcast to
1387// resolve the issue.
1388void SPIRVEmitIntrinsicsImpl::deduceOperandElementType(
1389 Instruction *I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
1390 const SmallPtrSetImpl<Value *> *AskOps, bool IsPostprocessing) {
1392 Type *KnownElemTy = nullptr;
1393 bool Incomplete = false;
1394 // look for known basic patterns of type inference
1395 if (auto *Ref = dyn_cast<PHINode>(I)) {
1396 if (!isPointerTy(I->getType()) ||
1397 !(KnownElemTy = GR->findDeducedElementType(I)))
1398 return;
1399 Incomplete = isTodoType(I);
1400 for (unsigned i = 0; i < Ref->getNumIncomingValues(); i++) {
1401 Value *Op = Ref->getIncomingValue(i);
1402 if (isPointerTy(Op->getType()))
1403 Ops.push_back(std::make_pair(Op, i));
1404 }
1405 } else if (auto *Ref = dyn_cast<AddrSpaceCastInst>(I)) {
1406 KnownElemTy = GR->findDeducedElementType(I);
1407 if (!KnownElemTy)
1408 return;
1409 Incomplete = isTodoType(I);
1410 Ops.push_back(std::make_pair(Ref->getPointerOperand(), 0));
1411 } else if (auto *Ref = dyn_cast<BitCastInst>(I)) {
1412 if (!isPointerTy(I->getType()))
1413 return;
1414 KnownElemTy = GR->findDeducedElementType(I);
1415 if (!KnownElemTy)
1416 return;
1417 Incomplete = isTodoType(I);
1418 Ops.push_back(std::make_pair(Ref->getOperand(0), 0));
1419 } else if (auto *Ref = dyn_cast<GetElementPtrInst>(I)) {
1420 if (GR->findDeducedElementType(Ref->getPointerOperand()))
1421 return;
1422 KnownElemTy = Ref->getSourceElementType();
1423 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1425 } else if (auto *Ref = dyn_cast<StructuredGEPInst>(I)) {
1426 if (GR->findDeducedElementType(Ref->getPointerOperand()))
1427 return;
1428 KnownElemTy = Ref->getBaseType();
1429 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1431 } else if (auto *Ref = dyn_cast<LoadInst>(I)) {
1432 KnownElemTy = I->getType();
1433 if (isUntypedPointerTy(KnownElemTy)) {
1434 // A T** loaded back from its alloca comes out opaque, dropping type info.
1435 // When the load is a pointer-to-pointer, type the alloca as that pointer.
1436 Type *LoadedElemTy = GR->findDeducedElementType(I);
1437 if (!LoadedElemTy || !isPointerTyOrWrapper(LoadedElemTy))
1438 return;
1439 Value *Root = Ref->getPointerOperand()->stripPointerCasts();
1440 if (!isa<AllocaInst>(Root))
1441 return;
1442 KnownElemTy = getTypedPointerWrapper(LoadedElemTy,
1443 getPointerAddressSpace(KnownElemTy));
1444 }
1445 Type *PointeeTy = GR->findDeducedElementType(Ref->getPointerOperand());
1446 if (PointeeTy && !isUntypedPointerTy(PointeeTy))
1447 return;
1448 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1450 } else if (auto *Ref = dyn_cast<StoreInst>(I)) {
1451 if (!(KnownElemTy =
1452 reconstructType(Ref->getValueOperand(), false, IsPostprocessing)))
1453 return;
1454 Type *PointeeTy = GR->findDeducedElementType(Ref->getPointerOperand());
1455 if (PointeeTy && !isUntypedPointerTy(PointeeTy))
1456 return;
1457 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1459 } else if (auto *Ref = dyn_cast<AtomicCmpXchgInst>(I)) {
1460 KnownElemTy = isPointerTy(I->getType())
1461 ? getAtomicElemTy(GR, I, Ref->getPointerOperand())
1462 : I->getType();
1463 if (!KnownElemTy)
1464 return;
1465 Incomplete = isTodoType(Ref->getPointerOperand());
1466 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1468 } else if (auto *Ref = dyn_cast<AtomicRMWInst>(I)) {
1469 KnownElemTy = isPointerTy(I->getType())
1470 ? getAtomicElemTy(GR, I, Ref->getPointerOperand())
1471 : I->getType();
1472 if (!KnownElemTy)
1473 return;
1474 Incomplete = isTodoType(Ref->getPointerOperand());
1475 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1477 } else if (auto *Ref = dyn_cast<SelectInst>(I)) {
1478 if (!isPointerTy(I->getType()) ||
1479 !(KnownElemTy = GR->findDeducedElementType(I)))
1480 return;
1481 Incomplete = isTodoType(I);
1482 for (unsigned i = 0; i < Ref->getNumOperands(); i++) {
1483 Value *Op = Ref->getOperand(i);
1484 if (isPointerTy(Op->getType()))
1485 Ops.push_back(std::make_pair(Op, i));
1486 }
1487 } else if (auto *Ref = dyn_cast<ReturnInst>(I)) {
1488 if (!isPointerTy(CurrF->getReturnType()))
1489 return;
1490 Value *Op = Ref->getReturnValue();
1491 if (!Op)
1492 return;
1493 if (deduceOperandElementTypeFunctionRet(I, IncompleteRets, AskOps,
1494 IsPostprocessing, KnownElemTy, Op,
1495 CurrF))
1496 return;
1497 Incomplete = isTodoType(CurrF);
1498 Ops.push_back(std::make_pair(Op, 0));
1499 } else if (auto *Ref = dyn_cast<ICmpInst>(I)) {
1500 if (!isPointerTy(Ref->getOperand(0)->getType()))
1501 return;
1502 Value *Op0 = Ref->getOperand(0);
1503 Value *Op1 = Ref->getOperand(1);
1504 bool Incomplete0 = isTodoType(Op0);
1505 bool Incomplete1 = isTodoType(Op1);
1506 Type *ElemTy1 = GR->findDeducedElementType(Op1);
1507 Type *ElemTy0 = (Incomplete0 && !Incomplete1 && ElemTy1)
1508 ? nullptr
1509 : GR->findDeducedElementType(Op0);
1510 if (ElemTy0) {
1511 KnownElemTy = ElemTy0;
1512 Incomplete = Incomplete0;
1513 Ops.push_back(std::make_pair(Op1, 1));
1514 } else if (ElemTy1) {
1515 KnownElemTy = ElemTy1;
1516 Incomplete = Incomplete1;
1517 Ops.push_back(std::make_pair(Op0, 0));
1518 }
1519 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1520 if (!CI->isIndirectCall())
1521 deduceOperandElementTypeCalledFunction(CI, Ops, KnownElemTy, Incomplete);
1522 else if (HaveFunPtrs)
1523 deduceOperandElementTypeFunctionPointer(CI, Ops, KnownElemTy,
1524 IsPostprocessing);
1525 }
1526
1527 // There is no enough info to deduce types or all is valid.
1528 if (!KnownElemTy || Ops.size() == 0)
1529 return;
1530
1531 LLVMContext &Ctx = CurrF->getContext();
1532 IRBuilder<> B(Ctx);
1533 for (auto &OpIt : Ops) {
1534 Value *Op = OpIt.first;
1535 if (AskOps && !AskOps->contains(Op))
1536 continue;
1537 Type *AskTy = nullptr;
1538 CallInst *AskCI = nullptr;
1539 if (IsPostprocessing && AskOps) {
1540 AskTy = GR->findDeducedElementType(Op);
1541 AskCI = GR->findAssignPtrTypeInstr(Op);
1542 assert(AskTy && AskCI);
1543 }
1544 Type *Ty = AskTy ? AskTy : GR->findDeducedElementType(Op);
1545 if (Ty == KnownElemTy)
1546 continue;
1547 Value *OpTyVal = getNormalizedPoisonValue(KnownElemTy);
1548 Type *OpTy = Op->getType();
1549 // Do not let a non-pointer element type clobber an already-deduced pointer
1550 // element type for the same operand.
1551 bool WouldClobberPtrWithNonPtr = Ty && isPointerTyOrWrapper(Ty) &&
1552 !isPointerTyOrWrapper(KnownElemTy) &&
1554 if (Op->hasUseList() && !WouldClobberPtrWithNonPtr &&
1555 (!Ty || AskTy || isUntypedPointerTy(Ty) || isTodoType(Op))) {
1556 Type *PrevElemTy = GR->findDeducedElementType(Op);
1557 GR->addDeducedElementType(Op, normalizeType(KnownElemTy));
1558 // check if KnownElemTy is complete
1559 if (!Incomplete)
1560 eraseTodoType(Op);
1561 else if (!IsPostprocessing)
1562 insertTodoType(Op);
1563 // check if there is existing Intrinsic::spv_assign_ptr_type instruction
1564 CallInst *AssignCI = AskCI ? AskCI : GR->findAssignPtrTypeInstr(Op);
1565 if (AssignCI == nullptr) {
1566 Instruction *User = dyn_cast<Instruction>(Op->use_begin()->get());
1567 setInsertPointSkippingPhis(B, User ? User->getNextNode() : I);
1568 CallInst *CI =
1569 buildIntrWithMD(Intrinsic::spv_assign_ptr_type, {OpTy}, OpTyVal, Op,
1570 {B.getInt32(getPointerAddressSpace(OpTy))}, B);
1571 GR->addAssignPtrTypeInstr(Op, CI);
1572 } else {
1573 GR->updateAssignType(AssignCI, Op, OpTyVal);
1574 DenseSet<std::pair<Value *, Value *>> VisitedSubst{
1575 std::make_pair(I, Op)};
1576 propagateElemTypeRec(Op, KnownElemTy, PrevElemTy, VisitedSubst);
1577 }
1578 } else {
1579 eraseTodoType(Op);
1580 CallInst *PtrCastI =
1581 buildSpvPtrcast(I->getParent()->getParent(), Op, KnownElemTy);
1582 if (OpIt.second == std::numeric_limits<unsigned>::max())
1583 dyn_cast<CallInst>(I)->setCalledOperand(PtrCastI);
1584 else
1585 I->setOperand(OpIt.second, PtrCastI);
1586 }
1587 }
1588 TypeValidated.insert(I);
1589}
1590
1591void SPIRVEmitIntrinsicsImpl::replaceMemInstrUses(Instruction *Old,
1592 Instruction *New,
1593 IRBuilder<> &B) {
1594 while (!Old->user_empty()) {
1595 auto *U = Old->user_back();
1596 if (isAssignTypeInstr(U)) {
1597 B.SetInsertPoint(U);
1598 SmallVector<Value *, 2> Args = {New, U->getOperand(1)};
1599 CallInst *AssignCI = B.CreateIntrinsicWithoutFolding(
1600 Intrinsic::spv_assign_type, {New->getType()}, Args);
1601 GR->addAssignPtrTypeInstr(New, AssignCI);
1602 U->eraseFromParent();
1603 } else if (isMemInstrToReplace(U) || isa<ReturnInst>(U) ||
1604 isa<CallInst>(U)) {
1605 U->replaceUsesOfWith(Old, New);
1606 // For a `llvm.spv.abort` call whose composite message argument was
1607 // rewritten to a value-id (i32), also retarget the call to a matching
1608 // intrinsic declaration so the IR verifier is satisfied. The SPIR-V
1609 // type of the value is tracked via the GlobalRegistry, so the selector
1610 // still emits OpAbortKHR with the original composite type.
1611 if (auto *CI = dyn_cast<CallInst>(U);
1612 CI && CI->getIntrinsicID() == Intrinsic::spv_abort) {
1613 Type *NewArgTy = New->getType();
1614 Type *ExpectedArgTy = CI->getFunctionType()->getParamType(0);
1615 if (NewArgTy != ExpectedArgTy) {
1616 Module *M = CI->getModule();
1618 M, Intrinsic::spv_abort, {NewArgTy});
1619 CI->setCalledFunction(NewF);
1620 }
1621 }
1622 } else if (isa<PHINode>(U) || isa<SelectInst>(U) || isa<FreezeInst>(U)) {
1623 // Aggregate-typed PHIs, selects and freezes have already been mutated to
1624 // the i32 value-id type up front in runOnFunction, so only the operand
1625 // needs replacing here; their extractvalue users are lowered to
1626 // spv_extractv by visitExtractValueInst.
1627 assert(U->getType() == New->getType() &&
1628 "aggregate PHI/select/freeze should have been mutated to value-id "
1629 "type");
1630 U->replaceUsesOfWith(Old, New);
1631 } else {
1632 llvm_unreachable("illegal aggregate intrinsic user");
1633 }
1634 }
1635 New->copyMetadata(*Old);
1636 Old->eraseFromParent();
1637}
1638
1639// Lower a poison or undef Op to its placeholder intrinsic.
1640Value *SPIRVEmitIntrinsicsImpl::lowerUndefOrPoison(Value *Op, IRBuilder<> &B,
1641 bool HasPoisonExt) {
1642 auto *UV = dyn_cast<UndefValue>(Op);
1643 if (!UV)
1644 return nullptr;
1645
1646 bool AsPoison = HasPoisonExt && isa<PoisonValue>(UV);
1647 if (isa<PoisonValue>(UV) && !HasPoisonExt)
1648 LLVM_DEBUG(dbgs() << "SPV_KHR_poison_freeze is not enabled. Poison is "
1649 "lowered as undef\n");
1650
1651 Intrinsic::ID IID = AsPoison ? Intrinsic::spv_poison : Intrinsic::spv_undef;
1652 Type *Ty = UV->getType();
1653
1654 // Aggregates use an i32-result placeholder with the real type kept in
1655 // AggrConstTypes and scalar poison uses a type-overloaded one.
1656 if (Ty->isAggregateType()) {
1657 auto *Call =
1658 AsPoison ? B.CreateIntrinsicWithoutFolding(IID, {B.getInt32Ty()}, {})
1659 : B.CreateIntrinsicWithoutFolding(IID, {});
1660 AggrConsts[Call] = UV;
1661 AggrConstTypes[Call] = Ty;
1662 return Call;
1663 }
1664
1665 if (AsPoison)
1666 return B.CreateIntrinsic(IID, {Ty}, {});
1667 return nullptr;
1668}
1669
1670// Replace aggregate undef or poison operands and extension-enabled scalar
1671// poison operands with placeholder intrinsics. Scalar undef is left as is. See
1672// lowerUndefOrPoison.
1673void SPIRVEmitIntrinsicsImpl::preprocessUndefsAndPoisons(IRBuilder<> &B) {
1674 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*CurrF);
1675 bool HasPoisonExt =
1676 STI->canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
1677
1678 SmallVector<Instruction *, 16> Insts;
1679 for (auto &I : instructions(CurrF))
1680 Insts.push_back(&I);
1681
1682 for (Instruction *I : Insts) {
1683 bool BPrepared = false;
1684 auto *Phi = dyn_cast<PHINode>(I);
1685 for (unsigned Idx = 0; Idx < I->getNumOperands(); ++Idx) {
1686 Value *Op = I->getOperand(Idx);
1687 if (!isa<UndefValue>(Op) || Op->getType()->isMetadataTy())
1688 continue;
1689 bool IsScalar = !Op->getType()->isAggregateType();
1690 bool AsPoison = HasPoisonExt && isa<PoisonValue>(Op);
1691 // Scalar undef or extensionless scalar poison is directly translatable.
1692 if (IsScalar && !AsPoison)
1693 continue;
1694 // Scalar poison in a phi materializes in the incoming block. Everything
1695 // else materializes right before I.
1696 if (IsScalar && Phi)
1697 B.SetInsertPoint(Phi->getIncomingBlock(Idx)->getTerminator());
1698 else if (!BPrepared) {
1700 BPrepared = true;
1701 }
1702 if (Value *Repl = lowerUndefOrPoison(Op, B, HasPoisonExt))
1703 I->setOperand(Idx, Repl);
1704 }
1705 }
1706}
1707
1708// Simplify addrspacecast(null) instructions to ConstantPointerNull of the
1709// target type. Casting null always yields null, and this avoids SPIR-V
1710// lowering issues where the null gets typed as an integer instead of a
1711// pointer.
1712void SPIRVEmitIntrinsicsImpl::simplifyNullAddrSpaceCasts() {
1713 for (Instruction &I : make_early_inc_range(instructions(CurrF)))
1714 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I))
1715 if (isa<ConstantPointerNull>(ASC->getPointerOperand())) {
1716 ASC->replaceAllUsesWith(
1718 ASC->eraseFromParent();
1719 }
1720}
1721
1722// True for an aggregate value the legalizer splits into a multi-result op
1723// (with.overflow -> G_UADDO, frexp/sincos/modf -> G_FFREXP/...). These keep a
1724// genuine multi-register result; all other aggregates become a single value-id.
1726 if (!V->getType()->isAggregateType())
1727 return false;
1728 return isa<IntrinsicInst>(V) && !isSpvIntrinsic(V);
1729}
1730
1731// True for an aggregate PHI/select/freeze, which is lowered to a single
1732// value-id.
1734 return (isa<PHINode>(I) || isa<SelectInst>(I) || isa<FreezeInst>(I)) &&
1735 I.getType()->isAggregateType();
1736}
1737
1738// Give each multi-register aggregate arm of an aggregate PHI/select/freeze a
1739// single value-id by reassembling it with extractvalue + insertvalue, so the
1740// arm matches the result once it is mutated to a value-id.
1741void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
1742 IRBuilder<> &B) {
1743 auto *Phi = dyn_cast<PHINode>(I);
1744 for (Use &U : I->operands()) {
1745 Value *Op = U.get();
1747 continue;
1748 // A PHI arm materializes in its incoming block, everything else after the
1749 // producer.
1750 if (Phi)
1751 B.SetInsertPoint(Phi->getIncomingBlock(U)->getTerminator());
1752 else
1754 auto *AggrTy = cast<StructType>(Op->getType());
1755 Value *Composite = PoisonValue::get(AggrTy);
1756 for (unsigned Idx = 0, E = AggrTy->getNumElements(); Idx != E; ++Idx) {
1757 Value *Field = B.CreateExtractValue(Op, Idx);
1758 Composite = B.CreateInsertValue(Composite, Field, Idx);
1759 }
1760 U.set(Composite);
1761 }
1762}
1763
1764void SPIRVEmitIntrinsicsImpl::preprocessCompositeConstants(IRBuilder<> &B) {
1765 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*CurrF);
1766 bool HasPoisonExt =
1767 STI->canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
1768 std::queue<Instruction *> Worklist;
1769 for (auto &I : instructions(CurrF))
1770 Worklist.push(&I);
1771
1772 while (!Worklist.empty()) {
1773 auto *I = Worklist.front();
1774 bool IsPhi = isa<PHINode>(I), BPrepared = false;
1775 assert(I);
1776 bool KeepInst = false;
1777 for (const auto &Op : I->operands()) {
1778 Constant *AggrConst = nullptr;
1779 Type *ResTy = nullptr;
1780 if (auto *COp = dyn_cast<ConstantVector>(Op)) {
1781 AggrConst = COp;
1782 ResTy = COp->getType();
1783 } else if (auto *COp = dyn_cast<ConstantArray>(Op)) {
1784 AggrConst = COp;
1785 ResTy = B.getInt32Ty();
1786 } else if (auto *COp = dyn_cast<ConstantStruct>(Op)) {
1787 AggrConst = COp;
1788 ResTy = B.getInt32Ty();
1789 } else if (auto *COp = dyn_cast<ConstantDataArray>(Op)) {
1790 AggrConst = COp;
1791 ResTy = B.getInt32Ty();
1792 } else if (auto *COp = dyn_cast<ConstantAggregateZero>(Op)) {
1793 AggrConst = COp;
1794 ResTy = Op->getType()->isVectorTy() ? COp->getType() : B.getInt32Ty();
1795 }
1796 if (AggrConst) {
1797 auto PrepareInsert = [&]() {
1798 if (BPrepared)
1799 return;
1800 IsPhi ? B.SetInsertPointPastAllocas(I->getParent()->getParent())
1801 : B.SetInsertPoint(I);
1802 BPrepared = true;
1803 };
1805 if (auto *COp = dyn_cast<ConstantDataSequential>(Op))
1806 for (unsigned i = 0; i < COp->getNumElements(); ++i)
1807 Args.push_back(COp->getElementAsConstant(i));
1808 else
1809 for (Value *Op : AggrConst->operands()) {
1810 // Simplify addrspacecast(null) to null in the target address space
1811 // so that null pointers get the correct pointer type when lowered.
1812 if (auto *CE = dyn_cast<ConstantExpr>(Op);
1813 CE && CE->getOpcode() == Instruction::AddrSpaceCast &&
1814 isa<ConstantPointerNull>(CE->getOperand(0)))
1816 // Undef or poison nested in a constant aggregate is not a direct
1817 // instruction operand, so preprocessUndefsAndPoisons() misses it.
1818 // An unlowered aggregate one would reach IRTranslator as an
1819 // untranslatable spv_const_composite operand.
1820 if (isa<UndefValue>(Op)) {
1821 PrepareInsert();
1822 if (Value *Repl = lowerUndefOrPoison(Op, B, HasPoisonExt))
1823 Op = Repl;
1824 }
1825 Args.push_back(Op);
1826 }
1827 PrepareInsert();
1828 auto *CI = B.CreateIntrinsicWithoutFolding(
1829 Intrinsic::spv_const_composite, {ResTy}, {Args});
1830 Worklist.push(CI);
1831 I->replaceUsesOfWith(Op, CI);
1832 KeepInst = true;
1833 AggrConsts[CI] = AggrConst;
1834 AggrConstTypes[CI] = deduceNestedTypeHelper(AggrConst, false);
1835 }
1836 }
1837 if (!KeepInst)
1838 Worklist.pop();
1839 }
1840}
1841
1843 IRBuilder<> &B) {
1844 LLVMContext &Ctx = I->getContext();
1846 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {I->getType()},
1847 {I, MetadataAsValue::get(Ctx, MDNode::get(Ctx, {Node}))});
1848}
1849
1851 unsigned RoundingModeDeco,
1852 IRBuilder<> &B) {
1853 LLVMContext &Ctx = I->getContext();
1854 Type *Int32Ty = Type::getInt32Ty(Ctx);
1855 MDNode *RoundingModeNode = MDNode::get(
1856 Ctx,
1858 ConstantInt::get(Int32Ty, SPIRV::Decoration::FPRoundingMode)),
1859 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, RoundingModeDeco))});
1860 createDecorationIntrinsic(I, RoundingModeNode, B);
1861}
1862
1864 IRBuilder<> &B) {
1865 LLVMContext &Ctx = I->getContext();
1866 Type *Int32Ty = Type::getInt32Ty(Ctx);
1867 MDNode *SaturatedConversionNode =
1868 MDNode::get(Ctx, {ConstantAsMetadata::get(ConstantInt::get(
1869 Int32Ty, SPIRV::Decoration::SaturatedConversion))});
1870 createDecorationIntrinsic(I, SaturatedConversionNode, B);
1871}
1872
1877
1878Instruction *SPIRVEmitIntrinsicsImpl::visitCallInst(CallInst &Call) {
1879 if (!Call.isInlineAsm())
1880 return &Call;
1881
1882 LLVMContext &Ctx = CurrF->getContext();
1883 // TODO: this does not retain elementtype info for memory constraints, which
1884 // in turn means that we lower them into pointers to i8, rather than
1885 // pointers to elementtype; this can be fixed during reverse translation
1886 // but we should correct it here, possibly by tweaking the function
1887 // type to take TypedPointerType args.
1888 Constant *TyC = UndefValue::get(SPIRV::getOriginalFunctionType(Call));
1889 MDString *ConstraintString =
1890 MDString::get(Ctx, SPIRV::getOriginalAsmConstraints(Call));
1892 buildMD(TyC),
1893 MetadataAsValue::get(Ctx, MDNode::get(Ctx, ConstraintString))};
1894 for (unsigned OpIdx = 0; OpIdx < Call.arg_size(); OpIdx++)
1895 Args.push_back(Call.getArgOperand(OpIdx));
1896
1898 B.SetInsertPoint(&Call);
1899 B.CreateIntrinsic(Intrinsic::spv_inline_asm, {Args});
1900 return &Call;
1901}
1902
1903// Use a tip about rounding mode to create a decoration.
1904void SPIRVEmitIntrinsicsImpl::useRoundingMode(ConstrainedFPIntrinsic *FPI,
1905 IRBuilder<> &B) {
1906 std::optional<RoundingMode> RM = FPI->getRoundingMode();
1907 if (!RM.has_value())
1908 return;
1909 unsigned RoundingModeDeco = std::numeric_limits<unsigned>::max();
1910 switch (RM.value()) {
1911 default:
1912 // ignore unknown rounding modes
1913 break;
1914 case RoundingMode::NearestTiesToEven:
1915 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTE;
1916 break;
1917 case RoundingMode::TowardNegative:
1918 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTN;
1919 break;
1920 case RoundingMode::TowardPositive:
1921 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTP;
1922 break;
1923 case RoundingMode::TowardZero:
1924 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTZ;
1925 break;
1926 case RoundingMode::Dynamic:
1927 case RoundingMode::NearestTiesToAway:
1928 // TODO: check if supported
1929 break;
1930 }
1931 if (RoundingModeDeco == std::numeric_limits<unsigned>::max())
1932 return;
1933 // Convert the tip about rounding mode into a decoration record.
1934 createRoundingModeDecoration(FPI, RoundingModeDeco, B);
1935}
1936
1937Instruction *SPIRVEmitIntrinsicsImpl::visitSwitchInst(SwitchInst &I) {
1938 BasicBlock *ParentBB = I.getParent();
1939 Function *F = ParentBB->getParent();
1940 IRBuilder<> B(ParentBB);
1941 B.SetInsertPoint(&I);
1942 SmallVector<Value *, 4> Args;
1944 Args.push_back(I.getCondition());
1945 BBCases.push_back(I.getDefaultDest());
1946 Args.push_back(BlockAddress::get(F, I.getDefaultDest()));
1947 for (auto &Case : I.cases()) {
1948 Args.push_back(Case.getCaseValue());
1949 BBCases.push_back(Case.getCaseSuccessor());
1950 Args.push_back(BlockAddress::get(F, Case.getCaseSuccessor()));
1951 }
1952 CallInst *NewI = B.CreateIntrinsicWithoutFolding(
1953 Intrinsic::spv_switch, {I.getOperand(0)->getType()}, {Args});
1954 // remove switch to avoid its unneeded and undesirable unwrap into branches
1955 // and conditions
1956 replaceAllUsesWith(&I, NewI);
1957 I.eraseFromParent();
1958 // insert artificial and temporary instruction to preserve valid CFG,
1959 // it will be removed after IR translation pass
1960 B.SetInsertPoint(ParentBB);
1961 IndirectBrInst *BrI = B.CreateIndirectBr(
1962 Constant::getNullValue(PointerType::getUnqual(ParentBB->getContext())),
1963 BBCases.size());
1964 for (BasicBlock *BBCase : BBCases)
1965 BrI->addDestination(BBCase);
1966 return BrI;
1967}
1968
1970 return GEP->getNumIndices() > 0 && match(GEP->getOperand(1), m_Zero());
1971}
1972
1973Instruction *SPIRVEmitIntrinsicsImpl::visitIntrinsicInst(IntrinsicInst &I) {
1974 auto *SGEP = dyn_cast<StructuredGEPInst>(&I);
1975 if (!SGEP)
1976 return &I;
1977
1978 IRBuilder<> B(I.getParent());
1979 B.SetInsertPoint(&I);
1980 SmallVector<Type *, 2> Types = {I.getType(), I.getOperand(0)->getType()};
1981 SmallVector<Value *, 4> Args;
1982 Args.push_back(/* inBounds= */ B.getInt1(true));
1983 Args.push_back(I.getOperand(0));
1984 Args.push_back(/* zero index */ B.getInt32(0));
1985 for (unsigned J = 0; J < SGEP->getNumIndices(); ++J)
1986 Args.push_back(SGEP->getIndexOperand(J));
1987
1988 Instruction *NewI =
1989 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, Types, Args);
1990 replaceAllUsesWithAndErase(B, &I, NewI);
1991 return NewI;
1992}
1993
1995SPIRVEmitIntrinsicsImpl::visitGetElementPtrInst(GetElementPtrInst &I) {
1996 IRBuilder<> B(I.getParent());
1997 B.SetInsertPoint(&I);
1998
1999 // OpPtrAccessChain requires a scalar pointer result; scalarize per-lane
2000 // GEPs that return <N x ptr> and rebuild the vector via insertelement.
2001 if (auto *RetVTy = dyn_cast<FixedVectorType>(I.getType())) {
2002 unsigned N = RetVTy->getNumElements();
2003 Value *PtrOp = I.getPointerOperand();
2004 bool PtrIsVec = isa<VectorType>(PtrOp->getType());
2005 Type *ResultPtrTy = RetVTy->getElementType();
2006 Type *ScalarPtrTy = PtrOp->getType()->getScalarType();
2007 SmallVector<Type *, 2> GepTypes = {ResultPtrTy, ScalarPtrTy};
2008 Value *InBounds = B.getInt1(I.isInBounds());
2009 Type *LanePointeeTy = getGEPType(&I);
2010 Type *SrcElemTy = I.getSourceElementType();
2011
2012 // Pin the lane pointee type on the vector operand and on each extracted
2013 // lane so the prelegalizer wraps them as OpTypeVector/OpTypePointer of
2014 // the right element type instead of defaulting to i8.
2015 if (PtrIsVec)
2016 GR->buildAssignPtr(B, SrcElemTy, PtrOp);
2017
2018 Value *VecResult = PoisonValue::get(RetVTy);
2019 for (unsigned Lane = 0; Lane < N; ++Lane) {
2020 Value *LaneIdx = B.getInt32(Lane);
2021 Value *ScalarPtr = PtrOp;
2022 if (PtrIsVec) {
2023 SmallVector<Type *, 3> ExtractTypes = {ScalarPtrTy, PtrOp->getType(),
2024 LaneIdx->getType()};
2025 ScalarPtr = B.CreateIntrinsic(Intrinsic::spv_extractelt, {ExtractTypes},
2026 {PtrOp, LaneIdx});
2027 GR->buildAssignPtr(B, SrcElemTy, ScalarPtr);
2028 }
2029 SmallVector<Value *, 4> Args;
2030 Args.push_back(InBounds);
2031 Args.push_back(ScalarPtr);
2032 for (Value *Idx : I.indices()) {
2033 if (isa<VectorType>(Idx->getType()))
2034 Args.push_back(B.CreateExtractElement(Idx, LaneIdx));
2035 else
2036 Args.push_back(Idx);
2037 }
2038 Value *ScalarGep = B.CreateIntrinsic(Intrinsic::spv_gep, GepTypes, Args);
2039 GR->buildAssignPtr(B, LanePointeeTy, ScalarGep);
2040 VecResult = B.CreateInsertElement(VecResult, ScalarGep, LaneIdx);
2041 }
2042
2043 auto *NewI = cast<Instruction>(VecResult);
2044 replaceAllUsesWithAndErase(B, &I, NewI);
2045
2046 if (CallInst *Old = GR->findAssignPtrTypeInstr(NewI)) {
2047 Old->eraseFromParent();
2048 GR->addAssignPtrTypeInstr(NewI, nullptr);
2049 }
2051 GR->buildAssignPtr(B, LanePointeeTy, NewI);
2052
2053 return NewI;
2054 }
2055
2057 // Logical SPIR-V cannot use the OpPtrAccessChain instruction. If the first
2058 // index of the GEP is not 0, then we need to try to adjust it.
2059 //
2060 // If the GEP is doing byte addressing, try to rebuild the full access chain
2061 // from the type of the pointer.
2062 if (getByteAddressingMultiplier(I.getSourceElementType())) {
2063 return buildLogicalAccessChainFromGEP(I);
2064 }
2065
2066 // Look for the array-to-pointer decay. If this is the pattern
2067 // we can adjust the types, and prepend a 0 to the indices.
2068 Value *PtrOp = I.getPointerOperand();
2069 Type *SrcElemTy = I.getSourceElementType();
2070 Type *DeducedPointeeTy = deduceElementType(PtrOp, true);
2071
2072 if (auto *ArrTy = dyn_cast<ArrayType>(DeducedPointeeTy)) {
2073 if (ArrTy->getElementType() == SrcElemTy) {
2074 SmallVector<Value *> NewIndices;
2075 Type *FirstIdxType = I.getOperand(1)->getType();
2076 NewIndices.push_back(ConstantInt::get(FirstIdxType, 0));
2077 for (Value *Idx : I.indices())
2078 NewIndices.push_back(Idx);
2079
2080 SmallVector<Type *, 2> Types = {I.getType(), I.getPointerOperandType()};
2081 SmallVector<Value *, 4> Args;
2082 Args.push_back(B.getInt1(I.isInBounds()));
2083 Args.push_back(I.getPointerOperand());
2084 Args.append(NewIndices.begin(), NewIndices.end());
2085
2086 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep,
2087 {Types}, {Args});
2088 replaceAllUsesWithAndErase(B, &I, NewI);
2089 return NewI;
2090 }
2091 }
2092 }
2093
2094 SmallVector<Type *, 2> Types = {I.getType(), I.getOperand(0)->getType()};
2095 SmallVector<Value *, 4> Args;
2096 Args.push_back(B.getInt1(I.isInBounds()));
2097 llvm::append_range(Args, I.operands());
2098 Instruction *NewI =
2099 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, {Types}, {Args});
2100 replaceAllUsesWithAndErase(B, &I, NewI);
2101 return NewI;
2102}
2103
2104Instruction *SPIRVEmitIntrinsicsImpl::visitBitCastInst(BitCastInst &I) {
2105 IRBuilder<> B(I.getParent());
2106 B.SetInsertPoint(&I);
2107 Value *Source = I.getOperand(0);
2108
2109 // SPIR-V, contrary to LLVM 17+ IR, supports bitcasts between pointers of
2110 // varying element types. In case of IR coming from older versions of LLVM
2111 // such bitcasts do not provide sufficient information, should be just skipped
2112 // here, and handled in insertPtrCastOrAssignTypeInstr.
2113 if (isPointerTy(I.getType())) {
2114 replaceAllUsesWith(&I, Source);
2115 I.eraseFromParent();
2116 return nullptr;
2117 }
2118
2119 SmallVector<Type *, 2> Types = {I.getType(), Source->getType()};
2120 SmallVector<Value *> Args(I.op_begin(), I.op_end());
2121 Instruction *NewI =
2122 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_bitcast, {Types}, {Args});
2123 replaceAllUsesWithAndErase(B, &I, NewI);
2124 return NewI;
2125}
2126
2127void SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeTargetExt(
2128 TargetExtType *AssignedType, Value *V, IRBuilder<> &B) {
2129 Type *VTy = V->getType();
2130
2131 // A couple of sanity checks.
2132 assert((isPointerTy(VTy)) && "Expect a pointer type!");
2133 if (Type *ElemTy = getPointeeType(VTy))
2134 if (ElemTy != AssignedType)
2135 report_fatal_error("Unexpected pointer element type!");
2136
2137 CallInst *AssignCI = GR->findAssignPtrTypeInstr(V);
2138 if (!AssignCI) {
2139 GR->buildAssignType(B, AssignedType, V);
2140 return;
2141 }
2142
2143 Type *CurrentType =
2145 cast<MetadataAsValue>(AssignCI->getOperand(1))->getMetadata())
2146 ->getType();
2147 if (CurrentType == AssignedType)
2148 return;
2149
2150 // Builtin types cannot be redeclared or casted.
2151 if (CurrentType->isTargetExtTy())
2152 report_fatal_error("Type mismatch " + CurrentType->getTargetExtName() +
2153 "/" + AssignedType->getTargetExtName() +
2154 " for value " + V->getName(),
2155 false);
2156
2157 // Our previous guess about the type seems to be wrong, let's update
2158 // inferred type according to a new, more precise type information.
2159 GR->updateAssignType(AssignCI, V, getNormalizedPoisonValue(AssignedType));
2160}
2161
2162void SPIRVEmitIntrinsicsImpl::replacePointerOperandWithPtrCast(
2163 Instruction *I, Value *Pointer, Type *ExpectedElementType,
2164 unsigned OperandToReplace, IRBuilder<> &B) {
2165 TypeValidated.insert(I);
2166
2167 // Do not emit spv_ptrcast if Pointer's element type is ExpectedElementType
2168 Type *PointerElemTy = deduceElementTypeHelper(Pointer, false);
2169 if (PointerElemTy == ExpectedElementType ||
2170 isEquivalentTypes(PointerElemTy, ExpectedElementType))
2171 return;
2172
2174 Value *ExpectedElementVal = getNormalizedPoisonValue(ExpectedElementType);
2175 MetadataAsValue *VMD = buildMD(ExpectedElementVal);
2176 unsigned AddressSpace = getPointerAddressSpace(Pointer->getType());
2177 bool FirstPtrCastOrAssignPtrType = true;
2178
2179 // Do not emit new spv_ptrcast if equivalent one already exists or when
2180 // spv_assign_ptr_type already targets this pointer with the same element
2181 // type.
2182 if (Pointer->hasUseList()) {
2183 for (auto User : Pointer->users()) {
2184 auto *II = dyn_cast<IntrinsicInst>(User);
2185 if (!II ||
2186 (II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type &&
2187 II->getIntrinsicID() != Intrinsic::spv_ptrcast) ||
2188 II->getOperand(0) != Pointer)
2189 continue;
2190
2191 // There is some spv_ptrcast/spv_assign_ptr_type already targeting this
2192 // pointer.
2193 FirstPtrCastOrAssignPtrType = false;
2194 if (II->getOperand(1) != VMD ||
2195 dyn_cast<ConstantInt>(II->getOperand(2))->getSExtValue() !=
2197 continue;
2198
2199 // The spv_ptrcast/spv_assign_ptr_type targeting this pointer is of the
2200 // same element type and address space.
2201 if (II->getIntrinsicID() != Intrinsic::spv_ptrcast)
2202 return;
2203
2204 // This must be a spv_ptrcast, do not emit new if this one has the same BB
2205 // as I. Otherwise, search for other spv_ptrcast/spv_assign_ptr_type.
2206 if (II->getParent() != I->getParent())
2207 continue;
2208
2209 I->setOperand(OperandToReplace, II);
2210 return;
2211 }
2212 }
2213
2214 // Never replace an already-deduced pointer element type with a non-pointer
2215 // one. The conflicting use comes from a mis-deduced expected type. Leave the
2216 // operand untouched rather than emitting a ptrcast that re-introduces the
2217 // collapsed type at the use site.
2218 if (PointerElemTy && isPointerTyOrWrapper(PointerElemTy) &&
2219 !isPointerTyOrWrapper(ExpectedElementType) &&
2220 tracesToPointerAlloca(Pointer))
2221 return;
2222
2223 if (isa<Instruction>(Pointer) || isa<Argument>(Pointer)) {
2224 if (FirstPtrCastOrAssignPtrType) {
2225 // If this would be the first spv_ptrcast, do not emit spv_ptrcast and
2226 // emit spv_assign_ptr_type instead.
2227 GR->buildAssignPtr(B, ExpectedElementType, Pointer);
2228 return;
2229 } else if (isTodoType(Pointer)) {
2230 eraseTodoType(Pointer);
2231 if (!isa<CallInst>(Pointer) && !isaGEP(Pointer) &&
2232 !isa<AllocaInst>(Pointer)) {
2233 // If this wouldn't be the first spv_ptrcast but existing type info is
2234 // uncomplete, update spv_assign_ptr_type arguments.
2235 if (CallInst *AssignCI = GR->findAssignPtrTypeInstr(Pointer)) {
2236 Type *PrevElemTy = GR->findDeducedElementType(Pointer);
2237 assert(PrevElemTy);
2238 DenseSet<std::pair<Value *, Value *>> VisitedSubst{
2239 std::make_pair(I, Pointer)};
2240 GR->updateAssignType(AssignCI, Pointer, ExpectedElementVal);
2241 propagateElemType(Pointer, PrevElemTy, VisitedSubst);
2242 } else {
2243 GR->buildAssignPtr(B, ExpectedElementType, Pointer);
2244 }
2245 return;
2246 }
2247 }
2248 }
2249
2250 // Emit spv_ptrcast
2251 SmallVector<Type *, 2> Types = {Pointer->getType(), Pointer->getType()};
2252 SmallVector<Value *, 2> Args = {Pointer, VMD, B.getInt32(AddressSpace)};
2253 auto *PtrCastI = B.CreateIntrinsic(Intrinsic::spv_ptrcast, {Types}, Args);
2254 I->setOperand(OperandToReplace, PtrCastI);
2255 // We need to set up a pointee type for the newly created spv_ptrcast.
2256 GR->buildAssignPtr(B, ExpectedElementType, PtrCastI);
2257}
2258
2259void SPIRVEmitIntrinsicsImpl::insertPtrCastOrAssignTypeInstr(Instruction *I,
2260 IRBuilder<> &B) {
2261 // Handle basic instructions:
2262 StoreInst *SI = dyn_cast<StoreInst>(I);
2263 if (IsKernelArgInt8(CurrF, SI)) {
2264 replacePointerOperandWithPtrCast(
2265 I, SI->getValueOperand(), IntegerType::getInt8Ty(CurrF->getContext()),
2266 0, B);
2267 }
2268 if (SI) {
2269 Value *Op = SI->getValueOperand();
2270 Value *Pointer = SI->getPointerOperand();
2271 Type *OpTy = Op->getType();
2272 if (auto *OpI = dyn_cast<Instruction>(Op)) {
2273 OpTy = restoreMutatedType(GR, OpI, OpTy);
2274 if (auto It = AggrConstTypes.find(OpI); It != AggrConstTypes.end())
2275 OpTy = It->second;
2276 }
2277 if (OpTy == Op->getType())
2278 OpTy = deduceElementTypeByValueDeep(OpTy, Op, false);
2279 replacePointerOperandWithPtrCast(I, Pointer, OpTy, 1, B);
2280 return;
2281 }
2282 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2283 Value *Pointer = LI->getPointerOperand();
2284 Type *OpTy = LI->getType();
2285 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
2286 if (Type *ElemTy = GR->findDeducedElementType(LI)) {
2287 OpTy = getTypedPointerWrapper(ElemTy, PtrTy->getAddressSpace());
2288 } else {
2289 Type *NewOpTy = OpTy;
2290 OpTy = deduceElementTypeByValueDeep(OpTy, LI, false);
2291 if (OpTy == NewOpTy)
2292 insertTodoType(Pointer);
2293 }
2294 }
2295 replacePointerOperandWithPtrCast(I, Pointer, OpTy, 0, B);
2296 return;
2297 }
2298 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2299 Value *Pointer = GEPI->getPointerOperand();
2300 Type *OpTy = nullptr;
2301
2302 // Logical SPIR-V is not allowed to use Op*PtrAccessChain instructions. If
2303 // the first index is 0, then we can trivially lower to OpAccessChain. If
2304 // not we need to try to rewrite the GEP. We avoid adding a pointer cast at
2305 // this time, and will rewrite the GEP when visiting it.
2306 if (TM.getSubtargetImpl()->isLogicalSPIRV() && !isFirstIndexZero(GEPI)) {
2307 return;
2308 }
2309
2310 // In all cases, fall back to the GEP type if type scavenging failed.
2311 if (!OpTy)
2312 OpTy = GEPI->getSourceElementType();
2313
2314 replacePointerOperandWithPtrCast(I, Pointer, OpTy, 0, B);
2315 if (isNestedPointer(OpTy))
2316 insertTodoType(Pointer);
2317 return;
2318 }
2319
2320 // TODO: review and merge with existing logics:
2321 // Handle calls to builtins (non-intrinsics):
2322 CallInst *CI = dyn_cast<CallInst>(I);
2323 if (!CI || CI->isIndirectCall() || CI->isInlineAsm() ||
2325 return;
2326
2327 // collect information about formal parameter types
2328 std::string DemangledName =
2330 Function *CalledF = CI->getCalledFunction();
2331 SmallVector<Type *, 4> CalledArgTys;
2332 bool HaveTypes = false;
2333 for (unsigned OpIdx = 0; OpIdx < CalledF->arg_size(); ++OpIdx) {
2334 Argument *CalledArg = CalledF->getArg(OpIdx);
2335 Type *ArgType = CalledArg->getType();
2336 if (!isPointerTy(ArgType)) {
2337 CalledArgTys.push_back(nullptr);
2338 } else if (Type *ArgTypeElem = getPointeeType(ArgType)) {
2339 CalledArgTys.push_back(ArgTypeElem);
2340 HaveTypes = true;
2341 } else {
2342 Type *ElemTy = GR->findDeducedElementType(CalledArg);
2343 if (!ElemTy && hasPointeeTypeAttr(CalledArg))
2344 ElemTy = getPointeeTypeByAttr(CalledArg);
2345 if (!ElemTy) {
2346 ElemTy = getPointeeTypeByCallInst(DemangledName, CalledF, OpIdx);
2347 if (ElemTy) {
2348 GR->addDeducedElementType(CalledArg, normalizeType(ElemTy));
2349 } else {
2350 for (User *U : CalledArg->users()) {
2351 if (Instruction *Inst = dyn_cast<Instruction>(U)) {
2352 if ((ElemTy = deduceElementTypeHelper(Inst, false)) != nullptr)
2353 break;
2354 }
2355 }
2356 }
2357 }
2358 HaveTypes |= ElemTy != nullptr;
2359 CalledArgTys.push_back(ElemTy);
2360 }
2361 }
2362
2363 if (DemangledName.empty() && !HaveTypes)
2364 return;
2365
2366 for (unsigned OpIdx = 0; OpIdx < CI->arg_size(); OpIdx++) {
2367 Value *ArgOperand = CI->getArgOperand(OpIdx);
2368 if (!isPointerTy(ArgOperand->getType()))
2369 continue;
2370
2371 // Constants (nulls/undefs) are handled in insertAssignPtrTypeIntrs()
2372 if (!isa<Instruction>(ArgOperand) && !isa<Argument>(ArgOperand)) {
2373 // However, we may have assumptions about the formal argument's type and
2374 // may have a need to insert a ptr cast for the actual parameter of this
2375 // call.
2376 Argument *CalledArg = CalledF->getArg(OpIdx);
2377 if (!GR->findDeducedElementType(CalledArg))
2378 continue;
2379 }
2380
2381 Type *ExpectedType =
2382 OpIdx < CalledArgTys.size() ? CalledArgTys[OpIdx] : nullptr;
2383 if (!ExpectedType && !DemangledName.empty())
2384 ExpectedType = SPIRV::parseBuiltinCallArgumentBaseType(
2385 DemangledName, OpIdx, I->getContext());
2386 if (!ExpectedType || ExpectedType->isVoidTy())
2387 continue;
2388
2389 if (ExpectedType->isTargetExtTy() &&
2391 insertAssignPtrTypeTargetExt(cast<TargetExtType>(ExpectedType),
2392 ArgOperand, B);
2393 else
2394 replacePointerOperandWithPtrCast(CI, ArgOperand, ExpectedType, OpIdx, B);
2395 }
2396}
2397
2399SPIRVEmitIntrinsicsImpl::visitInsertElementInst(InsertElementInst &I) {
2400 // If it's a <1 x Type> vector type, don't modify it. It's not a legal vector
2401 // type in LLT and IRTranslator will replace it by the scalar.
2402 if (isVector1(I.getType()))
2403 return &I;
2404
2405 SmallVector<Type *, 4> Types = {I.getType(), I.getOperand(0)->getType(),
2406 I.getOperand(1)->getType(),
2407 I.getOperand(2)->getType()};
2408 IRBuilder<> B(I.getParent());
2409 B.SetInsertPoint(&I);
2410 SmallVector<Value *> Args(I.op_begin(), I.op_end());
2411 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertelt,
2412 {Types}, {Args});
2413 replaceAllUsesWithAndErase(B, &I, NewI);
2414 return NewI;
2415}
2416
2418SPIRVEmitIntrinsicsImpl::visitExtractElementInst(ExtractElementInst &I) {
2419 // If it's a <1 x Type> vector type, don't modify it. It's not a legal vector
2420 // type in LLT and IRTranslator will replace it by the scalar.
2421 if (isVector1(I.getVectorOperandType()))
2422 return &I;
2423
2424 IRBuilder<> B(I.getParent());
2425 B.SetInsertPoint(&I);
2426 SmallVector<Type *, 3> Types = {I.getType(), I.getVectorOperandType(),
2427 I.getIndexOperand()->getType()};
2428 SmallVector<Value *, 2> Args = {I.getVectorOperand(), I.getIndexOperand()};
2429 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractelt,
2430 {Types}, {Args});
2431 replaceAllUsesWithAndErase(B, &I, NewI);
2432 return NewI;
2433}
2434
2435Instruction *SPIRVEmitIntrinsicsImpl::visitInsertValueInst(InsertValueInst &I) {
2436 IRBuilder<> B(I.getParent());
2437 B.SetInsertPoint(&I);
2438 SmallVector<Type *, 1> Types = {I.getInsertedValueOperand()->getType()};
2440 Value *AggregateOp = I.getAggregateOperand();
2441 if (isa<UndefValue>(AggregateOp))
2442 Args.push_back(UndefValue::get(B.getInt32Ty()));
2443 else
2444 Args.push_back(AggregateOp);
2445 Args.push_back(I.getInsertedValueOperand());
2446 for (auto &Op : I.indices())
2447 Args.push_back(B.getInt32(Op));
2448 Instruction *NewI =
2449 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertv, {Types}, {Args});
2450 replaceMemInstrUses(&I, NewI, B);
2451 return NewI;
2452}
2453
2455SPIRVEmitIntrinsicsImpl::visitExtractValueInst(ExtractValueInst &I) {
2456 IRBuilder<> B(I.getParent());
2457 B.SetInsertPoint(&I);
2458 if (I.getAggregateOperand()->getType()->isAggregateType()) {
2459 // Mutate an aggregate-returning spv_extractv producer to i32 so
2460 // IRTranslator does not see a multi-register value.
2461 CallBase *CB = dyn_cast<CallBase>(I.getAggregateOperand());
2462 if (!CB || CB->getIntrinsicID() != Intrinsic::spv_extractv)
2463 return &I;
2464 CB->mutateType(B.getInt32Ty());
2465 }
2466 SmallVector<Value *> Args(I.operands());
2467 for (auto &Op : I.indices())
2468 Args.push_back(B.getInt32(Op));
2469 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractv,
2470 {I.getType()}, {Args});
2471 // If this aggregate extract feeds another insertvalue, the extracted
2472 // composite is used as a SPIR-V value-id by llvm.spv.insertv. Keep the real
2473 // aggregate type in metadata, but expose the value itself as i32 so the
2474 // intrinsic signature remains valid.
2475 if (NewI->getType()->isAggregateType() &&
2476 any_of(I.users(), [](User *U) { return isa<InsertValueInst>(U); })) {
2477 AggrConstTypes[NewI] = I.getType();
2478 NewI->mutateType(B.getInt32Ty());
2479 replaceMemInstrUses(&I, NewI, B);
2480 return NewI;
2481 }
2482 replaceAllUsesWithAndErase(B, &I, NewI);
2483 // If the aggregate result feeds a return or callsite whose type was rewritten
2484 // to an i32 value-id by SPIRVPrepareFunctions, mutate it to match.
2485 if (NewI->getType()->isAggregateType()) {
2486 for (const Use &U : NewI->uses()) {
2487 User *Usr = U.getUser();
2488 if (auto *RI = dyn_cast<ReturnInst>(Usr)) {
2489 if (RI->getFunction()->getReturnType() != NewI->getType()) {
2490 NewI->mutateType(B.getInt32Ty());
2491 break;
2492 }
2493 continue;
2494 }
2495 auto *CB = dyn_cast<CallBase>(Usr);
2496 if (!CB || !CB->isArgOperand(&U))
2497 continue;
2498 unsigned ArgNo = CB->getArgOperandNo(&U);
2499 FunctionType *FT = CB->getFunctionType();
2500 if (ArgNo < FT->getNumParams() &&
2501 !FT->getParamType(ArgNo)->isAggregateType()) {
2502 NewI->mutateType(B.getInt32Ty());
2503 break;
2504 }
2505 }
2506 }
2507 return NewI;
2508}
2509
2510Instruction *SPIRVEmitIntrinsicsImpl::visitLoadInst(LoadInst &I) {
2511 if (!I.getType()->isAggregateType())
2512 return &I;
2513 IRBuilder<> B(I.getParent());
2514 B.SetInsertPoint(&I);
2515 TrackConstants = false;
2516 const auto *TLI = TM.getSubtargetImpl()->getTargetLowering();
2518 TLI->getLoadMemOperandFlags(I, CurrF->getDataLayout());
2519
2520 unsigned IntrinsicId;
2521 SmallVector<Value *, 4> Args = {I.getPointerOperand(), B.getInt16(Flags)};
2522 if (!I.isAtomic()) {
2523 IntrinsicId = Intrinsic::spv_load;
2524 Args.push_back(B.getInt32(I.getAlign().value()));
2525 } else {
2526 IntrinsicId = Intrinsic::spv_atomic_load;
2527 Args.push_back(B.getInt8(static_cast<uint8_t>(I.getOrdering())));
2528 }
2529 CallInst *NewI = B.CreateIntrinsicWithoutFolding(
2530 IntrinsicId, {I.getOperand(0)->getType()}, Args);
2531
2532 replaceMemInstrUses(&I, NewI, B);
2533 return NewI;
2534}
2535
2536Instruction *SPIRVEmitIntrinsicsImpl::visitStoreInst(StoreInst &I) {
2537 if (!AggrStores.contains(&I))
2538 return &I;
2539 IRBuilder<> B(I.getParent());
2540 B.SetInsertPoint(&I);
2541 TrackConstants = false;
2542 const auto *TLI = TM.getSubtargetImpl()->getTargetLowering();
2544 TLI->getStoreMemOperandFlags(I, CurrF->getDataLayout());
2545 auto *PtrOp = I.getPointerOperand();
2546
2547 if (I.getValueOperand()->getType()->isAggregateType()) {
2548 // It is possible that what used to be an ExtractValueInst has been replaced
2549 // with a call to the spv_extractv intrinsic, and that said call hasn't
2550 // had its return type replaced with i32 during the dedicated pass (because
2551 // it was emitted later); we have to handle this here, because IRTranslator
2552 // cannot deal with multi-register types at the moment.
2553 CallBase *CB = dyn_cast<CallBase>(I.getValueOperand());
2554 assert(CB && CB->getIntrinsicID() == Intrinsic::spv_extractv &&
2555 "Unexpected argument of aggregate type, should be spv_extractv!");
2556 CB->mutateType(B.getInt32Ty());
2557 }
2558
2559 unsigned IntrinsicId;
2560 SmallVector<Value *, 4> Args = {I.getValueOperand(), PtrOp,
2561 B.getInt16(Flags)};
2562 if (!I.isAtomic()) {
2563 IntrinsicId = Intrinsic::spv_store;
2564 Args.push_back(B.getInt32(I.getAlign().value()));
2565 } else {
2566 IntrinsicId = Intrinsic::spv_atomic_store;
2567 Args.push_back(B.getInt8(static_cast<uint8_t>(I.getOrdering())));
2568 }
2569 Instruction *NewI = B.CreateIntrinsicWithoutFolding(
2570 IntrinsicId, {I.getValueOperand()->getType(), PtrOp->getType()}, Args);
2571 NewI->copyMetadata(I);
2572 I.eraseFromParent();
2573 return NewI;
2574}
2575
2576Instruction *SPIRVEmitIntrinsicsImpl::visitAllocaInst(AllocaInst &I) {
2577 Value *ArraySize = nullptr;
2578 if (I.isArrayAllocation()) {
2579 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*I.getFunction());
2580 if (!STI->canUseExtension(
2581 SPIRV::Extension::SPV_INTEL_variable_length_array))
2583 "array allocation: this instruction requires the following "
2584 "SPIR-V extension: SPV_INTEL_variable_length_array",
2585 false);
2586 ArraySize = I.getArraySize();
2587 }
2588 IRBuilder<> B(I.getParent());
2589 B.SetInsertPoint(&I);
2590 TrackConstants = false;
2591 Type *PtrTy = I.getType();
2592 Instruction *NewI =
2593 ArraySize
2594 ? B.CreateIntrinsicWithoutFolding(
2595 Intrinsic::spv_alloca_array, {PtrTy, ArraySize->getType()},
2596 {ArraySize, B.getInt32(I.getAlign().value())})
2597 : B.CreateIntrinsicWithoutFolding(Intrinsic::spv_alloca, {PtrTy},
2598 {B.getInt32(I.getAlign().value())});
2599 replaceAllUsesWithAndErase(B, &I, NewI);
2600 return NewI;
2601}
2602
2604SPIRVEmitIntrinsicsImpl::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
2605 assert(I.getType()->isAggregateType() && "Aggregate result is expected");
2606 IRBuilder<> B(I.getParent());
2607 B.SetInsertPoint(&I);
2608 SmallVector<Value *> Args(I.operands());
2609 Args.push_back(B.getInt32(static_cast<uint32_t>(
2610 getMemScope(TM.getTargetTriple(), I.getContext(), I.getSyncScopeID()))));
2611 // Per SPIR-V spec atomic ops must combine the ordering bits with the
2612 // storage-class bit.
2613 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
2614 unsigned AS = I.getPointerOperand()->getType()->getPointerAddressSpace();
2615 uint32_t ScSem = static_cast<uint32_t>(
2617 Args.push_back(B.getInt32(
2618 static_cast<uint32_t>(getMemSemantics(I.getSuccessOrdering())) | ScSem));
2619 Args.push_back(B.getInt32(
2620 static_cast<uint32_t>(getMemSemantics(I.getFailureOrdering())) | ScSem));
2621 Instruction *NewI = B.CreateIntrinsicWithoutFolding(
2622 Intrinsic::spv_cmpxchg, {I.getPointerOperand()->getType()}, {Args});
2623 replaceMemInstrUses(&I, NewI, B);
2624 return NewI;
2625}
2626
2627static bool isAbortCall(const Instruction &I, const SPIRVSubtarget &ST) {
2628 auto *CI = dyn_cast<CallInst>(&I);
2629 if (!CI)
2630 return false;
2631 switch (CI->getIntrinsicID()) {
2632 case Intrinsic::spv_abort:
2633 return true;
2634 case Intrinsic::trap:
2635 case Intrinsic::ubsantrap:
2636 // When the extension is enabled, selection lowers these to OpAbortKHR.
2637 return ST.canUseExtension(SPIRV::Extension::SPV_KHR_abort);
2638 default:
2639 return false;
2640 }
2641}
2642
2643// The OpAbortKHR instruction itself is a block terminator, so we don't need to
2644// emit an extra OpUnreachable instruction.
2646 const SPIRVSubtarget &ST) {
2647 // Find a previous non-debug instruction.
2648 const Instruction *Prev = I.getPrevNode();
2649 while (Prev && Prev->isDebugOrPseudoInst())
2650 Prev = Prev->getPrevNode();
2651
2652 if (Prev && isAbortCall(*Prev, ST))
2653 return true;
2654
2656 *I.getParent(),
2657 [&ST](const Instruction &II) { return isAbortCall(II, ST); }) &&
2658 "abort-like call must be the last non-debug instruction before its "
2659 "block's terminator");
2660 return false;
2661}
2662
2663Instruction *SPIRVEmitIntrinsicsImpl::visitUnreachableInst(UnreachableInst &I) {
2664 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
2665 if (precededByAbortIntrinsic(I, ST))
2666 return &I;
2667 IRBuilder<> B(&I);
2668 B.CreateIntrinsic(Intrinsic::spv_unreachable, {});
2669 return &I;
2670}
2671
2672// llvm.compiler.used and llvm.used hold use-list entries that protect their
2673// referenced globals from DCE without participating in code generation.
2674static bool isUseListGlobal(StringRef Name) {
2675 return Name == "llvm.compiler.used" || Name == "llvm.used";
2676}
2677
2678// Returns true for module-level globals that should not have SPIR-V intrinsics
2679// emitted (use-list globals plus llvm.global.annotations).
2681 return isUseListGlobal(Name) || Name == "llvm.global.annotations";
2682}
2683
2684// Returns true if every use of GV traces back to llvm.compiler.used or
2685// llvm.used.
2689 while (!Stack.empty()) {
2690 const Value *V = Stack.pop_back_val();
2691 if (!Visited.insert(V).second)
2692 continue;
2693 if (const auto *GVUser = dyn_cast<GlobalVariable>(V)) {
2694 if (!isUseListGlobal(GVUser->getName()))
2695 return false;
2696 continue;
2697 }
2698 if (const auto *C = dyn_cast<Constant>(V)) {
2699 Stack.append(C->user_begin(), C->user_end());
2700 continue;
2701 }
2702 return false;
2703 }
2704 return true;
2705}
2706
2707static bool
2708shouldEmitIntrinsicsForGlobalValue(const GlobalVariableUsers &GVUsers,
2709 const GlobalVariable &GV,
2710 const Function *F) {
2711 // Skip special artificial variables.
2712 if (isArtificialGlobal(GV.getName()))
2713 return false;
2714
2715 auto &UserFunctions = GVUsers.getTransitiveUserFunctions(GV);
2716 if (UserFunctions.contains(F))
2717 return true;
2718
2719 // Do not emit the intrinsics in this function, it's going to be emitted on
2720 // the functions that reference it.
2721 if (!UserFunctions.empty())
2722 return false;
2723
2724 // Emit definitions for globals that are not referenced by any function on the
2725 // first function definition.
2726 const Module &M = *F->getParent();
2727 const Function &FirstDefinition = *M.getFunctionDefs().begin();
2728 return F == &FirstDefinition;
2729}
2730
2731Value *SPIRVEmitIntrinsicsImpl::buildSpvUndefComposite(Type *AggrTy,
2732 IRBuilder<> &B) {
2733 auto MakeLeaf = [&](Type *ElemTy) -> Instruction * {
2734 CallInst *Leaf = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_undef, {});
2735 AggrConsts[Leaf] = PoisonValue::get(ElemTy);
2736 AggrConstTypes[Leaf] = ElemTy;
2737 return Leaf;
2738 };
2739 SmallVector<Value *, 4> Elems;
2740 if (auto *ArrTy = dyn_cast<ArrayType>(AggrTy)) {
2741 Elems.assign(ArrTy->getNumElements(), MakeLeaf(ArrTy->getElementType()));
2742 } else {
2743 auto *StructTy = cast<StructType>(AggrTy);
2744 DenseMap<Type *, Instruction *> LeafByType;
2745 for (unsigned I = 0; I < StructTy->getNumElements(); ++I) {
2746 Type *ElemTy = StructTy->getContainedType(I);
2747 auto &Entry = LeafByType[ElemTy];
2748 if (!Entry)
2749 Entry = MakeLeaf(ElemTy);
2750 Elems.push_back(Entry);
2751 }
2752 }
2753 CallInst *Composite = B.CreateIntrinsicWithoutFolding(
2754 Intrinsic::spv_const_composite, {B.getInt32Ty()}, Elems);
2755 AggrConsts[Composite] = PoisonValue::get(AggrTy);
2756 AggrConstTypes[Composite] = AggrTy;
2757 return Composite;
2758}
2759
2760// If a function directly returns an aggregate-typed call result,
2761// the ReturnInst carries an aggregate while the function signature
2762// was rewritten to i32 by SPIRVPrepareFunctions. Rebuild the return value
2763// via extractvalue/insertvalue so the regular spv_extractv/spv_insertv
2764// lowering produces a valid OpReturnValue.
2765void SPIRVEmitIntrinsicsImpl::reconstructAggregateReturns(Function &Func,
2766 IRBuilder<> &B) {
2767 Type *OrigRetTy = GR->findMutated(&Func);
2768 if (!OrigRetTy || !OrigRetTy->isAggregateType())
2769 return;
2770 for (BasicBlock &BB : Func) {
2771 auto *RI = dyn_cast<ReturnInst>(BB.getTerminator());
2772 if (!RI)
2773 continue;
2774 Value *RetVal = RI->getReturnValue();
2775 if (!RetVal || RetVal->getType() != OrigRetTy || !isa<CallBase>(RetVal))
2776 continue;
2777 Type *AggrTy = RetVal->getType();
2778 uint64_t NumElts = isa<StructType>(AggrTy)
2779 ? cast<StructType>(AggrTy)->getNumElements()
2780 : cast<ArrayType>(AggrTy)->getNumElements();
2781 B.SetInsertPoint(RI);
2782 Value *Rebuilt = PoisonValue::get(AggrTy);
2783 for (uint64_t I = 0; I < NumElts; ++I) {
2784 Value *Elt = B.CreateExtractValue(RetVal, I);
2785 Rebuilt = B.CreateInsertValue(Rebuilt, Elt, I);
2786 }
2787 RI->setOperand(0, Rebuilt);
2788 }
2789}
2790
2791void SPIRVEmitIntrinsicsImpl::processGlobalValue(GlobalVariable &GV,
2792 IRBuilder<> &B) {
2793
2794 if (!shouldEmitIntrinsicsForGlobalValue(GVUsers, GV, CurrF))
2795 return;
2796
2797 // Record the pointee type for every global, not only initialized ones, so an
2798 // undef non-constant aggregate global is not later collapsed to its element
2799 // type. Result is ignored, because TypedPointerType is not supported
2800 // by llvm IR general logic.
2801 deduceElementTypeHelper(&GV, false);
2802
2803 Constant *Init = nullptr;
2804 if (hasInitializer(&GV)) {
2805 Init = GV.getInitializer();
2806 Value *InitOp = Init;
2807 if (isa<UndefValue>(Init) && Init->getType()->isAggregateType()) {
2808 const SPIRVSubtarget *STI = TM.getSubtargetImpl();
2809 bool UsePoison =
2810 isa<PoisonValue>(Init) &&
2811 STI->canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
2812 if (UsePoison) {
2813 CallInst *Call = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_poison,
2814 {B.getInt32Ty()}, {});
2815 AggrConsts[Call] = cast<PoisonValue>(Init);
2816 AggrConstTypes[Call] = Init->getType();
2817 InitOp = Call;
2818 } else {
2819 InitOp = buildSpvUndefComposite(Init->getType(), B);
2820 }
2821 }
2822 Type *Ty = isAggrConstForceInt32(Init) ? B.getInt32Ty() : Init->getType();
2823 Constant *Const = isAggrConstForceInt32(Init) ? B.getInt32(1) : Init;
2824 CallInst *InitInst = B.CreateIntrinsicWithoutFolding(
2825 Intrinsic::spv_init_global, {GV.getType(), Ty}, {&GV, Const});
2826 InitInst->setArgOperand(1, InitOp);
2827 }
2828 // Globals with only use-list references have no real function uses. Emit
2829 // spv_unref_global so buildGlobalVariable is called for them.
2830 if (!Init && hasOnlyArtificialUses(GV))
2831 B.CreateIntrinsic(Intrinsic::spv_unref_global, GV.getType(), &GV);
2832}
2833
2834// Return true, if we can't decide what is the pointee type now and will get
2835// back to the question later. Return false is spv_assign_ptr_type is not needed
2836// or can be inserted immediately.
2837bool SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeIntrs(Instruction *I,
2838 IRBuilder<> &B,
2839 bool UnknownElemTypeI8) {
2841 if (!isPointerTy(I->getType()) || !requireAssignType(I))
2842 return false;
2843
2845 if (Type *ElemTy = deduceElementType(I, UnknownElemTypeI8)) {
2846 GR->buildAssignPtr(B, ElemTy, I);
2847 return false;
2848 }
2849 return true;
2850}
2851
2852void SPIRVEmitIntrinsicsImpl::insertAssignTypeIntrs(Instruction *I,
2853 IRBuilder<> &B) {
2854 // TODO: extend the list of functions with known result types
2855 static StringMap<unsigned> ResTypeWellKnown = {
2856 {"async_work_group_copy", WellKnownTypes::Event},
2857 {"async_work_group_strided_copy", WellKnownTypes::Event},
2858 {"__spirv_GroupAsyncCopy", WellKnownTypes::Event}};
2859
2861
2862 bool IsKnown = false;
2863 if (auto *CI = dyn_cast<CallInst>(I)) {
2864 if (!CI->isIndirectCall() && !CI->isInlineAsm() &&
2865 CI->getCalledFunction() && !CI->getCalledFunction()->isIntrinsic()) {
2866 Function *CalledF = CI->getCalledFunction();
2867 std::string DemangledName =
2869 FPDecorationId DecorationId = FPDecorationId::NONE;
2870 if (DemangledName.length() > 0)
2871 DemangledName =
2872 SPIRV::lookupBuiltinNameHelper(DemangledName, &DecorationId);
2873 auto ResIt = ResTypeWellKnown.find(DemangledName);
2874 if (ResIt != ResTypeWellKnown.end()) {
2875 IsKnown = true;
2877 switch (ResIt->second) {
2878 case WellKnownTypes::Event:
2879 GR->buildAssignType(
2880 B, TargetExtType::get(I->getContext(), "spirv.Event"), I);
2881 break;
2882 }
2883 }
2884 // check if a floating rounding mode or saturation info is present
2885 switch (DecorationId) {
2886 default:
2887 break;
2888 case FPDecorationId::SAT:
2890 break;
2891 case FPDecorationId::RTE:
2893 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTE, B);
2894 break;
2895 case FPDecorationId::RTZ:
2897 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTZ, B);
2898 break;
2899 case FPDecorationId::RTP:
2901 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTP, B);
2902 break;
2903 case FPDecorationId::RTN:
2905 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTN, B);
2906 break;
2907 }
2908 }
2909 }
2910
2911 Type *Ty = I->getType();
2912 if (!IsKnown && !Ty->isVoidTy() && !isPointerTy(Ty) && requireAssignType(I)) {
2914 Type *TypeToAssign = Ty;
2915 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2916 if (isSpvAggrPlaceholder(II)) {
2917 auto It = AggrConstTypes.find(II);
2918 if (It == AggrConstTypes.end())
2919 report_fatal_error("Unknown composite intrinsic type");
2920 TypeToAssign = It->second;
2921 } else if (II->getIntrinsicID() == Intrinsic::spv_poison) {
2922 if (auto It = AggrConstTypes.find(II); It != AggrConstTypes.end())
2923 TypeToAssign = It->second;
2924 }
2925 } else if (auto It = AggrConstTypes.find(I); It != AggrConstTypes.end())
2926 TypeToAssign = It->second;
2927 TypeToAssign = restoreMutatedType(GR, I, TypeToAssign);
2928 GR->buildAssignType(B, TypeToAssign, I);
2929 }
2930 for (const auto &Op : I->operands()) {
2932 // Check GetElementPtrConstantExpr case.
2934 (isa<GEPOperator>(Op) ||
2935 (cast<ConstantExpr>(Op)->getOpcode() == CastInst::IntToPtr)))) {
2937 Type *OpTy = Op->getType();
2938 if (isa<UndefValue>(Op) && OpTy->isAggregateType()) {
2939 CallInst *AssignCI =
2940 buildIntrWithMD(Intrinsic::spv_assign_type, {B.getInt32Ty()}, Op,
2941 UndefValue::get(B.getInt32Ty()), {}, B);
2942 GR->addAssignPtrTypeInstr(Op, AssignCI);
2943 } else if (!isa<Instruction>(Op)) {
2944 Type *OpTy = Op->getType();
2945 Type *OpTyElem = getPointeeType(OpTy);
2946 if (OpTyElem) {
2947 GR->buildAssignPtr(B, OpTyElem, Op);
2948 } else if (isPointerTy(OpTy)) {
2949 Type *ElemTy = GR->findDeducedElementType(Op);
2950 GR->buildAssignPtr(B, ElemTy ? ElemTy : deduceElementType(Op, true),
2951 Op);
2952 } else {
2953 Value *OpTyVal = Op;
2954 if (OpTy->isTargetExtTy()) {
2955 // We need to do this in order to be consistent with how target ext
2956 // types are handled in `processInstrAfterVisit`
2957 OpTyVal = getNormalizedPoisonValue(OpTy);
2958 }
2959 CallInst *AssignCI =
2960 buildIntrWithMD(Intrinsic::spv_assign_type, {OpTy},
2961 getNormalizedPoisonValue(OpTy), OpTyVal, {}, B);
2962 GR->addAssignPtrTypeInstr(OpTyVal, AssignCI);
2963 }
2964 }
2965 }
2966 }
2967}
2968
2969bool SPIRVEmitIntrinsicsImpl::shouldTryToAddMemAliasingDecoration(
2970 Instruction *Inst) {
2971 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*Inst->getFunction());
2972 if (!STI->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing))
2973 return false;
2974 // Add aliasing decorations to internal load and store intrinsics.
2975 // Do not attach them to store atomic or load atomic intrinsics / instructions
2976 // since the extension is inconsistent at the moment (we cannot add the
2977 // decoration to atomic stores because they do not have an id).
2978 return match(Inst,
2980}
2981
2982void SPIRVEmitIntrinsicsImpl::insertSpirvDecorations(Instruction *I,
2983 IRBuilder<> &B) {
2984 if (MDNode *MD = I->getMetadata("spirv.Decorations")) {
2986 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {I->getType()},
2987 {I, MetadataAsValue::get(I->getContext(), MD)});
2988 }
2989 // Lower alias.scope/noalias metadata
2990 {
2991 auto processMemAliasingDecoration = [&](unsigned Kind) {
2992 if (MDNode *AliasListMD = I->getMetadata(Kind)) {
2993 if (shouldTryToAddMemAliasingDecoration(I)) {
2994 uint32_t Dec = Kind == LLVMContext::MD_alias_scope
2995 ? SPIRV::Decoration::AliasScopeINTEL
2996 : SPIRV::Decoration::NoAliasINTEL;
2998 I, ConstantInt::get(B.getInt32Ty(), Dec),
2999 MetadataAsValue::get(I->getContext(), AliasListMD)};
3001 B.CreateIntrinsic(Intrinsic::spv_assign_aliasing_decoration,
3002 {I->getType()}, {Args});
3003 }
3004 }
3005 };
3006 processMemAliasingDecoration(LLVMContext::MD_alias_scope);
3007 processMemAliasingDecoration(LLVMContext::MD_noalias);
3008 }
3009 // MD_fpmath
3010 if (MDNode *MD = I->getMetadata(LLVMContext::MD_fpmath)) {
3011 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*I->getFunction());
3012 bool AllowFPMaxError =
3013 STI->canUseExtension(SPIRV::Extension::SPV_INTEL_fp_max_error);
3014 if (!AllowFPMaxError)
3015 return;
3016
3018 B.CreateIntrinsic(Intrinsic::spv_assign_fpmaxerror_decoration,
3019 {I->getType()},
3020 {I, MetadataAsValue::get(I->getContext(), MD)});
3021 }
3022 if (I->getModule()->getTargetTriple().getVendor() == Triple::AMD &&
3024 // If present, we encode AMDGPU atomic metadata as UserSemantic string
3025 // decorations, which will be parsed during reverse translation.
3026 auto &Ctx = B.getContext();
3027 auto *US = ConstantAsMetadata::get(
3028 ConstantInt::get(B.getInt32Ty(), SPIRV::Decoration::UserSemantic));
3029
3031 if (I->hasMetadata("amdgpu.no.fine.grained.memory"))
3033 Ctx, {US, MDString::get(Ctx, "amdgpu.no.fine.grained.memory")}));
3034 if (I->hasMetadata("amdgpu.no.remote.memory"))
3036 Ctx, {US, MDString::get(Ctx, "amdgpu.no.remote.memory")}));
3037 if (I->hasMetadata("amdgpu.ignore.denormal.mode"))
3039 Ctx, {US, MDString::get(Ctx, "amdgpu.ignore.denormal.mode")}));
3040 if (!MDs.empty())
3041 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {I->getType()},
3042 {I, MetadataAsValue::get(Ctx, MDNode::get(Ctx, MDs))});
3043 }
3044}
3045
3047 const Module &M,
3049 &FPFastMathDefaultInfoMap,
3050 Function *F) {
3051 auto it = FPFastMathDefaultInfoMap.find(F);
3052 if (it != FPFastMathDefaultInfoMap.end())
3053 return it->second;
3054
3055 // If the map does not contain the entry, create a new one. Initialize it to
3056 // contain all 3 elements sorted by bit width of target type: {half, float,
3057 // double}.
3058 SPIRV::FPFastMathDefaultInfoVector FPFastMathDefaultInfoVec;
3059 FPFastMathDefaultInfoVec.emplace_back(Type::getHalfTy(M.getContext()),
3060 SPIRV::FPFastMathMode::None);
3061 FPFastMathDefaultInfoVec.emplace_back(Type::getFloatTy(M.getContext()),
3062 SPIRV::FPFastMathMode::None);
3063 FPFastMathDefaultInfoVec.emplace_back(Type::getDoubleTy(M.getContext()),
3064 SPIRV::FPFastMathMode::None);
3065 return FPFastMathDefaultInfoMap[F] = std::move(FPFastMathDefaultInfoVec);
3066}
3067
3069 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec,
3070 const Type *Ty) {
3071 size_t BitWidth = Ty->getScalarSizeInBits();
3072 int Index =
3074 BitWidth);
3075 assert(Index >= 0 && Index < 3 &&
3076 "Expected FPFastMathDefaultInfo for half, float, or double");
3077 assert(FPFastMathDefaultInfoVec.size() == 3 &&
3078 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3079 return FPFastMathDefaultInfoVec[Index];
3080}
3081
3082void SPIRVEmitIntrinsicsImpl::insertConstantsForFPFastMathDefault(Module &M) {
3083 const SPIRVSubtarget *ST = TM.getSubtargetImpl();
3084 if (!ST->canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2))
3085 return;
3086
3087 // Store the FPFastMathDefaultInfo in the FPFastMathDefaultInfoMap.
3088 // We need the entry point (function) as the key, and the target
3089 // type and flags as the value.
3090 // We also need to check ContractionOff and SignedZeroInfNanPreserve
3091 // execution modes, as they are now deprecated and must be replaced
3092 // with FPFastMathDefaultInfo.
3093 auto Node = M.getNamedMetadata("spirv.ExecutionMode");
3094 if (!Node) {
3095 if (!M.getNamedMetadata("opencl.enable.FP_CONTRACT")) {
3096 // This requires emitting ContractionOff. However, because
3097 // ContractionOff is now deprecated, we need to replace it with
3098 // FPFastMathDefaultInfo with FP Fast Math Mode bitmask set to all 0.
3099 // We need to create the constant for that.
3100
3101 // Create constant instruction with the bitmask flags.
3102 Constant *InitValue =
3103 ConstantInt::get(Type::getInt32Ty(M.getContext()), 0);
3104 // TODO: Reuse constant if there is one already with the required
3105 // value.
3106 [[maybe_unused]] GlobalVariable *GV =
3107 new GlobalVariable(M, // Module
3108 Type::getInt32Ty(M.getContext()), // Type
3109 true, // isConstant
3111 InitValue // Initializer
3112 );
3113 }
3114 return;
3115 }
3116
3117 // The table maps function pointers to their default FP fast math info. It
3118 // can be assumed that the SmallVector is sorted by the bit width of the
3119 // type. The first element is the smallest bit width, and the last element
3120 // is the largest bit width, therefore, we will have {half, float, double}
3121 // in the order of their bit widths.
3122 DenseMap<Function *, SPIRV::FPFastMathDefaultInfoVector>
3123 FPFastMathDefaultInfoMap;
3124
3125 for (unsigned i = 0; i < Node->getNumOperands(); i++) {
3126 MDNode *MDN = cast<MDNode>(Node->getOperand(i));
3127 assert(MDN->getNumOperands() >= 2 && "Expected at least 2 operands");
3129 cast<ConstantAsMetadata>(MDN->getOperand(0))->getValue());
3130 const auto EM =
3132 cast<ConstantAsMetadata>(MDN->getOperand(1))->getValue())
3133 ->getZExtValue();
3134 if (EM == SPIRV::ExecutionMode::FPFastMathDefault) {
3135 assert(MDN->getNumOperands() == 4 &&
3136 "Expected 4 operands for FPFastMathDefault");
3137 const Type *T = cast<ValueAsMetadata>(MDN->getOperand(2))->getType();
3138 unsigned Flags =
3140 cast<ConstantAsMetadata>(MDN->getOperand(3))->getValue())
3141 ->getZExtValue();
3142 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3143 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3144 SPIRV::FPFastMathDefaultInfo &Info =
3145 getFPFastMathDefaultInfo(FPFastMathDefaultInfoVec, T);
3146 Info.FastMathFlags = Flags;
3147 Info.FPFastMathDefault = true;
3148 } else if (EM == SPIRV::ExecutionMode::ContractionOff) {
3149 assert(MDN->getNumOperands() == 2 &&
3150 "Expected no operands for ContractionOff");
3151
3152 // We need to save this info for every possible FP type, i.e. {half,
3153 // float, double, fp128}.
3154 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3155 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3156 for (SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3157 Info.ContractionOff = true;
3158 }
3159 } else if (EM == SPIRV::ExecutionMode::SignedZeroInfNanPreserve) {
3160 assert(MDN->getNumOperands() == 3 &&
3161 "Expected 1 operand for SignedZeroInfNanPreserve");
3162 unsigned TargetWidth =
3164 cast<ConstantAsMetadata>(MDN->getOperand(2))->getValue())
3165 ->getZExtValue();
3166 // We need to save this info only for the FP type with TargetWidth.
3167 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3168 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3171 assert(Index >= 0 && Index < 3 &&
3172 "Expected FPFastMathDefaultInfo for half, float, or double");
3173 assert(FPFastMathDefaultInfoVec.size() == 3 &&
3174 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3175 FPFastMathDefaultInfoVec[Index].SignedZeroInfNanPreserve = true;
3176 }
3177 }
3178
3179 DenseMap<unsigned, GlobalVariable *> GlobalVars;
3180 for (auto &[Func, FPFastMathDefaultInfoVec] : FPFastMathDefaultInfoMap) {
3181 if (FPFastMathDefaultInfoVec.empty())
3182 continue;
3183
3184 for (const SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3185 assert(Info.Ty && "Expected target type for FPFastMathDefaultInfo");
3186 // Skip if none of the execution modes was used.
3187 unsigned Flags = Info.FastMathFlags;
3188 if (Flags == SPIRV::FPFastMathMode::None && !Info.ContractionOff &&
3189 !Info.SignedZeroInfNanPreserve && !Info.FPFastMathDefault)
3190 continue;
3191
3192 // Check if flags are compatible.
3193 if (Info.ContractionOff && (Flags & SPIRV::FPFastMathMode::AllowContract))
3194 report_fatal_error("Conflicting FPFastMathFlags: ContractionOff "
3195 "and AllowContract");
3196
3197 if (Info.SignedZeroInfNanPreserve &&
3198 !(Flags &
3199 (SPIRV::FPFastMathMode::NotNaN | SPIRV::FPFastMathMode::NotInf |
3200 SPIRV::FPFastMathMode::NSZ))) {
3201 if (Info.FPFastMathDefault)
3202 report_fatal_error("Conflicting FPFastMathFlags: "
3203 "SignedZeroInfNanPreserve but at least one of "
3204 "NotNaN/NotInf/NSZ is enabled.");
3205 }
3206
3207 if ((Flags & SPIRV::FPFastMathMode::AllowTransform) &&
3208 !((Flags & SPIRV::FPFastMathMode::AllowReassoc) &&
3209 (Flags & SPIRV::FPFastMathMode::AllowContract))) {
3210 report_fatal_error("Conflicting FPFastMathFlags: "
3211 "AllowTransform requires AllowReassoc and "
3212 "AllowContract to be set.");
3213 }
3214
3215 auto it = GlobalVars.find(Flags);
3216 GlobalVariable *GV = nullptr;
3217 if (it != GlobalVars.end()) {
3218 // Reuse existing global variable.
3219 GV = it->second;
3220 } else {
3221 // Create constant instruction with the bitmask flags.
3222 Constant *InitValue =
3223 ConstantInt::get(Type::getInt32Ty(M.getContext()), Flags);
3224 // TODO: Reuse constant if there is one already with the required
3225 // value.
3226 GV = new GlobalVariable(M, // Module
3227 Type::getInt32Ty(M.getContext()), // Type
3228 true, // isConstant
3230 InitValue // Initializer
3231 );
3232 GlobalVars[Flags] = GV;
3233 }
3234 }
3235 }
3236}
3237
3238void SPIRVEmitIntrinsicsImpl::processInstrAfterVisit(Instruction *I,
3239 IRBuilder<> &B) {
3240 auto *II = dyn_cast<IntrinsicInst>(I);
3241 bool IsConstComposite =
3242 II && II->getIntrinsicID() == Intrinsic::spv_const_composite;
3243 if (IsConstComposite && TrackConstants) {
3245 auto t = AggrConsts.find(I);
3246 assert(t != AggrConsts.end());
3247 auto *NewOp =
3248 buildIntrWithMD(Intrinsic::spv_track_constant,
3249 {II->getType(), II->getType()}, t->second, I, {}, B);
3250 replaceAllUsesWith(I, NewOp, false);
3251 NewOp->setArgOperand(0, I);
3252 }
3253 bool IsPhi = isa<PHINode>(I), BPrepared = false;
3254 for (const auto &Op : I->operands()) {
3255 if (isa<PHINode>(I) || isa<SwitchInst>(I) ||
3257 continue;
3258 unsigned OpNo = Op.getOperandNo();
3259 if (II && ((II->getIntrinsicID() == Intrinsic::spv_gep && OpNo == 0) ||
3260 (!II->isBundleOperand(OpNo) &&
3261 II->paramHasAttr(OpNo, Attribute::ImmArg))))
3262 continue;
3263
3264 if (!BPrepared) {
3265 IsPhi ? B.SetInsertPointPastAllocas(I->getParent()->getParent())
3266 : B.SetInsertPoint(I);
3267 BPrepared = true;
3268 }
3269 Type *OpTy = Op->getType();
3270 Type *OpElemTy = GR->findDeducedElementType(Op);
3271 Value *NewOp = Op;
3272 if (OpTy->isTargetExtTy()) {
3273 // Since this value is replaced by poison, we need to do the same in
3274 // `insertAssignTypeIntrs`.
3275 Value *OpTyVal = getNormalizedPoisonValue(OpTy);
3276 NewOp = buildIntrWithMD(Intrinsic::spv_track_constant,
3277 {OpTy, OpTyVal->getType()}, Op, OpTyVal, {}, B);
3278 }
3279 if (!IsConstComposite && isPointerTy(OpTy) && OpElemTy != nullptr &&
3280 OpElemTy != IntegerType::getInt8Ty(I->getContext())) {
3281 SmallVector<Type *, 2> Types = {OpTy, OpTy};
3282 SmallVector<Value *, 2> Args = {
3283 NewOp, buildMD(getNormalizedPoisonValue(OpElemTy)),
3284 B.getInt32(getPointerAddressSpace(OpTy))};
3285 CallInst *PtrCasted = B.CreateIntrinsicWithoutFolding(
3286 Intrinsic::spv_ptrcast, {Types}, Args);
3287 GR->buildAssignPtr(B, OpElemTy, PtrCasted);
3288 NewOp = PtrCasted;
3289 }
3290 if (NewOp != Op)
3291 I->setOperand(OpNo, NewOp);
3292 }
3293 if (Named.insert(I).second)
3294 emitAssignName(I, B);
3295}
3296
3297Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(Function *F,
3298 unsigned OpIdx) {
3299 SmallPtrSet<Function *, 0> FVisited;
3300 return deduceFunParamElementType(F, OpIdx, FVisited);
3301}
3302
3303Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(
3304 Function *F, unsigned OpIdx, SmallPtrSetImpl<Function *> &FVisited) {
3305 // maybe a cycle
3306 if (!FVisited.insert(F).second)
3307 return nullptr;
3308
3309 SmallPtrSet<Value *, 0> Visited;
3311 // search in function's call sites
3312 for (User *U : F->users()) {
3313 CallInst *CI = dyn_cast<CallInst>(U);
3314 if (!CI || OpIdx >= CI->arg_size())
3315 continue;
3316 Value *OpArg = CI->getArgOperand(OpIdx);
3317 if (!isPointerTy(OpArg->getType()))
3318 continue;
3319 // maybe we already know operand's element type
3320 if (Type *KnownTy = GR->findDeducedElementType(OpArg))
3321 return KnownTy;
3322 // try to deduce from the operand itself
3323 Visited.clear();
3324 if (Type *Ty = deduceElementTypeHelper(OpArg, Visited, false))
3325 return Ty;
3326 // search in actual parameter's users
3327 for (User *OpU : OpArg->users()) {
3329 if (!Inst || Inst == CI)
3330 continue;
3331 Visited.clear();
3332 if (Type *Ty = deduceElementTypeHelper(Inst, Visited, false))
3333 return Ty;
3334 }
3335 // check if it's a formal parameter of the outer function
3336 if (!CI->getParent() || !CI->getParent()->getParent())
3337 continue;
3338 Function *OuterF = CI->getParent()->getParent();
3339 if (FVisited.find(OuterF) != FVisited.end())
3340 continue;
3341 for (unsigned i = 0; i < OuterF->arg_size(); ++i) {
3342 if (OuterF->getArg(i) == OpArg) {
3343 Lookup.push_back(std::make_pair(OuterF, i));
3344 break;
3345 }
3346 }
3347 }
3348
3349 // search in function parameters
3350 for (auto &Pair : Lookup) {
3351 if (Type *Ty = deduceFunParamElementType(Pair.first, Pair.second, FVisited))
3352 return Ty;
3353 }
3354
3355 return nullptr;
3356}
3357
3358void SPIRVEmitIntrinsicsImpl::processParamTypesByFunHeader(Function *F,
3359 IRBuilder<> &B) {
3360 B.SetInsertPointPastAllocas(F);
3361 for (unsigned OpIdx = 0; OpIdx < F->arg_size(); ++OpIdx) {
3362 Argument *Arg = F->getArg(OpIdx);
3363 // Vector-of-pointers arg: deduce pointee from a GEP user so the function
3364 // type isn't emitted with the default i8 pointee.
3365 if (isUntypedPointerVectorTy(Arg->getType()) &&
3366 !GR->findDeducedElementType(Arg)) {
3367 for (User *U : Arg->users()) {
3369 if (GEP && GEP->getPointerOperand() == Arg) {
3370 GR->buildAssignPtr(B, GEP->getSourceElementType(), Arg);
3371 break;
3372 }
3373 }
3374 continue;
3375 }
3376 if (!isUntypedPointerTy(Arg->getType()))
3377 continue;
3378 Type *ElemTy = GR->findDeducedElementType(Arg);
3379 if (ElemTy)
3380 continue;
3381 if (hasPointeeTypeAttr(Arg) &&
3382 (ElemTy = getPointeeTypeByAttr(Arg)) != nullptr) {
3383 GR->buildAssignPtr(B, ElemTy, Arg);
3384 continue;
3385 }
3386 // search in function's call sites
3387 for (User *U : F->users()) {
3388 CallInst *CI = dyn_cast<CallInst>(U);
3389 if (!CI || OpIdx >= CI->arg_size())
3390 continue;
3391 Value *OpArg = CI->getArgOperand(OpIdx);
3392 if (!isPointerTy(OpArg->getType()))
3393 continue;
3394 // maybe we already know operand's element type
3395 if ((ElemTy = GR->findDeducedElementType(OpArg)) != nullptr)
3396 break;
3397 }
3398 if (ElemTy) {
3399 GR->buildAssignPtr(B, ElemTy, Arg);
3400 continue;
3401 }
3402 if (HaveFunPtrs) {
3403 for (User *U : Arg->users()) {
3404 CallInst *CI = dyn_cast<CallInst>(U);
3405 if (CI && !isa<IntrinsicInst>(CI) && CI->isIndirectCall() &&
3406 CI->getCalledOperand() == Arg &&
3407 CI->getParent()->getParent() == CurrF) {
3409 deduceOperandElementTypeFunctionPointer(CI, Ops, ElemTy, false);
3410 if (ElemTy) {
3411 GR->buildAssignPtr(B, ElemTy, Arg);
3412 break;
3413 }
3414 }
3415 }
3416 }
3417 }
3418}
3419
3420void SPIRVEmitIntrinsicsImpl::processParamTypes(Function *F, IRBuilder<> &B) {
3421 B.SetInsertPointPastAllocas(F);
3422 for (unsigned OpIdx = 0; OpIdx < F->arg_size(); ++OpIdx) {
3423 Argument *Arg = F->getArg(OpIdx);
3424 if (!isUntypedPointerTy(Arg->getType()))
3425 continue;
3426 Type *ElemTy = GR->findDeducedElementType(Arg);
3427 if (!ElemTy && (ElemTy = deduceFunParamElementType(F, OpIdx)) != nullptr) {
3428 if (CallInst *AssignCI = GR->findAssignPtrTypeInstr(Arg)) {
3429 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
3430 GR->updateAssignType(AssignCI, Arg, getNormalizedPoisonValue(ElemTy));
3431 propagateElemType(Arg, IntegerType::getInt8Ty(F->getContext()),
3432 VisitedSubst);
3433 } else {
3434 GR->buildAssignPtr(B, ElemTy, Arg);
3435 }
3436 }
3437 }
3438}
3439
3441 SPIRVGlobalRegistry *GR) {
3442 FunctionType *FTy = F->getFunctionType();
3443 bool IsNewFTy = false;
3445 for (Argument &Arg : F->args()) {
3446 Type *ArgTy = Arg.getType();
3447 if (ArgTy->isPointerTy())
3448 if (Type *ElemTy = GR->findDeducedElementType(&Arg)) {
3449 IsNewFTy = true;
3450 ArgTy = getTypedPointerWrapper(ElemTy, getPointerAddressSpace(ArgTy));
3451 }
3452 ArgTys.push_back(ArgTy);
3453 }
3454 return IsNewFTy
3455 ? FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg())
3456 : FTy;
3457}
3458
3459bool SPIRVEmitIntrinsicsImpl::processFunctionPointers(Module &M) {
3460 SmallVector<Function *> Worklist;
3461 for (auto &F : M) {
3462 if (F.isIntrinsic())
3463 continue;
3464 if (F.isDeclaration()) {
3465 for (User *U : F.users()) {
3466 CallInst *CI = dyn_cast<CallInst>(U);
3467 if (!CI || CI->getCalledFunction() != &F) {
3468 Worklist.push_back(&F);
3469 break;
3470 }
3471 }
3472 } else {
3473 if (F.user_empty())
3474 continue;
3475 Type *FPElemTy = GR->findDeducedElementType(&F);
3476 if (!FPElemTy)
3477 FPElemTy = getFunctionPointerElemType(&F, GR);
3478 for (User *U : F.users()) {
3479 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3480 if (!II || II->arg_size() != 3 || II->getOperand(0) != &F)
3481 continue;
3482 if (II->getIntrinsicID() == Intrinsic::spv_assign_ptr_type ||
3483 II->getIntrinsicID() == Intrinsic::spv_ptrcast) {
3485 break;
3486 }
3487 }
3488 }
3489 }
3490 if (Worklist.empty())
3491 return false;
3492
3493 LLVMContext &Ctx = M.getContext();
3495 BasicBlock *BB = BasicBlock::Create(Ctx, "entry", SF);
3496 IRBuilder<> IRB(BB);
3497
3498 for (Function *F : Worklist) {
3500 for (const auto &Arg : F->args())
3501 Args.push_back(getNormalizedPoisonValue(Arg.getType()));
3502 IRB.CreateCall(F, Args);
3503 }
3504 IRB.CreateRetVoid();
3505
3506 return true;
3507}
3508
3509// Apply types parsed from demangled function declarations.
3510void SPIRVEmitIntrinsicsImpl::applyDemangledPtrArgTypes(IRBuilder<> &B) {
3511 DenseMap<Function *, CallInst *> Ptrcasts;
3512 for (auto It : FDeclPtrTys) {
3513 Function *F = It.first;
3514 for (auto *U : F->users()) {
3515 CallInst *CI = dyn_cast<CallInst>(U);
3516 if (!CI || CI->getCalledFunction() != F)
3517 continue;
3518 unsigned Sz = CI->arg_size();
3519 for (auto [Idx, ElemTy] : It.second) {
3520 if (Idx >= Sz)
3521 continue;
3522 Value *Param = CI->getArgOperand(Idx);
3523 if (GR->findDeducedElementType(Param) || isa<GlobalValue>(Param))
3524 continue;
3525 if (Argument *Arg = dyn_cast<Argument>(Param)) {
3526 if (!hasPointeeTypeAttr(Arg)) {
3527 B.SetInsertPointPastAllocas(Arg->getParent());
3528 B.SetCurrentDebugLocation(DebugLoc());
3529 GR->buildAssignPtr(B, ElemTy, Arg);
3530 }
3531 } else if (isaGEP(Param)) {
3532 replaceUsesOfWithSpvPtrcast(Param, normalizeType(ElemTy), CI,
3533 Ptrcasts);
3534 } else if (isa<Instruction>(Param)) {
3535 GR->addDeducedElementType(Param, normalizeType(ElemTy));
3536 // insertAssignTypeIntrs() will complete buildAssignPtr()
3537 } else {
3538 B.SetInsertPoint(CI->getParent()
3539 ->getParent()
3540 ->getEntryBlock()
3541 .getFirstNonPHIOrDbgOrAlloca());
3542 GR->buildAssignPtr(B, ElemTy, Param);
3543 }
3544 CallInst *Ref = dyn_cast<CallInst>(Param);
3545 if (!Ref)
3546 continue;
3547 Function *RefF = Ref->getCalledFunction();
3548 if (!RefF || !isPointerTy(RefF->getReturnType()) ||
3549 GR->findDeducedElementType(RefF))
3550 continue;
3551 ElemTy = normalizeType(ElemTy);
3552 GR->addDeducedElementType(RefF, ElemTy);
3553 GR->addReturnType(
3555 ElemTy, getPointerAddressSpace(RefF->getReturnType())));
3556 }
3557 }
3558 }
3559}
3560
3561GetElementPtrInst *SPIRVEmitIntrinsicsImpl::simplifyZeroLengthArrayGepInst(
3562 GetElementPtrInst *GEP) {
3563 // getelementptr [0 x T], P, 0 (zero), I -> getelementptr T, P, I.
3564 // If type is 0-length array and first index is 0 (zero), drop both the
3565 // 0-length array type and the first index. This is a common pattern in
3566 // the IR, e.g. when using a zero-length array as a placeholder for a
3567 // flexible array such as unbound arrays.
3568 assert(GEP && "GEP is null");
3569 Type *SrcTy = GEP->getSourceElementType();
3570 SmallVector<Value *, 8> Indices(GEP->indices());
3571 ArrayType *ArrTy = dyn_cast<ArrayType>(SrcTy);
3572 if (ArrTy && ArrTy->getNumElements() == 0 && match(Indices[0], m_Zero())) {
3573 Indices.erase(Indices.begin());
3574 SrcTy = ArrTy->getElementType();
3575 return GetElementPtrInst::Create(SrcTy, GEP->getPointerOperand(), Indices,
3576 GEP->getNoWrapFlags(), "",
3577 GEP->getIterator());
3578 }
3579 return nullptr;
3580}
3581
3582void SPIRVEmitIntrinsicsImpl::emitUnstructuredLoopControls(Function &F,
3583 IRBuilder<> &B) {
3584 const SPIRVSubtarget *ST = TM.getSubtargetImpl(F);
3585 // Shaders use SPIRVStructurizer which emits OpLoopMerge via spv_loop_merge.
3586 if (ST->isShader())
3587 return;
3588
3589 if (ST->canUseExtension(
3590 SPIRV::Extension::SPV_INTEL_unstructured_loop_controls)) {
3591 for (BasicBlock &BB : F) {
3593 MDNode *LoopMD = Term->getMetadata(LLVMContext::MD_loop);
3594 if (!LoopMD)
3595 continue;
3596
3597 SmallVector<unsigned, 1> Ops =
3599 unsigned LC = Ops[0];
3600 if (LC == SPIRV::LoopControl::None)
3601 continue;
3602
3603 // Emit intrinsic: loop control mask + optional parameters.
3604 B.SetInsertPoint(Term);
3605 SmallVector<Value *, 4> IntrArgs;
3606 for (unsigned Op : Ops)
3607 IntrArgs.push_back(B.getInt32(Op));
3608 B.CreateIntrinsic(Intrinsic::spv_loop_control_intel, IntrArgs);
3609 }
3610 return;
3611 }
3612
3613 // For non-shader targets without the Intel extension, emit OpLoopMerge
3614 // using spv_loop_merge intrinsics, mirroring the structurizer approach.
3615 LoopInfo LI;
3616 LI.analyze(&F);
3617 if (LI.empty())
3618 return;
3619
3620 for (Loop *L : LI.getLoopsInPreorder()) {
3621 BasicBlock *Latch = L->getLoopLatch();
3622 if (!Latch)
3623 continue;
3624 BasicBlock *MergeBlock = L->getUniqueExitBlock();
3625 if (!MergeBlock)
3626 continue;
3627
3628 // Check for loop unroll metadata on the latch terminator.
3629 SmallVector<unsigned, 1> LoopControlOps =
3631 if (LoopControlOps[0] == SPIRV::LoopControl::None)
3632 continue;
3633
3634 BasicBlock *Header = L->getHeader();
3635 B.SetInsertPoint(Header->getTerminator());
3636 auto *MergeAddress = BlockAddress::get(&F, MergeBlock);
3637 auto *ContinueAddress = BlockAddress::get(&F, Latch);
3638 SmallVector<Value *, 4> Args = {MergeAddress, ContinueAddress};
3639 for (unsigned Imm : LoopControlOps)
3640 Args.emplace_back(B.getInt32(Imm));
3641 B.CreateIntrinsic(Intrinsic::spv_loop_merge, {Args});
3642 }
3643}
3644
3645bool SPIRVEmitIntrinsicsImpl::runOnFunction(Function &Func) {
3646 if (Func.isDeclaration())
3647 return false;
3648
3649 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(Func);
3650 GR = ST.getSPIRVGlobalRegistry();
3651
3652 if (!CurrF)
3653 HaveFunPtrs =
3654 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
3655
3656 CurrF = &Func;
3657 IRBuilder<> B(Func.getContext());
3658 AggrConsts.clear();
3659 AggrConstTypes.clear();
3660 AggrStores.clear();
3661
3662 processParamTypesByFunHeader(CurrF, B);
3663
3664 // Fix GEP result types ahead of inference, and simplify if possible.
3665 // Data structure for dead instructions that were simplified and replaced.
3666 SmallPtrSet<Instruction *, 4> DeadInsts;
3667 for (auto &I : instructions(Func)) {
3668 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3669 Type *ElTy = SI->getValueOperand()->getType();
3670 if (ElTy->isAggregateType() || ElTy->isVectorTy())
3671 AggrStores.insert(&I);
3672 continue;
3673 }
3674
3676 auto *SGEP = dyn_cast<StructuredGEPInst>(&I);
3677
3678 if ((!GEP && !SGEP) || GR->findDeducedElementType(&I))
3679 continue;
3680
3681 if (SGEP) {
3682 GR->addDeducedElementType(SGEP,
3683 normalizeType(SGEP->getResultElementType()));
3684 continue;
3685 }
3686
3687 GetElementPtrInst *NewGEP = simplifyZeroLengthArrayGepInst(GEP);
3688 if (NewGEP) {
3689 GEP->replaceAllUsesWith(NewGEP);
3690 DeadInsts.insert(GEP);
3691 GEP = NewGEP;
3692 }
3693 if (Type *GepTy = getGEPType(GEP))
3694 GR->addDeducedElementType(GEP, normalizeType(GepTy));
3695 }
3696 // Remove dead instructions that were simplified and replaced.
3697 for (auto *I : DeadInsts) {
3698 assert(I->use_empty() && "Dead instruction should not have any uses left");
3699 I->eraseFromParent();
3700 }
3701
3702 B.SetInsertPoint(&Func.getEntryBlock(), Func.getEntryBlock().begin());
3703 for (auto &GV : Func.getParent()->globals())
3704 processGlobalValue(GV, B);
3705
3706 reconstructAggregateReturns(Func, B);
3707 preprocessUndefsAndPoisons(B);
3708 simplifyNullAddrSpaceCasts();
3709 preprocessCompositeConstants(B);
3710
3711 // A PHINode, SelectInst or FreezeInst takes its result type from its
3712 // operands. Aggregate arms are lowered to i32 value-ids (composite constants
3713 // here, loads and other producers during the visitor pass below), so mutate
3714 // an aggregate PHI, select or freeze to match. The original type is tracked
3715 // in AggrConstTypes (used to assign the SPIR-V type) and its extractvalue
3716 // users are lowered to spv_extractv.
3717 Type *I32Ty = B.getInt32Ty();
3718 for (Instruction &I : instructions(Func)) {
3720 continue;
3721 // Give multi-register arms a value-id first, before the result is mutated.
3722 insertCompositeAggregateArms(&I, B);
3723 AggrConstTypes[&I] = I.getType();
3724 I.mutateType(I32Ty);
3725 }
3726
3727 preprocessBoolVectorBitcasts(Func);
3728 SmallVector<Instruction *> Worklist(
3730
3731 applyDemangledPtrArgTypes(B);
3732
3733 // Pass forward: use operand to deduce instructions result.
3734 for (auto &I : Worklist) {
3735 // Don't emit intrinsincs for convergence intrinsics.
3736 if (isConvergenceIntrinsic(I))
3737 continue;
3738
3739 bool Postpone = insertAssignPtrTypeIntrs(I, B, false);
3740 // if Postpone is true, we can't decide on pointee type yet
3741 insertAssignTypeIntrs(I, B);
3742 insertPtrCastOrAssignTypeInstr(I, B);
3744 // if instruction requires a pointee type set, let's check if we know it
3745 // already, and force it to be i8 if not
3746 if (Postpone && !GR->findAssignPtrTypeInstr(I))
3747 insertAssignPtrTypeIntrs(I, B, true);
3748
3749 if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(I))
3750 useRoundingMode(FPI, B);
3751 }
3752
3753 // Pass backward: use instructions results to specify/update/cast operands
3754 // where needed.
3755 SmallPtrSet<Instruction *, 4> IncompleteRets;
3756 for (auto &I : llvm::reverse(instructions(Func)))
3757 deduceOperandElementType(&I, &IncompleteRets);
3758
3759 // Pass forward for PHIs only, their operands are not preceed the
3760 // instruction in meaning of `instructions(Func)`.
3761 for (BasicBlock &BB : Func)
3762 for (PHINode &Phi : BB.phis())
3763 if (isPointerTy(Phi.getType()))
3764 deduceOperandElementType(&Phi, nullptr);
3765
3766 for (auto *I : Worklist) {
3767 TrackConstants = true;
3768 if (!I->getType()->isVoidTy() || isa<StoreInst>(I))
3770 // Visitors return either the original/newly created instruction for
3771 // further processing, nullptr otherwise.
3772 I = visit(*I);
3773 if (!I)
3774 continue;
3775
3776 // Don't emit intrinsics for convergence operations.
3777 if (isConvergenceIntrinsic(I))
3778 continue;
3779
3781 processInstrAfterVisit(I, B);
3782 }
3783
3784 emitUnstructuredLoopControls(Func, B);
3785
3786 return true;
3787}
3788
3789// Try to deduce a better type for pointers to untyped ptr.
3790bool SPIRVEmitIntrinsicsImpl::postprocessTypes(Module &M) {
3791 if (!GR || TodoTypeSz == 0)
3792 return false;
3793
3794 unsigned SzTodo = TodoTypeSz;
3795 DenseMap<Value *, SmallPtrSet<Value *, 4>> ToProcess;
3796 for (auto [Op, Enabled] : TodoType) {
3797 // TODO: add isa<CallInst>(Op) to continue
3798 if (!Enabled || isaGEP(Op))
3799 continue;
3800 CallInst *AssignCI = GR->findAssignPtrTypeInstr(Op);
3801 Type *KnownTy = GR->findDeducedElementType(Op);
3802 if (!KnownTy || !AssignCI)
3803 continue;
3804 assert(Op == AssignCI->getArgOperand(0));
3805 // Try to improve the type deduced after all Functions are processed.
3806 if (auto *CI = dyn_cast<Instruction>(Op)) {
3807 CurrF = CI->getParent()->getParent();
3808 SmallPtrSet<Value *, 0> Visited;
3809 if (Type *ElemTy = deduceElementTypeHelper(Op, Visited, false, true)) {
3810 if (ElemTy != KnownTy) {
3811 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
3812 propagateElemType(CI, ElemTy, VisitedSubst);
3813 eraseTodoType(Op);
3814 continue;
3815 }
3816 }
3817 }
3818
3819 if (Op->hasUseList()) {
3820 for (User *U : Op->users()) {
3822 if (Inst && !isa<IntrinsicInst>(Inst))
3823 ToProcess[Inst].insert(Op);
3824 }
3825 }
3826 }
3827 if (TodoTypeSz == 0)
3828 return true;
3829
3830 for (auto &F : M) {
3831 CurrF = &F;
3832 SmallPtrSet<Instruction *, 4> IncompleteRets;
3833 for (auto &I : llvm::reverse(instructions(F))) {
3834 auto It = ToProcess.find(&I);
3835 if (It == ToProcess.end())
3836 continue;
3837 It->second.remove_if([this](Value *V) { return !isTodoType(V); });
3838 if (It->second.size() == 0)
3839 continue;
3840 deduceOperandElementType(&I, &IncompleteRets, &It->second, true);
3841 if (TodoTypeSz == 0)
3842 return true;
3843 }
3844 }
3845
3846 return SzTodo > TodoTypeSz;
3847}
3848
3849// Parse and store argument types of function declarations where needed.
3850void SPIRVEmitIntrinsicsImpl::parseFunDeclarations(Module &M) {
3851 for (auto &F : M) {
3852 if (!F.isDeclaration() || F.isIntrinsic())
3853 continue;
3854 // get the demangled name
3855 std::string DemangledName = getOclOrSpirvBuiltinDemangledName(F.getName());
3856 if (DemangledName.empty())
3857 continue;
3858 // allow only OpGroupAsyncCopy use case at the moment
3859 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(F);
3860 auto [Grp, Opcode, ExtNo] = SPIRV::mapBuiltinToOpcode(
3861 DemangledName, ST.getPreferredInstructionSet());
3862 if (Opcode != SPIRV::OpGroupAsyncCopy)
3863 continue;
3864 // find pointer arguments
3865 SmallVector<unsigned> Idxs;
3866 for (unsigned OpIdx = 0; OpIdx < F.arg_size(); ++OpIdx) {
3867 Argument *Arg = F.getArg(OpIdx);
3868 if (isPointerTy(Arg->getType()) && !hasPointeeTypeAttr(Arg))
3869 Idxs.push_back(OpIdx);
3870 }
3871 if (!Idxs.size())
3872 continue;
3873 // parse function arguments
3874 LLVMContext &Ctx = F.getContext();
3876 SPIRV::parseBuiltinTypeStr(TypeStrs, DemangledName, Ctx);
3877 if (!TypeStrs.size())
3878 continue;
3879 // find type info for pointer arguments
3880 for (unsigned Idx : Idxs) {
3881 if (Idx >= TypeStrs.size())
3882 continue;
3883 if (Type *ElemTy =
3884 SPIRV::parseBuiltinCallArgumentType(TypeStrs[Idx].trim(), Ctx))
3886 !ElemTy->isTargetExtTy())
3887 FDeclPtrTys[&F].push_back(std::make_pair(Idx, ElemTy));
3888 }
3889 }
3890}
3891
3892bool SPIRVEmitIntrinsicsImpl::processMaskedMemIntrinsic(IntrinsicInst &I) {
3893 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
3894
3895 if (I.getIntrinsicID() == Intrinsic::masked_gather) {
3896 if (!ST.canUseExtension(
3897 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
3898 I.getContext().emitError(
3899 &I, "llvm.masked.gather requires SPV_INTEL_masked_gather_scatter "
3900 "extension");
3901 // Replace with poison to allow compilation to continue and report error.
3902 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
3903 I.eraseFromParent();
3904 return true;
3905 }
3906
3907 IRBuilder<> B(&I);
3908
3909 Value *Ptrs = I.getArgOperand(0);
3910 Value *Mask = I.getArgOperand(1);
3911 Value *Passthru = I.getArgOperand(2);
3912
3913 // Alignment is stored as a parameter attribute, not as a regular parameter.
3914 uint32_t Alignment = I.getParamAlign(0).valueOrOne().value();
3915
3916 SmallVector<Value *, 4> Args = {Ptrs, B.getInt32(Alignment), Mask,
3917 Passthru};
3918 SmallVector<Type *, 4> Types = {I.getType(), Ptrs->getType(),
3919 Mask->getType(), Passthru->getType()};
3920
3921 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_masked_gather, Types, Args);
3922 I.replaceAllUsesWith(NewI);
3923 I.eraseFromParent();
3924 return true;
3925 }
3926
3927 if (I.getIntrinsicID() == Intrinsic::masked_scatter) {
3928 if (!ST.canUseExtension(
3929 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
3930 I.getContext().emitError(
3931 &I, "llvm.masked.scatter requires SPV_INTEL_masked_gather_scatter "
3932 "extension");
3933 // Erase the intrinsic to allow compilation to continue and report error.
3934 I.eraseFromParent();
3935 return true;
3936 }
3937
3938 IRBuilder<> B(&I);
3939
3940 Value *Values = I.getArgOperand(0);
3941 Value *Ptrs = I.getArgOperand(1);
3942 Value *Mask = I.getArgOperand(2);
3943
3944 // Alignment is stored as a parameter attribute on the ptrs parameter (arg
3945 // 1).
3946 uint32_t Alignment = I.getParamAlign(1).valueOrOne().value();
3947
3948 SmallVector<Value *, 4> Args = {Values, Ptrs, B.getInt32(Alignment), Mask};
3949 SmallVector<Type *, 3> Types = {Values->getType(), Ptrs->getType(),
3950 Mask->getType()};
3951
3952 B.CreateIntrinsic(Intrinsic::spv_masked_scatter, Types, Args);
3953 I.eraseFromParent();
3954 return true;
3955 }
3956
3957 return false;
3958}
3959
3960// SPIR-V doesn't support bitcasts involving vector boolean type. Decompose such
3961// bitcasts into element-wise operations before building instructions
3962// worklist, so new instructions are properly visited and converted to
3963// SPIR-V intrinsics.
3964void SPIRVEmitIntrinsicsImpl::preprocessBoolVectorBitcasts(Function &F) {
3965 struct BoolVecBitcast {
3966 BitCastInst *BC;
3967 FixedVectorType *BoolVecTy;
3968 bool SrcIsBoolVec;
3969 };
3970
3971 auto getAsBoolVec = [](Type *Ty) -> FixedVectorType * {
3972 auto *VTy = dyn_cast<FixedVectorType>(Ty);
3973 return (VTy && VTy->getElementType()->isIntegerTy(1)) ? VTy : nullptr;
3974 };
3975
3977 for (auto &I : instructions(F)) {
3978 auto *BC = dyn_cast<BitCastInst>(&I);
3979 if (!BC)
3980 continue;
3981 if (auto *BVTy = getAsBoolVec(BC->getSrcTy()))
3982 ToReplace.push_back({BC, BVTy, true});
3983 else if (auto *BVTy = getAsBoolVec(BC->getDestTy()))
3984 ToReplace.push_back({BC, BVTy, false});
3985 }
3986
3987 for (auto &[BC, BoolVecTy, SrcIsBoolVec] : ToReplace) {
3988 IRBuilder<> B(BC);
3989 Value *Src = BC->getOperand(0);
3990 unsigned BoolVecN = BoolVecTy->getNumElements();
3991 // Use iN as the scalar intermediate type for the bool vector side.
3992 Type *IntTy = B.getIntNTy(BoolVecN);
3993
3994 // Convert source to scalar integer.
3995 Value *IntVal;
3996 if (SrcIsBoolVec) {
3997 // Extract each bool, zext, shift, and OR.
3998 IntVal = ConstantInt::get(IntTy, 0);
3999 for (unsigned I = 0; I < BoolVecN; ++I) {
4000 Value *Elem = B.CreateExtractElement(Src, B.getInt32(I));
4001 Value *Ext = B.CreateZExt(Elem, IntTy);
4002 if (I > 0)
4003 Ext = B.CreateShl(Ext, ConstantInt::get(IntTy, I));
4004 IntVal = B.CreateOr(IntVal, Ext);
4005 }
4006 } else {
4007 // Source is a non-bool type. If it's already a scalar integer, use it
4008 // directly, otherwise bitcast to iN first.
4009 IntVal = Src;
4010 if (!Src->getType()->isIntegerTy())
4011 IntVal = B.CreateBitCast(Src, IntTy);
4012 }
4013
4014 // Convert scalar integer to destination type.
4015 Value *Result;
4016 if (!SrcIsBoolVec) {
4017 // Test each bit with AND + icmp.
4018 Result = PoisonValue::get(BoolVecTy);
4019 for (unsigned I = 0; I < BoolVecN; ++I) {
4020 Value *Mask = ConstantInt::get(IntTy, APInt::getOneBitSet(BoolVecN, I));
4021 Value *And = B.CreateAnd(IntVal, Mask);
4022 Value *Cmp = B.CreateICmpNE(And, ConstantInt::get(IntTy, 0));
4023 Result = B.CreateInsertElement(Result, Cmp, B.getInt32(I));
4024 }
4025 } else {
4026 // Destination is a non-bool type. If it's a scalar integer, use IntVal
4027 // directly, otherwise bitcast from iN.
4028 Result = IntVal;
4029 if (!BC->getDestTy()->isIntegerTy())
4030 Result = B.CreateBitCast(IntVal, BC->getDestTy());
4031 }
4032
4033 BC->replaceAllUsesWith(Result);
4034 BC->eraseFromParent();
4035 }
4036}
4037
4038bool SPIRVEmitIntrinsicsImpl::convertMaskedMemIntrinsics(Module &M) {
4039 bool Changed = false;
4040
4041 for (Function &F : make_early_inc_range(M)) {
4042 if (!F.isIntrinsic())
4043 continue;
4044 Intrinsic::ID IID = F.getIntrinsicID();
4045 if (IID != Intrinsic::masked_gather && IID != Intrinsic::masked_scatter)
4046 continue;
4047
4048 for (User *U : make_early_inc_range(F.users())) {
4049 if (auto *II = dyn_cast<IntrinsicInst>(U))
4050 Changed |= processMaskedMemIntrinsic(*II);
4051 }
4052
4053 if (F.use_empty())
4054 F.eraseFromParent();
4055 }
4056
4057 return Changed;
4058}
4059
4060bool SPIRVEmitIntrinsicsImpl::runOnModule(Module &M) {
4061 bool Changed = false;
4062
4063 Changed |= convertMaskedMemIntrinsics(M);
4064
4065 parseFunDeclarations(M);
4066 insertConstantsForFPFastMathDefault(M);
4067 GVUsers.init(M);
4068
4069 TodoType.clear();
4070 for (auto &F : M)
4072
4073 // Specify function parameters after all functions were processed.
4074 for (auto &F : M) {
4075 // check if function parameter types are set
4076 CurrF = &F;
4077 if (!F.isDeclaration() && !F.isIntrinsic()) {
4078 IRBuilder<> B(F.getContext());
4079 processParamTypes(&F, B);
4080 }
4081 }
4082
4083 CanTodoType = false;
4084 Changed |= postprocessTypes(M);
4085
4086 if (HaveFunPtrs)
4087 Changed |= processFunctionPointers(M);
4088
4089 return Changed;
4090}
4091
4092PreservedAnalyses
4094 if (SPIRVEmitIntrinsicsImpl(TM).runOnModule(M))
4095 return PreservedAnalyses::none();
4096 return PreservedAnalyses::all();
4097}
4098
4100 return new SPIRVEmitIntrinsicsLegacy(TM);
4101}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
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[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
#define T
MachineInstr unsigned OpIdx
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 SPIRV::FPFastMathDefaultInfoVector & getOrCreateFPFastMathDefaultInfoVec(const Module &M, DenseMap< Function *, SPIRV::FPFastMathDefaultInfoVector > &FPFastMathDefaultInfoMap, Function *F)
static Type * getAtomicElemTy(SPIRVGlobalRegistry *GR, Instruction *I, Value *PointerOperand)
static void reportFatalOnTokenType(const Instruction *I)
static void setInsertPointAfterDef(IRBuilder<> &B, Instruction *I)
static void emitAssignName(Instruction *I, IRBuilder<> &B)
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 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 cl::opt< bool > SpirvEmitOpNames("spirv-emit-op-names", cl::desc("Emit OpName for all instructions"), cl::init(false))
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 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 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)
This file defines the SmallPtrSet class.
StringSet - A set-like wrapper for the StringMap.
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:240
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
const Function * getParent() const
Definition Argument.h:44
static unsigned getPointerOperandIndex()
static unsigned getPointerOperandIndex()
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
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:237
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.
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 getArgOperandNo(const Use *U) const
Given a use for a arg operand, get the arg operand number that corresponds to it.
unsigned arg_size() const
bool isArgOperand(const Use *U) 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:537
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
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
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:357
iterator begin()
Definition Function.h:837
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:251
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:353
size_t arg_size() const
Definition Function.h:885
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
Argument * getArg(unsigned i) const
Definition Function.h:870
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()
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:2893
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
Base class for instruction visitors.
Definition InstVisitor.h:78
LLVM_ABI bool isDebugOrPseudoInst() const LLVM_READONLY
Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst.
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()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
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:68
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:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:615
Flags
Flags values. These may be or'd together.
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:111
Metadata * getMetadata() const
Definition Metadata.h:202
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
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 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 buildAssignType(IRBuilder<> &B, Type *Ty, Value *Arg)
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 SPIRVSubtarget * getSubtargetImpl() const
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)
void push_back(const T &Elt)
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:213
iterator find(StringRef Key)
Definition StringMap.h:226
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:683
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:960
const Triple & getTargetTriple() const
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
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:288
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:279
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
Type * getArrayElementType() const
Definition Type.h:425
LLVM_ABI StringRef getTargetExtName() const
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:276
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:319
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:287
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
Definition Type.h:397
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:286
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
Definition Type.cpp:284
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:25
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
user_iterator user_begin()
Definition Value.h:402
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:426
user_iterator user_end()
Definition Value.h:410
iterator_range< use_iterator > uses()
Definition Value.h:380
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:807
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
bool user_empty() const
Definition Value.h:389
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
Changed
#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:81
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.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
initializer< Ty > init(const Ty &Val)
@ 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:82
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
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:315
@ Offset
Definition DWP.cpp:578
ModulePass * createSPIRVEmitIntrinsicsPass(const SPIRVTargetMachine &TM)
bool isTypedPointerWrapper(const TargetExtType *ExtTy)
Definition SPIRVUtils.h:421
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
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:2554
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:392
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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:385
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
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:633
FPDecorationId
Definition SPIRVUtils.h:565
SPIRV::Scope::Scope getMemScope(const Triple &TT, LLVMContext &Ctx, SyncScope::ID Id)
SPIRV::MemorySemantics::MemorySemantics getMemSemanticsForStorageClass(SPIRV::StorageClass::StorageClass SC)
bool isNestedPointer(const Type *Ty)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
Function * getOrCreateBackendServiceFunction(Module &M)
MetadataAsValue * buildMD(Value *Arg)
Definition SPIRVUtils.h:531
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
SmallVector< unsigned, 1 > getSpirvLoopControlOperandsFromLoopMetadata(MDNode *LoopMD)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
Type * getTypedPointerWrapper(Type *ElemTy, unsigned AS)
Definition SPIRVUtils.h:416
bool isVector1(Type *Ty)
Definition SPIRVUtils.h:509
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:380
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:1753
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
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
@ And
Bitwise or logical AND of integers.
DWARFExpression::Operation Op
Type * getPointeeTypeByAttr(Argument *Arg)
Definition SPIRVUtils.h:405
bool hasPointeeTypeAttr(Argument *Arg)
Definition SPIRVUtils.h:400
constexpr unsigned BitWidth
bool isEquivalentTypes(Type *Ty1, Type *Ty2)
Definition SPIRVUtils.h:471
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:361
Type * normalizeType(Type *Ty)
Definition SPIRVUtils.h:517
bool isPointerTyOrWrapper(const Type *Ty)
Definition SPIRVUtils.h:428
@ 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)
Definition SPIRVUtils.h:527
bool isUntypedPointerTy(const Type *T)
Definition SPIRVUtils.h:375
Type * reconstitutePeeledArrayType(Type *Ty)
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:154