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// Give a zero minnum/maxnum result the sign llvm.minimum/maximum(num) require.
478static Value *fixZeroSign(IRBuilderBase &Builder, bool IsMax, Value *Res,
479 Value *X, Value *Y) {
480 Type *Ty = X->getType();
481 Value *XSign = Builder.CreateCopySign(ConstantFP::get(Ty, 1.0), X);
482 Value *XNeg = Builder.CreateFCmpOLT(XSign, ConstantFP::getZero(Ty));
483 Value *Sign = IsMax ? Builder.CreateSelect(XNeg, Y, X)
484 : Builder.CreateSelect(XNeg, X, Y);
485 return Builder.CreateCopySign(Res, Sign);
486}
487
488// llvm.minimum/llvm.maximum return NaN if either operand is NaN and order -0.0
489// before +0.0, whereas OpenCL.std fmin/fmax and GLSL.std.450 NMin/NMax return
490// the other operand for a NaN and may return either zero. Expand them like
491// SPIRV-LLVM-Translator does, so that both produce the same OpenCL SPIR-V. For
492// llvm.minimum (llvm.maximum is symmetrical):
493// %m = call @llvm.minnum(%x, %y)
494// ; unless nsz: for non-NaN operands, the result has the sign of %x if that
495// ; is set (maximum: clear), and the sign of %y otherwise. This only changes
496// ; %m if it is a zero of the wrong sign.
497// %xsign = call @llvm.copysign(1.0, %x)
498// %xneg = fcmp olt %xsign, 0.0
499// %s = select %xneg, %x, %y
500// %m.s = call @llvm.copysign(%m, %s)
501// ; unless nnan
502// %uno = fcmp uno %x, %y
503// %res = select %uno, NaN, %m.s
504static Value *expandFMinimumMaximum(IRBuilderBase &Builder, bool IsMax,
505 Value *X, Value *Y, FastMathFlags FMF) {
506 Type *Ty = X->getType();
507 Value *Res = Builder.CreateIntrinsic(
508 IsMax ? Intrinsic::maxnum : Intrinsic::minnum, {Ty}, {X, Y}, FMF);
509 if (!FMF.noSignedZeros())
510 Res = fixZeroSign(Builder, IsMax, Res, X, Y);
511 if (!FMF.noNaNs()) {
512 Value *Uno = Builder.CreateFCmpUNO(X, Y);
513 Res = Builder.CreateSelect(Uno, ConstantFP::getQNaN(Ty), Res);
514 }
515 return Res;
516}
517
519 SmallVector<Instruction *> &EraseFromParent) {
520 IRBuilder<> Builder(II);
522 Builder, II->getIntrinsicID() == Intrinsic::maximum, II->getArgOperand(0),
523 II->getArgOperand(1), II->getFastMathFlags());
524 Res->takeName(II);
525 II->replaceAllUsesWith(Res);
526 EraseFromParent.push_back(II);
527}
528
529// The SPIR-V fmin/fmax and NMin/NMax that minnum/maxnum lower to may return NaN
530// for an sNaN input and either zero for -0.0 vs +0.0; minimumnum/maximumnum
531// may not.
532static void
534 SmallVector<Instruction *> &EraseFromParent) {
535 IRBuilder<> Builder(II);
536 bool IsMax = II->getIntrinsicID() == Intrinsic::maximumnum;
537 Value *X = II->getArgOperand(0), *Y = II->getArgOperand(1);
538 Type *Ty = X->getType();
539 FastMathFlags FMF = II->getFastMathFlags();
540 if (!FMF.noNaNs()) {
541 X = Builder.CreateSelect(Builder.CreateFCmpUNO(X, X), Y, X);
542 Y = Builder.CreateSelect(Builder.CreateFCmpUNO(Y, Y), X, Y);
543 }
544 // Don't forward flags: SPIR-V NSZ and Fast would also drop the sign of
545 // same-sign zeros.
546 Value *Res = Builder.CreateIntrinsic(
547 IsMax ? Intrinsic::maxnum : Intrinsic::minnum, {Ty}, {X, Y});
548 if (!FMF.noSignedZeros())
549 Res = fixZeroSign(Builder, IsMax, Res, X, Y);
550 Res->takeName(II);
551 II->replaceAllUsesWith(Res);
552 EraseFromParent.push_back(II);
553}
554
555// ExpandReductions only expands llvm.vector.reduce.fminimum/fmaximum on vectors
556// with a power-of-two number of elements. Expand the others into a chain of
557// llvm.minimum/llvm.maximum, expanded as above.
558static void
560 SmallVector<Instruction *> &EraseFromParent) {
561 bool IsMax = II->getIntrinsicID() == Intrinsic::vector_reduce_fmaximum;
562 Value *Vec = II->getArgOperand(0);
563 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
564 IRBuilder<> Builder(II);
566 for (unsigned I = 0; I < NumElts; ++I)
567 Elts.push_back(Builder.CreateExtractElement(Vec, I));
568 Value *Res = Elts[0];
569 for (Value *Elt : drop_begin(Elts))
570 Res =
571 expandFMinimumMaximum(Builder, IsMax, Res, Elt, II->getFastMathFlags());
572 Res->takeName(II);
573 II->replaceAllUsesWith(Res);
574 EraseFromParent.push_back(II);
575}
576
577// Substitutes calls to LLVM intrinsics with either calls to SPIR-V intrinsics
578// or calls to proper generated functions. Returns True if F was modified.
579bool SPIRVPrepareFunctionsImpl::substituteIntrinsicCalls(Function *F) {
580 if (F->isDeclaration())
581 return false;
582
583 bool Changed = false;
584 const SPIRVSubtarget &STI = TM.getSubtarget<SPIRVSubtarget>(*F);
585 SmallVector<Instruction *> EraseFromParent;
586 const TargetTransformInfo &TTI = GetTTI(*F);
587 for (BasicBlock &BB : *F) {
588 for (Instruction &I : make_early_inc_range(BB)) {
589 auto Call = dyn_cast<CallInst>(&I);
590 if (!Call)
591 continue;
593 if (!CF || !CF->isIntrinsic())
594 continue;
595 auto *II = cast<IntrinsicInst>(Call);
596 if (Intrinsic::isTargetIntrinsic(II->getIntrinsicID()) &&
597 II->getCalledOperand()->getName().starts_with("llvm.spv"))
598 continue;
599 switch (II->getIntrinsicID()) {
600 case Intrinsic::memset:
601 case Intrinsic::bswap:
603 break;
604 case Intrinsic::fshl:
605 case Intrinsic::fshr:
607 Changed = true;
608 break;
609 case Intrinsic::minimum:
610 case Intrinsic::maximum:
611 lowerFMinimumMaximum(II, EraseFromParent);
612 Changed = true;
613 break;
614 case Intrinsic::minimumnum:
615 case Intrinsic::maximumnum:
616 lowerFMinimumMaximumNum(II, EraseFromParent);
617 Changed = true;
618 break;
619 case Intrinsic::vector_reduce_fminimum:
620 case Intrinsic::vector_reduce_fmaximum:
621 lowerVectorReduceFMinimumMaximum(II, EraseFromParent);
622 Changed = true;
623 break;
624 case Intrinsic::assume:
625 case Intrinsic::expect:
626 case Intrinsic::expect_with_probability:
627 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_expect_assume))
629 Changed = true;
630 break;
631 case Intrinsic::lifetime_start:
632 if (!STI.isShader()) {
634 II, Intrinsic::SPVIntrinsics::spv_lifetime_start);
635 } else {
636 II->eraseFromParent();
637 Changed = true;
638 }
639 break;
640 case Intrinsic::lifetime_end:
641 if (!STI.isShader()) {
643 II, Intrinsic::SPVIntrinsics::spv_lifetime_end);
644 } else {
645 II->eraseFromParent();
646 Changed = true;
647 }
648 break;
649 case Intrinsic::ptr_annotation:
651 Changed = true;
652 break;
653 case Intrinsic::experimental_constrained_fmuladd:
654 lowerConstrainedFmuladd(II, EraseFromParent);
655 Changed = true;
656 break;
657 case Intrinsic::experimental_constrained_fcmp:
658 case Intrinsic::experimental_constrained_fcmps:
660 EraseFromParent);
661 Changed = true;
662 break;
663 default:
664 // Drop assume-like intrinsics that have no SPIR-V representation.
665 if (II->isAssumeLikeIntrinsic()) {
666 if (!II->getType()->isVoidTy())
667 II->replaceAllUsesWith(PoisonValue::get(II->getType()));
668 II->eraseFromParent();
669 Changed = true;
670 break;
671 }
672 if (STI.getTargetTriple().getVendor() == Triple::AMD ||
673 any_of(STI.getCLOpts().allow_unknown_intrinsics,
674 [II](StringRef Prefix) {
675 if (Prefix.empty())
676 return false;
677 return II->getCalledFunction()->getName().starts_with(
678 Prefix);
679 }))
681 break;
682 }
683 }
684 }
685 for (auto *I : EraseFromParent)
686 I->eraseFromParent();
687 return Changed;
688}
689
690static void
692 SmallVector<std::pair<int, Type *>> ChangedTys,
693 StringRef Name, StringRef AsmConstraints = "") {
694
695 LLVMContext &Ctx = NMD->getParent()->getContext();
696 Type *I32Ty = IntegerType::getInt32Ty(Ctx);
697
699 MDArgs.push_back(MDString::get(Ctx, Name));
700 transform(ChangedTys, std::back_inserter(MDArgs), [=, &Ctx](auto &&CTy) {
701 return MDNode::get(
702 Ctx, {ConstantAsMetadata::get(ConstantInt::get(I32Ty, CTy.first, true)),
704 });
705 if (!AsmConstraints.empty())
706 MDArgs.push_back(MDNode::get(Ctx, MDString::get(Ctx, AsmConstraints)));
707 NMD->addOperand(MDNode::get(Ctx, MDArgs));
708}
709
710// Drops attributes that are invalid on the i32 placeholders in the type of V.
711template <typename T> static void removeIncompatibleAttrs(T *V) {
712 FunctionType *FTy = V->getFunctionType();
713 AttributeList Attrs = V->getAttributes();
714 V->removeRetAttrs(AttributeFuncs::typeIncompatible(FTy->getReturnType(),
715 Attrs.getRetAttrs()));
716 for (auto [I, Ty] : enumerate(FTy->params()))
717 V->removeParamAttrs(
718 I, AttributeFuncs::typeIncompatible(Ty, Attrs.getParamAttrs(I)));
719}
720
721// Returns F if aggregate argument/return types are not present or cloned F
722// function with the types replaced by i32 types. The change in types is
723// noted in 'spv.cloned_funcs' metadata for later restoration.
724Function *
725SPIRVPrepareFunctionsImpl::removeAggregateTypesFromSignature(Function *F) {
726 bool IsRetAggr = F->getReturnType()->isAggregateType();
727 // Allow intrinsics with aggregate return/argument types to reach GlobalISel.
728 // Renaming/mutating the signature of an intrinsic would desync its name from
729 // its argument types and break the IR verifier.
730 if (F->isIntrinsic())
731 return F;
732
733 IRBuilder<> B(*F->getParent());
734
735 bool HasAggrArg = llvm::any_of(F->args(), [](Argument &Arg) {
736 return Arg.getType()->isAggregateType();
737 });
738 bool DoClone = IsRetAggr || HasAggrArg;
739 if (!DoClone)
740 return F;
741 SmallVector<std::pair<int, Type *>, 4> ChangedTypes;
742 Type *RetType = IsRetAggr ? B.getInt32Ty() : F->getReturnType();
743 if (IsRetAggr)
744 ChangedTypes.push_back(std::pair<int, Type *>(-1, F->getReturnType()));
745 SmallVector<Type *, 4> ArgTypes;
746 for (const auto &Arg : F->args()) {
747 if (Arg.getType()->isAggregateType()) {
748 ArgTypes.push_back(B.getInt32Ty());
749 ChangedTypes.push_back(
750 std::pair<int, Type *>(Arg.getArgNo(), Arg.getType()));
751 } else
752 ArgTypes.push_back(Arg.getType());
753 }
754 FunctionType *NewFTy =
755 FunctionType::get(RetType, ArgTypes, F->getFunctionType()->isVarArg());
756 Function *NewF =
757 Function::Create(NewFTy, F->getLinkage(), F->getAddressSpace(),
758 F->getName(), F->getParent());
759
761 auto NewFArgIt = NewF->arg_begin();
762 for (auto &Arg : F->args()) {
763 StringRef ArgName = Arg.getName();
764 NewFArgIt->setName(ArgName);
765 VMap[&Arg] = &(*NewFArgIt++);
766 }
768
769 CloneFunctionInto(NewF, F, VMap, CloneFunctionChangeType::LocalChangesOnly,
770 Returns);
771 NewF->takeName(F);
772 NewF->setComdat(F->getComdat());
774
776 NewF->getParent()->getOrInsertNamedMetadata("spv.cloned_funcs"),
777 std::move(ChangedTypes), NewF->getName());
778
779 for (User *U : F->users()) {
780 if (auto *CB = dyn_cast<CallBase>(U); CB && CB->getCalledFunction() == F) {
781 CB->mutateFunctionType(NewF->getFunctionType());
783 }
784 }
785 // NewF keeps F's address space, so their pointer types match and
786 // RAUW is safe despite the differing signatures.
787 assert(F->getType() == NewF->getType() &&
788 "RAUW requires F and NewF to share the same pointer type");
789 F->replaceAllUsesWith(NewF);
790
791 // register the mutation
792 if (RetType != F->getReturnType())
793 TM.getSubtarget<SPIRVSubtarget>(*F).getSPIRVGlobalRegistry()->addMutated(
794 NewF, F->getReturnType());
795 return NewF;
796}
797
798// Returns true iff `F`'s name resolves (after OpenCL/SPIR-V demangling and
799// builtin-name lookup) to the SPIR-V friendly built-in `__spirv_AbortKHR`.
800static bool isAbortKHRBuiltin(const Function &F) {
801 if (F.isIntrinsic())
802 return false;
803 StringRef Name = F.getName();
804 // Quick reject: the mangled or unmangled name must contain the substring.
805 if (!Name.contains("__spirv_AbortKHR"))
806 return false;
807 std::string Demangled = getOclOrSpirvBuiltinDemangledName(Name);
808 if (Demangled.empty())
809 return false;
810 return SPIRV::lookupBuiltinNameHelper(Demangled) == "__spirv_AbortKHR";
811}
812
813// Rewrites a single call to `__spirv_AbortKHR` into a call to the
814// `llvm.spv.abort` target intrinsic, then re-terminates the block with
815// `unreachable`. OpAbortKHR is itself a SPIR-V function-termination
816// instruction and must be the last instruction in its block, so any trailing
817// stores/lifetime intrinsics/`ret` emitted by the OpenCL ABI are dropped.
818// `changeToUnreachable` cleans up any successor PHI predecessor entries.
820 IRBuilder<> B(CI);
821 Value *Msg = CI->getArgOperand(0);
822 // The OpenCL C ABI may pass aggregate arguments by pointer (byval). In that
823 // case load the underlying value so that OpAbortKHR receives the composite
824 // itself, as required by the SPV_KHR_abort spec ("Message Type must be a
825 // concrete type").
826 if (CI->isByValArgument(0)) {
827 Type *AggTy = CI->getParamByValType(0);
828 Msg = B.CreateLoad(AggTy, Msg);
829 }
830 B.CreateIntrinsic(Intrinsic::spv_abort, {Msg->getType()}, {Msg});
832}
833
834// Replace OpenCL/SPIR-V style calls to `__spirv_AbortKHR(message)` (i.e.
835// calls to `F` when `F` is the `__spirv_AbortKHR` built-in) with calls to the
836// `llvm.spv.abort` target intrinsic.
837bool SPIRVPrepareFunctionsImpl::substituteAbortKHRCalls(Function *F) {
838 if (!isAbortKHRBuiltin(*F))
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 if (CI->arg_size() != 1)
847 continue;
849 Changed = true;
850 }
851
852 return Changed;
853}
854
855// When the SPV_KHR_abort extension is enabled, `llvm.trap` and
856// `llvm.ubsantrap` are lowered to `OpAbortKHR` during instruction selection.
857// `OpAbortKHR` is itself a SPIR-V block terminator, so any instructions that
858// follow the trap call within the same basic block (e.g. `ret`, lifetime
859// markers) would produce SPIR-V ops after `OpAbortKHR` and break validation.
860// Terminate the block right after each call to the trap intrinsics by replacing
861// the next instruction with `unreachable`.
862bool SPIRVPrepareFunctionsImpl::terminateBlocksAfterTrap(Module &M,
863 Intrinsic::ID IID) {
864 assert((IID == Intrinsic::trap || IID == Intrinsic::ubsantrap) &&
865 "Expected trap intrinsic ID");
866
868 if (!F)
869 return false;
870
871 // If the target doesn't support SPV_KHR_abort, we won't be able to lower
872 // the trap intrinsic to OpAbortKHR, so we can skip the block-terminating
873 // transformation.
874 const auto &ST = TM.getSubtarget<SPIRVSubtarget>(*F);
875 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_abort))
876 return false;
877
878 bool Changed = false;
879 for (User *U : make_early_inc_range(F->users())) {
880 auto *CI = dyn_cast<CallInst>(U);
881 if (!CI || CI->getCalledFunction() != F)
882 continue;
883 Instruction *Next = CI->getNextNode();
885 continue;
887 Changed = true;
888 }
889 return Changed;
890}
891
892static std::string fixMultiOutputConstraintString(StringRef Constraints) {
893 // We should only have one =r return for the made up ASM type.
895 SplitString(Constraints, Tmp, ",");
896 std::string SafeConstraints("=r,");
897 for (unsigned I = 0u; I != Tmp.size() - 1; ++I) {
898 if (Tmp[I].starts_with('=') && (Tmp[I][1] == '&' || isalnum(Tmp[I][1])))
899 continue;
900 SafeConstraints.append(Tmp[I]).append({','});
901 }
902 SafeConstraints.append(Tmp.back());
903
904 return SafeConstraints;
905}
906
907// Mutates indirect and inline ASM callsites iff aggregate argument/return types
908// are present with the types replaced by i32 types. The change in types is
909// noted in 'spv.mutated_callsites' metadata for later restoration. For ASM we
910// also have to mutate the constraint string as IRTranslator tries to handle
911// multiple outputs and expects an aggregate return type in their presence.
912bool SPIRVPrepareFunctionsImpl::removeAggregateTypesFromCalls(Function *F) {
913 if (F->isDeclaration() || F->isIntrinsic())
914 return false;
915
917 for (auto &&I : instructions(F)) {
918 if (auto *CB = dyn_cast<CallBase>(&I)) {
919 if (!CB->getCalledOperand() || CB->getCalledFunction())
920 continue;
921 if (CB->getType()->isAggregateType() ||
922 any_of(CB->args(),
923 [](auto &&Arg) { return Arg->getType()->isAggregateType(); }))
924 Calls.emplace_back(CB, nullptr);
925 }
926 }
927
928 if (Calls.empty())
929 return false;
930
931 IRBuilder<> B(*F->getParent());
932
933 unsigned MutatedCallIdx = 0;
934 for (auto &&[CB, NewFnTy] : Calls) {
936 SmallVector<Type *> NewArgTypes;
937
938 Type *RetTy = CB->getType();
939 if (RetTy->isAggregateType()) {
940 ChangedTypes.emplace_back(-1, RetTy);
941 RetTy = B.getInt32Ty();
942 }
943
944 for (auto &&Arg : CB->args()) {
945 if (Arg->getType()->isAggregateType()) {
946 NewArgTypes.push_back(B.getInt32Ty());
947 ChangedTypes.emplace_back(Arg.getOperandNo(), Arg->getType());
948 } else {
949 NewArgTypes.push_back(Arg->getType());
950 }
951 }
952 NewFnTy = FunctionType::get(RetTy, NewArgTypes,
953 CB->getFunctionType()->isVarArg());
954
955 // Keyed via instruction metadata, not a name.
956 std::string Key =
957 ("spv.mutated_callsite." + F->getName() + "." + Twine(MutatedCallIdx++))
958 .str();
959 CB->setMetadata(
960 "spv.mutated_callsite",
961 MDNode::get(F->getContext(), MDString::get(F->getContext(), Key)));
962
963 std::string Constraints;
964 if (auto *ASM = dyn_cast<InlineAsm>(CB->getCalledOperand())) {
965 Constraints = ASM->getConstraintString();
966
967 CB->setCalledOperand(InlineAsm::get(
968 NewFnTy, ASM->getAsmString(),
969 fixMultiOutputConstraintString(Constraints), ASM->hasSideEffects(),
970 ASM->isAlignStack(), ASM->getDialect(), ASM->canThrow()));
971 }
972
974 F->getParent()->getOrInsertNamedMetadata("spv.mutated_callsites"),
975 std::move(ChangedTypes), Key, Constraints);
976 }
977
978 for (auto &&[CB, NewFTy] : Calls) {
979 if (NewFTy->getReturnType() != CB->getType())
980 TM.getSubtarget<SPIRVSubtarget>(*F).getSPIRVGlobalRegistry()->addMutated(
981 CB, CB->getType());
982 CB->mutateFunctionType(NewFTy);
984 }
985
986 return true;
987}
988
989bool SPIRVPrepareFunctionsImpl::runOnModule(Module &M) {
990 // Resolve the SPIR-V environment from module content before any
991 // function-level processing. This must happen before legalization so that
992 // isShader()/isKernel() return correct values.
993 const_cast<SPIRVTargetMachine &>(TM)
994 .getMutableSubtargetImpl()
995 ->resolveEnvFromModule(M);
996
997 bool Changed = false;
998 if (M.getFunctionDefs().empty()) {
999 // If there are no function definitions, insert a service
1000 // function so that the global/constant tracking intrinsics
1001 // will be created. Without these intrinsics the generated SPIR-V
1002 // will be empty. The service function itself is not emitted.
1004 BasicBlock *BB = BasicBlock::Create(M.getContext(), "entry", SF);
1005 IRBuilder<> IRB(BB);
1006 IRB.CreateRetVoid();
1007 Changed = true;
1008 }
1009
1010 Changed |= terminateBlocksAfterTrap(M, Intrinsic::trap);
1011 Changed |= terminateBlocksAfterTrap(M, Intrinsic::ubsantrap);
1012
1013 for (GlobalVariable &GV : M.globals()) {
1014 // Strip + tag available_externally globals so AuxData can re-emit the
1015 // original linkage as NonSemantic.AuxData::Linkage.
1016 if (GV.hasAvailableExternallyLinkage() && !GV.isDeclaration()) {
1017 GV.addAttribute(SPIRV_WAS_AVAILABLE_EXTERNALLY_ATTR);
1018 GV.setLinkage(GlobalValue::ExternalLinkage);
1019 Changed = true;
1020 }
1021 }
1022
1023 std::vector<Function *> FuncsWorklist;
1024 for (Function &F : M) {
1025 // MachineFunctionPass skips available_externally; strip + tag so AuxData
1026 // can re-emit the original linkage as NonSemantic.AuxData::Linkage.
1027 if (F.hasAvailableExternallyLinkage() && !F.isDeclaration()) {
1029 F.setLinkage(GlobalValue::ExternalLinkage);
1030 Changed = true;
1031 }
1032 Changed |= substituteAbortKHRCalls(&F);
1033 Changed |= substituteIntrinsicCalls(&F);
1034 Changed |= sortBlocks(F);
1035 Changed |= removeAggregateTypesFromCalls(&F);
1036 FuncsWorklist.push_back(&F);
1037 }
1038
1039 for (auto *F : FuncsWorklist) {
1040 Function *NewF = removeAggregateTypesFromSignature(F);
1041
1042 if (NewF != F) {
1043 F->eraseFromParent();
1044 Changed = true;
1045 }
1046 }
1047 return Changed;
1048}
1049
1054 auto GetTTI = [&FAM](Function &F) -> const TargetTransformInfo & {
1055 return FAM.getResult<TargetIRAnalysis>(F);
1056 };
1057 return SPIRVPrepareFunctionsImpl(TM, GetTTI).runOnModule(M)
1060}
1061
1062ModulePass *
1064 return new SPIRVPrepareFunctionsLegacy(TM);
1065}
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 Value * fixZeroSign(IRBuilderBase &Builder, bool IsMax, Value *Res, Value *X, Value *Y)
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 lowerFMinimumMaximumNum(IntrinsicInst *II, SmallVector< Instruction * > &EraseFromParent)
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:562
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:61
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
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 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
LLVM_ABI void expandMemSetAsLoop(MemSetInst *MemSet, const TargetTransformInfo &TTI)
Expand MemSet as a loop according to the target's preferences.
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