LLVM 24.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 "SPIRVBuiltins.h"
23#include "SPIRVSubtarget.h"
24#include "SPIRVTargetMachine.h"
25#include "SPIRVUtils.h"
32#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/IntrinsicsSPIRV.h"
43#include <regex>
44
45using namespace llvm;
46
47namespace {
48
49class SPIRVPrepareFunctionsImpl {
50 const SPIRVTargetMachine &TM;
51 function_ref<const TargetTransformInfo &(Function &)> GetTTI;
52 bool substituteIntrinsicCalls(Function *F);
53 bool substituteAbortKHRCalls(Function *F);
54 bool terminateBlocksAfterTrap(Module &M, Intrinsic::ID IID);
55 Function *removeAggregateTypesFromSignature(Function *F);
56 bool removeAggregateTypesFromCalls(Function *F);
57
58public:
59 SPIRVPrepareFunctionsImpl(
60 const SPIRVTargetMachine &TM,
61 function_ref<const TargetTransformInfo &(Function &)> GetTTI)
62 : TM(TM), GetTTI(GetTTI) {}
63 bool runOnModule(Module &M);
64};
65
66class SPIRVPrepareFunctionsLegacy : public ModulePass {
67 const SPIRVTargetMachine &TM;
68
69public:
70 static char ID;
71 SPIRVPrepareFunctionsLegacy(const SPIRVTargetMachine &TM)
72 : ModulePass(ID), TM(TM) {}
73
74 bool runOnModule(Module &M) override {
75 auto GetTTI = [this](Function &F) -> const TargetTransformInfo & {
76 return getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
77 };
78 return SPIRVPrepareFunctionsImpl(TM, GetTTI).runOnModule(M);
79 }
80
81 void getAnalysisUsage(AnalysisUsage &AU) const override {
82 AU.addRequired<TargetTransformInfoWrapperPass>();
83 }
84
85 StringRef getPassName() const override { return "SPIRV prepare functions"; }
86};
87} // namespace
88
89char SPIRVPrepareFunctionsLegacy::ID = 0;
90
91INITIALIZE_PASS_BEGIN(SPIRVPrepareFunctionsLegacy, "spirv-prepare-functions",
92 "SPIRV prepare functions", false, false)
94INITIALIZE_PASS_END(SPIRVPrepareFunctionsLegacy, "spirv-prepare-functions",
95 "SPIRV prepare functions", false, false)
96
98 Function *IntrinsicFunc = II->getCalledFunction();
99 assert(IntrinsicFunc && "Missing function");
100 std::string FuncName = IntrinsicFunc->getName().str();
101 llvm::replace(FuncName, '.', '_');
102 FuncName = "spirv." + FuncName;
103 return FuncName;
104}
105
107 ArrayRef<Type *> ArgTypes,
108 StringRef Name) {
109 FunctionType *FT = FunctionType::get(RetTy, ArgTypes, false);
110 Function *F = M->getFunction(Name);
111 if (F && F->getFunctionType() == FT)
112 return F;
114 if (F)
115 NewF->setDSOLocal(F->isDSOLocal());
117 return NewF;
118}
119
121 const TargetTransformInfo &TTI) {
122 // For @llvm.memset.* intrinsic cases with constant value and length arguments
123 // are emulated via "storing" a constant array to the destination. For other
124 // cases we wrap the intrinsic in @spirv.llvm_memset_* function and expand the
125 // intrinsic to a loop via expandMemSetAsLoop().
126 if (auto *MSI = dyn_cast<MemSetInst>(Intrinsic))
127 if (isa<Constant>(MSI->getValue()) && isa<ConstantInt>(MSI->getLength()))
128 return false; // It is handled later using OpCopyMemorySized.
129
130 // An intrinsic with a metadata argument has no SPIR-V lowering and can't be
131 // turned into a function.
133 const Function *F = Intrinsic->getFunction();
134 F->getContext().diagnose(DiagnosticInfoUnsupported(
135 *F,
136 "cannot lower the intrinsic '" +
137 Intrinsic->getCalledFunction()->getName() +
138 "' that takes a metadata argument",
139 Intrinsic->getDebugLoc()));
140 if (!Intrinsic->getType()->isVoidTy())
141 Intrinsic->replaceAllUsesWith(PoisonValue::get(Intrinsic->getType()));
142 Intrinsic->eraseFromParent();
143 return true;
144 }
145
146 Module *M = Intrinsic->getModule();
147 std::string FuncName = lowerLLVMIntrinsicName(Intrinsic);
148 if (Intrinsic->isVolatile())
149 FuncName += ".volatile";
150 // Redirect @llvm.intrinsic.* call to @spirv.llvm_intrinsic_*
151 Function *F = M->getFunction(FuncName);
152 if (F) {
153 Intrinsic->setCalledFunction(F);
154 return true;
155 }
156 FunctionCallee FC =
157 M->getOrInsertFunction(FuncName, Intrinsic->getFunctionType());
158 auto IntrinsicID = Intrinsic->getIntrinsicID();
159 Intrinsic->setCalledFunction(FC);
160 F = cast<Function>(FC.getCallee());
161 F->setAttributes(Intrinsic->getAttributes());
162
163 switch (IntrinsicID) {
164 case Intrinsic::memset: {
165 auto *MSI = static_cast<MemSetInst *>(Intrinsic);
166 Argument *Dest = F->getArg(0);
167 Argument *Val = F->getArg(1);
168 Argument *Len = F->getArg(2);
169 Argument *IsVolatile = F->getArg(3);
170 Dest->setName("dest");
171 Val->setName("val");
172 Len->setName("len");
173 IsVolatile->setName("isvolatile");
174 BasicBlock *EntryBB = BasicBlock::Create(M->getContext(), "entry", F);
175 IRBuilder<> IRB(EntryBB);
176 auto *MemSet = IRB.CreateMemSet(Dest, Val, Len, MSI->getDestAlign(),
177 MSI->isVolatile());
178 IRB.CreateRetVoid();
180 MemSet->eraseFromParent();
181 break;
182 }
183 case Intrinsic::bswap: {
184 BasicBlock *EntryBB = BasicBlock::Create(M->getContext(), "entry", F);
185 IRBuilder<> IRB(EntryBB);
187 Intrinsic::bswap, Intrinsic->getType(), F->getArg(0));
188 IRB.CreateRet(BSwap);
189 IntrinsicLowering IL(M->getDataLayout());
190 IL.LowerIntrinsicCall(BSwap);
191 break;
192 }
193 default:
194 break;
195 }
196 return true;
197}
198
199static std::string getAnnotation(Value *AnnoVal, Value *OptAnnoVal) {
200 if (auto *Ref = dyn_cast_or_null<GetElementPtrInst>(AnnoVal))
201 AnnoVal = Ref->getOperand(0);
202 if (auto *Ref = dyn_cast_or_null<BitCastInst>(OptAnnoVal))
203 OptAnnoVal = Ref->getOperand(0);
204
205 std::string Anno;
206 if (auto *C = dyn_cast_or_null<Constant>(AnnoVal)) {
207 StringRef Str;
208 if (getConstantStringInfo(C, Str))
209 Anno = Str;
210 }
211 // handle optional annotation parameter in a way that Khronos Translator do
212 // (collect integers wrapped in a struct)
213 if (auto *C = dyn_cast_or_null<Constant>(OptAnnoVal);
214 C && C->getNumOperands()) {
215 Value *MaybeStruct = C->getOperand(0);
216 if (auto *Struct = dyn_cast<ConstantStruct>(MaybeStruct)) {
217 for (unsigned I = 0, E = Struct->getNumOperands(); I != E; ++I) {
218 if (auto *CInt = dyn_cast<ConstantInt>(Struct->getOperand(I)))
219 Anno += (I == 0 ? ": " : ", ") +
220 std::to_string(CInt->getType()->getIntegerBitWidth() == 1
221 ? CInt->getZExtValue()
222 : CInt->getSExtValue());
223 }
224 } else if (auto *Struct = dyn_cast<ConstantAggregateZero>(MaybeStruct)) {
225 // { i32 i32 ... } zeroinitializer
226 for (unsigned I = 0, E = Struct->getType()->getStructNumElements();
227 I != E; ++I)
228 Anno += I == 0 ? ": 0" : ", 0";
229 }
230 }
231 return Anno;
232}
233
235 const std::string &Anno,
236 LLVMContext &Ctx,
237 Type *Int32Ty) {
238 // Try to parse the annotation string according to the following rules:
239 // annotation := ({kind} | {kind:value,value,...})+
240 // kind := number
241 // value := number | string
242 static const std::regex R(
243 "\\{(\\d+)(?:[:,](\\d+|\"[^\"]*\")(?:,(\\d+|\"[^\"]*\"))*)?\\}");
245 int Pos = 0;
246 for (std::sregex_iterator
247 It = std::sregex_iterator(Anno.begin(), Anno.end(), R),
248 ItEnd = std::sregex_iterator();
249 It != ItEnd; ++It) {
250 if (It->position() != Pos)
252 Pos = It->position() + It->length();
253 std::smatch Match = *It;
255 for (std::size_t i = 1; i < Match.size(); ++i) {
256 std::ssub_match SMatch = Match[i];
257 std::string Item = SMatch.str();
258 if (Item.length() == 0)
259 break;
260 if (Item[0] == '"') {
261 Item = Item.substr(1, Item.length() - 2);
262 // Acceptable format of the string snippet is:
263 static const std::regex RStr("^(\\d+)(?:,(\\d+))*$");
264 if (std::smatch MatchStr; std::regex_match(Item, MatchStr, RStr)) {
265 for (std::size_t SubIdx = 1; SubIdx < MatchStr.size(); ++SubIdx)
266 if (std::string SubStr = MatchStr[SubIdx].str(); SubStr.length())
268 ConstantInt::get(Int32Ty, std::stoi(SubStr))));
269 } else {
270 MDsItem.push_back(MDString::get(Ctx, Item));
271 }
272 } else if (int32_t Num; llvm::to_integer(StringRef(Item), Num, 10)) {
273 MDsItem.push_back(
274 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Num)));
275 } else {
276 MDsItem.push_back(MDString::get(Ctx, Item));
277 }
278 }
279 if (MDsItem.size() == 0)
281 MDs.push_back(MDNode::get(Ctx, MDsItem));
282 }
283 return Pos == static_cast<int>(Anno.length()) ? std::move(MDs)
285}
286
288 LLVMContext &Ctx = II->getContext();
289 Type *Int32Ty = Type::getInt32Ty(Ctx);
290
291 // Retrieve an annotation string from arguments.
292 Value *PtrArg = nullptr;
293 if (auto *BI = dyn_cast<BitCastInst>(II->getArgOperand(0)))
294 PtrArg = BI->getOperand(0);
295 else
296 PtrArg = II->getOperand(0);
297 std::string Anno =
298 getAnnotation(II->getArgOperand(1),
299 4 < II->arg_size() ? II->getArgOperand(4) : nullptr);
300
301 // Parse the annotation.
302 SmallVector<Metadata *> MDs = parseAnnotation(II, Anno, Ctx, Int32Ty);
303
304 // If the annotation string is not parsed successfully we don't know the
305 // format used and output it as a general UserSemantic decoration.
306 // Otherwise MDs is a Metadata tuple (a decoration list) in the format
307 // expected by `spirv.Decorations`.
308 if (MDs.size() == 0) {
309 auto UserSemantic = ConstantAsMetadata::get(ConstantInt::get(
310 Int32Ty, static_cast<uint32_t>(SPIRV::Decoration::UserSemantic)));
311 MDs.push_back(MDNode::get(Ctx, {UserSemantic, MDString::get(Ctx, Anno)}));
312 }
313
314 // Build the internal intrinsic function.
315 IRBuilder<> IRB(II->getParent());
316 IRB.SetInsertPoint(II);
317 IRB.CreateIntrinsic(
318 Intrinsic::spv_assign_decoration, {PtrArg->getType()},
319 {PtrArg, MetadataAsValue::get(Ctx, MDNode::get(Ctx, MDs))});
320 II->replaceAllUsesWith(II->getOperand(0));
321}
322
323static void lowerFunnelShifts(IntrinsicInst *FSHIntrinsic) {
324 // Get a separate function - otherwise, we'd have to rework the CFG of the
325 // current one. Then simply replace the intrinsic uses with a call to the new
326 // function.
327 // Generate LLVM IR for i* @spirv.llvm_fsh?_i* (i* %a, i* %b, i* %c)
328 Module *M = FSHIntrinsic->getModule();
329 FunctionType *FSHFuncTy = FSHIntrinsic->getFunctionType();
330 Type *FSHRetTy = FSHFuncTy->getReturnType();
331 const std::string FuncName = lowerLLVMIntrinsicName(FSHIntrinsic);
332 Function *FSHFunc =
333 getOrCreateFunction(M, FSHRetTy, FSHFuncTy->params(), FuncName);
334
335 if (!FSHFunc->empty()) {
336 FSHIntrinsic->setCalledFunction(FSHFunc);
337 return;
338 }
339 BasicBlock *RotateBB = BasicBlock::Create(M->getContext(), "rotate", FSHFunc);
340 IRBuilder<> IRB(RotateBB);
341 Type *Ty = FSHFunc->getReturnType();
342 // Build the actual funnel shift rotate logic.
343 // In the comments, "int" is used interchangeably with "vector of int
344 // elements".
346 Type *IntTy = VectorTy ? VectorTy->getElementType() : Ty;
347 unsigned BitWidth = IntTy->getIntegerBitWidth();
348 ConstantInt *BitWidthConstant = IRB.getInt({BitWidth, BitWidth});
349 Value *BitWidthForInsts =
350 VectorTy
351 ? IRB.CreateVectorSplat(VectorTy->getNumElements(), BitWidthConstant)
352 : BitWidthConstant;
353 Value *RotateModVal =
354 IRB.CreateURem(/*Rotate*/ FSHFunc->getArg(2), BitWidthForInsts);
355 Value *FirstShift = nullptr, *SecShift = nullptr;
356 if (FSHIntrinsic->getIntrinsicID() == Intrinsic::fshr) {
357 // Shift the less significant number right, the "rotate" number of bits
358 // will be 0-filled on the left as a result of this regular shift.
359 FirstShift = IRB.CreateLShr(FSHFunc->getArg(1), RotateModVal);
360 } else {
361 // Shift the more significant number left, the "rotate" number of bits
362 // will be 0-filled on the right as a result of this regular shift.
363 FirstShift = IRB.CreateShl(FSHFunc->getArg(0), RotateModVal);
364 }
365 // We want the "rotate" number of the more significant int's LSBs (MSBs) to
366 // occupy the leftmost (rightmost) "0 space" left by the previous operation.
367 // Therefore, subtract the "rotate" number from the integer bitsize...
368 Value *SubRotateVal = IRB.CreateSub(BitWidthForInsts, RotateModVal);
369 if (FSHIntrinsic->getIntrinsicID() == Intrinsic::fshr) {
370 // ...and left-shift the more significant int by this number, zero-filling
371 // the LSBs.
372 SecShift = IRB.CreateShl(FSHFunc->getArg(0), SubRotateVal);
373 } else {
374 // ...and right-shift the less significant int by this number, zero-filling
375 // the MSBs.
376 SecShift = IRB.CreateLShr(FSHFunc->getArg(1), SubRotateVal);
377 }
378 // A simple binary addition of the shifted ints yields the final result.
379 IRB.CreateRet(IRB.CreateOr(FirstShift, SecShift));
380
381 FSHIntrinsic->setCalledFunction(FSHFunc);
382}
383
385 ConstrainedFPCmpIntrinsic *ConstrainedCmpIntrinsic,
386 SmallVector<Instruction *> &EraseFromParent) {
387 if (!ConstrainedCmpIntrinsic)
388 return;
389 // Extract the floating-point values being compared
390 Value *LHS = ConstrainedCmpIntrinsic->getArgOperand(0);
391 Value *RHS = ConstrainedCmpIntrinsic->getArgOperand(1);
392 FCmpInst::Predicate Pred = ConstrainedCmpIntrinsic->getPredicate();
393 IRBuilder<> Builder(ConstrainedCmpIntrinsic);
394 Value *FCmp = Builder.CreateFCmp(Pred, LHS, RHS);
395 ConstrainedCmpIntrinsic->replaceAllUsesWith(FCmp);
396 EraseFromParent.push_back(dyn_cast<Instruction>(ConstrainedCmpIntrinsic));
397}
398
400 // If we cannot use the SPV_KHR_expect_assume extension, then we need to
401 // ignore the intrinsic and move on. It should be removed later on by LLVM.
402 // Otherwise we should lower the intrinsic to the corresponding SPIR-V
403 // instruction.
404 // For @llvm.assume we have OpAssumeTrueKHR.
405 // For @llvm.expect and @llvm.expect.with.probability we have OpExpectKHR.
406 //
407 // We need to lower this into a builtin and then the builtin into a SPIR-V
408 // instruction.
409 if (II->getIntrinsicID() == Intrinsic::assume) {
411 II->getModule(), Intrinsic::SPVIntrinsics::spv_assume);
412 II->setCalledFunction(F);
413 } else if (II->getIntrinsicID() == Intrinsic::expect) {
415 II->getModule(), Intrinsic::SPVIntrinsics::spv_expect,
416 {II->getOperand(0)->getType()});
417 II->setCalledFunction(F);
418 } else if (II->getIntrinsicID() == Intrinsic::expect_with_probability) {
419 // OpExpectKHR has no probability operand. Keep the hint only if the
420 // expected value is likely, as LowerExpectIntrinsic does for PHIs.
421 Value *Res = II->getArgOperand(0);
422 double Prob =
423 cast<ConstantFP>(II->getArgOperand(2))->getValueAPF().convertToDouble();
424 if (Prob > 0.5)
425 Res = IRBuilder<>(II).CreateIntrinsic(
426 Intrinsic::SPVIntrinsics::spv_expect, {II->getType()},
427 {II->getArgOperand(0), II->getArgOperand(1)});
428 BasicBlock::iterator BI = II->getIterator();
429 ReplaceInstWithValue(BI, Res);
430 } else {
431 llvm_unreachable("Unknown intrinsic");
432 }
433}
434
436 auto *LifetimeArg0 = II->getArgOperand(0);
437
438 // If the lifetime argument is a poison value, the intrinsic has no effect.
439 if (isa<PoisonValue>(LifetimeArg0)) {
440 II->eraseFromParent();
441 return true;
442 }
443
444 auto *Alloca = dyn_cast<AllocaInst>(LifetimeArg0);
445 if (!Alloca || !Alloca->isStaticAlloca()) {
446 II->eraseFromParent();
447 return true;
448 }
449
450 IRBuilder<> Builder(II);
451 std::optional<TypeSize> Size =
452 Alloca->getAllocationSize(Alloca->getDataLayout());
453 Value *SizeVal = Builder.getInt64(Size ? *Size : -1);
454 Builder.CreateIntrinsic(NewID, Alloca->getType(), {SizeVal, LifetimeArg0});
455 II->eraseFromParent();
456 return true;
457}
458
459static void
461 SmallVector<Instruction *> &EraseFromParent) {
462 auto *FPI = cast<ConstrainedFPIntrinsic>(II);
463 Value *A = FPI->getArgOperand(0);
464 Value *Mul = FPI->getArgOperand(1);
465 Value *Add = FPI->getArgOperand(2);
466 IRBuilder<> Builder(II->getParent());
467 Builder.SetInsertPoint(II);
468 std::optional<RoundingMode> Rounding = FPI->getRoundingMode();
469 Value *Product = Builder.CreateFMul(A, Mul, II->getName() + ".mul");
470 Value *Result = Builder.CreateConstrainedFPBinOp(
471 Intrinsic::experimental_constrained_fadd, Product, Add, {},
472 II->getName() + ".add", nullptr, Rounding);
473 II->replaceAllUsesWith(Result);
474 EraseFromParent.push_back(II);
475}
476
477// llvm.minimum/llvm.maximum return NaN if either operand is NaN and order -0.0
478// before +0.0, whereas OpenCL.std fmin/fmax and GLSL.std.450 NMin/NMax return
479// the other operand for a NaN and may return either zero. Expand them like
480// SPIRV-LLVM-Translator does, so that both produce the same OpenCL SPIR-V. For
481// llvm.minimum (llvm.maximum is symmetrical):
482// %m = call @llvm.minnum(%x, %y)
483// ; unless nsz: for non-NaN operands, the result has the sign of %x if that
484// ; is set (maximum: clear), and the sign of %y otherwise. This only changes
485// ; %m if it is a zero of the wrong sign.
486// %xsign = call @llvm.copysign(1.0, %x)
487// %xneg = fcmp olt %xsign, 0.0
488// %s = select %xneg, %x, %y
489// %m.s = call @llvm.copysign(%m, %s)
490// ; unless nnan
491// %uno = fcmp uno %x, %y
492// %res = select %uno, NaN, %m.s
493static Value *expandFMinimumMaximum(IRBuilderBase &Builder, bool IsMax,
494 Value *X, Value *Y, FastMathFlags FMF) {
495 Type *Ty = X->getType();
496 Value *Res = Builder.CreateIntrinsic(
497 IsMax ? Intrinsic::maxnum : Intrinsic::minnum, {Ty}, {X, Y}, FMF);
498 if (!FMF.noSignedZeros()) {
499 Value *XSign = Builder.CreateCopySign(ConstantFP::get(Ty, 1.0), X);
500 Value *XNeg = Builder.CreateFCmpOLT(XSign, ConstantFP::getZero(Ty));
501 Value *Sign = IsMax ? Builder.CreateSelect(XNeg, Y, X)
502 : Builder.CreateSelect(XNeg, X, Y);
503 Res = Builder.CreateCopySign(Res, Sign);
504 }
505 if (!FMF.noNaNs()) {
506 Value *Uno = Builder.CreateFCmpUNO(X, Y);
507 Res = Builder.CreateSelect(Uno, ConstantFP::getQNaN(Ty), Res);
508 }
509 return Res;
510}
511
513 SmallVector<Instruction *> &EraseFromParent) {
514 IRBuilder<> Builder(II);
516 Builder, II->getIntrinsicID() == Intrinsic::maximum, II->getArgOperand(0),
517 II->getArgOperand(1), II->getFastMathFlags());
518 Res->takeName(II);
519 II->replaceAllUsesWith(Res);
520 EraseFromParent.push_back(II);
521}
522
523// ExpandReductions only expands llvm.vector.reduce.fminimum/fmaximum on vectors
524// with a power-of-two number of elements. Expand the others into a chain of
525// llvm.minimum/llvm.maximum, expanded as above.
526static void
528 SmallVector<Instruction *> &EraseFromParent) {
529 bool IsMax = II->getIntrinsicID() == Intrinsic::vector_reduce_fmaximum;
530 Value *Vec = II->getArgOperand(0);
531 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
532 IRBuilder<> Builder(II);
534 for (unsigned I = 0; I < NumElts; ++I)
535 Elts.push_back(Builder.CreateExtractElement(Vec, I));
536 Value *Res = Elts[0];
537 for (Value *Elt : drop_begin(Elts))
538 Res =
539 expandFMinimumMaximum(Builder, IsMax, Res, Elt, II->getFastMathFlags());
540 Res->takeName(II);
541 II->replaceAllUsesWith(Res);
542 EraseFromParent.push_back(II);
543}
544
545// Substitutes calls to LLVM intrinsics with either calls to SPIR-V intrinsics
546// or calls to proper generated functions. Returns True if F was modified.
547bool SPIRVPrepareFunctionsImpl::substituteIntrinsicCalls(Function *F) {
548 if (F->isDeclaration())
549 return false;
550
551 bool Changed = false;
552 const SPIRVSubtarget &STI = TM.getSubtarget<SPIRVSubtarget>(*F);
553 SmallVector<Instruction *> EraseFromParent;
554 const TargetTransformInfo &TTI = GetTTI(*F);
555 for (BasicBlock &BB : *F) {
556 for (Instruction &I : make_early_inc_range(BB)) {
557 auto Call = dyn_cast<CallInst>(&I);
558 if (!Call)
559 continue;
561 if (!CF || !CF->isIntrinsic())
562 continue;
563 auto *II = cast<IntrinsicInst>(Call);
564 if (Intrinsic::isTargetIntrinsic(II->getIntrinsicID()) &&
565 II->getCalledOperand()->getName().starts_with("llvm.spv"))
566 continue;
567 switch (II->getIntrinsicID()) {
568 case Intrinsic::memset:
569 case Intrinsic::bswap:
571 break;
572 case Intrinsic::fshl:
573 case Intrinsic::fshr:
575 Changed = true;
576 break;
577 case Intrinsic::minimum:
578 case Intrinsic::maximum:
579 lowerFMinimumMaximum(II, EraseFromParent);
580 Changed = true;
581 break;
582 case Intrinsic::vector_reduce_fminimum:
583 case Intrinsic::vector_reduce_fmaximum:
584 lowerVectorReduceFMinimumMaximum(II, EraseFromParent);
585 Changed = true;
586 break;
587 case Intrinsic::assume:
588 case Intrinsic::expect:
589 case Intrinsic::expect_with_probability:
590 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_expect_assume))
592 Changed = true;
593 break;
594 case Intrinsic::lifetime_start:
595 if (!STI.isShader()) {
597 II, Intrinsic::SPVIntrinsics::spv_lifetime_start);
598 } else {
599 II->eraseFromParent();
600 Changed = true;
601 }
602 break;
603 case Intrinsic::lifetime_end:
604 if (!STI.isShader()) {
606 II, Intrinsic::SPVIntrinsics::spv_lifetime_end);
607 } else {
608 II->eraseFromParent();
609 Changed = true;
610 }
611 break;
612 case Intrinsic::ptr_annotation:
614 Changed = true;
615 break;
616 case Intrinsic::experimental_constrained_fmuladd:
617 lowerConstrainedFmuladd(II, EraseFromParent);
618 Changed = true;
619 break;
620 case Intrinsic::experimental_constrained_fcmp:
621 case Intrinsic::experimental_constrained_fcmps:
623 EraseFromParent);
624 Changed = true;
625 break;
626 default:
627 // Drop assume-like intrinsics that have no SPIR-V representation.
628 if (II->isAssumeLikeIntrinsic()) {
629 if (!II->getType()->isVoidTy())
630 II->replaceAllUsesWith(PoisonValue::get(II->getType()));
631 II->eraseFromParent();
632 Changed = true;
633 break;
634 }
635 if (STI.getTargetTriple().getVendor() == Triple::AMD ||
636 any_of(STI.getCLOpts().allow_unknown_intrinsics,
637 [II](StringRef Prefix) {
638 if (Prefix.empty())
639 return false;
640 return II->getCalledFunction()->getName().starts_with(
641 Prefix);
642 }))
644 break;
645 }
646 }
647 }
648 for (auto *I : EraseFromParent)
649 I->eraseFromParent();
650 return Changed;
651}
652
653static void
655 SmallVector<std::pair<int, Type *>> ChangedTys,
656 StringRef Name, StringRef AsmConstraints = "") {
657
658 LLVMContext &Ctx = NMD->getParent()->getContext();
659 Type *I32Ty = IntegerType::getInt32Ty(Ctx);
660
662 MDArgs.push_back(MDString::get(Ctx, Name));
663 transform(ChangedTys, std::back_inserter(MDArgs), [=, &Ctx](auto &&CTy) {
664 return MDNode::get(
665 Ctx, {ConstantAsMetadata::get(ConstantInt::get(I32Ty, CTy.first, true)),
667 });
668 if (!AsmConstraints.empty())
669 MDArgs.push_back(MDNode::get(Ctx, MDString::get(Ctx, AsmConstraints)));
670 NMD->addOperand(MDNode::get(Ctx, MDArgs));
671}
672
673// Drops attributes that are invalid on the i32 placeholders in the type of V.
674template <typename T> static void removeIncompatibleAttrs(T *V) {
675 FunctionType *FTy = V->getFunctionType();
676 AttributeList Attrs = V->getAttributes();
677 V->removeRetAttrs(AttributeFuncs::typeIncompatible(FTy->getReturnType(),
678 Attrs.getRetAttrs()));
679 for (auto [I, Ty] : enumerate(FTy->params()))
680 V->removeParamAttrs(
681 I, AttributeFuncs::typeIncompatible(Ty, Attrs.getParamAttrs(I)));
682}
683
684// Returns F if aggregate argument/return types are not present or cloned F
685// function with the types replaced by i32 types. The change in types is
686// noted in 'spv.cloned_funcs' metadata for later restoration.
687Function *
688SPIRVPrepareFunctionsImpl::removeAggregateTypesFromSignature(Function *F) {
689 bool IsRetAggr = F->getReturnType()->isAggregateType();
690 // Allow intrinsics with aggregate return/argument types to reach GlobalISel.
691 // Renaming/mutating the signature of an intrinsic would desync its name from
692 // its argument types and break the IR verifier.
693 if (F->isIntrinsic())
694 return F;
695
696 IRBuilder<> B(*F->getParent());
697
698 bool HasAggrArg = llvm::any_of(F->args(), [](Argument &Arg) {
699 return Arg.getType()->isAggregateType();
700 });
701 bool DoClone = IsRetAggr || HasAggrArg;
702 if (!DoClone)
703 return F;
704 SmallVector<std::pair<int, Type *>, 4> ChangedTypes;
705 Type *RetType = IsRetAggr ? B.getInt32Ty() : F->getReturnType();
706 if (IsRetAggr)
707 ChangedTypes.push_back(std::pair<int, Type *>(-1, F->getReturnType()));
708 SmallVector<Type *, 4> ArgTypes;
709 for (const auto &Arg : F->args()) {
710 if (Arg.getType()->isAggregateType()) {
711 ArgTypes.push_back(B.getInt32Ty());
712 ChangedTypes.push_back(
713 std::pair<int, Type *>(Arg.getArgNo(), Arg.getType()));
714 } else
715 ArgTypes.push_back(Arg.getType());
716 }
717 FunctionType *NewFTy =
718 FunctionType::get(RetType, ArgTypes, F->getFunctionType()->isVarArg());
719 Function *NewF =
720 Function::Create(NewFTy, F->getLinkage(), F->getAddressSpace(),
721 F->getName(), F->getParent());
722
724 auto NewFArgIt = NewF->arg_begin();
725 for (auto &Arg : F->args()) {
726 StringRef ArgName = Arg.getName();
727 NewFArgIt->setName(ArgName);
728 VMap[&Arg] = &(*NewFArgIt++);
729 }
731
732 CloneFunctionInto(NewF, F, VMap, CloneFunctionChangeType::LocalChangesOnly,
733 Returns);
734 NewF->takeName(F);
735 NewF->setComdat(F->getComdat());
737
739 NewF->getParent()->getOrInsertNamedMetadata("spv.cloned_funcs"),
740 std::move(ChangedTypes), NewF->getName());
741
742 for (User *U : F->users()) {
743 if (auto *CB = dyn_cast<CallBase>(U); CB && CB->getCalledFunction() == F) {
744 CB->mutateFunctionType(NewF->getFunctionType());
746 }
747 }
748 // NewF keeps F's address space, so their pointer types match and
749 // RAUW is safe despite the differing signatures.
750 assert(F->getType() == NewF->getType() &&
751 "RAUW requires F and NewF to share the same pointer type");
752 F->replaceAllUsesWith(NewF);
753
754 // register the mutation
755 if (RetType != F->getReturnType())
756 TM.getSubtarget<SPIRVSubtarget>(*F).getSPIRVGlobalRegistry()->addMutated(
757 NewF, F->getReturnType());
758 return NewF;
759}
760
761// Returns true iff `F`'s name resolves (after OpenCL/SPIR-V demangling and
762// builtin-name lookup) to the SPIR-V friendly built-in `__spirv_AbortKHR`.
763static bool isAbortKHRBuiltin(const Function &F) {
764 if (F.isIntrinsic())
765 return false;
766 StringRef Name = F.getName();
767 // Quick reject: the mangled or unmangled name must contain the substring.
768 if (!Name.contains("__spirv_AbortKHR"))
769 return false;
770 std::string Demangled = getOclOrSpirvBuiltinDemangledName(Name);
771 if (Demangled.empty())
772 return false;
773 return SPIRV::lookupBuiltinNameHelper(Demangled) == "__spirv_AbortKHR";
774}
775
776// Rewrites a single call to `__spirv_AbortKHR` into a call to the
777// `llvm.spv.abort` target intrinsic, then re-terminates the block with
778// `unreachable`. OpAbortKHR is itself a SPIR-V function-termination
779// instruction and must be the last instruction in its block, so any trailing
780// stores/lifetime intrinsics/`ret` emitted by the OpenCL ABI are dropped.
781// `changeToUnreachable` cleans up any successor PHI predecessor entries.
783 IRBuilder<> B(CI);
784 Value *Msg = CI->getArgOperand(0);
785 // The OpenCL C ABI may pass aggregate arguments by pointer (byval). In that
786 // case load the underlying value so that OpAbortKHR receives the composite
787 // itself, as required by the SPV_KHR_abort spec ("Message Type must be a
788 // concrete type").
789 if (CI->isByValArgument(0)) {
790 Type *AggTy = CI->getParamByValType(0);
791 Msg = B.CreateLoad(AggTy, Msg);
792 }
793 B.CreateIntrinsic(Intrinsic::spv_abort, {Msg->getType()}, {Msg});
795}
796
797// Replace OpenCL/SPIR-V style calls to `__spirv_AbortKHR(message)` (i.e.
798// calls to `F` when `F` is the `__spirv_AbortKHR` built-in) with calls to the
799// `llvm.spv.abort` target intrinsic.
800bool SPIRVPrepareFunctionsImpl::substituteAbortKHRCalls(Function *F) {
801 if (!isAbortKHRBuiltin(*F))
802 return false;
803
804 bool Changed = false;
805 for (User *U : make_early_inc_range(F->users())) {
806 auto *CI = dyn_cast<CallInst>(U);
807 if (!CI || CI->getCalledFunction() != F)
808 continue;
809 if (CI->arg_size() != 1)
810 continue;
812 Changed = true;
813 }
814
815 return Changed;
816}
817
818// When the SPV_KHR_abort extension is enabled, `llvm.trap` and
819// `llvm.ubsantrap` are lowered to `OpAbortKHR` during instruction selection.
820// `OpAbortKHR` is itself a SPIR-V block terminator, so any instructions that
821// follow the trap call within the same basic block (e.g. `ret`, lifetime
822// markers) would produce SPIR-V ops after `OpAbortKHR` and break validation.
823// Terminate the block right after each call to the trap intrinsics by replacing
824// the next instruction with `unreachable`.
825bool SPIRVPrepareFunctionsImpl::terminateBlocksAfterTrap(Module &M,
826 Intrinsic::ID IID) {
827 assert((IID == Intrinsic::trap || IID == Intrinsic::ubsantrap) &&
828 "Expected trap intrinsic ID");
829
831 if (!F)
832 return false;
833
834 // If the target doesn't support SPV_KHR_abort, we won't be able to lower
835 // the trap intrinsic to OpAbortKHR, so we can skip the block-terminating
836 // transformation.
837 const auto &ST = TM.getSubtarget<SPIRVSubtarget>(*F);
838 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_abort))
839 return false;
840
841 bool Changed = false;
842 for (User *U : make_early_inc_range(F->users())) {
843 auto *CI = dyn_cast<CallInst>(U);
844 if (!CI || CI->getCalledFunction() != F)
845 continue;
846 Instruction *Next = CI->getNextNode();
848 continue;
850 Changed = true;
851 }
852 return Changed;
853}
854
855static std::string fixMultiOutputConstraintString(StringRef Constraints) {
856 // We should only have one =r return for the made up ASM type.
858 SplitString(Constraints, Tmp, ",");
859 std::string SafeConstraints("=r,");
860 for (unsigned I = 0u; I != Tmp.size() - 1; ++I) {
861 if (Tmp[I].starts_with('=') && (Tmp[I][1] == '&' || isalnum(Tmp[I][1])))
862 continue;
863 SafeConstraints.append(Tmp[I]).append({','});
864 }
865 SafeConstraints.append(Tmp.back());
866
867 return SafeConstraints;
868}
869
870// Mutates indirect and inline ASM callsites iff aggregate argument/return types
871// are present with the types replaced by i32 types. The change in types is
872// noted in 'spv.mutated_callsites' metadata for later restoration. For ASM we
873// also have to mutate the constraint string as IRTranslator tries to handle
874// multiple outputs and expects an aggregate return type in their presence.
875bool SPIRVPrepareFunctionsImpl::removeAggregateTypesFromCalls(Function *F) {
876 if (F->isDeclaration() || F->isIntrinsic())
877 return false;
878
880 for (auto &&I : instructions(F)) {
881 if (auto *CB = dyn_cast<CallBase>(&I)) {
882 if (!CB->getCalledOperand() || CB->getCalledFunction())
883 continue;
884 if (CB->getType()->isAggregateType() ||
885 any_of(CB->args(),
886 [](auto &&Arg) { return Arg->getType()->isAggregateType(); }))
887 Calls.emplace_back(CB, nullptr);
888 }
889 }
890
891 if (Calls.empty())
892 return false;
893
894 IRBuilder<> B(*F->getParent());
895
896 unsigned MutatedCallIdx = 0;
897 for (auto &&[CB, NewFnTy] : Calls) {
899 SmallVector<Type *> NewArgTypes;
900
901 Type *RetTy = CB->getType();
902 if (RetTy->isAggregateType()) {
903 ChangedTypes.emplace_back(-1, RetTy);
904 RetTy = B.getInt32Ty();
905 }
906
907 for (auto &&Arg : CB->args()) {
908 if (Arg->getType()->isAggregateType()) {
909 NewArgTypes.push_back(B.getInt32Ty());
910 ChangedTypes.emplace_back(Arg.getOperandNo(), Arg->getType());
911 } else {
912 NewArgTypes.push_back(Arg->getType());
913 }
914 }
915 NewFnTy = FunctionType::get(RetTy, NewArgTypes,
916 CB->getFunctionType()->isVarArg());
917
918 // Keyed via instruction metadata, not a name.
919 std::string Key =
920 ("spv.mutated_callsite." + F->getName() + "." + Twine(MutatedCallIdx++))
921 .str();
922 CB->setMetadata(
923 "spv.mutated_callsite",
924 MDNode::get(F->getContext(), MDString::get(F->getContext(), Key)));
925
926 std::string Constraints;
927 if (auto *ASM = dyn_cast<InlineAsm>(CB->getCalledOperand())) {
928 Constraints = ASM->getConstraintString();
929
930 CB->setCalledOperand(InlineAsm::get(
931 NewFnTy, ASM->getAsmString(),
932 fixMultiOutputConstraintString(Constraints), ASM->hasSideEffects(),
933 ASM->isAlignStack(), ASM->getDialect(), ASM->canThrow()));
934 }
935
937 F->getParent()->getOrInsertNamedMetadata("spv.mutated_callsites"),
938 std::move(ChangedTypes), Key, Constraints);
939 }
940
941 for (auto &&[CB, NewFTy] : Calls) {
942 if (NewFTy->getReturnType() != CB->getType())
943 TM.getSubtarget<SPIRVSubtarget>(*F).getSPIRVGlobalRegistry()->addMutated(
944 CB, CB->getType());
945 CB->mutateFunctionType(NewFTy);
947 }
948
949 return true;
950}
951
952bool SPIRVPrepareFunctionsImpl::runOnModule(Module &M) {
953 // Resolve the SPIR-V environment from module content before any
954 // function-level processing. This must happen before legalization so that
955 // isShader()/isKernel() return correct values.
956 const_cast<SPIRVTargetMachine &>(TM)
957 .getMutableSubtargetImpl()
958 ->resolveEnvFromModule(M);
959
960 bool Changed = false;
961 if (M.getFunctionDefs().empty()) {
962 // If there are no function definitions, insert a service
963 // function so that the global/constant tracking intrinsics
964 // will be created. Without these intrinsics the generated SPIR-V
965 // will be empty. The service function itself is not emitted.
967 BasicBlock *BB = BasicBlock::Create(M.getContext(), "entry", SF);
968 IRBuilder<> IRB(BB);
969 IRB.CreateRetVoid();
970 Changed = true;
971 }
972
973 Changed |= terminateBlocksAfterTrap(M, Intrinsic::trap);
974 Changed |= terminateBlocksAfterTrap(M, Intrinsic::ubsantrap);
975
976 for (GlobalVariable &GV : M.globals()) {
977 // Strip + tag available_externally globals so AuxData can re-emit the
978 // original linkage as NonSemantic.AuxData::Linkage.
979 if (GV.hasAvailableExternallyLinkage() && !GV.isDeclaration()) {
981 GV.setLinkage(GlobalValue::ExternalLinkage);
982 Changed = true;
983 }
984 }
985
986 std::vector<Function *> FuncsWorklist;
987 for (Function &F : M) {
988 // MachineFunctionPass skips available_externally; strip + tag so AuxData
989 // can re-emit the original linkage as NonSemantic.AuxData::Linkage.
990 if (F.hasAvailableExternallyLinkage() && !F.isDeclaration()) {
993 Changed = true;
994 }
995 Changed |= substituteAbortKHRCalls(&F);
996 Changed |= substituteIntrinsicCalls(&F);
997 Changed |= sortBlocks(F);
998 Changed |= removeAggregateTypesFromCalls(&F);
999 FuncsWorklist.push_back(&F);
1000 }
1001
1002 for (auto *F : FuncsWorklist) {
1003 Function *NewF = removeAggregateTypesFromSignature(F);
1004
1005 if (NewF != F) {
1006 F->eraseFromParent();
1007 Changed = true;
1008 }
1009 }
1010 return Changed;
1011}
1012
1017 auto GetTTI = [&FAM](Function &F) -> const TargetTransformInfo & {
1018 return FAM.getResult<TargetIRAnalysis>(F);
1019 };
1020 return SPIRVPrepareFunctionsImpl(TM, GetTTI).runOnModule(M)
1023}
1024
1025ModulePass *
1027 return new SPIRVPrepareFunctionsLegacy(TM);
1028}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Expand Atomic instructions
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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
#define T
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
const char * Msg
static Value * expandFMinimumMaximum(IRBuilderBase &Builder, bool IsMax, Value *X, Value *Y, FastMathFlags FMF)
static void lowerFunnelShifts(IntrinsicInst *FSHIntrinsic)
static std::string getAnnotation(Value *AnnoVal, Value *OptAnnoVal)
spirv prepare SPIRV prepare static false std::string lowerLLVMIntrinsicName(IntrinsicInst *II)
static void lowerVectorReduceFMinimumMaximum(IntrinsicInst *II, SmallVector< Instruction * > &EraseFromParent)
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 bool isAbortKHRBuiltin(const Function &F)
static SmallVector< Metadata * > parseAnnotation(Value *I, const std::string &Anno, LLVMContext &Ctx, Type *Int32Ty)
static void removeIncompatibleAttrs(T *V)
static std::string fixMultiOutputConstraintString(StringRef Constraints)
static void rewriteAbortKHRCall(CallInst *CI)
static void addFunctionTypeMutation(NamedMDNode *NMD, SmallVector< std::pair< int, Type * > > ChangedTys, StringRef Name, StringRef AsmConstraints="")
static bool toSpvLifetimeIntrinsic(IntrinsicInst *II, Intrinsic::ID NewID)
static void lowerExpectAssume(IntrinsicInst *II)
static void lowerFMinimumMaximum(IntrinsicInst *II, SmallVector< Instruction * > &EraseFromParent)
static Function * getOrCreateFunction(Module *M, Type *RetTy, ArrayRef< Type * > ArgTypes, StringRef Name)
#define SPIRV_WAS_AVAILABLE_EXTERNALLY_ATTR
Definition SPIRVUtils.h:559
This file contains some functions that are useful when dealing with strings.
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
BinaryOperator * Mul
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
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
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
Type * getParamByValType(unsigned ArgNo) const
Extract the byval type for a call or parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
This class represents a function call, abstracting a target machine's calling convention.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
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
Diagnostic information for unsupported feature in backend.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noNaNs() const
Definition FMF.h:65
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:169
bool empty() const
Definition Function.h:853
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
arg_iterator arg_begin()
Definition Function.h:862
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:252
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
void setCallingConv(CallingConv::ID CC)
Definition Function.h:277
Argument * getArg(unsigned i) const
Definition Function.h:880
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
Module * getParent()
Get the module that this global value is contained inside of...
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
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:1534
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
Definition IRBuilder.h:1194
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1513
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:602
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition IRBuilder.h:1189
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:486
Value * CreateURem(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1501
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
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.
LLVM_ABI 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:76
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
This class wraps the llvm.memset and llvm.memset.inline intrinsics.
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:105
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:332
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition Module.cpp:327
A tuple of MDNodes.
Definition Metadata.h:1806
Module * getParent()
Get the module that holds this named metadata collection.
Definition Metadata.h:1876
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
const SPIRVOptions & getCLOpts() const
bool canUseExtension(SPIRV::Extension::Extension E) const
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
Analysis pass providing the TargetTransformInfo.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:314
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:512
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
Type * getElementType() const
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI bool isTargetIntrinsic(ID IID)
isTargetIntrinsic - Returns true if IID is an intrinsic specific to a certain target.
std::string lookupBuiltinNameHelper(StringRef DemangledCall, FPDecorationId *DecorationId)
Parses the name part of the demangled builtin call.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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:649
bool sortBlocks(Function &F)
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI void ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V)
Replace all uses of an instruction (specified by BI) with a value, then remove and delete the origina...
LLVM_ABI void SplitString(StringRef Source, SmallVectorImpl< StringRef > &OutFragments, StringRef Delimiters=" \t\n\v\f\r")
SplitString - Split up the specified string according to the specified delimiters,...
Function * getOrCreateBackendServiceFunction(Module &M)
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
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:2042
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:1762
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
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
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Definition Local.cpp:2592
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
TargetTransformInfo TTI
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:1926
@ 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
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
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)
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879