LLVM 23.0.0git
SPIRVPrepareFunctions.cpp
Go to the documentation of this file.
1//===-- SPIRVPrepareFunctions.cpp - modify function signatures --*- 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// This pass modifies function signatures containing aggregate arguments
10// and/or return value before IRTranslator. Information about the original
11// signatures is stored in metadata. It is used during call lowering to
12// restore correct SPIR-V types of function arguments and return values.
13// This pass also substitutes some llvm intrinsic calls with calls to newly
14// generated functions (as the Khronos LLVM/SPIR-V Translator does).
15//
16// NOTE: this pass is a module-level one due to the necessity to modify
17// GVs/functions.
18//
19//===----------------------------------------------------------------------===//
20
21#include "SPIRV.h"
22#include "SPIRVSubtarget.h"
23#include "SPIRVTargetMachine.h"
24#include "SPIRVUtils.h"
29#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/IntrinsicsSPIRV.h"
37#include <regex>
38
39using namespace llvm;
40
41namespace {
42
43class SPIRVPrepareFunctions : public ModulePass {
44 const SPIRVTargetMachine &TM;
45 bool substituteIntrinsicCalls(Function *F);
46 Function *removeAggregateTypesFromSignature(Function *F);
47 bool removeAggregateTypesFromCalls(Function *F);
48
49public:
50 static char ID;
51 SPIRVPrepareFunctions(const SPIRVTargetMachine &TM)
52 : ModulePass(ID), TM(TM) {}
53
54 bool runOnModule(Module &M) override;
55
56 StringRef getPassName() const override { return "SPIRV prepare functions"; }
57
58 void getAnalysisUsage(AnalysisUsage &AU) const override {
59 ModulePass::getAnalysisUsage(AU);
60 }
61};
62
63static cl::list<std::string> SPVAllowUnknownIntrinsics(
64 "spv-allow-unknown-intrinsics", cl::CommaSeparated,
65 cl::desc("Emit unknown intrinsics as calls to external functions. A "
66 "comma-separated input list of intrinsic prefixes must be "
67 "provided, and only intrinsics carrying a listed prefix get "
68 "emitted as described."),
69 cl::value_desc("intrinsic_prefix_0,intrinsic_prefix_1"), cl::ValueOptional);
70} // namespace
71
72char SPIRVPrepareFunctions::ID = 0;
73
74INITIALIZE_PASS(SPIRVPrepareFunctions, "prepare-functions",
75 "SPIRV prepare functions", false, false)
76
77static std::string lowerLLVMIntrinsicName(IntrinsicInst *II) {
78 Function *IntrinsicFunc = II->getCalledFunction();
79 assert(IntrinsicFunc && "Missing function");
80 std::string FuncName = IntrinsicFunc->getName().str();
81 llvm::replace(FuncName, '.', '_');
82 FuncName = "spirv." + FuncName;
83 return FuncName;
84}
85
87 ArrayRef<Type *> ArgTypes,
88 StringRef Name) {
89 FunctionType *FT = FunctionType::get(RetTy, ArgTypes, false);
90 Function *F = M->getFunction(Name);
91 if (F && F->getFunctionType() == FT)
92 return F;
94 if (F)
95 NewF->setDSOLocal(F->isDSOLocal());
97 return NewF;
98}
99
101 const TargetTransformInfo &TTI) {
102 // For @llvm.memset.* intrinsic cases with constant value and length arguments
103 // are emulated via "storing" a constant array to the destination. For other
104 // cases we wrap the intrinsic in @spirv.llvm_memset_* function and expand the
105 // intrinsic to a loop via expandMemSetAsLoop().
106 if (auto *MSI = dyn_cast<MemSetInst>(Intrinsic))
107 if (isa<Constant>(MSI->getValue()) && isa<ConstantInt>(MSI->getLength()))
108 return false; // It is handled later using OpCopyMemorySized.
109
110 Module *M = Intrinsic->getModule();
111 std::string FuncName = lowerLLVMIntrinsicName(Intrinsic);
112 if (Intrinsic->isVolatile())
113 FuncName += ".volatile";
114 // Redirect @llvm.intrinsic.* call to @spirv.llvm_intrinsic_*
115 Function *F = M->getFunction(FuncName);
116 if (F) {
117 Intrinsic->setCalledFunction(F);
118 return true;
119 }
120 // TODO copy arguments attributes: nocapture writeonly.
121 FunctionCallee FC =
122 M->getOrInsertFunction(FuncName, Intrinsic->getFunctionType());
123 auto IntrinsicID = Intrinsic->getIntrinsicID();
124 Intrinsic->setCalledFunction(FC);
125
126 F = dyn_cast<Function>(FC.getCallee());
127 assert(F && "Callee must be a function");
128
129 switch (IntrinsicID) {
130 case Intrinsic::memset: {
131 auto *MSI = static_cast<MemSetInst *>(Intrinsic);
132 Argument *Dest = F->getArg(0);
133 Argument *Val = F->getArg(1);
134 Argument *Len = F->getArg(2);
135 Argument *IsVolatile = F->getArg(3);
136 Dest->setName("dest");
137 Val->setName("val");
138 Len->setName("len");
139 IsVolatile->setName("isvolatile");
140 BasicBlock *EntryBB = BasicBlock::Create(M->getContext(), "entry", F);
141 IRBuilder<> IRB(EntryBB);
142 auto *MemSet = IRB.CreateMemSet(Dest, Val, Len, MSI->getDestAlign(),
143 MSI->isVolatile());
144 IRB.CreateRetVoid();
146 MemSet->eraseFromParent();
147 break;
148 }
149 case Intrinsic::bswap: {
150 BasicBlock *EntryBB = BasicBlock::Create(M->getContext(), "entry", F);
151 IRBuilder<> IRB(EntryBB);
152 auto *BSwap = IRB.CreateIntrinsic(Intrinsic::bswap, Intrinsic->getType(),
153 F->getArg(0));
154 IRB.CreateRet(BSwap);
155 IntrinsicLowering IL(M->getDataLayout());
156 IL.LowerIntrinsicCall(BSwap);
157 break;
158 }
159 default:
160 break;
161 }
162 return true;
163}
164
165static std::string getAnnotation(Value *AnnoVal, Value *OptAnnoVal) {
166 if (auto *Ref = dyn_cast_or_null<GetElementPtrInst>(AnnoVal))
167 AnnoVal = Ref->getOperand(0);
168 if (auto *Ref = dyn_cast_or_null<BitCastInst>(OptAnnoVal))
169 OptAnnoVal = Ref->getOperand(0);
170
171 std::string Anno;
172 if (auto *C = dyn_cast_or_null<Constant>(AnnoVal)) {
173 StringRef Str;
174 if (getConstantStringInfo(C, Str))
175 Anno = Str;
176 }
177 // handle optional annotation parameter in a way that Khronos Translator do
178 // (collect integers wrapped in a struct)
179 if (auto *C = dyn_cast_or_null<Constant>(OptAnnoVal);
180 C && C->getNumOperands()) {
181 Value *MaybeStruct = C->getOperand(0);
182 if (auto *Struct = dyn_cast<ConstantStruct>(MaybeStruct)) {
183 for (unsigned I = 0, E = Struct->getNumOperands(); I != E; ++I) {
184 if (auto *CInt = dyn_cast<ConstantInt>(Struct->getOperand(I)))
185 Anno += (I == 0 ? ": " : ", ") +
186 std::to_string(CInt->getType()->getIntegerBitWidth() == 1
187 ? CInt->getZExtValue()
188 : CInt->getSExtValue());
189 }
190 } else if (auto *Struct = dyn_cast<ConstantAggregateZero>(MaybeStruct)) {
191 // { i32 i32 ... } zeroinitializer
192 for (unsigned I = 0, E = Struct->getType()->getStructNumElements();
193 I != E; ++I)
194 Anno += I == 0 ? ": 0" : ", 0";
195 }
196 }
197 return Anno;
198}
199
201 const std::string &Anno,
202 LLVMContext &Ctx,
203 Type *Int32Ty) {
204 // Try to parse the annotation string according to the following rules:
205 // annotation := ({kind} | {kind:value,value,...})+
206 // kind := number
207 // value := number | string
208 static const std::regex R(
209 "\\{(\\d+)(?:[:,](\\d+|\"[^\"]*\")(?:,(\\d+|\"[^\"]*\"))*)?\\}");
211 int Pos = 0;
212 for (std::sregex_iterator
213 It = std::sregex_iterator(Anno.begin(), Anno.end(), R),
214 ItEnd = std::sregex_iterator();
215 It != ItEnd; ++It) {
216 if (It->position() != Pos)
218 Pos = It->position() + It->length();
219 std::smatch Match = *It;
221 for (std::size_t i = 1; i < Match.size(); ++i) {
222 std::ssub_match SMatch = Match[i];
223 std::string Item = SMatch.str();
224 if (Item.length() == 0)
225 break;
226 if (Item[0] == '"') {
227 Item = Item.substr(1, Item.length() - 2);
228 // Acceptable format of the string snippet is:
229 static const std::regex RStr("^(\\d+)(?:,(\\d+))*$");
230 if (std::smatch MatchStr; std::regex_match(Item, MatchStr, RStr)) {
231 for (std::size_t SubIdx = 1; SubIdx < MatchStr.size(); ++SubIdx)
232 if (std::string SubStr = MatchStr[SubIdx].str(); SubStr.length())
234 ConstantInt::get(Int32Ty, std::stoi(SubStr))));
235 } else {
236 MDsItem.push_back(MDString::get(Ctx, Item));
237 }
238 } else if (int32_t Num; llvm::to_integer(StringRef(Item), Num, 10)) {
239 MDsItem.push_back(
240 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Num)));
241 } else {
242 MDsItem.push_back(MDString::get(Ctx, Item));
243 }
244 }
245 if (MDsItem.size() == 0)
247 MDs.push_back(MDNode::get(Ctx, MDsItem));
248 }
249 return Pos == static_cast<int>(Anno.length()) ? std::move(MDs)
251}
252
254 LLVMContext &Ctx = II->getContext();
256
257 // Retrieve an annotation string from arguments.
258 Value *PtrArg = nullptr;
259 if (auto *BI = dyn_cast<BitCastInst>(II->getArgOperand(0)))
260 PtrArg = BI->getOperand(0);
261 else
262 PtrArg = II->getOperand(0);
263 std::string Anno =
264 getAnnotation(II->getArgOperand(1),
265 4 < II->arg_size() ? II->getArgOperand(4) : nullptr);
266
267 // Parse the annotation.
269
270 // If the annotation string is not parsed successfully we don't know the
271 // format used and output it as a general UserSemantic decoration.
272 // Otherwise MDs is a Metadata tuple (a decoration list) in the format
273 // expected by `spirv.Decorations`.
274 if (MDs.size() == 0) {
275 auto UserSemantic = ConstantAsMetadata::get(ConstantInt::get(
276 Int32Ty, static_cast<uint32_t>(SPIRV::Decoration::UserSemantic)));
277 MDs.push_back(MDNode::get(Ctx, {UserSemantic, MDString::get(Ctx, Anno)}));
278 }
279
280 // Build the internal intrinsic function.
281 IRBuilder<> IRB(II->getParent());
282 IRB.SetInsertPoint(II);
283 IRB.CreateIntrinsic(
284 Intrinsic::spv_assign_decoration, {PtrArg->getType()},
285 {PtrArg, MetadataAsValue::get(Ctx, MDNode::get(Ctx, MDs))});
286 II->replaceAllUsesWith(II->getOperand(0));
287}
288
289static void lowerFunnelShifts(IntrinsicInst *FSHIntrinsic) {
290 // Get a separate function - otherwise, we'd have to rework the CFG of the
291 // current one. Then simply replace the intrinsic uses with a call to the new
292 // function.
293 // Generate LLVM IR for i* @spirv.llvm_fsh?_i* (i* %a, i* %b, i* %c)
294 Module *M = FSHIntrinsic->getModule();
295 FunctionType *FSHFuncTy = FSHIntrinsic->getFunctionType();
296 Type *FSHRetTy = FSHFuncTy->getReturnType();
297 const std::string FuncName = lowerLLVMIntrinsicName(FSHIntrinsic);
298 Function *FSHFunc =
299 getOrCreateFunction(M, FSHRetTy, FSHFuncTy->params(), FuncName);
300
301 if (!FSHFunc->empty()) {
302 FSHIntrinsic->setCalledFunction(FSHFunc);
303 return;
304 }
305 BasicBlock *RotateBB = BasicBlock::Create(M->getContext(), "rotate", FSHFunc);
306 IRBuilder<> IRB(RotateBB);
307 Type *Ty = FSHFunc->getReturnType();
308 // Build the actual funnel shift rotate logic.
309 // In the comments, "int" is used interchangeably with "vector of int
310 // elements".
312 Type *IntTy = VectorTy ? VectorTy->getElementType() : Ty;
313 unsigned BitWidth = IntTy->getIntegerBitWidth();
314 ConstantInt *BitWidthConstant = IRB.getInt({BitWidth, BitWidth});
315 Value *BitWidthForInsts =
316 VectorTy
317 ? IRB.CreateVectorSplat(VectorTy->getNumElements(), BitWidthConstant)
318 : BitWidthConstant;
319 Value *RotateModVal =
320 IRB.CreateURem(/*Rotate*/ FSHFunc->getArg(2), BitWidthForInsts);
321 Value *FirstShift = nullptr, *SecShift = nullptr;
322 if (FSHIntrinsic->getIntrinsicID() == Intrinsic::fshr) {
323 // Shift the less significant number right, the "rotate" number of bits
324 // will be 0-filled on the left as a result of this regular shift.
325 FirstShift = IRB.CreateLShr(FSHFunc->getArg(1), RotateModVal);
326 } else {
327 // Shift the more significant number left, the "rotate" number of bits
328 // will be 0-filled on the right as a result of this regular shift.
329 FirstShift = IRB.CreateShl(FSHFunc->getArg(0), RotateModVal);
330 }
331 // We want the "rotate" number of the more significant int's LSBs (MSBs) to
332 // occupy the leftmost (rightmost) "0 space" left by the previous operation.
333 // Therefore, subtract the "rotate" number from the integer bitsize...
334 Value *SubRotateVal = IRB.CreateSub(BitWidthForInsts, RotateModVal);
335 if (FSHIntrinsic->getIntrinsicID() == Intrinsic::fshr) {
336 // ...and left-shift the more significant int by this number, zero-filling
337 // the LSBs.
338 SecShift = IRB.CreateShl(FSHFunc->getArg(0), SubRotateVal);
339 } else {
340 // ...and right-shift the less significant int by this number, zero-filling
341 // the MSBs.
342 SecShift = IRB.CreateLShr(FSHFunc->getArg(1), SubRotateVal);
343 }
344 // A simple binary addition of the shifted ints yields the final result.
345 IRB.CreateRet(IRB.CreateOr(FirstShift, SecShift));
346
347 FSHIntrinsic->setCalledFunction(FSHFunc);
348}
349
351 ConstrainedFPCmpIntrinsic *ConstrainedCmpIntrinsic,
352 SmallVector<Instruction *> &EraseFromParent) {
353 if (!ConstrainedCmpIntrinsic)
354 return;
355 // Extract the floating-point values being compared
356 Value *LHS = ConstrainedCmpIntrinsic->getArgOperand(0);
357 Value *RHS = ConstrainedCmpIntrinsic->getArgOperand(1);
358 FCmpInst::Predicate Pred = ConstrainedCmpIntrinsic->getPredicate();
359 IRBuilder<> Builder(ConstrainedCmpIntrinsic);
360 Value *FCmp = Builder.CreateFCmp(Pred, LHS, RHS);
361 ConstrainedCmpIntrinsic->replaceAllUsesWith(FCmp);
362 EraseFromParent.push_back(dyn_cast<Instruction>(ConstrainedCmpIntrinsic));
363}
364
366 // If we cannot use the SPV_KHR_expect_assume extension, then we need to
367 // ignore the intrinsic and move on. It should be removed later on by LLVM.
368 // Otherwise we should lower the intrinsic to the corresponding SPIR-V
369 // instruction.
370 // For @llvm.assume we have OpAssumeTrueKHR.
371 // For @llvm.expect we have OpExpectKHR.
372 //
373 // We need to lower this into a builtin and then the builtin into a SPIR-V
374 // instruction.
375 if (II->getIntrinsicID() == Intrinsic::assume) {
377 II->getModule(), Intrinsic::SPVIntrinsics::spv_assume);
378 II->setCalledFunction(F);
379 } else if (II->getIntrinsicID() == Intrinsic::expect) {
381 II->getModule(), Intrinsic::SPVIntrinsics::spv_expect,
382 {II->getOperand(0)->getType()});
383 II->setCalledFunction(F);
384 } else {
385 llvm_unreachable("Unknown intrinsic");
386 }
387}
388
390 auto *LifetimeArg0 = II->getArgOperand(0);
391
392 // If the lifetime argument is a poison value, the intrinsic has no effect.
393 if (isa<PoisonValue>(LifetimeArg0)) {
394 II->eraseFromParent();
395 return true;
396 }
397
398 IRBuilder<> Builder(II);
399 auto *Alloca = cast<AllocaInst>(LifetimeArg0);
400 std::optional<TypeSize> Size =
401 Alloca->getAllocationSize(Alloca->getDataLayout());
402 Value *SizeVal = Builder.getInt64(Size ? *Size : -1);
403 Builder.CreateIntrinsic(NewID, Alloca->getType(), {SizeVal, LifetimeArg0});
404 II->eraseFromParent();
405 return true;
406}
407
408static void
410 SmallVector<Instruction *> &EraseFromParent) {
411 auto *FPI = cast<ConstrainedFPIntrinsic>(II);
412 Value *A = FPI->getArgOperand(0);
413 Value *Mul = FPI->getArgOperand(1);
414 Value *Add = FPI->getArgOperand(2);
415 IRBuilder<> Builder(II->getParent());
416 Builder.SetInsertPoint(II);
417 std::optional<RoundingMode> Rounding = FPI->getRoundingMode();
418 Value *Product = Builder.CreateFMul(A, Mul, II->getName() + ".mul");
419 Value *Result = Builder.CreateConstrainedFPBinOp(
420 Intrinsic::experimental_constrained_fadd, Product, Add, {},
421 II->getName() + ".add", nullptr, Rounding);
422 II->replaceAllUsesWith(Result);
423 EraseFromParent.push_back(II);
424}
425
426// Substitutes calls to LLVM intrinsics with either calls to SPIR-V intrinsics
427// or calls to proper generated functions. Returns True if F was modified.
428bool SPIRVPrepareFunctions::substituteIntrinsicCalls(Function *F) {
429 bool Changed = false;
430 const SPIRVSubtarget &STI = TM.getSubtarget<SPIRVSubtarget>(*F);
431 SmallVector<Instruction *> EraseFromParent;
432 const TargetTransformInfo &TTI = TM.getTargetTransformInfo(*F);
433 for (BasicBlock &BB : *F) {
434 for (Instruction &I : make_early_inc_range(BB)) {
435 auto Call = dyn_cast<CallInst>(&I);
436 if (!Call)
437 continue;
439 if (!CF || !CF->isIntrinsic())
440 continue;
441 auto *II = cast<IntrinsicInst>(Call);
442 switch (II->getIntrinsicID()) {
443 case Intrinsic::memset:
444 case Intrinsic::bswap:
446 break;
447 case Intrinsic::fshl:
448 case Intrinsic::fshr:
450 Changed = true;
451 break;
452 case Intrinsic::assume:
453 case Intrinsic::expect:
454 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_expect_assume))
456 Changed = true;
457 break;
458 case Intrinsic::lifetime_start:
459 if (!STI.isShader()) {
461 II, Intrinsic::SPVIntrinsics::spv_lifetime_start);
462 } else {
463 II->eraseFromParent();
464 Changed = true;
465 }
466 break;
467 case Intrinsic::lifetime_end:
468 if (!STI.isShader()) {
470 II, Intrinsic::SPVIntrinsics::spv_lifetime_end);
471 } else {
472 II->eraseFromParent();
473 Changed = true;
474 }
475 break;
476 case Intrinsic::ptr_annotation:
478 Changed = true;
479 break;
480 case Intrinsic::experimental_constrained_fmuladd:
481 lowerConstrainedFmuladd(II, EraseFromParent);
482 Changed = true;
483 break;
484 case Intrinsic::experimental_constrained_fcmp:
485 case Intrinsic::experimental_constrained_fcmps:
487 EraseFromParent);
488 Changed = true;
489 break;
490 default:
491 if (TM.getTargetTriple().getVendor() == Triple::AMD ||
492 any_of(SPVAllowUnknownIntrinsics, [II](auto &&Prefix) {
493 if (Prefix.empty())
494 return false;
495 return II->getCalledFunction()->getName().starts_with(Prefix);
496 }))
498 break;
499 }
500 }
501 }
502 for (auto *I : EraseFromParent)
503 I->eraseFromParent();
504 return Changed;
505}
506
507static void
509 SmallVector<std::pair<int, Type *>> ChangedTys,
510 StringRef Name) {
511
512 LLVMContext &Ctx = NMD->getParent()->getContext();
513 Type *I32Ty = IntegerType::getInt32Ty(Ctx);
514
516 MDArgs.push_back(MDString::get(Ctx, Name));
517 transform(ChangedTys, std::back_inserter(MDArgs), [=, &Ctx](auto &&CTy) {
518 return MDNode::get(
519 Ctx, {ConstantAsMetadata::get(ConstantInt::get(I32Ty, CTy.first, true)),
521 });
522 NMD->addOperand(MDNode::get(Ctx, MDArgs));
523}
524// Returns F if aggregate argument/return types are not present or cloned F
525// function with the types replaced by i32 types. The change in types is
526// noted in 'spv.cloned_funcs' metadata for later restoration.
527Function *
528SPIRVPrepareFunctions::removeAggregateTypesFromSignature(Function *F) {
529 bool IsRetAggr = F->getReturnType()->isAggregateType();
530 // Allow intrinsics with aggregate return type to reach GlobalISel
531 if (F->isIntrinsic() && IsRetAggr)
532 return F;
533
534 IRBuilder<> B(F->getContext());
535
536 bool HasAggrArg = llvm::any_of(F->args(), [](Argument &Arg) {
537 return Arg.getType()->isAggregateType();
538 });
539 bool DoClone = IsRetAggr || HasAggrArg;
540 if (!DoClone)
541 return F;
542 SmallVector<std::pair<int, Type *>, 4> ChangedTypes;
543 Type *RetType = IsRetAggr ? B.getInt32Ty() : F->getReturnType();
544 if (IsRetAggr)
545 ChangedTypes.push_back(std::pair<int, Type *>(-1, F->getReturnType()));
546 SmallVector<Type *, 4> ArgTypes;
547 for (const auto &Arg : F->args()) {
548 if (Arg.getType()->isAggregateType()) {
549 ArgTypes.push_back(B.getInt32Ty());
550 ChangedTypes.push_back(
551 std::pair<int, Type *>(Arg.getArgNo(), Arg.getType()));
552 } else
553 ArgTypes.push_back(Arg.getType());
554 }
555 FunctionType *NewFTy =
556 FunctionType::get(RetType, ArgTypes, F->getFunctionType()->isVarArg());
557 Function *NewF =
558 Function::Create(NewFTy, F->getLinkage(), F->getAddressSpace(),
559 F->getName(), F->getParent());
560
562 auto NewFArgIt = NewF->arg_begin();
563 for (auto &Arg : F->args()) {
564 StringRef ArgName = Arg.getName();
565 NewFArgIt->setName(ArgName);
566 VMap[&Arg] = &(*NewFArgIt++);
567 }
569
570 CloneFunctionInto(NewF, F, VMap, CloneFunctionChangeType::LocalChangesOnly,
571 Returns);
572 NewF->takeName(F);
573
575 NewF->getParent()->getOrInsertNamedMetadata("spv.cloned_funcs"),
576 std::move(ChangedTypes), NewF->getName());
577
578 for (auto *U : make_early_inc_range(F->users())) {
579 if (CallInst *CI;
580 (CI = dyn_cast<CallInst>(U)) && CI->getCalledFunction() == F)
581 CI->mutateFunctionType(NewF->getFunctionType());
582 if (auto *C = dyn_cast<Constant>(U))
583 C->handleOperandChange(F, NewF);
584 else
585 U->replaceUsesOfWith(F, NewF);
586 }
587
588 // register the mutation
589 if (RetType != F->getReturnType())
590 TM.getSubtarget<SPIRVSubtarget>(*F).getSPIRVGlobalRegistry()->addMutated(
591 NewF, F->getReturnType());
592 return NewF;
593}
594
595// Mutates indirect callsites iff if aggregate argument/return types are present
596// with the types replaced by i32 types. The change in types is noted in
597// 'spv.mutated_callsites' metadata for later restoration.
598bool SPIRVPrepareFunctions::removeAggregateTypesFromCalls(Function *F) {
599 if (F->isDeclaration() || F->isIntrinsic())
600 return false;
601
603 for (auto &&I : instructions(F)) {
604 if (auto *CB = dyn_cast<CallBase>(&I)) {
605 if (!CB->getCalledOperand() || CB->getCalledFunction())
606 continue;
607 if (CB->getType()->isAggregateType() ||
608 any_of(CB->args(),
609 [](auto &&Arg) { return Arg->getType()->isAggregateType(); }))
610 Calls.emplace_back(CB, nullptr);
611 }
612 }
613
614 if (Calls.empty())
615 return false;
616
617 IRBuilder<> B(F->getContext());
618
619 for (auto &&[CB, NewFnTy] : Calls) {
621 SmallVector<Type *> NewArgTypes;
622
623 Type *RetTy = CB->getType();
624 if (RetTy->isAggregateType()) {
625 ChangedTypes.emplace_back(-1, RetTy);
626 RetTy = B.getInt32Ty();
627 }
628
629 for (auto &&Arg : CB->args()) {
630 if (Arg->getType()->isAggregateType()) {
631 NewArgTypes.push_back(B.getInt32Ty());
632 ChangedTypes.emplace_back(Arg.getOperandNo(), Arg->getType());
633 } else {
634 NewArgTypes.push_back(Arg->getType());
635 }
636 }
637 NewFnTy = FunctionType::get(RetTy, NewArgTypes,
638 CB->getFunctionType()->isVarArg());
639
640 if (!CB->hasName())
641 CB->setName("spv.mutated_callsite." + F->getName());
642 else
643 CB->setName("spv.named_mutated_callsite." + F->getName() + "." +
644 CB->getName());
645
647 F->getParent()->getOrInsertNamedMetadata("spv.mutated_callsites"),
648 std::move(ChangedTypes), CB->getName());
649 }
650
651 for (auto &&[CB, NewFTy] : Calls) {
652 if (NewFTy->getReturnType() != CB->getType())
653 TM.getSubtarget<SPIRVSubtarget>(*F).getSPIRVGlobalRegistry()->addMutated(
654 CB, CB->getType());
655 CB->mutateFunctionType(NewFTy);
656 }
657
658 return true;
659}
660
661bool SPIRVPrepareFunctions::runOnModule(Module &M) {
662 // Resolve the SPIR-V environment from module content before any
663 // function-level processing. This must happen before legalization so that
664 // isShader()/isKernel() return correct values.
665 const_cast<SPIRVTargetMachine &>(TM)
666 .getMutableSubtargetImpl()
667 ->resolveEnvFromModule(M);
668
669 bool Changed = false;
670 for (Function &F : M) {
671 Changed |= substituteIntrinsicCalls(&F);
672 Changed |= sortBlocks(F);
673 Changed |= removeAggregateTypesFromCalls(&F);
674 }
675
676 std::vector<Function *> FuncsWorklist;
677 for (auto &F : M)
678 FuncsWorklist.push_back(&F);
679
680 for (auto *F : FuncsWorklist) {
681 Function *NewF = removeAggregateTypesFromSignature(F);
682
683 if (NewF != F) {
684 F->eraseFromParent();
685 Changed = true;
686 }
687 }
688 return Changed;
689}
690
691ModulePass *
693 return new SPIRVPrepareFunctions(TM);
694}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static void lowerFunnelShifts(IntrinsicInst *FSHIntrinsic)
static std::string getAnnotation(Value *AnnoVal, Value *OptAnnoVal)
static void lowerConstrainedFPCmpIntrinsic(ConstrainedFPCmpIntrinsic *ConstrainedCmpIntrinsic, SmallVector< Instruction * > &EraseFromParent)
static void lowerConstrainedFmuladd(IntrinsicInst *II, SmallVector< Instruction * > &EraseFromParent)
static void lowerPtrAnnotation(IntrinsicInst *II)
static bool lowerIntrinsicToFunction(IntrinsicInst *Intrinsic, const TargetTransformInfo &TTI)
static SmallVector< Metadata * > parseAnnotation(Value *I, const std::string &Anno, LLVMContext &Ctx, Type *Int32Ty)
static bool toSpvLifetimeIntrinsic(IntrinsicInst *II, Intrinsic::ID NewID)
static void lowerExpectAssume(IntrinsicInst *II)
static void addFunctionTypeMutation(NamedMDNode *NMD, SmallVector< std::pair< int, Type * > > ChangedTys, StringRef Name)
static Function * getOrCreateFunction(Module *M, Type *RetTy, ArrayRef< Type * > ArgTypes, StringRef Name)
This file contains some functions that are useful when dealing with strings.
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
BinaryOperator * Mul
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Constrained floating point compare intrinsics.
LLVM_ABI FCmpInst::Predicate getPredicate() const
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
bool empty() const
Definition Function.h:859
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:211
arg_iterator arg_begin()
Definition Function.h:868
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:251
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
void setCallingConv(CallingConv::ID CC)
Definition Function.h:276
Argument * getArg(unsigned i) const
Definition Function.h:886
Module * getParent()
Get the module that this global value is contained inside of...
void setDSOLocal(bool Local)
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1516
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
Definition IRBuilder.h:1175
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1423
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1495
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, MaybeAlign Align, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert a memset to the specified pointer and the specified value.
Definition IRBuilder.h:629
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition IRBuilder.h:1170
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:207
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1576
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:537
Value * CreateURem(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1483
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2787
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
void LowerIntrinsicCall(CallInst *CI)
Replace a call to the specified intrinsic function.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
This class wraps the llvm.memset and llvm.memset.inline intrinsics.
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:110
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:285
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition Module.cpp:308
A tuple of MDNodes.
Definition Metadata.h:1760
Module * getParent()
Get the module that holds this named metadata collection.
Definition Metadata.h:1830
LLVM_ABI void addOperand(MDNode *M)
bool canUseExtension(SPIRV::Extension::Extension E) const
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:225
const Triple & getTargetTriple() const
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
VendorType getVendor() const
Get the parsed vendor type of this triple.
Definition Triple.h:425
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:296
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:304
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:509
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:397
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:403
Type * getElementType() const
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
Definition InstrProf.h:296
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:634
bool sortBlocks(Function &F)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2026
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1910
@ Add
Sum of integers.
constexpr unsigned BitWidth
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI void expandMemSetAsLoop(MemSetInst *MemSet, const TargetTransformInfo *TTI=nullptr)
Expand MemSet as a loop.
LLVM_ABI void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, CloneFunctionChangeType Changes, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc into NewFunc, transforming the old arguments into references to VMap values.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool to_integer(StringRef S, N &Num, unsigned Base=0)
Convert the string S to an integer of the specified type using the radix Base. If Base is 0,...
ModulePass * createSPIRVPrepareFunctionsPass(const SPIRVTargetMachine &TM)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870