LLVM 24.0.0git
BPFAdjustOpt.cpp
Go to the documentation of this file.
1//===---------------- BPFAdjustOpt.cpp - Adjust Optimization --------------===//
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// Adjust optimization to make the code more kernel verifier friendly.
10//
11//===----------------------------------------------------------------------===//
12
13#include "BPF.h"
14#include "BPFCORE.h"
15#include "llvm/IR/Instruction.h"
17#include "llvm/IR/IntrinsicsBPF.h"
18#include "llvm/IR/Module.h"
20#include "llvm/IR/Type.h"
21#include "llvm/IR/User.h"
22#include "llvm/IR/Value.h"
23#include "llvm/Pass.h"
25
26#define DEBUG_TYPE "bpf-adjust-opt"
27
28using namespace llvm;
29using namespace llvm::PatternMatch;
30
31static cl::opt<bool>
32 DisableBPFserializeICMP("bpf-disable-serialize-icmp", cl::Hidden,
33 cl::desc("BPF: Disable Serializing ICMP insns."),
34 cl::init(false));
35
37 "bpf-disable-avoid-speculation", cl::Hidden,
38 cl::desc("BPF: Disable Avoiding Speculative Code Motion."),
39 cl::init(false));
40
41namespace {
42class BPFAdjustOptImpl {
43 struct PassThroughInfo {
45 Instruction *UsedInst;
46 uint32_t OpIdx;
47 PassThroughInfo(Instruction *I, Instruction *U, uint32_t Idx)
48 : Input(I), UsedInst(U), OpIdx(Idx) {}
49 };
50
51public:
52 BPFAdjustOptImpl(Module *M) : M(M) {}
53
54 bool run();
55
56private:
57 Module *M;
59
60 bool adjustICmpToBuiltin();
61 void adjustBasicBlock(BasicBlock &BB);
62 bool serializeICMPCrossBB(BasicBlock &BB);
63 void adjustInst(Instruction &I);
64 bool serializeICMPInBB(Instruction &I);
65 bool avoidSpeculation(Instruction &I);
66 bool insertPassThrough();
67};
68
69} // End anonymous namespace
70
71bool BPFAdjustOptImpl::run() {
72 bool Changed = adjustICmpToBuiltin();
73
74 // The verifier checks a global function on its own against its BTF type,
75 // and freplace can replace it. The callers know the prototype and no more.
76 for (Function &F : *M) {
77 if (F.isDeclaration() || F.hasLocalLinkage())
78 continue;
79 F.addFnAttr(Attribute::NoIPA);
80 Changed = true;
81 }
82
83 for (Function &F : *M)
84 for (auto &BB : F) {
85 adjustBasicBlock(BB);
86 for (auto &I : BB)
87 adjustInst(I);
88 }
89 return insertPassThrough() || Changed;
90}
91
92// Commit acabad9ff6bf ("[InstCombine] try to canonicalize icmp with
93// trunc op into mask and cmp") added a transformation to
94// convert "(conv)a < power_2_const" to "a & <const>" in certain
95// cases and bpf kernel verifier has to handle the resulted code
96// conservatively and this may reject otherwise legitimate program.
97// Here, we change related icmp code to a builtin which will
98// be restored to original icmp code later to prevent that
99// InstCombine transformatin.
100bool BPFAdjustOptImpl::adjustICmpToBuiltin() {
101 bool Changed = false;
102 ICmpInst *ToBeDeleted = nullptr;
103 for (Function &F : *M)
104 for (auto &BB : F)
105 for (auto &I : BB) {
106 if (ToBeDeleted) {
107 ToBeDeleted->eraseFromParent();
108 ToBeDeleted = nullptr;
109 }
110
111 auto *Icmp = dyn_cast<ICmpInst>(&I);
112 if (!Icmp)
113 continue;
114
115 Value *Op0 = Icmp->getOperand(0);
116 if (!isa<TruncInst>(Op0))
117 continue;
118
119 auto ConstOp1 = dyn_cast<ConstantInt>(Icmp->getOperand(1));
120 if (!ConstOp1)
121 continue;
122
123 auto ConstOp1Val = ConstOp1->getValue().getZExtValue();
124 auto Op = Icmp->getPredicate();
125 if (Op == ICmpInst::ICMP_ULT || Op == ICmpInst::ICMP_UGE) {
126 if ((ConstOp1Val - 1) & ConstOp1Val)
127 continue;
128 } else if (Op == ICmpInst::ICMP_ULE || Op == ICmpInst::ICMP_UGT) {
129 if (ConstOp1Val & (ConstOp1Val + 1))
130 continue;
131 } else {
132 continue;
133 }
134
135 Constant *Opcode =
136 ConstantInt::get(Type::getInt32Ty(BB.getContext()), Op);
138 M, Intrinsic::bpf_compare, {Op0->getType(), ConstOp1->getType()});
139 auto *NewInst = CallInst::Create(Fn, {Opcode, Op0, ConstOp1});
140 NewInst->insertBefore(I.getIterator());
141 Icmp->replaceAllUsesWith(NewInst);
142 Changed = true;
143 ToBeDeleted = Icmp;
144 }
145
146 return Changed;
147}
148
149bool BPFAdjustOptImpl::insertPassThrough() {
150 for (auto &Info : PassThroughs) {
152 M, Info.UsedInst->getParent(), Info.Input, Info.UsedInst);
153 Info.UsedInst->setOperand(Info.OpIdx, CI);
154 }
155
156 return !PassThroughs.empty();
157}
158
159// To avoid combining conditionals in the same basic block by
160// instrcombine optimization.
161bool BPFAdjustOptImpl::serializeICMPInBB(Instruction &I) {
162 // For:
163 // comp1 = icmp <opcode> ...;
164 // comp2 = icmp <opcode> ...;
165 // ... or comp1 comp2 ...
166 // changed to:
167 // comp1 = icmp <opcode> ...;
168 // comp2 = icmp <opcode> ...;
169 // new_comp1 = __builtin_bpf_passthrough(seq_num, comp1)
170 // ... or new_comp1 comp2 ...
171 Value *Op0, *Op1;
172 // Use LogicalOr (accept `or i1` as well as `select i1 Op0, true, Op1`)
173 if (!match(&I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
174 return false;
175 auto *Icmp1 = dyn_cast<ICmpInst>(Op0);
176 if (!Icmp1)
177 return false;
178 auto *Icmp2 = dyn_cast<ICmpInst>(Op1);
179 if (!Icmp2)
180 return false;
181
182 Value *Icmp1Op0 = Icmp1->getOperand(0);
183 Value *Icmp2Op0 = Icmp2->getOperand(0);
184 if (Icmp1Op0 != Icmp2Op0)
185 return false;
186
187 // Now we got two icmp instructions which feed into
188 // an "or" instruction.
189 PassThroughInfo Info(Icmp1, &I, 0);
190 PassThroughs.push_back(Info);
191 return true;
192}
193
194// To avoid combining conditionals in the same basic block by
195// instrcombine optimization.
196bool BPFAdjustOptImpl::serializeICMPCrossBB(BasicBlock &BB) {
197 // For:
198 // B1:
199 // comp1 = icmp <opcode> ...;
200 // if (comp1) goto B2 else B3;
201 // B2:
202 // comp2 = icmp <opcode> ...;
203 // if (comp2) goto B4 else B5;
204 // B4:
205 // ...
206 // changed to:
207 // B1:
208 // comp1 = icmp <opcode> ...;
209 // comp1 = __builtin_bpf_passthrough(seq_num, comp1);
210 // if (comp1) goto B2 else B3;
211 // B2:
212 // comp2 = icmp <opcode> ...;
213 // if (comp2) goto B4 else B5;
214 // B4:
215 // ...
216
217 // Check basic predecessors, if two of them (say B1, B2) are using
218 // icmp instructions to generate conditions and one is the predesessor
219 // of another (e.g., B1 is the predecessor of B2). Add a passthrough
220 // barrier after icmp inst of block B1.
222 if (!B2)
223 return false;
224
225 BasicBlock *B1 = B2->getSinglePredecessor();
226 if (!B1)
227 return false;
228
229 Instruction *TI = B2->getTerminator();
230 auto *BI = dyn_cast<CondBrInst>(TI);
231 if (!BI)
232 return false;
233 auto *Cond = dyn_cast<ICmpInst>(BI->getCondition());
234 if (!Cond || &*B2->getFirstNonPHIIt() != Cond)
235 return false;
236 Value *B2Op0 = Cond->getOperand(0);
237 auto Cond2Op = Cond->getPredicate();
238
239 TI = B1->getTerminator();
240 BI = dyn_cast<CondBrInst>(TI);
241 if (!BI)
242 return false;
243 Cond = dyn_cast<ICmpInst>(BI->getCondition());
244 if (!Cond)
245 return false;
246 Value *B1Op0 = Cond->getOperand(0);
247 auto Cond1Op = Cond->getPredicate();
248
249 if (B1Op0 != B2Op0)
250 return false;
251
252 if (Cond1Op == ICmpInst::ICMP_SGT || Cond1Op == ICmpInst::ICMP_SGE) {
253 if (Cond2Op != ICmpInst::ICMP_SLT && Cond2Op != ICmpInst::ICMP_SLE)
254 return false;
255 } else if (Cond1Op == ICmpInst::ICMP_SLT || Cond1Op == ICmpInst::ICMP_SLE) {
256 if (Cond2Op != ICmpInst::ICMP_SGT && Cond2Op != ICmpInst::ICMP_SGE)
257 return false;
258 } else if (Cond1Op == ICmpInst::ICMP_ULT || Cond1Op == ICmpInst::ICMP_ULE) {
259 if (Cond2Op != ICmpInst::ICMP_UGT && Cond2Op != ICmpInst::ICMP_UGE)
260 return false;
261 } else if (Cond1Op == ICmpInst::ICMP_UGT || Cond1Op == ICmpInst::ICMP_UGE) {
262 if (Cond2Op != ICmpInst::ICMP_ULT && Cond2Op != ICmpInst::ICMP_ULE)
263 return false;
264 } else {
265 return false;
266 }
267
268 PassThroughInfo Info(Cond, BI, 0);
269 PassThroughs.push_back(Info);
270
271 return true;
272}
273
274// To avoid speculative hoisting certain computations out of
275// a basic block.
276bool BPFAdjustOptImpl::avoidSpeculation(Instruction &I) {
277 if (auto *LdInst = dyn_cast<LoadInst>(&I)) {
278 if (auto *GV = dyn_cast<GlobalVariable>(LdInst->getOperand(0))) {
279 if (GV->hasAttribute(BPFCoreSharedInfo::AmaAttr) ||
280 GV->hasAttribute(BPFCoreSharedInfo::TypeIdAttr))
281 return false;
282 }
283 }
284
285 if (!isa<LoadInst>(&I) && !isa<CallInst>(&I))
286 return false;
287
288 // For:
289 // B1:
290 // var = ...
291 // ...
292 // /* icmp may not be in the same block as var = ... */
293 // comp1 = icmp <opcode> var, <const>;
294 // if (comp1) goto B2 else B3;
295 // B2:
296 // ... var ...
297 // change to:
298 // B1:
299 // var = ...
300 // ...
301 // /* icmp may not be in the same block as var = ... */
302 // comp1 = icmp <opcode> var, <const>;
303 // if (comp1) goto B2 else B3;
304 // B2:
305 // var = __builtin_bpf_passthrough(seq_num, var);
306 // ... var ...
307 bool isCandidate = false;
309 for (User *U : I.users()) {
311 if (!Inst)
312 continue;
313
314 // May cover a little bit more than the
315 // above pattern.
316 if (auto *Icmp1 = dyn_cast<ICmpInst>(Inst)) {
317 Value *Icmp1Op1 = Icmp1->getOperand(1);
318 if (!isa<Constant>(Icmp1Op1))
319 return false;
320 isCandidate = true;
321 continue;
322 }
323
324 // Ignore the use in the same basic block as the definition.
325 if (Inst->getParent() == I.getParent())
326 continue;
327
328 // use in a different basic block, If there is a call or
329 // load/store insn before this instruction in this basic
330 // block. Most likely it cannot be hoisted out. Skip it.
331 for (auto &I2 : *Inst->getParent()) {
332 if (isa<CallInst>(&I2))
333 return false;
334 if (isa<LoadInst>(&I2) || isa<StoreInst>(&I2))
335 return false;
336 if (&I2 == Inst)
337 break;
338 }
339
340 // It should be used in a GEP or a simple arithmetic like
341 // ZEXT/SEXT which is used for GEP.
342 if (Inst->getOpcode() == Instruction::ZExt ||
343 Inst->getOpcode() == Instruction::SExt) {
344 PassThroughInfo Info(&I, Inst, 0);
345 Candidates.push_back(Info);
346 } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
347 // traverse GEP inst to find Use operand index
348 unsigned i, e;
349 for (i = 1, e = GI->getNumOperands(); i != e; ++i) {
350 Value *V = GI->getOperand(i);
351 if (V == &I)
352 break;
353 }
354 if (i == e)
355 continue;
356
357 PassThroughInfo Info(&I, GI, i);
358 Candidates.push_back(Info);
359 }
360 }
361
362 if (!isCandidate || Candidates.empty())
363 return false;
364
365 llvm::append_range(PassThroughs, Candidates);
366 return true;
367}
368
369void BPFAdjustOptImpl::adjustBasicBlock(BasicBlock &BB) {
370 if (!DisableBPFserializeICMP && serializeICMPCrossBB(BB))
371 return;
372}
373
374void BPFAdjustOptImpl::adjustInst(Instruction &I) {
375 if (!DisableBPFserializeICMP && serializeICMPInBB(I))
376 return;
377 if (!DisableBPFavoidSpeculation && avoidSpeculation(I))
378 return;
379}
380
static cl::opt< bool > DisableBPFserializeICMP("bpf-disable-serialize-icmp", cl::Hidden, cl::desc("BPF: Disable Serializing ICMP insns."), cl::init(false))
static cl::opt< bool > DisableBPFavoidSpeculation("bpf-disable-avoid-speculation", cl::Hidden, cl::desc("BPF: Disable Avoiding Speculative Code Motion."), cl::init(false))
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
SmallVector< MachineOperand, 4 > Cond
The Input class is used to parse a yaml document into in-memory structs and vectors.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static constexpr StringRef TypeIdAttr
The attribute attached to globals representing a type id.
Definition BPFCORE.h:64
static Instruction * insertPassThrough(Module *M, BasicBlock *BB, Instruction *Input, Instruction *Before)
Insert a bpf passthrough builtin function.
static constexpr StringRef AmaAttr
The attribute attached to globals representing a field access.
Definition BPFCORE.h:62
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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
void push_back(const T &Elt)
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const ParentTy * getParent() const
Definition ilist_node.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
constexpr double e
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
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
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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
DWARFExpression::Operation Op
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39