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