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"
18#include "llvm/IR/InstIterator.h"
19#include "llvm/IR/Instructions.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(x: &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>(Val: V))
69 return V;
70 auto *CE = cast<ConstantExpr>(Val: V);
71 LLVM_DEBUG(dbgs() << "[lowerConstantExpressions] " << *CE);
72 auto ReplInst = CE->getAsInstruction();
73 auto InsPoint = II->getParent() == &*FBegin ? II : &FBegin->back();
74 ReplInst->insertBefore(InsertPos: 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>(Val: U);
81 // Only replace users in scope of current function.
82 if (InstUser && InstUser->getParent()->getParent() == &F)
83 Users.push_back(x: InstUser);
84 }
85 for (auto &User : Users) {
86 if (ReplInst->getParent() == User->getParent() &&
87 User->comesBefore(Other: ReplInst))
88 ReplInst->moveBefore(InsertPos: User->getIterator());
89 User->replaceUsesOfWith(From: CE, To: 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(Range: Vec->operands(), P: [](Value *V) {
99 return isa<ConstantExpr>(Val: V) || isa<Function>(Val: 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(Range: Vec->operands(), d_first: std::back_inserter(x&: OpList),
105 F: [LowerOp](Value *V) { return LowerOp(V); });
106 Value *Repl = nullptr;
107 unsigned Idx = 0;
108 auto *PhiII = dyn_cast<PHINode>(Val: II);
109 Instruction *InsPoint =
110 PhiII ? &PhiII->getIncomingBlock(i: NumOfOp)->back() : II;
111 std::list<Instruction *> ReplList;
112 for (auto V : OpList) {
113 if (auto *Inst = dyn_cast<Instruction>(Val: V))
114 ReplList.push_back(x: Inst);
115 Repl = InsertElementInst::Create(
116 Vec: (Repl ? Repl : PoisonValue::get(T: Vec->getType())), NewElt: V,
117 Idx: ConstantInt::get(Ty: Type::getInt32Ty(C&: Ctx), V: Idx++), NameStr: "",
118 InsertBefore: InsPoint->getIterator());
119 }
120 WorkList.splice(position: WorkList.begin(), x&: 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(i: OI);
127 if (auto *Vec = dyn_cast<ConstantVector>(Val: Op)) {
128 Value *ReplInst = LowerConstantVec(Vec, OI);
129 if (ReplInst)
130 II->replaceUsesOfWith(From: Op, To: ReplInst);
131 } else if (auto CE = dyn_cast<ConstantExpr>(Val: Op)) {
132 WorkList.push_front(x: cast<Instruction>(Val: LowerOp(CE)));
133 } else if (auto MDAsVal = dyn_cast<MetadataAsValue>(Val: Op)) {
134 auto ConstMD = dyn_cast<ConstantAsMetadata>(Val: MDAsVal->getMetadata());
135 if (!ConstMD)
136 continue;
137 Constant *C = ConstMD->getValue();
138 Value *ReplInst = nullptr;
139 if (auto *Vec = dyn_cast<ConstantVector>(Val: C))
140 ReplInst = LowerConstantVec(Vec, OI);
141 if (auto *CE = dyn_cast<ConstantExpr>(Val: C))
142 ReplInst = LowerOp(CE);
143 if (!ReplInst)
144 continue;
145 Metadata *RepMD = ValueAsMetadata::get(V: ReplInst);
146 Value *RepMDVal = MetadataAsValue::get(Context&: Ctx, MD: RepMD);
147 II->setOperand(i: OI, Val: RepMDVal);
148 WorkList.push_front(x: cast<Instruction>(Val: 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.
158static void runLowerI1Comparisons(Function &F) {
159 for (auto &I : make_early_inc_range(Range: instructions(F))) {
160 auto *Cmp = dyn_cast<ICmpInst>(Val: &I);
161 if (!Cmp)
162 continue;
163
164 bool IsI1 = Cmp->getOperand(i_nocapture: 0)->getType()->getScalarType()->isIntegerTy(BitWidth: 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(i_nocapture: 0);
175 Value *Q = Cmp->getOperand(i_nocapture: 1);
176
177 IRBuilder<> Builder(Cmp);
178 Value *Result = nullptr;
179 switch (Pred) {
180 case ICmpInst::ICMP_UGT:
181 case ICmpInst::ICMP_SLT:
182 // Result = p & !q
183 Result = Builder.CreateAnd(LHS: P, RHS: Builder.CreateNot(V: Q));
184 break;
185 case ICmpInst::ICMP_ULT:
186 case ICmpInst::ICMP_SGT:
187 // Result = q & !p
188 Result = Builder.CreateAnd(LHS: Q, RHS: Builder.CreateNot(V: P));
189 break;
190 case ICmpInst::ICMP_ULE:
191 case ICmpInst::ICMP_SGE:
192 // Result = q | !p
193 Result = Builder.CreateOr(LHS: Q, RHS: Builder.CreateNot(V: P));
194 break;
195 case ICmpInst::ICMP_UGE:
196 case ICmpInst::ICMP_SLE:
197 // Result = p | !q
198 Result = Builder.CreateOr(LHS: P, RHS: Builder.CreateNot(V: Q));
199 break;
200 default:
201 llvm_unreachable("Unexpected predicate");
202 }
203
204 Result->takeName(V: Cmp);
205 Cmp->replaceAllUsesWith(V: Result);
206 Cmp->eraseFromParent();
207 }
208}
209
210static bool runImpl(Function &F) {
211 runLowerI1Comparisons(F);
212 runLowerConstExpr(F);
213 return true;
214}
215
216PreservedAnalyses SPIRVRegularizerPass::run(Function &F,
217 FunctionAnalysisManager &AM) {
218 return runImpl(F) ? PreservedAnalyses::none() : PreservedAnalyses::all();
219}
220
221FunctionPass *llvm::createSPIRVRegularizerPass() {
222 return new SPIRVRegularizerLegacy();
223}
224