LLVM 22.0.0git
CodeMoverUtils.cpp
Go to the documentation of this file.
1//===- CodeMoverUtils.cpp - CodeMover Utilities ----------------------------==//
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 family of functions perform movements on basic blocks, and instructions
10// contained within a function.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/Statistic.h"
19#include "llvm/IR/Dominators.h"
20
21using namespace llvm;
22
23#define DEBUG_TYPE "codemover-utils"
24
25STATISTIC(HasDependences,
26 "Cannot move across instructions that has memory dependences");
27STATISTIC(MayThrowException, "Cannot move across instructions that may throw");
28STATISTIC(NotMovedPHINode, "Movement of PHINodes are not supported");
29STATISTIC(NotMovedTerminator, "Movement of Terminator are not supported");
30
31namespace {
32/// Represent a control condition. A control condition is a condition of a
33/// terminator to decide which successors to execute. The pointer field
34/// represents the address of the condition of the terminator. The integer field
35/// is a bool, it is true when the basic block is executed when V is true. For
36/// example, `br %cond, bb0, bb1` %cond is a control condition of bb0 with the
37/// integer field equals to true, while %cond is a control condition of bb1 with
38/// the integer field equals to false.
39using ControlCondition = PointerIntPair<Value *, 1, bool>;
40#ifndef NDEBUG
41raw_ostream &operator<<(raw_ostream &OS, const ControlCondition &C) {
42 OS << "[" << *C.getPointer() << ", " << (C.getInt() ? "true" : "false")
43 << "]";
44 return OS;
45}
46#endif
47
48/// Represent a set of control conditions required to execute ToBB from FromBB.
49class ControlConditions {
50 using ConditionVectorTy = SmallVector<ControlCondition, 6>;
51
52 /// A SmallVector of control conditions.
53 ConditionVectorTy Conditions;
54
55public:
56 /// Return a ControlConditions which stores all conditions required to execute
57 /// \p BB from \p Dominator. If \p MaxLookup is non-zero, it limits the
58 /// number of conditions to collect. Return std::nullopt if not all conditions
59 /// are collected successfully, or we hit the limit.
60 static const std::optional<ControlConditions>
61 collectControlConditions(const BasicBlock &BB, const BasicBlock &Dominator,
62 const DominatorTree &DT,
63 const PostDominatorTree &PDT,
64 unsigned MaxLookup = 6);
65
66 /// Return true if there exists no control conditions required to execute ToBB
67 /// from FromBB.
68 bool isUnconditional() const { return Conditions.empty(); }
69
70 /// Return a constant reference of Conditions.
71 const ConditionVectorTy &getControlConditions() const { return Conditions; }
72
73 /// Add \p V as one of the ControlCondition in Condition with IsTrueCondition
74 /// equals to \p True. Return true if inserted successfully.
75 bool addControlCondition(ControlCondition C);
76
77 /// Return true if for all control conditions in Conditions, there exists an
78 /// equivalent control condition in \p Other.Conditions.
79 bool isEquivalent(const ControlConditions &Other) const;
80
81 /// Return true if \p C1 and \p C2 are equivalent.
82 static bool isEquivalent(const ControlCondition &C1,
83 const ControlCondition &C2);
84
85private:
86 ControlConditions() = default;
87
88 static bool isEquivalent(const Value &V1, const Value &V2);
89 static bool isInverse(const Value &V1, const Value &V2);
90};
91} // namespace
92
93static bool domTreeLevelBefore(DominatorTree *DT, const Instruction *InstA,
94 const Instruction *InstB) {
95 // Use ordered basic block in case the 2 instructions are in the same
96 // block.
97 if (InstA->getParent() == InstB->getParent())
98 return InstA->comesBefore(InstB);
99
100 DomTreeNode *DA = DT->getNode(InstA->getParent());
101 DomTreeNode *DB = DT->getNode(InstB->getParent());
102 return DA->getLevel() < DB->getLevel();
103}
104
105const std::optional<ControlConditions>
106ControlConditions::collectControlConditions(const BasicBlock &BB,
107 const BasicBlock &Dominator,
108 const DominatorTree &DT,
109 const PostDominatorTree &PDT,
110 unsigned MaxLookup) {
111 assert(DT.dominates(&Dominator, &BB) && "Expecting Dominator to dominate BB");
112
113 ControlConditions Conditions;
114 unsigned NumConditions = 0;
115
116 // BB is executed unconditional from itself.
117 if (&Dominator == &BB)
118 return Conditions;
119
120 const BasicBlock *CurBlock = &BB;
121 // Walk up the dominator tree from the associated DT node for BB to the
122 // associated DT node for Dominator.
123 do {
124 assert(DT.getNode(CurBlock) && "Expecting a valid DT node for CurBlock");
125 BasicBlock *IDom = DT.getNode(CurBlock)->getIDom()->getBlock();
126 assert(DT.dominates(&Dominator, IDom) &&
127 "Expecting Dominator to dominate IDom");
128
129 // Limitation: can only handle branch instruction currently.
130 const BranchInst *BI = dyn_cast<BranchInst>(IDom->getTerminator());
131 if (!BI)
132 return std::nullopt;
133
134 bool Inserted = false;
135 if (PDT.dominates(CurBlock, IDom)) {
136 LLVM_DEBUG(dbgs() << CurBlock->getName()
137 << " is executed unconditionally from "
138 << IDom->getName() << "\n");
139 } else if (PDT.dominates(CurBlock, BI->getSuccessor(0))) {
140 LLVM_DEBUG(dbgs() << CurBlock->getName() << " is executed when \""
141 << *BI->getCondition() << "\" is true from "
142 << IDom->getName() << "\n");
143 Inserted = Conditions.addControlCondition(
144 ControlCondition(BI->getCondition(), true));
145 } else if (PDT.dominates(CurBlock, BI->getSuccessor(1))) {
146 LLVM_DEBUG(dbgs() << CurBlock->getName() << " is executed when \""
147 << *BI->getCondition() << "\" is false from "
148 << IDom->getName() << "\n");
149 Inserted = Conditions.addControlCondition(
150 ControlCondition(BI->getCondition(), false));
151 } else
152 return std::nullopt;
153
154 if (Inserted)
155 ++NumConditions;
156
157 if (MaxLookup != 0 && NumConditions > MaxLookup)
158 return std::nullopt;
159
160 CurBlock = IDom;
161 } while (CurBlock != &Dominator);
162
163 return Conditions;
164}
165
166bool ControlConditions::addControlCondition(ControlCondition C) {
167 bool Inserted = false;
168 if (none_of(Conditions, [&](ControlCondition &Exists) {
169 return ControlConditions::isEquivalent(C, Exists);
170 })) {
171 Conditions.push_back(C);
172 Inserted = true;
173 }
174
175 LLVM_DEBUG(dbgs() << (Inserted ? "Inserted " : "Not inserted ") << C << "\n");
176 return Inserted;
177}
178
179bool ControlConditions::isEquivalent(const ControlConditions &Other) const {
180 if (Conditions.empty() && Other.Conditions.empty())
181 return true;
182
183 if (Conditions.size() != Other.Conditions.size())
184 return false;
185
186 return all_of(Conditions, [&](const ControlCondition &C) {
187 return any_of(Other.Conditions, [&](const ControlCondition &OtherC) {
188 return ControlConditions::isEquivalent(C, OtherC);
189 });
190 });
191}
192
193bool ControlConditions::isEquivalent(const ControlCondition &C1,
194 const ControlCondition &C2) {
195 if (C1.getInt() == C2.getInt()) {
196 if (isEquivalent(*C1.getPointer(), *C2.getPointer()))
197 return true;
198 } else if (isInverse(*C1.getPointer(), *C2.getPointer()))
199 return true;
200
201 return false;
202}
203
204// FIXME: Use SCEV and reuse GVN/CSE logic to check for equivalence between
205// Values.
206// Currently, isEquivalent rely on other passes to ensure equivalent conditions
207// have the same value, e.g. GVN.
208bool ControlConditions::isEquivalent(const Value &V1, const Value &V2) {
209 return &V1 == &V2;
210}
211
212bool ControlConditions::isInverse(const Value &V1, const Value &V2) {
213 if (const CmpInst *Cmp1 = dyn_cast<CmpInst>(&V1))
214 if (const CmpInst *Cmp2 = dyn_cast<CmpInst>(&V2)) {
215 if (Cmp1->getPredicate() == Cmp2->getInversePredicate() &&
216 Cmp1->getOperand(0) == Cmp2->getOperand(0) &&
217 Cmp1->getOperand(1) == Cmp2->getOperand(1))
218 return true;
219
220 if (Cmp1->getPredicate() ==
221 CmpInst::getSwappedPredicate(Cmp2->getInversePredicate()) &&
222 Cmp1->getOperand(0) == Cmp2->getOperand(1) &&
223 Cmp1->getOperand(1) == Cmp2->getOperand(0))
224 return true;
225 }
226 return false;
227}
228
230 llvm::Statistic &Stat) {
231 ++Stat;
232 LLVM_DEBUG(dbgs() << "Unable to move instruction: " << I << ". "
233 << Stat.getDesc());
234 return false;
235}
236
237/// Collect all instructions in between \p StartInst and \p EndInst, and store
238/// them in \p InBetweenInsts.
239static void
241 SmallPtrSetImpl<Instruction *> &InBetweenInsts) {
242 assert(InBetweenInsts.empty() && "Expecting InBetweenInsts to be empty");
243
244 /// Get the next instructions of \p I, and push them to \p WorkList.
245 auto getNextInsts = [](Instruction &I,
247 if (Instruction *NextInst = I.getNextNode())
248 WorkList.insert(NextInst);
249 else {
250 assert(I.isTerminator() && "Expecting a terminator instruction");
251 for (BasicBlock *Succ : successors(&I))
252 WorkList.insert(&Succ->front());
253 }
254 };
255
257 getNextInsts(StartInst, WorkList);
258 while (!WorkList.empty()) {
259 Instruction *CurInst = *WorkList.begin();
260 WorkList.erase(CurInst);
261
262 if (CurInst == &EndInst)
263 continue;
264
265 if (!InBetweenInsts.insert(CurInst).second)
266 continue;
267
268 getNextInsts(*CurInst, WorkList);
269 }
270}
271
273 DominatorTree &DT, const PostDominatorTree *PDT,
274 DependenceInfo *DI, bool CheckForEntireBlock) {
275 // Skip tests when we don't have PDT or DI
276 if (!PDT || !DI)
277 return false;
278
279 // Cannot move itself before itself.
280 if (&I == &InsertPoint)
281 return false;
282
283 // Not moved.
284 if (I.getNextNode() == &InsertPoint)
285 return true;
286
287 if (isa<PHINode>(I) || isa<PHINode>(InsertPoint))
288 return reportInvalidCandidate(I, NotMovedPHINode);
289
290 if (I.isTerminator())
291 return reportInvalidCandidate(I, NotMovedTerminator);
292
293 if (isReachedBefore(&I, &InsertPoint, &DT, PDT))
294 for (const Use &U : I.uses())
295 if (auto *UserInst = dyn_cast<Instruction>(U.getUser())) {
296 // If InsertPoint is in a BB that comes after I, then we cannot move if
297 // I is used in the terminator of the current BB.
298 if (I.getParent() == InsertPoint.getParent() &&
299 UserInst == I.getParent()->getTerminator())
300 return false;
301 if (UserInst != &InsertPoint && !DT.dominates(&InsertPoint, U)) {
302 // If UserInst is an instruction that appears later in the same BB as
303 // I, then it is okay to move since I will still be available when
304 // UserInst is executed.
305 if (CheckForEntireBlock && I.getParent() == UserInst->getParent() &&
306 DT.dominates(&I, UserInst))
307 continue;
308 return false;
309 }
310 }
311 if (isReachedBefore(&InsertPoint, &I, &DT, PDT))
312 for (const Value *Op : I.operands())
313 if (auto *OpInst = dyn_cast<Instruction>(Op)) {
314 if (&InsertPoint == OpInst)
315 return false;
316 // If OpInst is an instruction that appears earlier in the same BB as
317 // I, then it is okay to move since OpInst will still be available.
318 if (CheckForEntireBlock && I.getParent() == OpInst->getParent() &&
319 DT.dominates(OpInst, &I))
320 continue;
321 if (!DT.dominates(OpInst, &InsertPoint))
322 return false;
323 }
324
325 DT.updateDFSNumbers();
326 const bool MoveForward = domTreeLevelBefore(&DT, &I, &InsertPoint);
327 Instruction &StartInst = (MoveForward ? I : InsertPoint);
328 Instruction &EndInst = (MoveForward ? InsertPoint : I);
330 collectInstructionsInBetween(StartInst, EndInst, InstsToCheck);
331 if (!MoveForward)
332 InstsToCheck.insert(&InsertPoint);
333
334 // Check if there exists instructions which may throw, may synchonize, or may
335 // never return, from I to InsertPoint.
337 if (llvm::any_of(InstsToCheck, [](Instruction *I) {
338 if (I->mayThrow())
339 return true;
340
341 const CallBase *CB = dyn_cast<CallBase>(I);
342 if (!CB)
343 return false;
344 if (!CB->hasFnAttr(Attribute::WillReturn))
345 return true;
346 if (!CB->hasFnAttr(Attribute::NoSync))
347 return true;
348
349 return false;
350 })) {
351 return reportInvalidCandidate(I, MayThrowException);
352 }
353
354 // Check if I has any output/flow/anti dependences with instructions from \p
355 // StartInst to \p EndInst.
356 if (llvm::any_of(InstsToCheck, [&DI, &I](Instruction *CurInst) {
357 auto DepResult = DI->depends(&I, CurInst);
358 if (DepResult && (DepResult->isOutput() || DepResult->isFlow() ||
359 DepResult->isAnti()))
360 return true;
361 return false;
362 }))
363 return reportInvalidCandidate(I, HasDependences);
364
365 return true;
366}
367
369 DominatorTree &DT, const PostDominatorTree *PDT,
370 DependenceInfo *DI) {
371 return llvm::all_of(BB, [&](Instruction &I) {
372 if (BB.getTerminator() == &I)
373 return true;
374
375 return isSafeToMoveBefore(I, InsertPoint, DT, PDT, DI,
376 /*CheckForEntireBlock=*/true);
377 });
378}
379
381 DominatorTree &DT,
382 const PostDominatorTree &PDT,
383 DependenceInfo &DI) {
384 for (Instruction &I :
387
388 if (isSafeToMoveBefore(I, *MovePos, DT, &PDT, &DI))
389 I.moveBeforePreserving(MovePos);
390 }
391}
392
394 DominatorTree &DT,
395 const PostDominatorTree &PDT,
396 DependenceInfo &DI) {
397 Instruction *MovePos = ToBB.getTerminator();
398 while (FromBB.size() > 1) {
399 Instruction &I = FromBB.front();
400 if (isSafeToMoveBefore(I, *MovePos, DT, &PDT, &DI))
401 I.moveBeforePreserving(MovePos->getIterator());
402 }
403}
404
406 const BasicBlock *OtherBlock,
407 const DominatorTree *DT,
408 const PostDominatorTree *PDT) {
409 const BasicBlock *CommonDominator =
410 DT->findNearestCommonDominator(ThisBlock, OtherBlock);
411 if (CommonDominator == nullptr)
412 return false;
413
414 /// Recursively check the predecessors of \p ThisBlock up to
415 /// their common dominator, and see if any of them post-dominates
416 /// \p OtherBlock.
419 WorkList.push_back(ThisBlock);
420 while (!WorkList.empty()) {
421 const BasicBlock *CurBlock = WorkList.pop_back_val();
422 Visited.insert(CurBlock);
423 if (PDT->dominates(CurBlock, OtherBlock))
424 return true;
425
426 for (const auto *Pred : predecessors(CurBlock)) {
427 if (Pred == CommonDominator || Visited.count(Pred))
428 continue;
429 WorkList.push_back(Pred);
430 }
431 }
432 return false;
433}
434
436 const DominatorTree *DT,
437 const PostDominatorTree *PDT) {
438 const BasicBlock *BB0 = I0->getParent();
439 const BasicBlock *BB1 = I1->getParent();
440 if (BB0 == BB1)
441 return DT->dominates(I0, I1);
442
443 return nonStrictlyPostDominate(BB1, BB0, DT, PDT);
444}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool reportInvalidCandidate(const Instruction &I, llvm::Statistic &Stat)
static bool domTreeLevelBefore(DominatorTree *DT, const Instruction *InstA, const Instruction *InstB)
static void collectInstructionsInBetween(Instruction &StartInst, const Instruction &EndInst, SmallPtrSetImpl< Instruction * > &InBetweenInsts)
Collect all instructions in between StartInst and EndInst, and store them in InBetweenInsts.
#define I(x, y, z)
Definition MD5.cpp:57
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
const Instruction & front() const
Definition BasicBlock.h:482
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
size_t size() const
Definition BasicBlock.h:480
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
BasicBlock * getSuccessor(unsigned i) const
Value * getCondition() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:827
DependenceInfo - This class is the main dependence-analysis driver.
LLVM_ABI std::unique_ptr< Dependence > depends(Instruction *Src, Instruction *Dst, bool UnderRuntimeAssumptions=false)
depends - Tests for a dependence between the Src and Dst instructions.
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
void updateDFSNumbers() const
updateDFSNumbers - Assign In and Out numbers to the nodes while walking dominator tree in dfs order.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
PointerIntPair - This class implements a pair of a pointer and small integer.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
LLVM_ABI bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
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
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1737
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
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:632
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI void moveInstructionsToTheEnd(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI)
Move instructions, in an order-preserving manner, from FromBB to the end of ToBB when proven safe.
LLVM_ABI bool isReachedBefore(const Instruction *I0, const Instruction *I1, const DominatorTree *DT, const PostDominatorTree *PDT)
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:94
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:1744
NoopStatistic Statistic
Definition Statistic.h:162
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1751
LLVM_ABI bool nonStrictlyPostDominate(const BasicBlock *ThisBlock, const BasicBlock *OtherBlock, const DominatorTree *DT, const PostDominatorTree *PDT)
In case that two BBs ThisBlock and OtherBlock are control flow equivalent but they do not strictly do...
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_ABI void moveInstructionsToTheBeginning(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI)
Move instructions, in an order-preserving manner, from FromBB to the beginning of ToBB when proven sa...
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI bool isSafeToMoveBefore(Instruction &I, Instruction &InsertPoint, DominatorTree &DT, const PostDominatorTree *PDT=nullptr, DependenceInfo *DI=nullptr, bool CheckForEntireBlock=false)
Return true if I can be safely moved before InsertPoint.