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 buildAssignPtr(IRBuilder<> &B, Type *ElemTy, Value *Arg);
102
103 void replaceMemInstrUses(Instruction *Old, Instruction *New, IRBuilder<> &B);
104 void processInstrAfterVisit(Instruction *I, IRBuilder<> &B);
105 void insertAssignPtrTypeIntrs(Instruction *I, IRBuilder<> &B);
106 void insertAssignTypeIntrs(Instruction *I, IRBuilder<> &B);
107 void insertAssignTypeInstrForTargetExtTypes(TargetExtType *AssignedType,
108 Value *V, IRBuilder<> &B);
109 void replacePointerOperandWithPtrCast(Instruction *I, Value *Pointer,
110 Type *ExpectedElementType,
111 unsigned OperandToReplace,
112 IRBuilder<> &B);
113 void insertPtrCastOrAssignTypeInstr(Instruction *I, IRBuilder<> &B);
114 void processGlobalValue(GlobalVariable &GV, IRBuilder<> &B);
115 void processParamTypes(Function *F, IRBuilder<> &B);
116 void processParamTypesByFunHeader(Function *F, IRBuilder<> &B);
117 Type *deduceFunParamElementType(Function *F, unsigned OpIdx);
118 Type *deduceFunParamElementType(Function *F, unsigned OpIdx,
119 std::unordered_set<Function *> &FVisited);
120
121public:
122 static char ID;
123 SPIRVEmitIntrinsics() : ModulePass(ID) {
125 }
126 SPIRVEmitIntrinsics(SPIRVTargetMachine *_TM) : ModulePass(ID), TM(_TM) {
128 }
142
143 StringRef getPassName() const override { return "SPIRV emit intrinsics"; }
144
145 bool runOnModule(Module &M) override;
146 bool runOnFunction(Function &F);
147
148 void getAnalysisUsage(AnalysisUsage &AU) const override {
150 }
151};
152} // namespace
153
154char SPIRVEmitIntrinsics::ID = 0;
155
156INITIALIZE_PASS(SPIRVEmitIntrinsics, "emit-intrinsics", "SPIRV emit intrinsics",
157 false, false)
158
159static inline bool isAssignTypeInstr(const Instruction *I) {
160 return isa<IntrinsicInst>(I) &&
161 cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::spv_assign_type;
162}
163
165 return isa<StoreInst>(I) || isa<LoadInst>(I) || isa<InsertValueInst>(I) ||
166 isa<ExtractValueInst>(I) || isa<AtomicCmpXchgInst>(I);
167}
168
169static bool isAggrToReplace(const Value *V) {
170 return isa<ConstantAggregate>(V) || isa<ConstantDataArray>(V) ||
171 (isa<ConstantAggregateZero>(V) && !V->getType()->isVectorTy());
172}
173
175 if (isa<PHINode>(I))
176 B.SetInsertPoint(I->getParent(), I->getParent()->getFirstInsertionPt());
177 else
178 B.SetInsertPoint(I);
179}
180
182 IntrinsicInst *Intr = dyn_cast<IntrinsicInst>(I);
183 if (Intr) {
184 switch (Intr->getIntrinsicID()) {
185 case Intrinsic::invariant_start:
186 case Intrinsic::invariant_end:
187 return false;
188 }
189 }
190 return true;
191}
192
193static inline void reportFatalOnTokenType(const Instruction *I) {
194 if (I->getType()->isTokenTy())
195 report_fatal_error("A token is encountered but SPIR-V without extensions "
196 "does not support token type",
197 false);
198}
199
200void SPIRVEmitIntrinsics::buildAssignPtr(IRBuilder<> &B, Type *ElemTy,
201 Value *Arg) {
202 CallInst *AssignPtrTyCI =
203 buildIntrWithMD(Intrinsic::spv_assign_ptr_type, {Arg->getType()},
204 Constant::getNullValue(ElemTy), Arg,
205 {B.getInt32(getPointerAddressSpace(Arg->getType()))}, B);
206 GR->addDeducedElementType(AssignPtrTyCI, ElemTy);
207 GR->addDeducedElementType(Arg, ElemTy);
208 AssignPtrTypeInstr[Arg] = AssignPtrTyCI;
209}
210
211// Set element pointer type to the given value of ValueTy and tries to
212// specify this type further (recursively) by Operand value, if needed.
213Type *SPIRVEmitIntrinsics::deduceElementTypeByValueDeep(
214 Type *ValueTy, Value *Operand, std::unordered_set<Value *> &Visited) {
215 Type *Ty = ValueTy;
216 if (Operand) {
217 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
218 if (Type *NestedTy = deduceElementTypeHelper(Operand, Visited))
219 Ty = TypedPointerType::get(NestedTy, PtrTy->getAddressSpace());
220 } else {
221 Ty = deduceNestedTypeHelper(dyn_cast<User>(Operand), Ty, Visited);
222 }
223 }
224 return Ty;
225}
226
227// Traverse User instructions to deduce an element pointer type of the operand.
228Type *SPIRVEmitIntrinsics::deduceElementTypeByUsersDeep(
229 Value *Op, std::unordered_set<Value *> &Visited) {
230 if (!Op || !isPointerTy(Op->getType()))
231 return nullptr;
232
233 if (auto PType = dyn_cast<TypedPointerType>(Op->getType()))
234 return PType->getElementType();
235
236 // maybe we already know operand's element type
237 if (Type *KnownTy = GR->findDeducedElementType(Op))
238 return KnownTy;
239
240 for (User *OpU : Op->users()) {
241 if (Instruction *Inst = dyn_cast<Instruction>(OpU)) {
242 if (Type *Ty = deduceElementTypeHelper(Inst, Visited))
243 return Ty;
244 }
245 }
246 return nullptr;
247}
248
249// Implements what we know in advance about intrinsics and builtin calls
250// TODO: consider feasibility of this particular case to be generalized by
251// encoding knowledge about intrinsics and builtin calls by corresponding
252// specification rules
254 Function *CalledF, unsigned OpIdx) {
255 if ((DemangledName.starts_with("__spirv_ocl_printf(") ||
256 DemangledName.starts_with("printf(")) &&
257 OpIdx == 0)
258 return IntegerType::getInt8Ty(CalledF->getContext());
259 return nullptr;
260}
261
262// Deduce and return a successfully deduced Type of the Instruction,
263// or nullptr otherwise.
264Type *SPIRVEmitIntrinsics::deduceElementTypeHelper(Value *I) {
265 std::unordered_set<Value *> Visited;
266 return deduceElementTypeHelper(I, Visited);
267}
268
269Type *SPIRVEmitIntrinsics::deduceElementTypeHelper(
270 Value *I, std::unordered_set<Value *> &Visited) {
271 // allow to pass nullptr as an argument
272 if (!I)
273 return nullptr;
274
275 // maybe already known
276 if (Type *KnownTy = GR->findDeducedElementType(I))
277 return KnownTy;
278
279 // maybe a cycle
280 if (Visited.find(I) != Visited.end())
281 return nullptr;
282 Visited.insert(I);
283
284 // fallback value in case when we fail to deduce a type
285 Type *Ty = nullptr;
286 // look for known basic patterns of type inference
287 if (auto *Ref = dyn_cast<AllocaInst>(I)) {
288 Ty = Ref->getAllocatedType();
289 } else if (auto *Ref = dyn_cast<GetElementPtrInst>(I)) {
290 Ty = Ref->getResultElementType();
291 } else if (auto *Ref = dyn_cast<GlobalValue>(I)) {
292 Ty = deduceElementTypeByValueDeep(
293 Ref->getValueType(),
294 Ref->getNumOperands() > 0 ? Ref->getOperand(0) : nullptr, Visited);
295 } else if (auto *Ref = dyn_cast<AddrSpaceCastInst>(I)) {
296 Ty = deduceElementTypeHelper(Ref->getPointerOperand(), Visited);
297 } else if (auto *Ref = dyn_cast<BitCastInst>(I)) {
298 if (Type *Src = Ref->getSrcTy(), *Dest = Ref->getDestTy();
299 isPointerTy(Src) && isPointerTy(Dest))
300 Ty = deduceElementTypeHelper(Ref->getOperand(0), Visited);
301 } else if (auto *Ref = dyn_cast<AtomicCmpXchgInst>(I)) {
302 Value *Op = Ref->getNewValOperand();
303 Ty = deduceElementTypeByValueDeep(Op->getType(), Op, Visited);
304 } else if (auto *Ref = dyn_cast<AtomicRMWInst>(I)) {
305 Value *Op = Ref->getValOperand();
306 Ty = deduceElementTypeByValueDeep(Op->getType(), Op, Visited);
307 } else if (auto *Ref = dyn_cast<PHINode>(I)) {
308 for (unsigned i = 0; i < Ref->getNumIncomingValues(); i++) {
309 Ty = deduceElementTypeByUsersDeep(Ref->getIncomingValue(i), Visited);
310 if (Ty)
311 break;
312 }
313 } else if (auto *Ref = dyn_cast<SelectInst>(I)) {
314 for (Value *Op : {Ref->getTrueValue(), Ref->getFalseValue()}) {
315 Ty = deduceElementTypeByUsersDeep(Op, Visited);
316 if (Ty)
317 break;
318 }
319 }
320
321 // remember the found relationship
322 if (Ty) {
323 // specify nested types if needed, otherwise return unchanged
324 GR->addDeducedElementType(I, Ty);
325 }
326
327 return Ty;
328}
329
330// Re-create a type of the value if it has untyped pointer fields, also nested.
331// Return the original value type if no corrections of untyped pointer
332// information is found or needed.
333Type *SPIRVEmitIntrinsics::deduceNestedTypeHelper(User *U) {
334 std::unordered_set<Value *> Visited;
335 return deduceNestedTypeHelper(U, U->getType(), Visited);
336}
337
338Type *SPIRVEmitIntrinsics::deduceNestedTypeHelper(
339 User *U, Type *OrigTy, std::unordered_set<Value *> &Visited) {
340 if (!U)
341 return OrigTy;
342
343 // maybe already known
344 if (Type *KnownTy = GR->findDeducedCompositeType(U))
345 return KnownTy;
346
347 // maybe a cycle
348 if (Visited.find(U) != Visited.end())
349 return OrigTy;
350 Visited.insert(U);
351
352 if (dyn_cast<StructType>(OrigTy)) {
354 bool Change = false;
355 for (unsigned i = 0; i < U->getNumOperands(); ++i) {
356 Value *Op = U->getOperand(i);
357 Type *OpTy = Op->getType();
358 Type *Ty = OpTy;
359 if (Op) {
360 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
361 if (Type *NestedTy = deduceElementTypeHelper(Op, Visited))
362 Ty = TypedPointerType::get(NestedTy, PtrTy->getAddressSpace());
363 } else {
364 Ty = deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited);
365 }
366 }
367 Tys.push_back(Ty);
368 Change |= Ty != OpTy;
369 }
370 if (Change) {
371 Type *NewTy = StructType::create(Tys);
372 GR->addDeducedCompositeType(U, NewTy);
373 return NewTy;
374 }
375 } else if (auto *ArrTy = dyn_cast<ArrayType>(OrigTy)) {
376 if (Value *Op = U->getNumOperands() > 0 ? U->getOperand(0) : nullptr) {
377 Type *OpTy = ArrTy->getElementType();
378 Type *Ty = OpTy;
379 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
380 if (Type *NestedTy = deduceElementTypeHelper(Op, Visited))
381 Ty = TypedPointerType::get(NestedTy, PtrTy->getAddressSpace());
382 } else {
383 Ty = deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited);
384 }
385 if (Ty != OpTy) {
386 Type *NewTy = ArrayType::get(Ty, ArrTy->getNumElements());
387 GR->addDeducedCompositeType(U, NewTy);
388 return NewTy;
389 }
390 }
391 } else if (auto *VecTy = dyn_cast<VectorType>(OrigTy)) {
392 if (Value *Op = U->getNumOperands() > 0 ? U->getOperand(0) : nullptr) {
393 Type *OpTy = VecTy->getElementType();
394 Type *Ty = OpTy;
395 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
396 if (Type *NestedTy = deduceElementTypeHelper(Op, Visited))
397 Ty = TypedPointerType::get(NestedTy, PtrTy->getAddressSpace());
398 } else {
399 Ty = deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited);
400 }
401 if (Ty != OpTy) {
402 Type *NewTy = VectorType::get(Ty, VecTy->getElementCount());
403 GR->addDeducedCompositeType(U, NewTy);
404 return NewTy;
405 }
406 }
407 }
408
409 return OrigTy;
410}
411
412Type *SPIRVEmitIntrinsics::deduceElementType(Value *I) {
413 if (Type *Ty = deduceElementTypeHelper(I))
414 return Ty;
415 return IntegerType::getInt8Ty(I->getContext());
416}
417
418// If the Instruction has Pointer operands with unresolved types, this function
419// tries to deduce them. If the Instruction has Pointer operands with known
420// types which differ from expected, this function tries to insert a bitcast to
421// resolve the issue.
422void SPIRVEmitIntrinsics::deduceOperandElementType(Instruction *I) {
424 Type *KnownElemTy = nullptr;
425 // look for known basic patterns of type inference
426 if (auto *Ref = dyn_cast<PHINode>(I)) {
427 if (!isPointerTy(I->getType()) ||
428 !(KnownElemTy = GR->findDeducedElementType(I)))
429 return;
430 for (unsigned i = 0; i < Ref->getNumIncomingValues(); i++) {
431 Value *Op = Ref->getIncomingValue(i);
432 if (isPointerTy(Op->getType()))
433 Ops.push_back(std::make_pair(Op, i));
434 }
435 } else if (auto *Ref = dyn_cast<SelectInst>(I)) {
436 if (!isPointerTy(I->getType()) ||
437 !(KnownElemTy = GR->findDeducedElementType(I)))
438 return;
439 for (unsigned i = 0; i < Ref->getNumOperands(); i++) {
440 Value *Op = Ref->getOperand(i);
441 if (isPointerTy(Op->getType()))
442 Ops.push_back(std::make_pair(Op, i));
443 }
444 } else if (auto *Ref = dyn_cast<ReturnInst>(I)) {
445 Type *RetTy = F->getReturnType();
446 if (!isPointerTy(RetTy))
447 return;
448 Value *Op = Ref->getReturnValue();
449 if (!Op)
450 return;
451 if (!(KnownElemTy = GR->findDeducedElementType(F))) {
452 if (Type *OpElemTy = GR->findDeducedElementType(Op)) {
453 GR->addDeducedElementType(F, OpElemTy);
454 TypedPointerType *DerivedTy =
456 GR->addReturnType(F, DerivedTy);
457 }
458 return;
459 }
460 Ops.push_back(std::make_pair(Op, 0));
461 } else if (auto *Ref = dyn_cast<ICmpInst>(I)) {
462 if (!isPointerTy(Ref->getOperand(0)->getType()))
463 return;
464 Value *Op0 = Ref->getOperand(0);
465 Value *Op1 = Ref->getOperand(1);
466 Type *ElemTy0 = GR->findDeducedElementType(Op0);
467 Type *ElemTy1 = GR->findDeducedElementType(Op1);
468 if (ElemTy0) {
469 KnownElemTy = ElemTy0;
470 Ops.push_back(std::make_pair(Op1, 1));
471 } else if (ElemTy1) {
472 KnownElemTy = ElemTy1;
473 Ops.push_back(std::make_pair(Op0, 0));
474 }
475 }
476
477 // There is no enough info to deduce types or all is valid.
478 if (!KnownElemTy || Ops.size() == 0)
479 return;
480
481 LLVMContext &Ctx = F->getContext();
482 IRBuilder<> B(Ctx);
483 for (auto &OpIt : Ops) {
484 Value *Op = OpIt.first;
485 if (Op->use_empty())
486 continue;
487 Type *Ty = GR->findDeducedElementType(Op);
488 if (Ty == KnownElemTy)
489 continue;
490 if (Instruction *User = dyn_cast<Instruction>(Op->use_begin()->get()))
491 setInsertPointSkippingPhis(B, User->getNextNode());
492 else
493 B.SetInsertPoint(I);
494 Value *OpTyVal = Constant::getNullValue(KnownElemTy);
495 Type *OpTy = Op->getType();
496 if (!Ty) {
497 GR->addDeducedElementType(Op, KnownElemTy);
498 // check if there is existing Intrinsic::spv_assign_ptr_type instruction
499 auto It = AssignPtrTypeInstr.find(Op);
500 if (It == AssignPtrTypeInstr.end()) {
501 CallInst *CI =
502 buildIntrWithMD(Intrinsic::spv_assign_ptr_type, {OpTy}, OpTyVal, Op,
503 {B.getInt32(getPointerAddressSpace(OpTy))}, B);
504 AssignPtrTypeInstr[Op] = CI;
505 } else {
506 It->second->setArgOperand(
507 1,
509 Ctx, MDNode::get(Ctx, ValueAsMetadata::getConstant(OpTyVal))));
510 }
511 } else {
512 SmallVector<Type *, 2> Types = {OpTy, OpTy};
514 Ctx, MDNode::get(Ctx, ValueAsMetadata::getConstant(OpTyVal)));
516 B.getInt32(getPointerAddressSpace(OpTy))};
517 CallInst *PtrCastI =
518 B.CreateIntrinsic(Intrinsic::spv_ptrcast, {Types}, Args);
519 I->setOperand(OpIt.second, PtrCastI);
520 }
521 }
522}
523
524void SPIRVEmitIntrinsics::replaceMemInstrUses(Instruction *Old,
525 Instruction *New,
526 IRBuilder<> &B) {
527 while (!Old->user_empty()) {
528 auto *U = Old->user_back();
529 if (isAssignTypeInstr(U)) {
530 B.SetInsertPoint(U);
531 SmallVector<Value *, 2> Args = {New, U->getOperand(1)};
532 B.CreateIntrinsic(Intrinsic::spv_assign_type, {New->getType()}, Args);
533 U->eraseFromParent();
534 } else if (isMemInstrToReplace(U) || isa<ReturnInst>(U) ||
535 isa<CallInst>(U)) {
536 U->replaceUsesOfWith(Old, New);
537 } else {
538 llvm_unreachable("illegal aggregate intrinsic user");
539 }
540 }
541 Old->eraseFromParent();
542}
543
544void SPIRVEmitIntrinsics::preprocessUndefs(IRBuilder<> &B) {
545 std::queue<Instruction *> Worklist;
546 for (auto &I : instructions(F))
547 Worklist.push(&I);
548
549 while (!Worklist.empty()) {
550 Instruction *I = Worklist.front();
551 Worklist.pop();
552
553 for (auto &Op : I->operands()) {
554 auto *AggrUndef = dyn_cast<UndefValue>(Op);
555 if (!AggrUndef || !Op->getType()->isAggregateType())
556 continue;
557
558 B.SetInsertPoint(I);
559 auto *IntrUndef = B.CreateIntrinsic(Intrinsic::spv_undef, {}, {});
560 Worklist.push(IntrUndef);
561 I->replaceUsesOfWith(Op, IntrUndef);
562 AggrConsts[IntrUndef] = AggrUndef;
563 AggrConstTypes[IntrUndef] = AggrUndef->getType();
564 }
565 }
566}
567
568void SPIRVEmitIntrinsics::preprocessCompositeConstants(IRBuilder<> &B) {
569 std::queue<Instruction *> Worklist;
570 for (auto &I : instructions(F))
571 Worklist.push(&I);
572
573 while (!Worklist.empty()) {
574 auto *I = Worklist.front();
575 assert(I);
576 bool KeepInst = false;
577 for (const auto &Op : I->operands()) {
578 auto BuildCompositeIntrinsic =
580 IRBuilder<> &B, std::queue<Instruction *> &Worklist,
581 bool &KeepInst, SPIRVEmitIntrinsics &SEI) {
582 B.SetInsertPoint(I);
583 auto *CCI =
584 B.CreateIntrinsic(Intrinsic::spv_const_composite, {}, {Args});
585 Worklist.push(CCI);
586 I->replaceUsesOfWith(Op, CCI);
587 KeepInst = true;
588 SEI.AggrConsts[CCI] = AggrC;
589 SEI.AggrConstTypes[CCI] = SEI.deduceNestedTypeHelper(AggrC);
590 };
591
592 if (auto *AggrC = dyn_cast<ConstantAggregate>(Op)) {
593 SmallVector<Value *> Args(AggrC->op_begin(), AggrC->op_end());
594 BuildCompositeIntrinsic(AggrC, Args, Op, I, B, Worklist, KeepInst,
595 *this);
596 } else if (auto *AggrC = dyn_cast<ConstantDataArray>(Op)) {
598 for (unsigned i = 0; i < AggrC->getNumElements(); ++i)
599 Args.push_back(AggrC->getElementAsConstant(i));
600 BuildCompositeIntrinsic(AggrC, Args, Op, I, B, Worklist, KeepInst,
601 *this);
602 } else if (isa<ConstantAggregateZero>(Op) &&
603 !Op->getType()->isVectorTy()) {
604 auto *AggrC = cast<ConstantAggregateZero>(Op);
605 SmallVector<Value *> Args(AggrC->op_begin(), AggrC->op_end());
606 BuildCompositeIntrinsic(AggrC, Args, Op, I, B, Worklist, KeepInst,
607 *this);
608 }
609 }
610 if (!KeepInst)
611 Worklist.pop();
612 }
613}
614
615Instruction *SPIRVEmitIntrinsics::visitSwitchInst(SwitchInst &I) {
616 BasicBlock *ParentBB = I.getParent();
617 IRBuilder<> B(ParentBB);
618 B.SetInsertPoint(&I);
621 for (auto &Op : I.operands()) {
622 if (Op.get()->getType()->isSized()) {
623 Args.push_back(Op);
624 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op.get())) {
625 BBCases.push_back(BB);
626 Args.push_back(BlockAddress::get(BB->getParent(), BB));
627 } else {
628 report_fatal_error("Unexpected switch operand");
629 }
630 }
631 CallInst *NewI = B.CreateIntrinsic(Intrinsic::spv_switch,
632 {I.getOperand(0)->getType()}, {Args});
633 // remove switch to avoid its unneeded and undesirable unwrap into branches
634 // and conditions
635 I.replaceAllUsesWith(NewI);
636 I.eraseFromParent();
637 // insert artificial and temporary instruction to preserve valid CFG,
638 // it will be removed after IR translation pass
639 B.SetInsertPoint(ParentBB);
640 IndirectBrInst *BrI = B.CreateIndirectBr(
641 Constant::getNullValue(PointerType::getUnqual(ParentBB->getContext())),
642 BBCases.size());
643 for (BasicBlock *BBCase : BBCases)
644 BrI->addDestination(BBCase);
645 return BrI;
646}
647
648Instruction *SPIRVEmitIntrinsics::visitGetElementPtrInst(GetElementPtrInst &I) {
649 IRBuilder<> B(I.getParent());
650 B.SetInsertPoint(&I);
651 SmallVector<Type *, 2> Types = {I.getType(), I.getOperand(0)->getType()};
653 Args.push_back(B.getInt1(I.isInBounds()));
654 for (auto &Op : I.operands())
655 Args.push_back(Op);
656 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_gep, {Types}, {Args});
657 I.replaceAllUsesWith(NewI);
658 I.eraseFromParent();
659 return NewI;
660}
661
662Instruction *SPIRVEmitIntrinsics::visitBitCastInst(BitCastInst &I) {
663 IRBuilder<> B(I.getParent());
664 B.SetInsertPoint(&I);
665 Value *Source = I.getOperand(0);
666
667 // SPIR-V, contrary to LLVM 17+ IR, supports bitcasts between pointers of
668 // varying element types. In case of IR coming from older versions of LLVM
669 // such bitcasts do not provide sufficient information, should be just skipped
670 // here, and handled in insertPtrCastOrAssignTypeInstr.
671 if (isPointerTy(I.getType())) {
672 I.replaceAllUsesWith(Source);
673 I.eraseFromParent();
674 return nullptr;
675 }
676
677 SmallVector<Type *, 2> Types = {I.getType(), Source->getType()};
678 SmallVector<Value *> Args(I.op_begin(), I.op_end());
679 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_bitcast, {Types}, {Args});
680 std::string InstName = I.hasName() ? I.getName().str() : "";
681 I.replaceAllUsesWith(NewI);
682 I.eraseFromParent();
683 NewI->setName(InstName);
684 return NewI;
685}
686
687void SPIRVEmitIntrinsics::insertAssignTypeInstrForTargetExtTypes(
688 TargetExtType *AssignedType, Value *V, IRBuilder<> &B) {
689 // Do not emit spv_assign_type if the V is of the AssignedType already.
690 if (V->getType() == AssignedType)
691 return;
692
693 // Do not emit spv_assign_type if there is one already targetting V. If the
694 // found spv_assign_type assigns a type different than AssignedType, report an
695 // error. Builtin types cannot be redeclared or casted.
696 for (auto User : V->users()) {
697 auto *II = dyn_cast<IntrinsicInst>(User);
698 if (!II || II->getIntrinsicID() != Intrinsic::spv_assign_type)
699 continue;
700
701 MetadataAsValue *VMD = cast<MetadataAsValue>(II->getOperand(1));
703 dyn_cast<ConstantAsMetadata>(VMD->getMetadata())->getType();
704 if (BuiltinType != AssignedType)
705 report_fatal_error("Type mismatch " + BuiltinType->getTargetExtName() +
706 "/" + AssignedType->getTargetExtName() +
707 " for value " + V->getName(),
708 false);
709 return;
710 }
711
712 Constant *Const = UndefValue::get(AssignedType);
713 buildIntrWithMD(Intrinsic::spv_assign_type, {V->getType()}, Const, V, {}, B);
714}
715
716void SPIRVEmitIntrinsics::replacePointerOperandWithPtrCast(
717 Instruction *I, Value *Pointer, Type *ExpectedElementType,
718 unsigned OperandToReplace, IRBuilder<> &B) {
719 // If Pointer is the result of nop BitCastInst (ptr -> ptr), use the source
720 // pointer instead. The BitCastInst should be later removed when visited.
721 while (BitCastInst *BC = dyn_cast<BitCastInst>(Pointer))
722 Pointer = BC->getOperand(0);
723
724 // Do not emit spv_ptrcast if Pointer's element type is ExpectedElementType
725 Type *PointerElemTy = deduceElementTypeHelper(Pointer);
726 if (PointerElemTy == ExpectedElementType)
727 return;
728
730 Constant *ExpectedElementTypeConst =
731 Constant::getNullValue(ExpectedElementType);
733 ValueAsMetadata::getConstant(ExpectedElementTypeConst);
734 MDTuple *TyMD = MDNode::get(F->getContext(), CM);
735 MetadataAsValue *VMD = MetadataAsValue::get(F->getContext(), TyMD);
736 unsigned AddressSpace = getPointerAddressSpace(Pointer->getType());
737 bool FirstPtrCastOrAssignPtrType = true;
738
739 // Do not emit new spv_ptrcast if equivalent one already exists or when
740 // spv_assign_ptr_type already targets this pointer with the same element
741 // type.
742 for (auto User : Pointer->users()) {
743 auto *II = dyn_cast<IntrinsicInst>(User);
744 if (!II ||
745 (II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type &&
746 II->getIntrinsicID() != Intrinsic::spv_ptrcast) ||
747 II->getOperand(0) != Pointer)
748 continue;
749
750 // There is some spv_ptrcast/spv_assign_ptr_type already targeting this
751 // pointer.
752 FirstPtrCastOrAssignPtrType = false;
753 if (II->getOperand(1) != VMD ||
754 dyn_cast<ConstantInt>(II->getOperand(2))->getSExtValue() !=
756 continue;
757
758 // The spv_ptrcast/spv_assign_ptr_type targeting this pointer is of the same
759 // element type and address space.
760 if (II->getIntrinsicID() != Intrinsic::spv_ptrcast)
761 return;
762
763 // This must be a spv_ptrcast, do not emit new if this one has the same BB
764 // as I. Otherwise, search for other spv_ptrcast/spv_assign_ptr_type.
765 if (II->getParent() != I->getParent())
766 continue;
767
768 I->setOperand(OperandToReplace, II);
769 return;
770 }
771
772 // // Do not emit spv_ptrcast if it would cast to the default pointer element
773 // // type (i8) of the same address space.
774 // if (ExpectedElementType->isIntegerTy(8))
775 // return;
776
777 // If this would be the first spv_ptrcast, do not emit spv_ptrcast and emit
778 // spv_assign_ptr_type instead.
779 if (FirstPtrCastOrAssignPtrType &&
780 (isa<Instruction>(Pointer) || isa<Argument>(Pointer))) {
781 CallInst *CI = buildIntrWithMD(
782 Intrinsic::spv_assign_ptr_type, {Pointer->getType()},
783 ExpectedElementTypeConst, Pointer, {B.getInt32(AddressSpace)}, B);
784 GR->addDeducedElementType(CI, ExpectedElementType);
785 GR->addDeducedElementType(Pointer, ExpectedElementType);
786 AssignPtrTypeInstr[Pointer] = CI;
787 return;
788 }
789
790 // Emit spv_ptrcast
791 SmallVector<Type *, 2> Types = {Pointer->getType(), Pointer->getType()};
793 auto *PtrCastI = B.CreateIntrinsic(Intrinsic::spv_ptrcast, {Types}, Args);
794 I->setOperand(OperandToReplace, PtrCastI);
795}
796
797void SPIRVEmitIntrinsics::insertPtrCastOrAssignTypeInstr(Instruction *I,
798 IRBuilder<> &B) {
799 // Handle basic instructions:
800 StoreInst *SI = dyn_cast<StoreInst>(I);
801 if (SI && F->getCallingConv() == CallingConv::SPIR_KERNEL &&
802 isPointerTy(SI->getValueOperand()->getType()) &&
803 isa<Argument>(SI->getValueOperand())) {
804 return replacePointerOperandWithPtrCast(
805 I, SI->getValueOperand(), IntegerType::getInt8Ty(F->getContext()), 0,
806 B);
807 } else if (SI) {
808 return replacePointerOperandWithPtrCast(
809 I, SI->getPointerOperand(), SI->getValueOperand()->getType(), 1, B);
810 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
811 return replacePointerOperandWithPtrCast(I, LI->getPointerOperand(),
812 LI->getType(), 0, B);
813 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
814 return replacePointerOperandWithPtrCast(I, GEPI->getPointerOperand(),
815 GEPI->getSourceElementType(), 0, B);
816 }
817
818 // Handle calls to builtins (non-intrinsics):
819 CallInst *CI = dyn_cast<CallInst>(I);
820 if (!CI || CI->isIndirectCall() || CI->isInlineAsm() ||
822 return;
823
824 // collect information about formal parameter types
825 std::string DemangledName =
827 Function *CalledF = CI->getCalledFunction();
828 SmallVector<Type *, 4> CalledArgTys;
829 bool HaveTypes = false;
830 for (unsigned OpIdx = 0; OpIdx < CalledF->arg_size(); ++OpIdx) {
831 Argument *CalledArg = CalledF->getArg(OpIdx);
832 Type *ArgType = CalledArg->getType();
833 if (!isPointerTy(ArgType)) {
834 CalledArgTys.push_back(nullptr);
835 } else if (isTypedPointerTy(ArgType)) {
836 CalledArgTys.push_back(cast<TypedPointerType>(ArgType)->getElementType());
837 HaveTypes = true;
838 } else {
839 Type *ElemTy = GR->findDeducedElementType(CalledArg);
840 if (!ElemTy && hasPointeeTypeAttr(CalledArg))
841 ElemTy = getPointeeTypeByAttr(CalledArg);
842 if (!ElemTy) {
843 ElemTy = getPointeeTypeByCallInst(DemangledName, CalledF, OpIdx);
844 if (ElemTy) {
845 GR->addDeducedElementType(CalledArg, ElemTy);
846 } else {
847 for (User *U : CalledArg->users()) {
848 if (Instruction *Inst = dyn_cast<Instruction>(U)) {
849 if ((ElemTy = deduceElementTypeHelper(Inst)) != nullptr)
850 break;
851 }
852 }
853 }
854 }
855 HaveTypes |= ElemTy != nullptr;
856 CalledArgTys.push_back(ElemTy);
857 }
858 }
859
860 if (DemangledName.empty() && !HaveTypes)
861 return;
862
863 for (unsigned OpIdx = 0; OpIdx < CI->arg_size(); OpIdx++) {
864 Value *ArgOperand = CI->getArgOperand(OpIdx);
865 if (!isa<PointerType>(ArgOperand->getType()) &&
866 !isa<TypedPointerType>(ArgOperand->getType()))
867 continue;
868
869 // Constants (nulls/undefs) are handled in insertAssignPtrTypeIntrs()
870 if (!isa<Instruction>(ArgOperand) && !isa<Argument>(ArgOperand)) {
871 // However, we may have assumptions about the formal argument's type and
872 // may have a need to insert a ptr cast for the actual parameter of this
873 // call.
874 Argument *CalledArg = CalledF->getArg(OpIdx);
875 if (!GR->findDeducedElementType(CalledArg))
876 continue;
877 }
878
879 Type *ExpectedType =
880 OpIdx < CalledArgTys.size() ? CalledArgTys[OpIdx] : nullptr;
881 if (!ExpectedType && !DemangledName.empty())
883 DemangledName, OpIdx, I->getContext());
884 if (!ExpectedType)
885 continue;
886
887 if (ExpectedType->isTargetExtTy())
888 insertAssignTypeInstrForTargetExtTypes(cast<TargetExtType>(ExpectedType),
889 ArgOperand, B);
890 else
891 replacePointerOperandWithPtrCast(CI, ArgOperand, ExpectedType, OpIdx, B);
892 }
893}
894
895Instruction *SPIRVEmitIntrinsics::visitInsertElementInst(InsertElementInst &I) {
896 SmallVector<Type *, 4> Types = {I.getType(), I.getOperand(0)->getType(),
897 I.getOperand(1)->getType(),
898 I.getOperand(2)->getType()};
899 IRBuilder<> B(I.getParent());
900 B.SetInsertPoint(&I);
901 SmallVector<Value *> Args(I.op_begin(), I.op_end());
902 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_insertelt, {Types}, {Args});
903 std::string InstName = I.hasName() ? I.getName().str() : "";
904 I.replaceAllUsesWith(NewI);
905 I.eraseFromParent();
906 NewI->setName(InstName);
907 return NewI;
908}
909
911SPIRVEmitIntrinsics::visitExtractElementInst(ExtractElementInst &I) {
912 IRBuilder<> B(I.getParent());
913 B.SetInsertPoint(&I);
914 SmallVector<Type *, 3> Types = {I.getType(), I.getVectorOperandType(),
915 I.getIndexOperand()->getType()};
916 SmallVector<Value *, 2> Args = {I.getVectorOperand(), I.getIndexOperand()};
917 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_extractelt, {Types}, {Args});
918 std::string InstName = I.hasName() ? I.getName().str() : "";
919 I.replaceAllUsesWith(NewI);
920 I.eraseFromParent();
921 NewI->setName(InstName);
922 return NewI;
923}
924
925Instruction *SPIRVEmitIntrinsics::visitInsertValueInst(InsertValueInst &I) {
926 IRBuilder<> B(I.getParent());
927 B.SetInsertPoint(&I);
928 SmallVector<Type *, 1> Types = {I.getInsertedValueOperand()->getType()};
930 for (auto &Op : I.operands())
931 if (isa<UndefValue>(Op))
932 Args.push_back(UndefValue::get(B.getInt32Ty()));
933 else
934 Args.push_back(Op);
935 for (auto &Op : I.indices())
936 Args.push_back(B.getInt32(Op));
937 Instruction *NewI =
938 B.CreateIntrinsic(Intrinsic::spv_insertv, {Types}, {Args});
939 replaceMemInstrUses(&I, NewI, B);
940 return NewI;
941}
942
943Instruction *SPIRVEmitIntrinsics::visitExtractValueInst(ExtractValueInst &I) {
944 IRBuilder<> B(I.getParent());
945 B.SetInsertPoint(&I);
947 for (auto &Op : I.operands())
948 Args.push_back(Op);
949 for (auto &Op : I.indices())
950 Args.push_back(B.getInt32(Op));
951 auto *NewI =
952 B.CreateIntrinsic(Intrinsic::spv_extractv, {I.getType()}, {Args});
953 I.replaceAllUsesWith(NewI);
954 I.eraseFromParent();
955 return NewI;
956}
957
958Instruction *SPIRVEmitIntrinsics::visitLoadInst(LoadInst &I) {
959 if (!I.getType()->isAggregateType())
960 return &I;
961 IRBuilder<> B(I.getParent());
962 B.SetInsertPoint(&I);
963 TrackConstants = false;
964 const auto *TLI = TM->getSubtargetImpl()->getTargetLowering();
966 TLI->getLoadMemOperandFlags(I, F->getParent()->getDataLayout());
967 auto *NewI =
968 B.CreateIntrinsic(Intrinsic::spv_load, {I.getOperand(0)->getType()},
969 {I.getPointerOperand(), B.getInt16(Flags),
970 B.getInt8(I.getAlign().value())});
971 replaceMemInstrUses(&I, NewI, B);
972 return NewI;
973}
974
975Instruction *SPIRVEmitIntrinsics::visitStoreInst(StoreInst &I) {
976 if (!AggrStores.contains(&I))
977 return &I;
978 IRBuilder<> B(I.getParent());
979 B.SetInsertPoint(&I);
980 TrackConstants = false;
981 const auto *TLI = TM->getSubtargetImpl()->getTargetLowering();
983 TLI->getStoreMemOperandFlags(I, F->getParent()->getDataLayout());
984 auto *PtrOp = I.getPointerOperand();
985 auto *NewI = B.CreateIntrinsic(
986 Intrinsic::spv_store, {I.getValueOperand()->getType(), PtrOp->getType()},
987 {I.getValueOperand(), PtrOp, B.getInt16(Flags),
988 B.getInt8(I.getAlign().value())});
989 I.eraseFromParent();
990 return NewI;
991}
992
993Instruction *SPIRVEmitIntrinsics::visitAllocaInst(AllocaInst &I) {
994 Value *ArraySize = nullptr;
995 if (I.isArrayAllocation()) {
996 const SPIRVSubtarget *STI = TM->getSubtargetImpl(*I.getFunction());
997 if (!STI->canUseExtension(
998 SPIRV::Extension::SPV_INTEL_variable_length_array))
1000 "array allocation: this instruction requires the following "
1001 "SPIR-V extension: SPV_INTEL_variable_length_array",
1002 false);
1003 ArraySize = I.getArraySize();
1004 }
1005 IRBuilder<> B(I.getParent());
1006 B.SetInsertPoint(&I);
1007 TrackConstants = false;
1008 Type *PtrTy = I.getType();
1009 auto *NewI =
1010 ArraySize ? B.CreateIntrinsic(Intrinsic::spv_alloca_array,
1011 {PtrTy, ArraySize->getType()}, {ArraySize})
1012 : B.CreateIntrinsic(Intrinsic::spv_alloca, {PtrTy}, {});
1013 std::string InstName = I.hasName() ? I.getName().str() : "";
1014 I.replaceAllUsesWith(NewI);
1015 I.eraseFromParent();
1016 NewI->setName(InstName);
1017 return NewI;
1018}
1019
1020Instruction *SPIRVEmitIntrinsics::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1021 assert(I.getType()->isAggregateType() && "Aggregate result is expected");
1022 IRBuilder<> B(I.getParent());
1023 B.SetInsertPoint(&I);
1025 for (auto &Op : I.operands())
1026 Args.push_back(Op);
1027 Args.push_back(B.getInt32(I.getSyncScopeID()));
1028 Args.push_back(B.getInt32(
1029 static_cast<uint32_t>(getMemSemantics(I.getSuccessOrdering()))));
1030 Args.push_back(B.getInt32(
1031 static_cast<uint32_t>(getMemSemantics(I.getFailureOrdering()))));
1032 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_cmpxchg,
1033 {I.getPointerOperand()->getType()}, {Args});
1034 replaceMemInstrUses(&I, NewI, B);
1035 return NewI;
1036}
1037
1038Instruction *SPIRVEmitIntrinsics::visitUnreachableInst(UnreachableInst &I) {
1039 IRBuilder<> B(I.getParent());
1040 B.SetInsertPoint(&I);
1041 B.CreateIntrinsic(Intrinsic::spv_unreachable, {}, {});
1042 return &I;
1043}
1044
1045void SPIRVEmitIntrinsics::processGlobalValue(GlobalVariable &GV,
1046 IRBuilder<> &B) {
1047 // Skip special artifical variable llvm.global.annotations.
1048 if (GV.getName() == "llvm.global.annotations")
1049 return;
1050 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
1051 // Deduce element type and store results in Global Registry.
1052 // Result is ignored, because TypedPointerType is not supported
1053 // by llvm IR general logic.
1054 deduceElementTypeHelper(&GV);
1056 Type *Ty = isAggrToReplace(Init) ? B.getInt32Ty() : Init->getType();
1057 Constant *Const = isAggrToReplace(Init) ? B.getInt32(1) : Init;
1058 auto *InitInst = B.CreateIntrinsic(Intrinsic::spv_init_global,
1059 {GV.getType(), Ty}, {&GV, Const});
1060 InitInst->setArgOperand(1, Init);
1061 }
1062 if ((!GV.hasInitializer() || isa<UndefValue>(GV.getInitializer())) &&
1063 GV.getNumUses() == 0)
1064 B.CreateIntrinsic(Intrinsic::spv_unref_global, GV.getType(), &GV);
1065}
1066
1067void SPIRVEmitIntrinsics::insertAssignPtrTypeIntrs(Instruction *I,
1068 IRBuilder<> &B) {
1070 if (!isPointerTy(I->getType()) || !requireAssignType(I) ||
1071 isa<BitCastInst>(I))
1072 return;
1073
1074 setInsertPointSkippingPhis(B, I->getNextNode());
1075
1076 Type *ElemTy = deduceElementType(I);
1077 Constant *EltTyConst = UndefValue::get(ElemTy);
1078 unsigned AddressSpace = getPointerAddressSpace(I->getType());
1079 CallInst *CI = buildIntrWithMD(Intrinsic::spv_assign_ptr_type, {I->getType()},
1080 EltTyConst, I, {B.getInt32(AddressSpace)}, B);
1081 GR->addDeducedElementType(CI, ElemTy);
1082 AssignPtrTypeInstr[I] = CI;
1083}
1084
1085void SPIRVEmitIntrinsics::insertAssignTypeIntrs(Instruction *I,
1086 IRBuilder<> &B) {
1088 Type *Ty = I->getType();
1089 if (!Ty->isVoidTy() && !isPointerTy(Ty) && requireAssignType(I)) {
1090 setInsertPointSkippingPhis(B, I->getNextNode());
1091 Type *TypeToAssign = Ty;
1092 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1093 if (II->getIntrinsicID() == Intrinsic::spv_const_composite ||
1094 II->getIntrinsicID() == Intrinsic::spv_undef) {
1095 auto It = AggrConstTypes.find(II);
1096 if (It == AggrConstTypes.end())
1097 report_fatal_error("Unknown composite intrinsic type");
1098 TypeToAssign = It->second;
1099 }
1100 }
1101 Constant *Const = UndefValue::get(TypeToAssign);
1102 buildIntrWithMD(Intrinsic::spv_assign_type, {Ty}, Const, I, {}, B);
1103 }
1104 for (const auto &Op : I->operands()) {
1105 if (isa<ConstantPointerNull>(Op) || isa<UndefValue>(Op) ||
1106 // Check GetElementPtrConstantExpr case.
1107 (isa<ConstantExpr>(Op) && isa<GEPOperator>(Op))) {
1109 if (isa<UndefValue>(Op) && Op->getType()->isAggregateType())
1110 buildIntrWithMD(Intrinsic::spv_assign_type, {B.getInt32Ty()}, Op,
1111 UndefValue::get(B.getInt32Ty()), {}, B);
1112 else if (!isa<Instruction>(Op)) // TODO: This case could be removed
1113 buildIntrWithMD(Intrinsic::spv_assign_type, {Op->getType()}, Op, Op, {},
1114 B);
1115 }
1116 }
1117}
1118
1119void SPIRVEmitIntrinsics::processInstrAfterVisit(Instruction *I,
1120 IRBuilder<> &B) {
1121 auto *II = dyn_cast<IntrinsicInst>(I);
1122 if (II && II->getIntrinsicID() == Intrinsic::spv_const_composite &&
1123 TrackConstants) {
1124 B.SetInsertPoint(I->getNextNode());
1125 Type *Ty = B.getInt32Ty();
1126 auto t = AggrConsts.find(I);
1127 assert(t != AggrConsts.end());
1128 auto *NewOp = buildIntrWithMD(Intrinsic::spv_track_constant, {Ty, Ty},
1129 t->second, I, {}, B);
1130 I->replaceAllUsesWith(NewOp);
1131 NewOp->setArgOperand(0, I);
1132 }
1133 for (const auto &Op : I->operands()) {
1134 if ((isa<ConstantAggregateZero>(Op) && Op->getType()->isVectorTy()) ||
1135 isa<PHINode>(I) || isa<SwitchInst>(I))
1136 TrackConstants = false;
1137 if ((isa<ConstantData>(Op) || isa<ConstantExpr>(Op)) && TrackConstants) {
1138 unsigned OpNo = Op.getOperandNo();
1139 if (II && ((II->getIntrinsicID() == Intrinsic::spv_gep && OpNo == 0) ||
1140 (II->paramHasAttr(OpNo, Attribute::ImmArg))))
1141 continue;
1142 B.SetInsertPoint(I);
1143 Value *OpTyVal = Op;
1144 if (Op->getType()->isTargetExtTy())
1145 OpTyVal = Constant::getNullValue(
1146 IntegerType::get(I->getContext(), GR->getPointerSize()));
1147 auto *NewOp = buildIntrWithMD(Intrinsic::spv_track_constant,
1148 {Op->getType(), OpTyVal->getType()}, Op,
1149 OpTyVal, {}, B);
1150 I->setOperand(OpNo, NewOp);
1151 }
1152 }
1153 if (I->hasName()) {
1155 setInsertPointSkippingPhis(B, I->getNextNode());
1156 std::vector<Value *> Args = {I};
1157 addStringImm(I->getName(), B, Args);
1158 B.CreateIntrinsic(Intrinsic::spv_assign_name, {I->getType()}, Args);
1159 }
1160}
1161
1162Type *SPIRVEmitIntrinsics::deduceFunParamElementType(Function *F,
1163 unsigned OpIdx) {
1164 std::unordered_set<Function *> FVisited;
1165 return deduceFunParamElementType(F, OpIdx, FVisited);
1166}
1167
1168Type *SPIRVEmitIntrinsics::deduceFunParamElementType(
1169 Function *F, unsigned OpIdx, std::unordered_set<Function *> &FVisited) {
1170 // maybe a cycle
1171 if (FVisited.find(F) != FVisited.end())
1172 return nullptr;
1173 FVisited.insert(F);
1174
1175 std::unordered_set<Value *> Visited;
1177 // search in function's call sites
1178 for (User *U : F->users()) {
1179 CallInst *CI = dyn_cast<CallInst>(U);
1180 if (!CI || OpIdx >= CI->arg_size())
1181 continue;
1182 Value *OpArg = CI->getArgOperand(OpIdx);
1183 if (!isPointerTy(OpArg->getType()))
1184 continue;
1185 // maybe we already know operand's element type
1186 if (Type *KnownTy = GR->findDeducedElementType(OpArg))
1187 return KnownTy;
1188 // try to deduce from the operand itself
1189 Visited.clear();
1190 if (Type *Ty = deduceElementTypeHelper(OpArg, Visited))
1191 return Ty;
1192 // search in actual parameter's users
1193 for (User *OpU : OpArg->users()) {
1194 Instruction *Inst = dyn_cast<Instruction>(OpU);
1195 if (!Inst || Inst == CI)
1196 continue;
1197 Visited.clear();
1198 if (Type *Ty = deduceElementTypeHelper(Inst, Visited))
1199 return Ty;
1200 }
1201 // check if it's a formal parameter of the outer function
1202 if (!CI->getParent() || !CI->getParent()->getParent())
1203 continue;
1204 Function *OuterF = CI->getParent()->getParent();
1205 if (FVisited.find(OuterF) != FVisited.end())
1206 continue;
1207 for (unsigned i = 0; i < OuterF->arg_size(); ++i) {
1208 if (OuterF->getArg(i) == OpArg) {
1209 Lookup.push_back(std::make_pair(OuterF, i));
1210 break;
1211 }
1212 }
1213 }
1214
1215 // search in function parameters
1216 for (auto &Pair : Lookup) {
1217 if (Type *Ty = deduceFunParamElementType(Pair.first, Pair.second, FVisited))
1218 return Ty;
1219 }
1220
1221 return nullptr;
1222}
1223
1224void SPIRVEmitIntrinsics::processParamTypesByFunHeader(Function *F,
1225 IRBuilder<> &B) {
1226 B.SetInsertPointPastAllocas(F);
1227 for (unsigned OpIdx = 0; OpIdx < F->arg_size(); ++OpIdx) {
1228 Argument *Arg = F->getArg(OpIdx);
1229 if (!isUntypedPointerTy(Arg->getType()))
1230 continue;
1231 Type *ElemTy = GR->findDeducedElementType(Arg);
1232 if (!ElemTy && hasPointeeTypeAttr(Arg) &&
1233 (ElemTy = getPointeeTypeByAttr(Arg)) != nullptr)
1234 buildAssignPtr(B, ElemTy, Arg);
1235 }
1236}
1237
1238void SPIRVEmitIntrinsics::processParamTypes(Function *F, IRBuilder<> &B) {
1239 B.SetInsertPointPastAllocas(F);
1240 for (unsigned OpIdx = 0; OpIdx < F->arg_size(); ++OpIdx) {
1241 Argument *Arg = F->getArg(OpIdx);
1242 if (!isUntypedPointerTy(Arg->getType()))
1243 continue;
1244 Type *ElemTy = GR->findDeducedElementType(Arg);
1245 if (!ElemTy && (ElemTy = deduceFunParamElementType(F, OpIdx)) != nullptr)
1246 buildAssignPtr(B, ElemTy, Arg);
1247 }
1248}
1249
1250bool SPIRVEmitIntrinsics::runOnFunction(Function &Func) {
1251 if (Func.isDeclaration())
1252 return false;
1253
1254 const SPIRVSubtarget &ST = TM->getSubtarget<SPIRVSubtarget>(Func);
1255 GR = ST.getSPIRVGlobalRegistry();
1256
1257 F = &Func;
1258 IRBuilder<> B(Func.getContext());
1259 AggrConsts.clear();
1260 AggrConstTypes.clear();
1261 AggrStores.clear();
1262
1263 processParamTypesByFunHeader(F, B);
1264
1265 // StoreInst's operand type can be changed during the next transformations,
1266 // so we need to store it in the set. Also store already transformed types.
1267 for (auto &I : instructions(Func)) {
1268 StoreInst *SI = dyn_cast<StoreInst>(&I);
1269 if (!SI)
1270 continue;
1271 Type *ElTy = SI->getValueOperand()->getType();
1272 if (ElTy->isAggregateType() || ElTy->isVectorTy())
1273 AggrStores.insert(&I);
1274 }
1275
1276 B.SetInsertPoint(&Func.getEntryBlock(), Func.getEntryBlock().begin());
1277 for (auto &GV : Func.getParent()->globals())
1278 processGlobalValue(GV, B);
1279
1280 preprocessUndefs(B);
1281 preprocessCompositeConstants(B);
1283 for (auto &I : instructions(Func))
1284 Worklist.push_back(&I);
1285
1286 for (auto &I : Worklist) {
1287 insertAssignPtrTypeIntrs(I, B);
1288 insertAssignTypeIntrs(I, B);
1289 insertPtrCastOrAssignTypeInstr(I, B);
1290 }
1291
1292 for (auto &I : instructions(Func))
1293 deduceOperandElementType(&I);
1294
1295 for (auto *I : Worklist) {
1296 TrackConstants = true;
1297 if (!I->getType()->isVoidTy() || isa<StoreInst>(I))
1298 B.SetInsertPoint(I->getNextNode());
1299 // Visitors return either the original/newly created instruction for further
1300 // processing, nullptr otherwise.
1301 I = visit(*I);
1302 if (!I)
1303 continue;
1304 processInstrAfterVisit(I, B);
1305 }
1306
1307 return true;
1308}
1309
1310bool SPIRVEmitIntrinsics::runOnModule(Module &M) {
1311 bool Changed = false;
1312
1313 for (auto &F : M) {
1314 Changed |= runOnFunction(F);
1315 }
1316
1317 for (auto &F : M) {
1318 // check if function parameter types are set
1319 if (!F.isDeclaration() && !F.isIntrinsic()) {
1320 const SPIRVSubtarget &ST = TM->getSubtarget<SPIRVSubtarget>(F);
1321 GR = ST.getSPIRVGlobalRegistry();
1322 IRBuilder<> B(F.getContext());
1323 processParamTypes(&F, B);
1324 }
1325 }
1326
1327 return Changed;
1328}
1329
1331 return new SPIRVEmitIntrinsics(TM);
1332}
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 Type * getPointeeTypeByCallInst(StringRef DemangledName, Function *CalledF, unsigned OpIdx)
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:237
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:356
size_t arg_size() const
Definition: Function.h:851
Argument * getArg(unsigned i) const
Definition: Function.h:836
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
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:278
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
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:257
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