LLVM 19.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 "SPIRVBuiltins.h"
16#include "SPIRVMetadata.h"
17#include "SPIRVSubtarget.h"
18#include "SPIRVTargetMachine.h"
19#include "SPIRVUtils.h"
20#include "llvm/IR/IRBuilder.h"
22#include "llvm/IR/InstVisitor.h"
23#include "llvm/IR/IntrinsicsSPIRV.h"
25
26#include <queue>
27
28// This pass performs the following transformation on LLVM IR level required
29// for the following translation to SPIR-V:
30// - replaces direct usages of aggregate constants with target-specific
31// intrinsics;
32// - replaces aggregates-related instructions (extract/insert, ld/st, etc)
33// with a target-specific intrinsics;
34// - emits intrinsics for the global variable initializers since IRTranslator
35// doesn't handle them and it's not very convenient to translate them
36// ourselves;
37// - emits intrinsics to keep track of the string names assigned to the values;
38// - emits intrinsics to keep track of constants (this is necessary to have an
39// LLVM IR constant after the IRTranslation is completed) for their further
40// deduplication;
41// - emits intrinsics to keep track of original LLVM types of the values
42// to be able to emit proper SPIR-V types eventually.
43//
44// TODO: consider removing spv.track.constant in favor of spv.assign.type.
45
46using namespace llvm;
47
48namespace llvm {
50} // namespace llvm
51
52namespace {
53class SPIRVEmitIntrinsics
54 : public ModulePass,
55 public InstVisitor<SPIRVEmitIntrinsics, Instruction *> {
56 SPIRVTargetMachine *TM = nullptr;
57 SPIRVGlobalRegistry *GR = nullptr;
58 Function *F = nullptr;
59 bool TrackConstants = true;
62 DenseSet<Instruction *> AggrStores;
63
64 // a registry of created Intrinsic::spv_assign_ptr_type instructions
65 DenseMap<Value *, CallInst *> AssignPtrTypeInstr;
66
67 // deduce element type of untyped pointers
68 Type *deduceElementType(Value *I);
69 Type *deduceElementTypeHelper(Value *I);
70 Type *deduceElementTypeHelper(Value *I, std::unordered_set<Value *> &Visited);
71 Type *deduceElementTypeByValueDeep(Type *ValueTy, Value *Operand,
72 std::unordered_set<Value *> &Visited);
73 Type *deduceElementTypeByUsersDeep(Value *Op,
74 std::unordered_set<Value *> &Visited);
75
76 // deduce nested types of composites
77 Type *deduceNestedTypeHelper(User *U);
78 Type *deduceNestedTypeHelper(User *U, Type *Ty,
79 std::unordered_set<Value *> &Visited);
80
81 // deduce Types of operands of the Instruction if possible
82 void deduceOperandElementType(Instruction *I);
83
84 void preprocessCompositeConstants(IRBuilder<> &B);
85 void preprocessUndefs(IRBuilder<> &B);
86
87 CallInst *buildIntrWithMD(Intrinsic::ID IntrID, ArrayRef<Type *> Types,
88 Value *Arg, Value *Arg2, ArrayRef<Constant *> Imms,
89 IRBuilder<> &B) {
91 MDTuple *TyMD = MDNode::get(F->getContext(), CM);
92 MetadataAsValue *VMD = MetadataAsValue::get(F->getContext(), TyMD);
94 Args.push_back(Arg2);
95 Args.push_back(VMD);
96 for (auto *Imm : Imms)
97 Args.push_back(Imm);
98 return B.CreateIntrinsic(IntrID, {Types}, Args);
99 }
100
101 void replaceMemInstrUses(Instruction *Old, Instruction *New, IRBuilder<> &B);
102 void processInstrAfterVisit(Instruction *I, IRBuilder<> &B);
103 void insertAssignPtrTypeIntrs(Instruction *I, IRBuilder<> &B);
104 void insertAssignTypeIntrs(Instruction *I, IRBuilder<> &B);
105 void insertAssignTypeInstrForTargetExtTypes(TargetExtType *AssignedType,
106 Value *V, IRBuilder<> &B);
107 void replacePointerOperandWithPtrCast(Instruction *I, Value *Pointer,
108 Type *ExpectedElementType,
109 unsigned OperandToReplace,
110 IRBuilder<> &B);
111 void insertPtrCastOrAssignTypeInstr(Instruction *I, IRBuilder<> &B);
112 void processGlobalValue(GlobalVariable &GV, IRBuilder<> &B);
113 void processParamTypes(Function *F, IRBuilder<> &B);
114 Type *deduceFunParamElementType(Function *F, unsigned OpIdx);
115 Type *deduceFunParamElementType(Function *F, unsigned OpIdx,
116 std::unordered_set<Function *> &FVisited);
117
118public:
119 static char ID;
120 SPIRVEmitIntrinsics() : ModulePass(ID) {
122 }
123 SPIRVEmitIntrinsics(SPIRVTargetMachine *_TM) : ModulePass(ID), TM(_TM) {
125 }
139
140 StringRef getPassName() const override { return "SPIRV emit intrinsics"; }
141
142 bool runOnModule(Module &M) override;
143 bool runOnFunction(Function &F);
144
145 void getAnalysisUsage(AnalysisUsage &AU) const override {
147 }
148};
149} // namespace
150
151char SPIRVEmitIntrinsics::ID = 0;
152
153INITIALIZE_PASS(SPIRVEmitIntrinsics, "emit-intrinsics", "SPIRV emit intrinsics",
154 false, false)
155
156static inline bool isAssignTypeInstr(const Instruction *I) {
157 return isa<IntrinsicInst>(I) &&
158 cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::spv_assign_type;
159}
160
162 return isa<StoreInst>(I) || isa<LoadInst>(I) || isa<InsertValueInst>(I) ||
163 isa<ExtractValueInst>(I) || isa<AtomicCmpXchgInst>(I);
164}
165
166static bool isAggrToReplace(const Value *V) {
167 return isa<ConstantAggregate>(V) || isa<ConstantDataArray>(V) ||
168 (isa<ConstantAggregateZero>(V) && !V->getType()->isVectorTy());
169}
170
172 if (isa<PHINode>(I))
173 B.SetInsertPoint(I->getParent(), I->getParent()->getFirstInsertionPt());
174 else
175 B.SetInsertPoint(I);
176}
177
179 IntrinsicInst *Intr = dyn_cast<IntrinsicInst>(I);
180 if (Intr) {
181 switch (Intr->getIntrinsicID()) {
182 case Intrinsic::invariant_start:
183 case Intrinsic::invariant_end:
184 return false;
185 }
186 }
187 return true;
188}
189
190static inline void reportFatalOnTokenType(const Instruction *I) {
191 if (I->getType()->isTokenTy())
192 report_fatal_error("A token is encountered but SPIR-V without extensions "
193 "does not support token type",
194 false);
195}
196
197// Set element pointer type to the given value of ValueTy and tries to
198// specify this type further (recursively) by Operand value, if needed.
199Type *SPIRVEmitIntrinsics::deduceElementTypeByValueDeep(
200 Type *ValueTy, Value *Operand, std::unordered_set<Value *> &Visited) {
201 Type *Ty = ValueTy;
202 if (Operand) {
203 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
204 if (Type *NestedTy = deduceElementTypeHelper(Operand, Visited))
205 Ty = TypedPointerType::get(NestedTy, PtrTy->getAddressSpace());
206 } else {
207 Ty = deduceNestedTypeHelper(dyn_cast<User>(Operand), Ty, Visited);
208 }
209 }
210 return Ty;
211}
212
213// Traverse User instructions to deduce an element pointer type of the operand.
214Type *SPIRVEmitIntrinsics::deduceElementTypeByUsersDeep(
215 Value *Op, std::unordered_set<Value *> &Visited) {
216 if (!Op || !isPointerTy(Op->getType()))
217 return nullptr;
218
219 if (auto PType = dyn_cast<TypedPointerType>(Op->getType()))
220 return PType->getElementType();
221
222 // maybe we already know operand's element type
223 if (Type *KnownTy = GR->findDeducedElementType(Op))
224 return KnownTy;
225
226 for (User *OpU : Op->users()) {
227 if (Instruction *Inst = dyn_cast<Instruction>(OpU)) {
228 if (Type *Ty = deduceElementTypeHelper(Inst, Visited))
229 return Ty;
230 }
231 }
232 return nullptr;
233}
234
235// Deduce and return a successfully deduced Type of the Instruction,
236// or nullptr otherwise.
237Type *SPIRVEmitIntrinsics::deduceElementTypeHelper(Value *I) {
238 std::unordered_set<Value *> Visited;
239 return deduceElementTypeHelper(I, Visited);
240}
241
242Type *SPIRVEmitIntrinsics::deduceElementTypeHelper(
243 Value *I, std::unordered_set<Value *> &Visited) {
244 // allow to pass nullptr as an argument
245 if (!I)
246 return nullptr;
247
248 // maybe already known
249 if (Type *KnownTy = GR->findDeducedElementType(I))
250 return KnownTy;
251
252 // maybe a cycle
253 if (Visited.find(I) != Visited.end())
254 return nullptr;
255 Visited.insert(I);
256
257 // fallback value in case when we fail to deduce a type
258 Type *Ty = nullptr;
259 // look for known basic patterns of type inference
260 if (auto *Ref = dyn_cast<AllocaInst>(I)) {
261 Ty = Ref->getAllocatedType();
262 } else if (auto *Ref = dyn_cast<GetElementPtrInst>(I)) {
263 Ty = Ref->getResultElementType();
264 } else if (auto *Ref = dyn_cast<GlobalValue>(I)) {
265 Ty = deduceElementTypeByValueDeep(
266 Ref->getValueType(),
267 Ref->getNumOperands() > 0 ? Ref->getOperand(0) : nullptr, Visited);
268 } else if (auto *Ref = dyn_cast<AddrSpaceCastInst>(I)) {
269 Ty = deduceElementTypeHelper(Ref->getPointerOperand(), Visited);
270 } else if (auto *Ref = dyn_cast<BitCastInst>(I)) {
271 if (Type *Src = Ref->getSrcTy(), *Dest = Ref->getDestTy();
272 isPointerTy(Src) && isPointerTy(Dest))
273 Ty = deduceElementTypeHelper(Ref->getOperand(0), Visited);
274 } else if (auto *Ref = dyn_cast<AtomicCmpXchgInst>(I)) {
275 Value *Op = Ref->getNewValOperand();
276 Ty = deduceElementTypeByValueDeep(Op->getType(), Op, Visited);
277 } else if (auto *Ref = dyn_cast<AtomicRMWInst>(I)) {
278 Value *Op = Ref->getValOperand();
279 Ty = deduceElementTypeByValueDeep(Op->getType(), Op, Visited);
280 } else if (auto *Ref = dyn_cast<PHINode>(I)) {
281 for (unsigned i = 0; i < Ref->getNumIncomingValues(); i++) {
282 Ty = deduceElementTypeByUsersDeep(Ref->getIncomingValue(i), Visited);
283 if (Ty)
284 break;
285 }
286 } else if (auto *Ref = dyn_cast<SelectInst>(I)) {
287 for (Value *Op : {Ref->getTrueValue(), Ref->getFalseValue()}) {
288 Ty = deduceElementTypeByUsersDeep(Op, Visited);
289 if (Ty)
290 break;
291 }
292 }
293
294 // remember the found relationship
295 if (Ty) {
296 // specify nested types if needed, otherwise return unchanged
297 GR->addDeducedElementType(I, Ty);
298 }
299
300 return Ty;
301}
302
303// Re-create a type of the value if it has untyped pointer fields, also nested.
304// Return the original value type if no corrections of untyped pointer
305// information is found or needed.
306Type *SPIRVEmitIntrinsics::deduceNestedTypeHelper(User *U) {
307 std::unordered_set<Value *> Visited;
308 return deduceNestedTypeHelper(U, U->getType(), Visited);
309}
310
311Type *SPIRVEmitIntrinsics::deduceNestedTypeHelper(
312 User *U, Type *OrigTy, std::unordered_set<Value *> &Visited) {
313 if (!U)
314 return OrigTy;
315
316 // maybe already known
317 if (Type *KnownTy = GR->findDeducedCompositeType(U))
318 return KnownTy;
319
320 // maybe a cycle
321 if (Visited.find(U) != Visited.end())
322 return OrigTy;
323 Visited.insert(U);
324
325 if (dyn_cast<StructType>(OrigTy)) {
327 bool Change = false;
328 for (unsigned i = 0; i < U->getNumOperands(); ++i) {
329 Value *Op = U->getOperand(i);
330 Type *OpTy = Op->getType();
331 Type *Ty = OpTy;
332 if (Op) {
333 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
334 if (Type *NestedTy = deduceElementTypeHelper(Op, Visited))
335 Ty = TypedPointerType::get(NestedTy, PtrTy->getAddressSpace());
336 } else {
337 Ty = deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited);
338 }
339 }
340 Tys.push_back(Ty);
341 Change |= Ty != OpTy;
342 }
343 if (Change) {
344 Type *NewTy = StructType::create(Tys);
345 GR->addDeducedCompositeType(U, NewTy);
346 return NewTy;
347 }
348 } else if (auto *ArrTy = dyn_cast<ArrayType>(OrigTy)) {
349 if (Value *Op = U->getNumOperands() > 0 ? U->getOperand(0) : nullptr) {
350 Type *OpTy = ArrTy->getElementType();
351 Type *Ty = OpTy;
352 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
353 if (Type *NestedTy = deduceElementTypeHelper(Op, Visited))
354 Ty = TypedPointerType::get(NestedTy, PtrTy->getAddressSpace());
355 } else {
356 Ty = deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited);
357 }
358 if (Ty != OpTy) {
359 Type *NewTy = ArrayType::get(Ty, ArrTy->getNumElements());
360 GR->addDeducedCompositeType(U, NewTy);
361 return NewTy;
362 }
363 }
364 } else if (auto *VecTy = dyn_cast<VectorType>(OrigTy)) {
365 if (Value *Op = U->getNumOperands() > 0 ? U->getOperand(0) : nullptr) {
366 Type *OpTy = VecTy->getElementType();
367 Type *Ty = OpTy;
368 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
369 if (Type *NestedTy = deduceElementTypeHelper(Op, Visited))
370 Ty = TypedPointerType::get(NestedTy, PtrTy->getAddressSpace());
371 } else {
372 Ty = deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited);
373 }
374 if (Ty != OpTy) {
375 Type *NewTy = VectorType::get(Ty, VecTy->getElementCount());
376 GR->addDeducedCompositeType(U, NewTy);
377 return NewTy;
378 }
379 }
380 }
381
382 return OrigTy;
383}
384
385Type *SPIRVEmitIntrinsics::deduceElementType(Value *I) {
386 if (Type *Ty = deduceElementTypeHelper(I))
387 return Ty;
388 return IntegerType::getInt8Ty(I->getContext());
389}
390
391// If the Instruction has Pointer operands with unresolved types, this function
392// tries to deduce them. If the Instruction has Pointer operands with known
393// types which differ from expected, this function tries to insert a bitcast to
394// resolve the issue.
395void SPIRVEmitIntrinsics::deduceOperandElementType(Instruction *I) {
397 Type *KnownElemTy = nullptr;
398 // look for known basic patterns of type inference
399 if (auto *Ref = dyn_cast<PHINode>(I)) {
400 if (!isPointerTy(I->getType()) ||
401 !(KnownElemTy = GR->findDeducedElementType(I)))
402 return;
403 for (unsigned i = 0; i < Ref->getNumIncomingValues(); i++) {
404 Value *Op = Ref->getIncomingValue(i);
405 if (isPointerTy(Op->getType()))
406 Ops.push_back(std::make_pair(Op, i));
407 }
408 } else if (auto *Ref = dyn_cast<SelectInst>(I)) {
409 if (!isPointerTy(I->getType()) ||
410 !(KnownElemTy = GR->findDeducedElementType(I)))
411 return;
412 for (unsigned i = 0; i < Ref->getNumOperands(); i++) {
413 Value *Op = Ref->getOperand(i);
414 if (isPointerTy(Op->getType()))
415 Ops.push_back(std::make_pair(Op, i));
416 }
417 } else if (auto *Ref = dyn_cast<ReturnInst>(I)) {
418 Type *RetTy = F->getReturnType();
419 if (!isPointerTy(RetTy))
420 return;
421 Value *Op = Ref->getReturnValue();
422 if (!Op)
423 return;
424 if (!(KnownElemTy = GR->findDeducedElementType(F))) {
425 if (Type *OpElemTy = GR->findDeducedElementType(Op)) {
426 GR->addDeducedElementType(F, OpElemTy);
427 TypedPointerType *DerivedTy =
429 GR->addReturnType(F, DerivedTy);
430 }
431 return;
432 }
433 Ops.push_back(std::make_pair(Op, 0));
434 } else if (auto *Ref = dyn_cast<ICmpInst>(I)) {
435 if (!isPointerTy(Ref->getOperand(0)->getType()))
436 return;
437 Value *Op0 = Ref->getOperand(0);
438 Value *Op1 = Ref->getOperand(1);
439 Type *ElemTy0 = GR->findDeducedElementType(Op0);
440 Type *ElemTy1 = GR->findDeducedElementType(Op1);
441 if (ElemTy0) {
442 KnownElemTy = ElemTy0;
443 Ops.push_back(std::make_pair(Op1, 1));
444 } else if (ElemTy1) {
445 KnownElemTy = ElemTy1;
446 Ops.push_back(std::make_pair(Op0, 0));
447 }
448 }
449
450 // There is no enough info to deduce types or all is valid.
451 if (!KnownElemTy || Ops.size() == 0)
452 return;
453
454 LLVMContext &Ctx = F->getContext();
455 IRBuilder<> B(Ctx);
456 for (auto &OpIt : Ops) {
457 Value *Op = OpIt.first;
458 if (Op->use_empty())
459 continue;
460 Type *Ty = GR->findDeducedElementType(Op);
461 if (Ty == KnownElemTy)
462 continue;
463 if (Instruction *User = dyn_cast<Instruction>(Op->use_begin()->get()))
464 setInsertPointSkippingPhis(B, User->getNextNode());
465 else
466 B.SetInsertPoint(I);
467 Value *OpTyVal = Constant::getNullValue(KnownElemTy);
468 Type *OpTy = Op->getType();
469 if (!Ty) {
470 GR->addDeducedElementType(Op, KnownElemTy);
471 // check if there is existing Intrinsic::spv_assign_ptr_type instruction
472 auto It = AssignPtrTypeInstr.find(Op);
473 if (It == AssignPtrTypeInstr.end()) {
474 CallInst *CI =
475 buildIntrWithMD(Intrinsic::spv_assign_ptr_type, {OpTy}, OpTyVal, Op,
476 {B.getInt32(getPointerAddressSpace(OpTy))}, B);
477 AssignPtrTypeInstr[Op] = CI;
478 } else {
479 It->second->setArgOperand(
480 1,
482 Ctx, MDNode::get(Ctx, ValueAsMetadata::getConstant(OpTyVal))));
483 }
484 } else {
485 SmallVector<Type *, 2> Types = {OpTy, OpTy};
487 Ctx, MDNode::get(Ctx, ValueAsMetadata::getConstant(OpTyVal)));
489 B.getInt32(getPointerAddressSpace(OpTy))};
490 CallInst *PtrCastI =
491 B.CreateIntrinsic(Intrinsic::spv_ptrcast, {Types}, Args);
492 I->setOperand(OpIt.second, PtrCastI);
493 }
494 }
495}
496
497void SPIRVEmitIntrinsics::replaceMemInstrUses(Instruction *Old,
498 Instruction *New,
499 IRBuilder<> &B) {
500 while (!Old->user_empty()) {
501 auto *U = Old->user_back();
502 if (isAssignTypeInstr(U)) {
503 B.SetInsertPoint(U);
504 SmallVector<Value *, 2> Args = {New, U->getOperand(1)};
505 B.CreateIntrinsic(Intrinsic::spv_assign_type, {New->getType()}, Args);
506 U->eraseFromParent();
507 } else if (isMemInstrToReplace(U) || isa<ReturnInst>(U) ||
508 isa<CallInst>(U)) {
509 U->replaceUsesOfWith(Old, New);
510 } else {
511 llvm_unreachable("illegal aggregate intrinsic user");
512 }
513 }
514 Old->eraseFromParent();
515}
516
517void SPIRVEmitIntrinsics::preprocessUndefs(IRBuilder<> &B) {
518 std::queue<Instruction *> Worklist;
519 for (auto &I : instructions(F))
520 Worklist.push(&I);
521
522 while (!Worklist.empty()) {
523 Instruction *I = Worklist.front();
524 Worklist.pop();
525
526 for (auto &Op : I->operands()) {
527 auto *AggrUndef = dyn_cast<UndefValue>(Op);
528 if (!AggrUndef || !Op->getType()->isAggregateType())
529 continue;
530
531 B.SetInsertPoint(I);
532 auto *IntrUndef = B.CreateIntrinsic(Intrinsic::spv_undef, {}, {});
533 Worklist.push(IntrUndef);
534 I->replaceUsesOfWith(Op, IntrUndef);
535 AggrConsts[IntrUndef] = AggrUndef;
536 AggrConstTypes[IntrUndef] = AggrUndef->getType();
537 }
538 }
539}
540
541void SPIRVEmitIntrinsics::preprocessCompositeConstants(IRBuilder<> &B) {
542 std::queue<Instruction *> Worklist;
543 for (auto &I : instructions(F))
544 Worklist.push(&I);
545
546 while (!Worklist.empty()) {
547 auto *I = Worklist.front();
548 assert(I);
549 bool KeepInst = false;
550 for (const auto &Op : I->operands()) {
551 auto BuildCompositeIntrinsic =
553 IRBuilder<> &B, std::queue<Instruction *> &Worklist,
554 bool &KeepInst, SPIRVEmitIntrinsics &SEI) {
555 B.SetInsertPoint(I);
556 auto *CCI =
557 B.CreateIntrinsic(Intrinsic::spv_const_composite, {}, {Args});
558 Worklist.push(CCI);
559 I->replaceUsesOfWith(Op, CCI);
560 KeepInst = true;
561 SEI.AggrConsts[CCI] = AggrC;
562 SEI.AggrConstTypes[CCI] = SEI.deduceNestedTypeHelper(AggrC);
563 };
564
565 if (auto *AggrC = dyn_cast<ConstantAggregate>(Op)) {
566 SmallVector<Value *> Args(AggrC->op_begin(), AggrC->op_end());
567 BuildCompositeIntrinsic(AggrC, Args, Op, I, B, Worklist, KeepInst,
568 *this);
569 } else if (auto *AggrC = dyn_cast<ConstantDataArray>(Op)) {
571 for (unsigned i = 0; i < AggrC->getNumElements(); ++i)
572 Args.push_back(AggrC->getElementAsConstant(i));
573 BuildCompositeIntrinsic(AggrC, Args, Op, I, B, Worklist, KeepInst,
574 *this);
575 } else if (isa<ConstantAggregateZero>(Op) &&
576 !Op->getType()->isVectorTy()) {
577 auto *AggrC = cast<ConstantAggregateZero>(Op);
578 SmallVector<Value *> Args(AggrC->op_begin(), AggrC->op_end());
579 BuildCompositeIntrinsic(AggrC, Args, Op, I, B, Worklist, KeepInst,
580 *this);
581 }
582 }
583 if (!KeepInst)
584 Worklist.pop();
585 }
586}
587
588Instruction *SPIRVEmitIntrinsics::visitSwitchInst(SwitchInst &I) {
589 BasicBlock *ParentBB = I.getParent();
590 IRBuilder<> B(ParentBB);
591 B.SetInsertPoint(&I);
594 for (auto &Op : I.operands()) {
595 if (Op.get()->getType()->isSized()) {
596 Args.push_back(Op);
597 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op.get())) {
598 BBCases.push_back(BB);
599 Args.push_back(BlockAddress::get(BB->getParent(), BB));
600 } else {
601 report_fatal_error("Unexpected switch operand");
602 }
603 }
604 CallInst *NewI = B.CreateIntrinsic(Intrinsic::spv_switch,
605 {I.getOperand(0)->getType()}, {Args});
606 // remove switch to avoid its unneeded and undesirable unwrap into branches
607 // and conditions
608 I.replaceAllUsesWith(NewI);
609 I.eraseFromParent();
610 // insert artificial and temporary instruction to preserve valid CFG,
611 // it will be removed after IR translation pass
612 B.SetInsertPoint(ParentBB);
613 IndirectBrInst *BrI = B.CreateIndirectBr(
614 Constant::getNullValue(PointerType::getUnqual(ParentBB->getContext())),
615 BBCases.size());
616 for (BasicBlock *BBCase : BBCases)
617 BrI->addDestination(BBCase);
618 return BrI;
619}
620
621Instruction *SPIRVEmitIntrinsics::visitGetElementPtrInst(GetElementPtrInst &I) {
622 IRBuilder<> B(I.getParent());
623 B.SetInsertPoint(&I);
624 SmallVector<Type *, 2> Types = {I.getType(), I.getOperand(0)->getType()};
626 Args.push_back(B.getInt1(I.isInBounds()));
627 for (auto &Op : I.operands())
628 Args.push_back(Op);
629 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_gep, {Types}, {Args});
630 I.replaceAllUsesWith(NewI);
631 I.eraseFromParent();
632 return NewI;
633}
634
635Instruction *SPIRVEmitIntrinsics::visitBitCastInst(BitCastInst &I) {
636 IRBuilder<> B(I.getParent());
637 B.SetInsertPoint(&I);
638 Value *Source = I.getOperand(0);
639
640 // SPIR-V, contrary to LLVM 17+ IR, supports bitcasts between pointers of
641 // varying element types. In case of IR coming from older versions of LLVM
642 // such bitcasts do not provide sufficient information, should be just skipped
643 // here, and handled in insertPtrCastOrAssignTypeInstr.
644 if (isPointerTy(I.getType())) {
645 I.replaceAllUsesWith(Source);
646 I.eraseFromParent();
647 return nullptr;
648 }
649
650 SmallVector<Type *, 2> Types = {I.getType(), Source->getType()};
651 SmallVector<Value *> Args(I.op_begin(), I.op_end());
652 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_bitcast, {Types}, {Args});
653 std::string InstName = I.hasName() ? I.getName().str() : "";
654 I.replaceAllUsesWith(NewI);
655 I.eraseFromParent();
656 NewI->setName(InstName);
657 return NewI;
658}
659
660void SPIRVEmitIntrinsics::insertAssignTypeInstrForTargetExtTypes(
661 TargetExtType *AssignedType, Value *V, IRBuilder<> &B) {
662 // Do not emit spv_assign_type if the V is of the AssignedType already.
663 if (V->getType() == AssignedType)
664 return;
665
666 // Do not emit spv_assign_type if there is one already targetting V. If the
667 // found spv_assign_type assigns a type different than AssignedType, report an
668 // error. Builtin types cannot be redeclared or casted.
669 for (auto User : V->users()) {
670 auto *II = dyn_cast<IntrinsicInst>(User);
671 if (!II || II->getIntrinsicID() != Intrinsic::spv_assign_type)
672 continue;
673
674 MetadataAsValue *VMD = cast<MetadataAsValue>(II->getOperand(1));
676 dyn_cast<ConstantAsMetadata>(VMD->getMetadata())->getType();
677 if (BuiltinType != AssignedType)
678 report_fatal_error("Type mismatch " + BuiltinType->getTargetExtName() +
679 "/" + AssignedType->getTargetExtName() +
680 " for value " + V->getName(),
681 false);
682 return;
683 }
684
685 Constant *Const = UndefValue::get(AssignedType);
686 buildIntrWithMD(Intrinsic::spv_assign_type, {V->getType()}, Const, V, {}, B);
687}
688
689void SPIRVEmitIntrinsics::replacePointerOperandWithPtrCast(
690 Instruction *I, Value *Pointer, Type *ExpectedElementType,
691 unsigned OperandToReplace, IRBuilder<> &B) {
692 // If Pointer is the result of nop BitCastInst (ptr -> ptr), use the source
693 // pointer instead. The BitCastInst should be later removed when visited.
694 while (BitCastInst *BC = dyn_cast<BitCastInst>(Pointer))
695 Pointer = BC->getOperand(0);
696
697 // Do not emit spv_ptrcast if Pointer's element type is ExpectedElementType
698 Type *PointerElemTy = deduceElementTypeHelper(Pointer);
699 if (PointerElemTy == ExpectedElementType)
700 return;
701
703 Constant *ExpectedElementTypeConst =
704 Constant::getNullValue(ExpectedElementType);
706 ValueAsMetadata::getConstant(ExpectedElementTypeConst);
707 MDTuple *TyMD = MDNode::get(F->getContext(), CM);
708 MetadataAsValue *VMD = MetadataAsValue::get(F->getContext(), TyMD);
709 unsigned AddressSpace = getPointerAddressSpace(Pointer->getType());
710 bool FirstPtrCastOrAssignPtrType = true;
711
712 // Do not emit new spv_ptrcast if equivalent one already exists or when
713 // spv_assign_ptr_type already targets this pointer with the same element
714 // type.
715 for (auto User : Pointer->users()) {
716 auto *II = dyn_cast<IntrinsicInst>(User);
717 if (!II ||
718 (II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type &&
719 II->getIntrinsicID() != Intrinsic::spv_ptrcast) ||
720 II->getOperand(0) != Pointer)
721 continue;
722
723 // There is some spv_ptrcast/spv_assign_ptr_type already targeting this
724 // pointer.
725 FirstPtrCastOrAssignPtrType = false;
726 if (II->getOperand(1) != VMD ||
727 dyn_cast<ConstantInt>(II->getOperand(2))->getSExtValue() !=
729 continue;
730
731 // The spv_ptrcast/spv_assign_ptr_type targeting this pointer is of the same
732 // element type and address space.
733 if (II->getIntrinsicID() != Intrinsic::spv_ptrcast)
734 return;
735
736 // This must be a spv_ptrcast, do not emit new if this one has the same BB
737 // as I. Otherwise, search for other spv_ptrcast/spv_assign_ptr_type.
738 if (II->getParent() != I->getParent())
739 continue;
740
741 I->setOperand(OperandToReplace, II);
742 return;
743 }
744
745 // // Do not emit spv_ptrcast if it would cast to the default pointer element
746 // // type (i8) of the same address space.
747 // if (ExpectedElementType->isIntegerTy(8))
748 // return;
749
750 // If this would be the first spv_ptrcast, do not emit spv_ptrcast and emit
751 // spv_assign_ptr_type instead.
752 if (FirstPtrCastOrAssignPtrType &&
753 (isa<Instruction>(Pointer) || isa<Argument>(Pointer))) {
754 CallInst *CI = buildIntrWithMD(
755 Intrinsic::spv_assign_ptr_type, {Pointer->getType()},
756 ExpectedElementTypeConst, Pointer, {B.getInt32(AddressSpace)}, B);
757 GR->addDeducedElementType(CI, ExpectedElementType);
758 GR->addDeducedElementType(Pointer, ExpectedElementType);
759 AssignPtrTypeInstr[Pointer] = CI;
760 return;
761 }
762
763 // Emit spv_ptrcast
764 SmallVector<Type *, 2> Types = {Pointer->getType(), Pointer->getType()};
766 auto *PtrCastI = B.CreateIntrinsic(Intrinsic::spv_ptrcast, {Types}, Args);
767 I->setOperand(OperandToReplace, PtrCastI);
768}
769
770void SPIRVEmitIntrinsics::insertPtrCastOrAssignTypeInstr(Instruction *I,
771 IRBuilder<> &B) {
772 // Handle basic instructions:
773 StoreInst *SI = dyn_cast<StoreInst>(I);
774 if (SI && F->getCallingConv() == CallingConv::SPIR_KERNEL &&
775 isPointerTy(SI->getValueOperand()->getType()) &&
776 isa<Argument>(SI->getValueOperand())) {
777 return replacePointerOperandWithPtrCast(
778 I, SI->getValueOperand(), IntegerType::getInt8Ty(F->getContext()), 0,
779 B);
780 } else if (SI) {
781 return replacePointerOperandWithPtrCast(
782 I, SI->getPointerOperand(), SI->getValueOperand()->getType(), 1, B);
783 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
784 return replacePointerOperandWithPtrCast(I, LI->getPointerOperand(),
785 LI->getType(), 0, B);
786 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
787 return replacePointerOperandWithPtrCast(I, GEPI->getPointerOperand(),
788 GEPI->getSourceElementType(), 0, B);
789 }
790
791 // Handle calls to builtins (non-intrinsics):
792 CallInst *CI = dyn_cast<CallInst>(I);
793 if (!CI || CI->isIndirectCall() || CI->isInlineAsm() ||
795 return;
796
797 // collect information about formal parameter types
798 Function *CalledF = CI->getCalledFunction();
799 SmallVector<Type *, 4> CalledArgTys;
800 bool HaveTypes = false;
801 for (unsigned OpIdx = 0; OpIdx < CalledF->arg_size(); ++OpIdx) {
802 Argument *CalledArg = CalledF->getArg(OpIdx);
803 Type *ArgType = CalledArg->getType();
804 if (!isPointerTy(ArgType)) {
805 CalledArgTys.push_back(nullptr);
806 } else if (isTypedPointerTy(ArgType)) {
807 CalledArgTys.push_back(cast<TypedPointerType>(ArgType)->getElementType());
808 HaveTypes = true;
809 } else {
810 Type *ElemTy = GR->findDeducedElementType(CalledArg);
811 if (!ElemTy && hasPointeeTypeAttr(CalledArg))
812 ElemTy = getPointeeTypeByAttr(CalledArg);
813 if (!ElemTy) {
814 for (User *U : CalledArg->users()) {
815 if (Instruction *Inst = dyn_cast<Instruction>(U)) {
816 if ((ElemTy = deduceElementTypeHelper(Inst)) != nullptr)
817 break;
818 }
819 }
820 }
821 HaveTypes |= ElemTy != nullptr;
822 CalledArgTys.push_back(ElemTy);
823 }
824 }
825
826 std::string DemangledName =
828 if (DemangledName.empty() && !HaveTypes)
829 return;
830
831 for (unsigned OpIdx = 0; OpIdx < CI->arg_size(); OpIdx++) {
832 Value *ArgOperand = CI->getArgOperand(OpIdx);
833 if (!isa<PointerType>(ArgOperand->getType()) &&
834 !isa<TypedPointerType>(ArgOperand->getType()))
835 continue;
836
837 // Constants (nulls/undefs) are handled in insertAssignPtrTypeIntrs()
838 if (!isa<Instruction>(ArgOperand) && !isa<Argument>(ArgOperand))
839 continue;
840
841 Type *ExpectedType =
842 OpIdx < CalledArgTys.size() ? CalledArgTys[OpIdx] : nullptr;
843 if (!ExpectedType && !DemangledName.empty())
845 DemangledName, OpIdx, I->getContext());
846 if (!ExpectedType)
847 continue;
848
849 if (ExpectedType->isTargetExtTy())
850 insertAssignTypeInstrForTargetExtTypes(cast<TargetExtType>(ExpectedType),
851 ArgOperand, B);
852 else
853 replacePointerOperandWithPtrCast(CI, ArgOperand, ExpectedType, OpIdx, B);
854 }
855}
856
857Instruction *SPIRVEmitIntrinsics::visitInsertElementInst(InsertElementInst &I) {
858 SmallVector<Type *, 4> Types = {I.getType(), I.getOperand(0)->getType(),
859 I.getOperand(1)->getType(),
860 I.getOperand(2)->getType()};
861 IRBuilder<> B(I.getParent());
862 B.SetInsertPoint(&I);
863 SmallVector<Value *> Args(I.op_begin(), I.op_end());
864 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_insertelt, {Types}, {Args});
865 std::string InstName = I.hasName() ? I.getName().str() : "";
866 I.replaceAllUsesWith(NewI);
867 I.eraseFromParent();
868 NewI->setName(InstName);
869 return NewI;
870}
871
873SPIRVEmitIntrinsics::visitExtractElementInst(ExtractElementInst &I) {
874 IRBuilder<> B(I.getParent());
875 B.SetInsertPoint(&I);
876 SmallVector<Type *, 3> Types = {I.getType(), I.getVectorOperandType(),
877 I.getIndexOperand()->getType()};
878 SmallVector<Value *, 2> Args = {I.getVectorOperand(), I.getIndexOperand()};
879 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_extractelt, {Types}, {Args});
880 std::string InstName = I.hasName() ? I.getName().str() : "";
881 I.replaceAllUsesWith(NewI);
882 I.eraseFromParent();
883 NewI->setName(InstName);
884 return NewI;
885}
886
887Instruction *SPIRVEmitIntrinsics::visitInsertValueInst(InsertValueInst &I) {
888 IRBuilder<> B(I.getParent());
889 B.SetInsertPoint(&I);
890 SmallVector<Type *, 1> Types = {I.getInsertedValueOperand()->getType()};
892 for (auto &Op : I.operands())
893 if (isa<UndefValue>(Op))
894 Args.push_back(UndefValue::get(B.getInt32Ty()));
895 else
896 Args.push_back(Op);
897 for (auto &Op : I.indices())
898 Args.push_back(B.getInt32(Op));
899 Instruction *NewI =
900 B.CreateIntrinsic(Intrinsic::spv_insertv, {Types}, {Args});
901 replaceMemInstrUses(&I, NewI, B);
902 return NewI;
903}
904
905Instruction *SPIRVEmitIntrinsics::visitExtractValueInst(ExtractValueInst &I) {
906 IRBuilder<> B(I.getParent());
907 B.SetInsertPoint(&I);
909 for (auto &Op : I.operands())
910 Args.push_back(Op);
911 for (auto &Op : I.indices())
912 Args.push_back(B.getInt32(Op));
913 auto *NewI =
914 B.CreateIntrinsic(Intrinsic::spv_extractv, {I.getType()}, {Args});
915 I.replaceAllUsesWith(NewI);
916 I.eraseFromParent();
917 return NewI;
918}
919
920Instruction *SPIRVEmitIntrinsics::visitLoadInst(LoadInst &I) {
921 if (!I.getType()->isAggregateType())
922 return &I;
923 IRBuilder<> B(I.getParent());
924 B.SetInsertPoint(&I);
925 TrackConstants = false;
926 const auto *TLI = TM->getSubtargetImpl()->getTargetLowering();
928 TLI->getLoadMemOperandFlags(I, F->getParent()->getDataLayout());
929 auto *NewI =
930 B.CreateIntrinsic(Intrinsic::spv_load, {I.getOperand(0)->getType()},
931 {I.getPointerOperand(), B.getInt16(Flags),
932 B.getInt8(I.getAlign().value())});
933 replaceMemInstrUses(&I, NewI, B);
934 return NewI;
935}
936
937Instruction *SPIRVEmitIntrinsics::visitStoreInst(StoreInst &I) {
938 if (!AggrStores.contains(&I))
939 return &I;
940 IRBuilder<> B(I.getParent());
941 B.SetInsertPoint(&I);
942 TrackConstants = false;
943 const auto *TLI = TM->getSubtargetImpl()->getTargetLowering();
945 TLI->getStoreMemOperandFlags(I, F->getParent()->getDataLayout());
946 auto *PtrOp = I.getPointerOperand();
947 auto *NewI = B.CreateIntrinsic(
948 Intrinsic::spv_store, {I.getValueOperand()->getType(), PtrOp->getType()},
949 {I.getValueOperand(), PtrOp, B.getInt16(Flags),
950 B.getInt8(I.getAlign().value())});
951 I.eraseFromParent();
952 return NewI;
953}
954
955Instruction *SPIRVEmitIntrinsics::visitAllocaInst(AllocaInst &I) {
956 Value *ArraySize = nullptr;
957 if (I.isArrayAllocation()) {
958 const SPIRVSubtarget *STI = TM->getSubtargetImpl(*I.getFunction());
959 if (!STI->canUseExtension(
960 SPIRV::Extension::SPV_INTEL_variable_length_array))
962 "array allocation: this instruction requires the following "
963 "SPIR-V extension: SPV_INTEL_variable_length_array",
964 false);
965 ArraySize = I.getArraySize();
966 }
967 IRBuilder<> B(I.getParent());
968 B.SetInsertPoint(&I);
969 TrackConstants = false;
970 Type *PtrTy = I.getType();
971 auto *NewI =
972 ArraySize ? B.CreateIntrinsic(Intrinsic::spv_alloca_array,
973 {PtrTy, ArraySize->getType()}, {ArraySize})
974 : B.CreateIntrinsic(Intrinsic::spv_alloca, {PtrTy}, {});
975 std::string InstName = I.hasName() ? I.getName().str() : "";
976 I.replaceAllUsesWith(NewI);
977 I.eraseFromParent();
978 NewI->setName(InstName);
979 return NewI;
980}
981
982Instruction *SPIRVEmitIntrinsics::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
983 assert(I.getType()->isAggregateType() && "Aggregate result is expected");
984 IRBuilder<> B(I.getParent());
985 B.SetInsertPoint(&I);
987 for (auto &Op : I.operands())
988 Args.push_back(Op);
989 Args.push_back(B.getInt32(I.getSyncScopeID()));
990 Args.push_back(B.getInt32(
991 static_cast<uint32_t>(getMemSemantics(I.getSuccessOrdering()))));
992 Args.push_back(B.getInt32(
993 static_cast<uint32_t>(getMemSemantics(I.getFailureOrdering()))));
994 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_cmpxchg,
995 {I.getPointerOperand()->getType()}, {Args});
996 replaceMemInstrUses(&I, NewI, B);
997 return NewI;
998}
999
1000Instruction *SPIRVEmitIntrinsics::visitUnreachableInst(UnreachableInst &I) {
1001 IRBuilder<> B(I.getParent());
1002 B.SetInsertPoint(&I);
1003 B.CreateIntrinsic(Intrinsic::spv_unreachable, {}, {});
1004 return &I;
1005}
1006
1007void SPIRVEmitIntrinsics::processGlobalValue(GlobalVariable &GV,
1008 IRBuilder<> &B) {
1009 // Skip special artifical variable llvm.global.annotations.
1010 if (GV.getName() == "llvm.global.annotations")
1011 return;
1012 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
1013 // Deduce element type and store results in Global Registry.
1014 // Result is ignored, because TypedPointerType is not supported
1015 // by llvm IR general logic.
1016 deduceElementTypeHelper(&GV);
1018 Type *Ty = isAggrToReplace(Init) ? B.getInt32Ty() : Init->getType();
1019 Constant *Const = isAggrToReplace(Init) ? B.getInt32(1) : Init;
1020 auto *InitInst = B.CreateIntrinsic(Intrinsic::spv_init_global,
1021 {GV.getType(), Ty}, {&GV, Const});
1022 InitInst->setArgOperand(1, Init);
1023 }
1024 if ((!GV.hasInitializer() || isa<UndefValue>(GV.getInitializer())) &&
1025 GV.getNumUses() == 0)
1026 B.CreateIntrinsic(Intrinsic::spv_unref_global, GV.getType(), &GV);
1027}
1028
1029void SPIRVEmitIntrinsics::insertAssignPtrTypeIntrs(Instruction *I,
1030 IRBuilder<> &B) {
1032 if (!isPointerTy(I->getType()) || !requireAssignType(I) ||
1033 isa<BitCastInst>(I))
1034 return;
1035
1036 setInsertPointSkippingPhis(B, I->getNextNode());
1037
1038 Type *ElemTy = deduceElementType(I);
1039 Constant *EltTyConst = UndefValue::get(ElemTy);
1040 unsigned AddressSpace = getPointerAddressSpace(I->getType());
1041 CallInst *CI = buildIntrWithMD(Intrinsic::spv_assign_ptr_type, {I->getType()},
1042 EltTyConst, I, {B.getInt32(AddressSpace)}, B);
1043 GR->addDeducedElementType(CI, ElemTy);
1044 AssignPtrTypeInstr[I] = CI;
1045}
1046
1047void SPIRVEmitIntrinsics::insertAssignTypeIntrs(Instruction *I,
1048 IRBuilder<> &B) {
1050 Type *Ty = I->getType();
1051 if (!Ty->isVoidTy() && !isPointerTy(Ty) && requireAssignType(I)) {
1052 setInsertPointSkippingPhis(B, I->getNextNode());
1053 Type *TypeToAssign = Ty;
1054 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1055 if (II->getIntrinsicID() == Intrinsic::spv_const_composite ||
1056 II->getIntrinsicID() == Intrinsic::spv_undef) {
1057 auto It = AggrConstTypes.find(II);
1058 if (It == AggrConstTypes.end())
1059 report_fatal_error("Unknown composite intrinsic type");
1060 TypeToAssign = It->second;
1061 }
1062 }
1063 Constant *Const = UndefValue::get(TypeToAssign);
1064 buildIntrWithMD(Intrinsic::spv_assign_type, {Ty}, Const, I, {}, B);
1065 }
1066 for (const auto &Op : I->operands()) {
1067 if (isa<ConstantPointerNull>(Op) || isa<UndefValue>(Op) ||
1068 // Check GetElementPtrConstantExpr case.
1069 (isa<ConstantExpr>(Op) && isa<GEPOperator>(Op))) {
1071 if (isa<UndefValue>(Op) && Op->getType()->isAggregateType())
1072 buildIntrWithMD(Intrinsic::spv_assign_type, {B.getInt32Ty()}, Op,
1073 UndefValue::get(B.getInt32Ty()), {}, B);
1074 else if (!isa<Instruction>(Op)) // TODO: This case could be removed
1075 buildIntrWithMD(Intrinsic::spv_assign_type, {Op->getType()}, Op, Op, {},
1076 B);
1077 }
1078 }
1079}
1080
1081void SPIRVEmitIntrinsics::processInstrAfterVisit(Instruction *I,
1082 IRBuilder<> &B) {
1083 auto *II = dyn_cast<IntrinsicInst>(I);
1084 if (II && II->getIntrinsicID() == Intrinsic::spv_const_composite &&
1085 TrackConstants) {
1086 B.SetInsertPoint(I->getNextNode());
1087 Type *Ty = B.getInt32Ty();
1088 auto t = AggrConsts.find(I);
1089 assert(t != AggrConsts.end());
1090 auto *NewOp = buildIntrWithMD(Intrinsic::spv_track_constant, {Ty, Ty},
1091 t->second, I, {}, B);
1092 I->replaceAllUsesWith(NewOp);
1093 NewOp->setArgOperand(0, I);
1094 }
1095 for (const auto &Op : I->operands()) {
1096 if ((isa<ConstantAggregateZero>(Op) && Op->getType()->isVectorTy()) ||
1097 isa<PHINode>(I) || isa<SwitchInst>(I))
1098 TrackConstants = false;
1099 if ((isa<ConstantData>(Op) || isa<ConstantExpr>(Op)) && TrackConstants) {
1100 unsigned OpNo = Op.getOperandNo();
1101 if (II && ((II->getIntrinsicID() == Intrinsic::spv_gep && OpNo == 0) ||
1102 (II->paramHasAttr(OpNo, Attribute::ImmArg))))
1103 continue;
1104 B.SetInsertPoint(I);
1105 auto *NewOp =
1106 buildIntrWithMD(Intrinsic::spv_track_constant,
1107 {Op->getType(), Op->getType()}, Op, Op, {}, B);
1108 I->setOperand(OpNo, NewOp);
1109 }
1110 }
1111 if (I->hasName()) {
1113 setInsertPointSkippingPhis(B, I->getNextNode());
1114 std::vector<Value *> Args = {I};
1115 addStringImm(I->getName(), B, Args);
1116 B.CreateIntrinsic(Intrinsic::spv_assign_name, {I->getType()}, Args);
1117 }
1118}
1119
1120Type *SPIRVEmitIntrinsics::deduceFunParamElementType(Function *F,
1121 unsigned OpIdx) {
1122 std::unordered_set<Function *> FVisited;
1123 return deduceFunParamElementType(F, OpIdx, FVisited);
1124}
1125
1126Type *SPIRVEmitIntrinsics::deduceFunParamElementType(
1127 Function *F, unsigned OpIdx, std::unordered_set<Function *> &FVisited) {
1128 // maybe a cycle
1129 if (FVisited.find(F) != FVisited.end())
1130 return nullptr;
1131 FVisited.insert(F);
1132
1133 std::unordered_set<Value *> Visited;
1135 // search in function's call sites
1136 for (User *U : F->users()) {
1137 CallInst *CI = dyn_cast<CallInst>(U);
1138 if (!CI || OpIdx >= CI->arg_size())
1139 continue;
1140 Value *OpArg = CI->getArgOperand(OpIdx);
1141 if (!isPointerTy(OpArg->getType()))
1142 continue;
1143 // maybe we already know operand's element type
1144 if (Type *KnownTy = GR->findDeducedElementType(OpArg))
1145 return KnownTy;
1146 // try to deduce from the operand itself
1147 Visited.clear();
1148 if (Type *Ty = deduceElementTypeHelper(OpArg, Visited))
1149 return Ty;
1150 // search in actual parameter's users
1151 for (User *OpU : OpArg->users()) {
1152 Instruction *Inst = dyn_cast<Instruction>(OpU);
1153 if (!Inst || Inst == CI)
1154 continue;
1155 Visited.clear();
1156 if (Type *Ty = deduceElementTypeHelper(Inst, Visited))
1157 return Ty;
1158 }
1159 // check if it's a formal parameter of the outer function
1160 if (!CI->getParent() || !CI->getParent()->getParent())
1161 continue;
1162 Function *OuterF = CI->getParent()->getParent();
1163 if (FVisited.find(OuterF) != FVisited.end())
1164 continue;
1165 for (unsigned i = 0; i < OuterF->arg_size(); ++i) {
1166 if (OuterF->getArg(i) == OpArg) {
1167 Lookup.push_back(std::make_pair(OuterF, i));
1168 break;
1169 }
1170 }
1171 }
1172
1173 // search in function parameters
1174 for (auto &Pair : Lookup) {
1175 if (Type *Ty = deduceFunParamElementType(Pair.first, Pair.second, FVisited))
1176 return Ty;
1177 }
1178
1179 return nullptr;
1180}
1181
1182void SPIRVEmitIntrinsics::processParamTypes(Function *F, IRBuilder<> &B) {
1183 B.SetInsertPointPastAllocas(F);
1184 for (unsigned OpIdx = 0; OpIdx < F->arg_size(); ++OpIdx) {
1185 Argument *Arg = F->getArg(OpIdx);
1186 if (!isUntypedPointerTy(Arg->getType()))
1187 continue;
1188
1189 Type *ElemTy = GR->findDeducedElementType(Arg);
1190 if (!ElemTy) {
1191 if (hasPointeeTypeAttr(Arg) &&
1192 (ElemTy = getPointeeTypeByAttr(Arg)) != nullptr) {
1193 GR->addDeducedElementType(Arg, ElemTy);
1194 } else if ((ElemTy = deduceFunParamElementType(F, OpIdx)) != nullptr) {
1195 CallInst *AssignPtrTyCI = buildIntrWithMD(
1196 Intrinsic::spv_assign_ptr_type, {Arg->getType()},
1197 Constant::getNullValue(ElemTy), Arg,
1198 {B.getInt32(getPointerAddressSpace(Arg->getType()))}, B);
1199 GR->addDeducedElementType(AssignPtrTyCI, ElemTy);
1200 GR->addDeducedElementType(Arg, ElemTy);
1201 AssignPtrTypeInstr[Arg] = AssignPtrTyCI;
1202 }
1203 }
1204 }
1205}
1206
1207bool SPIRVEmitIntrinsics::runOnFunction(Function &Func) {
1208 if (Func.isDeclaration())
1209 return false;
1210
1211 const SPIRVSubtarget &ST = TM->getSubtarget<SPIRVSubtarget>(Func);
1212 GR = ST.getSPIRVGlobalRegistry();
1213
1214 F = &Func;
1215 IRBuilder<> B(Func.getContext());
1216 AggrConsts.clear();
1217 AggrConstTypes.clear();
1218 AggrStores.clear();
1219
1220 // StoreInst's operand type can be changed during the next transformations,
1221 // so we need to store it in the set. Also store already transformed types.
1222 for (auto &I : instructions(Func)) {
1223 StoreInst *SI = dyn_cast<StoreInst>(&I);
1224 if (!SI)
1225 continue;
1226 Type *ElTy = SI->getValueOperand()->getType();
1227 if (ElTy->isAggregateType() || ElTy->isVectorTy())
1228 AggrStores.insert(&I);
1229 }
1230
1231 B.SetInsertPoint(&Func.getEntryBlock(), Func.getEntryBlock().begin());
1232 for (auto &GV : Func.getParent()->globals())
1233 processGlobalValue(GV, B);
1234
1235 preprocessUndefs(B);
1236 preprocessCompositeConstants(B);
1238 for (auto &I : instructions(Func))
1239 Worklist.push_back(&I);
1240
1241 for (auto &I : Worklist) {
1242 insertAssignPtrTypeIntrs(I, B);
1243 insertAssignTypeIntrs(I, B);
1244 insertPtrCastOrAssignTypeInstr(I, B);
1245 }
1246
1247 for (auto &I : instructions(Func))
1248 deduceOperandElementType(&I);
1249
1250 for (auto *I : Worklist) {
1251 TrackConstants = true;
1252 if (!I->getType()->isVoidTy() || isa<StoreInst>(I))
1253 B.SetInsertPoint(I->getNextNode());
1254 // Visitors return either the original/newly created instruction for further
1255 // processing, nullptr otherwise.
1256 I = visit(*I);
1257 if (!I)
1258 continue;
1259 processInstrAfterVisit(I, B);
1260 }
1261
1262 return true;
1263}
1264
1265bool SPIRVEmitIntrinsics::runOnModule(Module &M) {
1266 bool Changed = false;
1267
1268 for (auto &F : M) {
1269 Changed |= runOnFunction(F);
1270 }
1271
1272 for (auto &F : M) {
1273 // check if function parameter types are set
1274 if (!F.isDeclaration() && !F.isIntrinsic()) {
1275 const SPIRVSubtarget &ST = TM->getSubtarget<SPIRVSubtarget>(F);
1276 GR = ST.getSPIRVGlobalRegistry();
1277 IRBuilder<> B(F.getContext());
1278 processParamTypes(&F, B);
1279 }
1280 }
1281
1282 return Changed;
1283}
1284
1286 return new SPIRVEmitIntrinsics(TM);
1287}
aarch64 promote const
unsigned Intr
always inline
Expand Atomic instructions
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
return RetTy
static bool runOnFunction(Function &F, bool PostInlining)
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
const char LLVMTargetMachineRef TM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isMemInstrToReplace(Instruction *I)
static bool isAggrToReplace(const Value *V)
static void reportFatalOnTokenType(const Instruction *I)
static void setInsertPointSkippingPhis(IRBuilder<> &B, Instruction *I)
static bool requireAssignType(Instruction *I)
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:40
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
an instruction to allocate memory on the stack
Definition: Instructions.h:59
Represent the analysis usage information of a pass.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:539
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:206
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:168
This class represents a no-op cast from one type to another.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1846
bool isInlineAsm() const
Check if this call is an inline asm statement.
Definition: InstrTypes.h:1809
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1742
bool isIndirectCall() const
Return true if the callsite is an indirect call.
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1687
void setArgOperand(unsigned i, Value *v)
Definition: InstrTypes.h:1692
unsigned arg_size() const
Definition: InstrTypes.h:1685
This class represents a function call, abstracting a target machine's calling convention.
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
This class represents an Operation in the Expression.
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
iterator end()
Definition: DenseMap.h:84
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
This instruction extracts a single (scalar) element from a VectorType value.
This instruction extracts a struct member or array element value from an aggregate value.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition: Function.h:236
size_t arg_size() const
Definition: Function.h:847
Argument * getArg(unsigned i) const
Definition: Function.h:832
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:973
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:294
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2666
Indirect Branch Instruction.
void addDestination(BasicBlock *Dest)
Add a destination.
This instruction inserts a single (scalar) element into a VectorType value.
This instruction inserts a struct field of array element value into an aggregate value.
Base class for instruction visitors.
Definition: InstVisitor.h:78
RetTy visitExtractElementInst(ExtractElementInst &I)
Definition: InstVisitor.h:191
RetTy visitInsertValueInst(InsertValueInst &I)
Definition: InstVisitor.h:195
RetTy visitUnreachableInst(UnreachableInst &I)
Definition: InstVisitor.h:241
RetTy visitAtomicCmpXchgInst(AtomicCmpXchgInst &I)
Definition: InstVisitor.h:171
RetTy visitBitCastInst(BitCastInst &I)
Definition: InstVisitor.h:187
RetTy visitSwitchInst(SwitchInst &I)
Definition: InstVisitor.h:232
RetTy visitExtractValueInst(ExtractValueInst &I)
Definition: InstVisitor.h:194
RetTy visitStoreInst(StoreInst &I)
Definition: InstVisitor.h:170
RetTy visitInsertElementInst(InsertElementInst &I)
Definition: InstVisitor.h:192
RetTy visitAllocaInst(AllocaInst &I)
Definition: InstVisitor.h:168
RetTy visitGetElementPtrInst(GetElementPtrInst &I)
Definition: InstVisitor.h:174
void visitInstruction(Instruction &I)
Definition: InstVisitor.h:280
RetTy visitLoadInst(LoadInst &I)
Definition: InstVisitor.h:169
const BasicBlock * getParent() const
Definition: Instruction.h:152
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Definition: Instruction.h:149
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:47
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:184
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
Tuple of metadata.
Definition: Metadata.h:1470
Flags
Flags values. These may be or'd together.
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:176
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:103
Metadata * getMetadata() const
Definition: Metadata.h:193
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:251
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:37
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Type * findDeducedCompositeType(const Value *Val)
void addDeducedElementType(Value *Val, Type *Ty)
void addReturnType(const Function *ArgF, TypedPointerType *DerivedTy)
void addDeducedCompositeType(Value *Val, Type *Ty)
Type * findDeducedElementType(const Value *Val)
bool canUseExtension(SPIRV::Extension::Extension E) const
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:317
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:513
Multiway switch.
Class to represent target extensions types, which are generally unintrospectable from target-independ...
Definition: DerivedTypes.h:720
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:265
StringRef getTargetExtName() const
bool isTargetExtTy() const
Return true if this is a target extension type.
Definition: Type.h:207
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition: Type.h:295
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:140
A few GPU targets, such as DXIL and SPIR-V, have typed pointers.
static TypedPointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1808
This function has undefined behavior.
op_iterator op_begin()
Definition: User.h:234
op_iterator op_end()
Definition: User.h:236
static ConstantAsMetadata * getConstant(Value *C)
Definition: Metadata.h:472
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
iterator_range< user_iterator > users()
Definition: Value.h:421
unsigned getNumUses() const
This method computes the number of uses of this Value.
Definition: Value.cpp:255
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
bool user_empty() const
Definition: Value.h:385
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:185
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ SPIR_KERNEL
Used for SPIR kernel functions.
Definition: CallingConv.h:144
Type * parseBuiltinCallArgumentBaseType(const StringRef DemangledCall, unsigned ArgIdx, LLVMContext &Ctx)
Parses the provided ArgIdx argument base type in the DemangledCall skeleton.
NodeAddr< FuncNode * > Func
Definition: RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void initializeSPIRVEmitIntrinsicsPass(PassRegistry &)
ModulePass * createSPIRVEmitIntrinsicsPass(SPIRVTargetMachine *TM)
unsigned getPointerAddressSpace(const Type *T)
Definition: SPIRVUtils.h:122
AddressSpace
Definition: NVPTXBaseInfo.h:21
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
Definition: SPIRVUtils.cpp:307
bool isTypedPointerTy(const Type *T)
Definition: SPIRVUtils.h:106
bool isPointerTy(const Type *T)
Definition: SPIRVUtils.h:116
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:156
@ Ref
The access may reference the value stored in memory.
DWARFExpression::Operation Op
Type * getPointeeTypeByAttr(Argument *Arg)
Definition: SPIRVUtils.h:135
bool hasPointeeTypeAttr(Argument *Arg)
Definition: SPIRVUtils.h:130
void addStringImm(const StringRef &Str, MCInst &Inst)
Definition: SPIRVUtils.cpp:51
bool isUntypedPointerTy(const Type *T)
Definition: SPIRVUtils.h:111
SPIRV::MemorySemantics::MemorySemantics getMemSemantics(AtomicOrdering Ord)
Definition: SPIRVUtils.cpp:208