LLVM 24.0.0git
SPIRVRegularizer.cpp
Go to the documentation of this file.
1//===-- SPIRVRegularizer.cpp - regularize IR for SPIR-V ---------*- 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 implements regularization of LLVM IR for SPIR-V. The prototype of
10// the pass was taken from SPIRV-LLVM translator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SPIRV.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/IR/Constants.h"
17#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/PassManager.h"
21
22#include <list>
23
24#define DEBUG_TYPE "spirv-regularizer"
25
26using namespace llvm;
27
28static bool runImpl(Function &F);
29
30namespace {
31struct SPIRVRegularizerLegacy : public FunctionPass {
32public:
33 static char ID;
34 SPIRVRegularizerLegacy() : FunctionPass(ID) {}
35 bool runOnFunction(Function &F) override { return runImpl(F); }
36 StringRef getPassName() const override { return "SPIR-V Regularizer"; }
37
38 void getAnalysisUsage(AnalysisUsage &AU) const override {
39 FunctionPass::getAnalysisUsage(AU);
40 }
41};
42} // namespace
43
44char SPIRVRegularizerLegacy::ID = 0;
45
46INITIALIZE_PASS(SPIRVRegularizerLegacy, DEBUG_TYPE, "SPIR-V Regularizer", false,
47 false)
48
49// Since SPIR-V cannot represent constant expression, constant expressions
50// in LLVM IR need to be lowered to instructions. For each function,
51// the constant expressions used by instructions of the function are replaced
52// by instructions placed in the entry block since it dominates all other BBs.
53// Each constant expression only needs to be lowered once in each function
54// and all uses of it by instructions in that function are replaced by
55// one instruction.
56// TODO: remove redundant instructions for common subexpression.
57static void runLowerConstExpr(Function &F) {
58 LLVMContext &Ctx = F.getContext();
59 std::list<Instruction *> WorkList;
60 for (auto &II : instructions(F))
61 WorkList.push_back(&II);
62
63 auto FBegin = F.begin();
64 while (!WorkList.empty()) {
65 Instruction *II = WorkList.front();
66
67 auto LowerOp = [&II, &FBegin, &F](Value *V) -> Value * {
68 if (isa<Function>(V))
69 return V;
70 auto *CE = cast<ConstantExpr>(V);
71 LLVM_DEBUG(dbgs() << "[lowerConstantExpressions] " << *CE);
72 auto ReplInst = CE->getAsInstruction();
73 auto InsPoint = II->getParent() == &*FBegin ? II : &FBegin->back();
74 ReplInst->insertBefore(InsPoint->getIterator());
75 LLVM_DEBUG(dbgs() << " -> " << *ReplInst << '\n');
76 std::vector<Instruction *> Users;
77 // Do not replace use during iteration of use. Do it in another loop.
78 for (auto U : CE->users()) {
79 LLVM_DEBUG(dbgs() << "[lowerConstantExpressions] Use: " << *U << '\n');
80 auto InstUser = dyn_cast<Instruction>(U);
81 // Only replace users in scope of current function.
82 if (InstUser && InstUser->getParent()->getParent() == &F)
83 Users.push_back(InstUser);
84 }
85 for (auto &User : Users) {
86 if (ReplInst->getParent() == User->getParent() &&
87 User->comesBefore(ReplInst))
88 ReplInst->moveBefore(User->getIterator());
89 User->replaceUsesOfWith(CE, ReplInst);
90 }
91 return ReplInst;
92 };
93
94 WorkList.pop_front();
95 auto LowerConstantVec = [&II, &LowerOp, &WorkList,
96 &Ctx](ConstantVector *Vec,
97 unsigned NumOfOp) -> Value * {
98 if (llvm::all_of(Vec->operands(), [](Value *V) {
99 return isa<ConstantExpr>(V) || isa<Function>(V);
100 })) {
101 // Expand a vector of constexprs and construct it back with
102 // series of insertelement instructions.
103 std::list<Value *> OpList;
104 llvm::transform(Vec->operands(), std::back_inserter(OpList),
105 [LowerOp](Value *V) { return LowerOp(V); });
106 Value *Repl = nullptr;
107 unsigned Idx = 0;
108 auto *PhiII = dyn_cast<PHINode>(II);
109 Instruction *InsPoint =
110 PhiII ? &PhiII->getIncomingBlock(NumOfOp)->back() : II;
111 std::list<Instruction *> ReplList;
112 for (auto V : OpList) {
113 if (auto *Inst = dyn_cast<Instruction>(V))
114 ReplList.push_back(Inst);
116 (Repl ? Repl : PoisonValue::get(Vec->getType())), V,
117 ConstantInt::get(Type::getInt32Ty(Ctx), Idx++), "",
118 InsPoint->getIterator());
119 }
120 WorkList.splice(WorkList.begin(), ReplList);
121 return Repl;
122 }
123 return nullptr;
124 };
125 for (unsigned OI = 0, OE = II->getNumOperands(); OI != OE; ++OI) {
126 auto *Op = II->getOperand(OI);
127 if (auto *Vec = dyn_cast<ConstantVector>(Op)) {
128 Value *ReplInst = LowerConstantVec(Vec, OI);
129 if (ReplInst)
130 II->replaceUsesOfWith(Op, ReplInst);
131 } else if (auto CE = dyn_cast<ConstantExpr>(Op)) {
132 WorkList.push_front(cast<Instruction>(LowerOp(CE)));
133 } else if (auto MDAsVal = dyn_cast<MetadataAsValue>(Op)) {
134 auto ConstMD = dyn_cast<ConstantAsMetadata>(MDAsVal->getMetadata());
135 if (!ConstMD)
136 continue;
137 Constant *C = ConstMD->getValue();
138 Value *ReplInst = nullptr;
139 if (auto *Vec = dyn_cast<ConstantVector>(C))
140 ReplInst = LowerConstantVec(Vec, OI);
141 if (auto *CE = dyn_cast<ConstantExpr>(C))
142 ReplInst = LowerOp(CE);
143 if (!ReplInst)
144 continue;
145 Metadata *RepMD = ValueAsMetadata::get(ReplInst);
146 Value *RepMDVal = MetadataAsValue::get(Ctx, RepMD);
147 II->setOperand(OI, RepMDVal);
148 WorkList.push_front(cast<Instruction>(ReplInst));
149 }
150 }
151 }
152}
153
154// Lower i1 comparisons with certain predicates to logical operations.
155// The backend treats i1 as boolean values, and SPIR-V only allows logical
156// operations for boolean values. This function lowers i1 comparisons with
157// certain predicates to logical operations to generate valid SPIR-V.
159 for (auto &I : make_early_inc_range(instructions(F))) {
160 auto *Cmp = dyn_cast<ICmpInst>(&I);
161 if (!Cmp)
162 continue;
163
164 bool IsI1 = Cmp->getOperand(0)->getType()->getScalarType()->isIntegerTy(1);
165 if (!IsI1)
166 continue;
167
168 auto Pred = Cmp->getPredicate();
169 bool IsTargetPred =
170 Pred >= ICmpInst::ICMP_UGT && Pred <= ICmpInst::ICMP_SLE;
171 if (!IsTargetPred)
172 continue;
173
174 Value *P = Cmp->getOperand(0);
175 Value *Q = Cmp->getOperand(1);
176
177 IRBuilder<> Builder(Cmp);
178 Value *Result = nullptr;
179 switch (Pred) {
182 // Result = p & !q
183 Result = Builder.CreateAnd(P, Builder.CreateNot(Q));
184 break;
187 // Result = q & !p
188 Result = Builder.CreateAnd(Q, Builder.CreateNot(P));
189 break;
192 // Result = q | !p
193 Result = Builder.CreateOr(Q, Builder.CreateNot(P));
194 break;
197 // Result = p | !q
198 Result = Builder.CreateOr(P, Builder.CreateNot(Q));
199 break;
200 default:
201 llvm_unreachable("Unexpected predicate");
202 }
203
204 Result->takeName(Cmp);
205 Cmp->replaceAllUsesWith(Result);
206 Cmp->eraseFromParent();
207 }
208}
209
210static bool runImpl(Function &F) {
212 runLowerConstExpr(F);
213 return true;
214}
215
220
222 return new SPIRVRegularizerLegacy();
223}
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static bool runImpl(MachineFunction &MF)
Definition CFIFixup.cpp:304
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static void runLowerI1Comparisons(Function &F)
static bool runImpl(Function &F)
This file contains some templates that are useful if you are working with the STL at all.
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
Constant Vector Declarations.
Definition Constants.h:674
FixedVectorType * getType() const
Specialize the getType() method to always return a FixedVectorType, which reduces the amount of casti...
Definition Constants.h:697
This is an important base class in LLVM.
Definition Constant.h:43
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2903
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:111
Root of the metadata hierarchy.
Definition Metadata.h:64
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(Function &F, FunctionAnalysisManager &AM)
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
op_range operands()
Definition User.h:267
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:510
LLVM Value Representation.
Definition Value.h:75
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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:633
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2026
FunctionPass * createSPIRVRegularizerPass()
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.