xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Utils/CodeMoverUtils.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
1480093f4SDimitry Andric //===- CodeMoverUtils.cpp - CodeMover Utilities ----------------------------==//
2480093f4SDimitry Andric //
3480093f4SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4480093f4SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5480093f4SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6480093f4SDimitry Andric //
7480093f4SDimitry Andric //===----------------------------------------------------------------------===//
8480093f4SDimitry Andric //
9480093f4SDimitry Andric // This family of functions perform movements on basic blocks, and instructions
10480093f4SDimitry Andric // contained within a function.
11480093f4SDimitry Andric //
12480093f4SDimitry Andric //===----------------------------------------------------------------------===//
13480093f4SDimitry Andric 
14480093f4SDimitry Andric #include "llvm/Transforms/Utils/CodeMoverUtils.h"
15*5ffd83dbSDimitry Andric #include "llvm/ADT/Optional.h"
16480093f4SDimitry Andric #include "llvm/ADT/Statistic.h"
17480093f4SDimitry Andric #include "llvm/Analysis/DependenceAnalysis.h"
18480093f4SDimitry Andric #include "llvm/Analysis/PostDominators.h"
19480093f4SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
20480093f4SDimitry Andric #include "llvm/IR/Dominators.h"
21480093f4SDimitry Andric 
22480093f4SDimitry Andric using namespace llvm;
23480093f4SDimitry Andric 
24480093f4SDimitry Andric #define DEBUG_TYPE "codemover-utils"
25480093f4SDimitry Andric 
26480093f4SDimitry Andric STATISTIC(HasDependences,
27480093f4SDimitry Andric           "Cannot move across instructions that has memory dependences");
28480093f4SDimitry Andric STATISTIC(MayThrowException, "Cannot move across instructions that may throw");
29480093f4SDimitry Andric STATISTIC(NotControlFlowEquivalent,
30480093f4SDimitry Andric           "Instructions are not control flow equivalent");
31480093f4SDimitry Andric STATISTIC(NotMovedPHINode, "Movement of PHINodes are not supported");
32480093f4SDimitry Andric STATISTIC(NotMovedTerminator, "Movement of Terminator are not supported");
33480093f4SDimitry Andric 
34*5ffd83dbSDimitry Andric namespace {
35*5ffd83dbSDimitry Andric /// Represent a control condition. A control condition is a condition of a
36*5ffd83dbSDimitry Andric /// terminator to decide which successors to execute. The pointer field
37*5ffd83dbSDimitry Andric /// represents the address of the condition of the terminator. The integer field
38*5ffd83dbSDimitry Andric /// is a bool, it is true when the basic block is executed when V is true. For
39*5ffd83dbSDimitry Andric /// example, `br %cond, bb0, bb1` %cond is a control condition of bb0 with the
40*5ffd83dbSDimitry Andric /// integer field equals to true, while %cond is a control condition of bb1 with
41*5ffd83dbSDimitry Andric /// the integer field equals to false.
42*5ffd83dbSDimitry Andric using ControlCondition = PointerIntPair<Value *, 1, bool>;
43*5ffd83dbSDimitry Andric #ifndef NDEBUG
44*5ffd83dbSDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const ControlCondition &C) {
45*5ffd83dbSDimitry Andric   OS << "[" << *C.getPointer() << ", " << (C.getInt() ? "true" : "false")
46*5ffd83dbSDimitry Andric      << "]";
47*5ffd83dbSDimitry Andric   return OS;
48*5ffd83dbSDimitry Andric }
49*5ffd83dbSDimitry Andric #endif
50*5ffd83dbSDimitry Andric 
51*5ffd83dbSDimitry Andric /// Represent a set of control conditions required to execute ToBB from FromBB.
52*5ffd83dbSDimitry Andric class ControlConditions {
53*5ffd83dbSDimitry Andric   using ConditionVectorTy = SmallVector<ControlCondition, 6>;
54*5ffd83dbSDimitry Andric 
55*5ffd83dbSDimitry Andric   /// A SmallVector of control conditions.
56*5ffd83dbSDimitry Andric   ConditionVectorTy Conditions;
57*5ffd83dbSDimitry Andric 
58*5ffd83dbSDimitry Andric public:
59*5ffd83dbSDimitry Andric   /// Return a ControlConditions which stores all conditions required to execute
60*5ffd83dbSDimitry Andric   /// \p BB from \p Dominator. If \p MaxLookup is non-zero, it limits the
61*5ffd83dbSDimitry Andric   /// number of conditions to collect. Return None if not all conditions are
62*5ffd83dbSDimitry Andric   /// collected successfully, or we hit the limit.
63*5ffd83dbSDimitry Andric   static const Optional<ControlConditions>
64*5ffd83dbSDimitry Andric   collectControlConditions(const BasicBlock &BB, const BasicBlock &Dominator,
65*5ffd83dbSDimitry Andric                            const DominatorTree &DT,
66*5ffd83dbSDimitry Andric                            const PostDominatorTree &PDT,
67*5ffd83dbSDimitry Andric                            unsigned MaxLookup = 6);
68*5ffd83dbSDimitry Andric 
69*5ffd83dbSDimitry Andric   /// Return true if there exists no control conditions required to execute ToBB
70*5ffd83dbSDimitry Andric   /// from FromBB.
71*5ffd83dbSDimitry Andric   bool isUnconditional() const { return Conditions.empty(); }
72*5ffd83dbSDimitry Andric 
73*5ffd83dbSDimitry Andric   /// Return a constant reference of Conditions.
74*5ffd83dbSDimitry Andric   const ConditionVectorTy &getControlConditions() const { return Conditions; }
75*5ffd83dbSDimitry Andric 
76*5ffd83dbSDimitry Andric   /// Add \p V as one of the ControlCondition in Condition with IsTrueCondition
77*5ffd83dbSDimitry Andric   /// equals to \p True. Return true if inserted successfully.
78*5ffd83dbSDimitry Andric   bool addControlCondition(ControlCondition C);
79*5ffd83dbSDimitry Andric 
80*5ffd83dbSDimitry Andric   /// Return true if for all control conditions in Conditions, there exists an
81*5ffd83dbSDimitry Andric   /// equivalent control condition in \p Other.Conditions.
82*5ffd83dbSDimitry Andric   bool isEquivalent(const ControlConditions &Other) const;
83*5ffd83dbSDimitry Andric 
84*5ffd83dbSDimitry Andric   /// Return true if \p C1 and \p C2 are equivalent.
85*5ffd83dbSDimitry Andric   static bool isEquivalent(const ControlCondition &C1,
86*5ffd83dbSDimitry Andric                            const ControlCondition &C2);
87*5ffd83dbSDimitry Andric 
88*5ffd83dbSDimitry Andric private:
89*5ffd83dbSDimitry Andric   ControlConditions() = default;
90*5ffd83dbSDimitry Andric 
91*5ffd83dbSDimitry Andric   static bool isEquivalent(const Value &V1, const Value &V2);
92*5ffd83dbSDimitry Andric   static bool isInverse(const Value &V1, const Value &V2);
93*5ffd83dbSDimitry Andric };
94*5ffd83dbSDimitry Andric } // namespace
95*5ffd83dbSDimitry Andric 
96*5ffd83dbSDimitry Andric static bool domTreeLevelBefore(DominatorTree *DT, const Instruction *InstA,
97*5ffd83dbSDimitry Andric                                const Instruction *InstB) {
98*5ffd83dbSDimitry Andric   // Use ordered basic block in case the 2 instructions are in the same
99*5ffd83dbSDimitry Andric   // block.
100*5ffd83dbSDimitry Andric   if (InstA->getParent() == InstB->getParent())
101*5ffd83dbSDimitry Andric     return InstA->comesBefore(InstB);
102*5ffd83dbSDimitry Andric 
103*5ffd83dbSDimitry Andric   DomTreeNode *DA = DT->getNode(InstA->getParent());
104*5ffd83dbSDimitry Andric   DomTreeNode *DB = DT->getNode(InstB->getParent());
105*5ffd83dbSDimitry Andric   return DA->getLevel() < DB->getLevel();
106*5ffd83dbSDimitry Andric }
107*5ffd83dbSDimitry Andric 
108*5ffd83dbSDimitry Andric const Optional<ControlConditions> ControlConditions::collectControlConditions(
109*5ffd83dbSDimitry Andric     const BasicBlock &BB, const BasicBlock &Dominator, const DominatorTree &DT,
110*5ffd83dbSDimitry Andric     const PostDominatorTree &PDT, unsigned MaxLookup) {
111*5ffd83dbSDimitry Andric   assert(DT.dominates(&Dominator, &BB) && "Expecting Dominator to dominate BB");
112*5ffd83dbSDimitry Andric 
113*5ffd83dbSDimitry Andric   ControlConditions Conditions;
114*5ffd83dbSDimitry Andric   unsigned NumConditions = 0;
115*5ffd83dbSDimitry Andric 
116*5ffd83dbSDimitry Andric   // BB is executed unconditional from itself.
117*5ffd83dbSDimitry Andric   if (&Dominator == &BB)
118*5ffd83dbSDimitry Andric     return Conditions;
119*5ffd83dbSDimitry Andric 
120*5ffd83dbSDimitry Andric   const BasicBlock *CurBlock = &BB;
121*5ffd83dbSDimitry Andric   // Walk up the dominator tree from the associated DT node for BB to the
122*5ffd83dbSDimitry Andric   // associated DT node for Dominator.
123*5ffd83dbSDimitry Andric   do {
124*5ffd83dbSDimitry Andric     assert(DT.getNode(CurBlock) && "Expecting a valid DT node for CurBlock");
125*5ffd83dbSDimitry Andric     BasicBlock *IDom = DT.getNode(CurBlock)->getIDom()->getBlock();
126*5ffd83dbSDimitry Andric     assert(DT.dominates(&Dominator, IDom) &&
127*5ffd83dbSDimitry Andric            "Expecting Dominator to dominate IDom");
128*5ffd83dbSDimitry Andric 
129*5ffd83dbSDimitry Andric     // Limitation: can only handle branch instruction currently.
130*5ffd83dbSDimitry Andric     const BranchInst *BI = dyn_cast<BranchInst>(IDom->getTerminator());
131*5ffd83dbSDimitry Andric     if (!BI)
132*5ffd83dbSDimitry Andric       return None;
133*5ffd83dbSDimitry Andric 
134*5ffd83dbSDimitry Andric     bool Inserted = false;
135*5ffd83dbSDimitry Andric     if (PDT.dominates(CurBlock, IDom)) {
136*5ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << CurBlock->getName()
137*5ffd83dbSDimitry Andric                         << " is executed unconditionally from "
138*5ffd83dbSDimitry Andric                         << IDom->getName() << "\n");
139*5ffd83dbSDimitry Andric     } else if (PDT.dominates(CurBlock, BI->getSuccessor(0))) {
140*5ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << CurBlock->getName() << " is executed when \""
141*5ffd83dbSDimitry Andric                         << *BI->getCondition() << "\" is true from "
142*5ffd83dbSDimitry Andric                         << IDom->getName() << "\n");
143*5ffd83dbSDimitry Andric       Inserted = Conditions.addControlCondition(
144*5ffd83dbSDimitry Andric           ControlCondition(BI->getCondition(), true));
145*5ffd83dbSDimitry Andric     } else if (PDT.dominates(CurBlock, BI->getSuccessor(1))) {
146*5ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << CurBlock->getName() << " is executed when \""
147*5ffd83dbSDimitry Andric                         << *BI->getCondition() << "\" is false from "
148*5ffd83dbSDimitry Andric                         << IDom->getName() << "\n");
149*5ffd83dbSDimitry Andric       Inserted = Conditions.addControlCondition(
150*5ffd83dbSDimitry Andric           ControlCondition(BI->getCondition(), false));
151*5ffd83dbSDimitry Andric     } else
152*5ffd83dbSDimitry Andric       return None;
153*5ffd83dbSDimitry Andric 
154*5ffd83dbSDimitry Andric     if (Inserted)
155*5ffd83dbSDimitry Andric       ++NumConditions;
156*5ffd83dbSDimitry Andric 
157*5ffd83dbSDimitry Andric     if (MaxLookup != 0 && NumConditions > MaxLookup)
158*5ffd83dbSDimitry Andric       return None;
159*5ffd83dbSDimitry Andric 
160*5ffd83dbSDimitry Andric     CurBlock = IDom;
161*5ffd83dbSDimitry Andric   } while (CurBlock != &Dominator);
162*5ffd83dbSDimitry Andric 
163*5ffd83dbSDimitry Andric   return Conditions;
164*5ffd83dbSDimitry Andric }
165*5ffd83dbSDimitry Andric 
166*5ffd83dbSDimitry Andric bool ControlConditions::addControlCondition(ControlCondition C) {
167*5ffd83dbSDimitry Andric   bool Inserted = false;
168*5ffd83dbSDimitry Andric   if (none_of(Conditions, [&](ControlCondition &Exists) {
169*5ffd83dbSDimitry Andric         return ControlConditions::isEquivalent(C, Exists);
170*5ffd83dbSDimitry Andric       })) {
171*5ffd83dbSDimitry Andric     Conditions.push_back(C);
172*5ffd83dbSDimitry Andric     Inserted = true;
173*5ffd83dbSDimitry Andric   }
174*5ffd83dbSDimitry Andric 
175*5ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << (Inserted ? "Inserted " : "Not inserted ") << C << "\n");
176*5ffd83dbSDimitry Andric   return Inserted;
177*5ffd83dbSDimitry Andric }
178*5ffd83dbSDimitry Andric 
179*5ffd83dbSDimitry Andric bool ControlConditions::isEquivalent(const ControlConditions &Other) const {
180*5ffd83dbSDimitry Andric   if (Conditions.empty() && Other.Conditions.empty())
181*5ffd83dbSDimitry Andric     return true;
182*5ffd83dbSDimitry Andric 
183*5ffd83dbSDimitry Andric   if (Conditions.size() != Other.Conditions.size())
184*5ffd83dbSDimitry Andric     return false;
185*5ffd83dbSDimitry Andric 
186*5ffd83dbSDimitry Andric   return all_of(Conditions, [&](const ControlCondition &C) {
187*5ffd83dbSDimitry Andric     return any_of(Other.Conditions, [&](const ControlCondition &OtherC) {
188*5ffd83dbSDimitry Andric       return ControlConditions::isEquivalent(C, OtherC);
189*5ffd83dbSDimitry Andric     });
190*5ffd83dbSDimitry Andric   });
191*5ffd83dbSDimitry Andric }
192*5ffd83dbSDimitry Andric 
193*5ffd83dbSDimitry Andric bool ControlConditions::isEquivalent(const ControlCondition &C1,
194*5ffd83dbSDimitry Andric                                      const ControlCondition &C2) {
195*5ffd83dbSDimitry Andric   if (C1.getInt() == C2.getInt()) {
196*5ffd83dbSDimitry Andric     if (isEquivalent(*C1.getPointer(), *C2.getPointer()))
197*5ffd83dbSDimitry Andric       return true;
198*5ffd83dbSDimitry Andric   } else if (isInverse(*C1.getPointer(), *C2.getPointer()))
199*5ffd83dbSDimitry Andric     return true;
200*5ffd83dbSDimitry Andric 
201*5ffd83dbSDimitry Andric   return false;
202*5ffd83dbSDimitry Andric }
203*5ffd83dbSDimitry Andric 
204*5ffd83dbSDimitry Andric // FIXME: Use SCEV and reuse GVN/CSE logic to check for equivalence between
205*5ffd83dbSDimitry Andric // Values.
206*5ffd83dbSDimitry Andric // Currently, isEquivalent rely on other passes to ensure equivalent conditions
207*5ffd83dbSDimitry Andric // have the same value, e.g. GVN.
208*5ffd83dbSDimitry Andric bool ControlConditions::isEquivalent(const Value &V1, const Value &V2) {
209*5ffd83dbSDimitry Andric   return &V1 == &V2;
210*5ffd83dbSDimitry Andric }
211*5ffd83dbSDimitry Andric 
212*5ffd83dbSDimitry Andric bool ControlConditions::isInverse(const Value &V1, const Value &V2) {
213*5ffd83dbSDimitry Andric   if (const CmpInst *Cmp1 = dyn_cast<CmpInst>(&V1))
214*5ffd83dbSDimitry Andric     if (const CmpInst *Cmp2 = dyn_cast<CmpInst>(&V2)) {
215*5ffd83dbSDimitry Andric       if (Cmp1->getPredicate() == Cmp2->getInversePredicate() &&
216*5ffd83dbSDimitry Andric           Cmp1->getOperand(0) == Cmp2->getOperand(0) &&
217*5ffd83dbSDimitry Andric           Cmp1->getOperand(1) == Cmp2->getOperand(1))
218*5ffd83dbSDimitry Andric         return true;
219*5ffd83dbSDimitry Andric 
220*5ffd83dbSDimitry Andric       if (Cmp1->getPredicate() ==
221*5ffd83dbSDimitry Andric               CmpInst::getSwappedPredicate(Cmp2->getInversePredicate()) &&
222*5ffd83dbSDimitry Andric           Cmp1->getOperand(0) == Cmp2->getOperand(1) &&
223*5ffd83dbSDimitry Andric           Cmp1->getOperand(1) == Cmp2->getOperand(0))
224*5ffd83dbSDimitry Andric         return true;
225*5ffd83dbSDimitry Andric     }
226*5ffd83dbSDimitry Andric   return false;
227*5ffd83dbSDimitry Andric }
228*5ffd83dbSDimitry Andric 
229480093f4SDimitry Andric bool llvm::isControlFlowEquivalent(const Instruction &I0, const Instruction &I1,
230480093f4SDimitry Andric                                    const DominatorTree &DT,
231480093f4SDimitry Andric                                    const PostDominatorTree &PDT) {
232480093f4SDimitry Andric   return isControlFlowEquivalent(*I0.getParent(), *I1.getParent(), DT, PDT);
233480093f4SDimitry Andric }
234480093f4SDimitry Andric 
235480093f4SDimitry Andric bool llvm::isControlFlowEquivalent(const BasicBlock &BB0, const BasicBlock &BB1,
236480093f4SDimitry Andric                                    const DominatorTree &DT,
237480093f4SDimitry Andric                                    const PostDominatorTree &PDT) {
238480093f4SDimitry Andric   if (&BB0 == &BB1)
239480093f4SDimitry Andric     return true;
240480093f4SDimitry Andric 
241*5ffd83dbSDimitry Andric   if ((DT.dominates(&BB0, &BB1) && PDT.dominates(&BB1, &BB0)) ||
242*5ffd83dbSDimitry Andric       (PDT.dominates(&BB0, &BB1) && DT.dominates(&BB1, &BB0)))
243*5ffd83dbSDimitry Andric     return true;
244*5ffd83dbSDimitry Andric 
245*5ffd83dbSDimitry Andric   // If the set of conditions required to execute BB0 and BB1 from their common
246*5ffd83dbSDimitry Andric   // dominator are the same, then BB0 and BB1 are control flow equivalent.
247*5ffd83dbSDimitry Andric   const BasicBlock *CommonDominator = DT.findNearestCommonDominator(&BB0, &BB1);
248*5ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "The nearest common dominator of " << BB0.getName()
249*5ffd83dbSDimitry Andric                     << " and " << BB1.getName() << " is "
250*5ffd83dbSDimitry Andric                     << CommonDominator->getName() << "\n");
251*5ffd83dbSDimitry Andric 
252*5ffd83dbSDimitry Andric   const Optional<ControlConditions> BB0Conditions =
253*5ffd83dbSDimitry Andric       ControlConditions::collectControlConditions(BB0, *CommonDominator, DT,
254*5ffd83dbSDimitry Andric                                                   PDT);
255*5ffd83dbSDimitry Andric   if (BB0Conditions == None)
256*5ffd83dbSDimitry Andric     return false;
257*5ffd83dbSDimitry Andric 
258*5ffd83dbSDimitry Andric   const Optional<ControlConditions> BB1Conditions =
259*5ffd83dbSDimitry Andric       ControlConditions::collectControlConditions(BB1, *CommonDominator, DT,
260*5ffd83dbSDimitry Andric                                                   PDT);
261*5ffd83dbSDimitry Andric   if (BB1Conditions == None)
262*5ffd83dbSDimitry Andric     return false;
263*5ffd83dbSDimitry Andric 
264*5ffd83dbSDimitry Andric   return BB0Conditions->isEquivalent(*BB1Conditions);
265480093f4SDimitry Andric }
266480093f4SDimitry Andric 
267480093f4SDimitry Andric static bool reportInvalidCandidate(const Instruction &I,
268480093f4SDimitry Andric                                    llvm::Statistic &Stat) {
269480093f4SDimitry Andric   ++Stat;
270480093f4SDimitry Andric   LLVM_DEBUG(dbgs() << "Unable to move instruction: " << I << ". "
271480093f4SDimitry Andric                     << Stat.getDesc());
272480093f4SDimitry Andric   return false;
273480093f4SDimitry Andric }
274480093f4SDimitry Andric 
275480093f4SDimitry Andric /// Collect all instructions in between \p StartInst and \p EndInst, and store
276480093f4SDimitry Andric /// them in \p InBetweenInsts.
277480093f4SDimitry Andric static void
278480093f4SDimitry Andric collectInstructionsInBetween(Instruction &StartInst, const Instruction &EndInst,
279480093f4SDimitry Andric                              SmallPtrSetImpl<Instruction *> &InBetweenInsts) {
280480093f4SDimitry Andric   assert(InBetweenInsts.empty() && "Expecting InBetweenInsts to be empty");
281480093f4SDimitry Andric 
282480093f4SDimitry Andric   /// Get the next instructions of \p I, and push them to \p WorkList.
283480093f4SDimitry Andric   auto getNextInsts = [](Instruction &I,
284480093f4SDimitry Andric                          SmallPtrSetImpl<Instruction *> &WorkList) {
285480093f4SDimitry Andric     if (Instruction *NextInst = I.getNextNode())
286480093f4SDimitry Andric       WorkList.insert(NextInst);
287480093f4SDimitry Andric     else {
288480093f4SDimitry Andric       assert(I.isTerminator() && "Expecting a terminator instruction");
289480093f4SDimitry Andric       for (BasicBlock *Succ : successors(&I))
290480093f4SDimitry Andric         WorkList.insert(&Succ->front());
291480093f4SDimitry Andric     }
292480093f4SDimitry Andric   };
293480093f4SDimitry Andric 
294480093f4SDimitry Andric   SmallPtrSet<Instruction *, 10> WorkList;
295480093f4SDimitry Andric   getNextInsts(StartInst, WorkList);
296480093f4SDimitry Andric   while (!WorkList.empty()) {
297480093f4SDimitry Andric     Instruction *CurInst = *WorkList.begin();
298480093f4SDimitry Andric     WorkList.erase(CurInst);
299480093f4SDimitry Andric 
300480093f4SDimitry Andric     if (CurInst == &EndInst)
301480093f4SDimitry Andric       continue;
302480093f4SDimitry Andric 
303480093f4SDimitry Andric     if (!InBetweenInsts.insert(CurInst).second)
304480093f4SDimitry Andric       continue;
305480093f4SDimitry Andric 
306480093f4SDimitry Andric     getNextInsts(*CurInst, WorkList);
307480093f4SDimitry Andric   }
308480093f4SDimitry Andric }
309480093f4SDimitry Andric 
310480093f4SDimitry Andric bool llvm::isSafeToMoveBefore(Instruction &I, Instruction &InsertPoint,
311*5ffd83dbSDimitry Andric                               DominatorTree &DT, const PostDominatorTree *PDT,
312*5ffd83dbSDimitry Andric                               DependenceInfo *DI) {
313*5ffd83dbSDimitry Andric   // Skip tests when we don't have PDT or DI
314*5ffd83dbSDimitry Andric   if (!PDT || !DI)
315*5ffd83dbSDimitry Andric     return false;
316*5ffd83dbSDimitry Andric 
317480093f4SDimitry Andric   // Cannot move itself before itself.
318480093f4SDimitry Andric   if (&I == &InsertPoint)
319480093f4SDimitry Andric     return false;
320480093f4SDimitry Andric 
321480093f4SDimitry Andric   // Not moved.
322480093f4SDimitry Andric   if (I.getNextNode() == &InsertPoint)
323480093f4SDimitry Andric     return true;
324480093f4SDimitry Andric 
325480093f4SDimitry Andric   if (isa<PHINode>(I) || isa<PHINode>(InsertPoint))
326480093f4SDimitry Andric     return reportInvalidCandidate(I, NotMovedPHINode);
327480093f4SDimitry Andric 
328480093f4SDimitry Andric   if (I.isTerminator())
329480093f4SDimitry Andric     return reportInvalidCandidate(I, NotMovedTerminator);
330480093f4SDimitry Andric 
331480093f4SDimitry Andric   // TODO remove this limitation.
332*5ffd83dbSDimitry Andric   if (!isControlFlowEquivalent(I, InsertPoint, DT, *PDT))
333480093f4SDimitry Andric     return reportInvalidCandidate(I, NotControlFlowEquivalent);
334480093f4SDimitry Andric 
335*5ffd83dbSDimitry Andric   if (!DT.dominates(&InsertPoint, &I))
336480093f4SDimitry Andric     for (const Use &U : I.uses())
337480093f4SDimitry Andric       if (auto *UserInst = dyn_cast<Instruction>(U.getUser()))
338480093f4SDimitry Andric         if (UserInst != &InsertPoint && !DT.dominates(&InsertPoint, U))
339480093f4SDimitry Andric           return false;
340*5ffd83dbSDimitry Andric   if (!DT.dominates(&I, &InsertPoint))
341480093f4SDimitry Andric     for (const Value *Op : I.operands())
342480093f4SDimitry Andric       if (auto *OpInst = dyn_cast<Instruction>(Op))
343480093f4SDimitry Andric         if (&InsertPoint == OpInst || !DT.dominates(OpInst, &InsertPoint))
344480093f4SDimitry Andric           return false;
345480093f4SDimitry Andric 
346*5ffd83dbSDimitry Andric   DT.updateDFSNumbers();
347*5ffd83dbSDimitry Andric   const bool MoveForward = domTreeLevelBefore(&DT, &I, &InsertPoint);
348480093f4SDimitry Andric   Instruction &StartInst = (MoveForward ? I : InsertPoint);
349480093f4SDimitry Andric   Instruction &EndInst = (MoveForward ? InsertPoint : I);
350480093f4SDimitry Andric   SmallPtrSet<Instruction *, 10> InstsToCheck;
351480093f4SDimitry Andric   collectInstructionsInBetween(StartInst, EndInst, InstsToCheck);
352480093f4SDimitry Andric   if (!MoveForward)
353480093f4SDimitry Andric     InstsToCheck.insert(&InsertPoint);
354480093f4SDimitry Andric 
355480093f4SDimitry Andric   // Check if there exists instructions which may throw, may synchonize, or may
356480093f4SDimitry Andric   // never return, from I to InsertPoint.
357480093f4SDimitry Andric   if (!isSafeToSpeculativelyExecute(&I))
358480093f4SDimitry Andric     if (std::any_of(InstsToCheck.begin(), InstsToCheck.end(),
359480093f4SDimitry Andric                     [](Instruction *I) {
360480093f4SDimitry Andric                       if (I->mayThrow())
361480093f4SDimitry Andric                         return true;
362480093f4SDimitry Andric 
363480093f4SDimitry Andric                       const CallBase *CB = dyn_cast<CallBase>(I);
364480093f4SDimitry Andric                       if (!CB)
365480093f4SDimitry Andric                         return false;
366480093f4SDimitry Andric                       if (!CB->hasFnAttr(Attribute::WillReturn))
367480093f4SDimitry Andric                         return true;
368480093f4SDimitry Andric                       if (!CB->hasFnAttr(Attribute::NoSync))
369480093f4SDimitry Andric                         return true;
370480093f4SDimitry Andric 
371480093f4SDimitry Andric                       return false;
372480093f4SDimitry Andric                     })) {
373480093f4SDimitry Andric       return reportInvalidCandidate(I, MayThrowException);
374480093f4SDimitry Andric     }
375480093f4SDimitry Andric 
376480093f4SDimitry Andric   // Check if I has any output/flow/anti dependences with instructions from \p
377480093f4SDimitry Andric   // StartInst to \p EndInst.
378480093f4SDimitry Andric   if (std::any_of(InstsToCheck.begin(), InstsToCheck.end(),
379480093f4SDimitry Andric                   [&DI, &I](Instruction *CurInst) {
380*5ffd83dbSDimitry Andric                     auto DepResult = DI->depends(&I, CurInst, true);
381480093f4SDimitry Andric                     if (DepResult &&
382480093f4SDimitry Andric                         (DepResult->isOutput() || DepResult->isFlow() ||
383480093f4SDimitry Andric                          DepResult->isAnti()))
384480093f4SDimitry Andric                       return true;
385480093f4SDimitry Andric                     return false;
386480093f4SDimitry Andric                   }))
387480093f4SDimitry Andric     return reportInvalidCandidate(I, HasDependences);
388480093f4SDimitry Andric 
389480093f4SDimitry Andric   return true;
390480093f4SDimitry Andric }
391480093f4SDimitry Andric 
392*5ffd83dbSDimitry Andric bool llvm::isSafeToMoveBefore(BasicBlock &BB, Instruction &InsertPoint,
393*5ffd83dbSDimitry Andric                               DominatorTree &DT, const PostDominatorTree *PDT,
394*5ffd83dbSDimitry Andric                               DependenceInfo *DI) {
395*5ffd83dbSDimitry Andric   return llvm::all_of(BB, [&](Instruction &I) {
396*5ffd83dbSDimitry Andric     if (BB.getTerminator() == &I)
397*5ffd83dbSDimitry Andric       return true;
398*5ffd83dbSDimitry Andric 
399*5ffd83dbSDimitry Andric     return isSafeToMoveBefore(I, InsertPoint, DT, PDT, DI);
400*5ffd83dbSDimitry Andric   });
401*5ffd83dbSDimitry Andric }
402*5ffd83dbSDimitry Andric 
403*5ffd83dbSDimitry Andric void llvm::moveInstructionsToTheBeginning(BasicBlock &FromBB, BasicBlock &ToBB,
404*5ffd83dbSDimitry Andric                                           DominatorTree &DT,
405*5ffd83dbSDimitry Andric                                           const PostDominatorTree &PDT,
406*5ffd83dbSDimitry Andric                                           DependenceInfo &DI) {
407480093f4SDimitry Andric   for (auto It = ++FromBB.rbegin(); It != FromBB.rend();) {
408480093f4SDimitry Andric     Instruction *MovePos = ToBB.getFirstNonPHIOrDbg();
409480093f4SDimitry Andric     Instruction &I = *It;
410480093f4SDimitry Andric     // Increment the iterator before modifying FromBB.
411480093f4SDimitry Andric     ++It;
412480093f4SDimitry Andric 
413*5ffd83dbSDimitry Andric     if (isSafeToMoveBefore(I, *MovePos, DT, &PDT, &DI))
414*5ffd83dbSDimitry Andric       I.moveBefore(MovePos);
415*5ffd83dbSDimitry Andric   }
416*5ffd83dbSDimitry Andric }
417*5ffd83dbSDimitry Andric 
418*5ffd83dbSDimitry Andric void llvm::moveInstructionsToTheEnd(BasicBlock &FromBB, BasicBlock &ToBB,
419*5ffd83dbSDimitry Andric                                     DominatorTree &DT,
420*5ffd83dbSDimitry Andric                                     const PostDominatorTree &PDT,
421*5ffd83dbSDimitry Andric                                     DependenceInfo &DI) {
422*5ffd83dbSDimitry Andric   Instruction *MovePos = ToBB.getTerminator();
423*5ffd83dbSDimitry Andric   while (FromBB.size() > 1) {
424*5ffd83dbSDimitry Andric     Instruction &I = FromBB.front();
425*5ffd83dbSDimitry Andric     if (isSafeToMoveBefore(I, *MovePos, DT, &PDT, &DI))
426480093f4SDimitry Andric       I.moveBefore(MovePos);
427480093f4SDimitry Andric   }
428480093f4SDimitry Andric }
429