1 //===- NaryReassociate.cpp - Reassociate n-ary expressions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass reassociates n-ary add expressions and eliminates the redundancy
11 // exposed by the reassociation.
13 // A motivating example:
15 // void foo(int a, int b) {
20 // An ideal compiler should reassociate (a + 2) + b to (a + b) + 2 and simplify
27 // However, the Reassociate pass is unable to do that because it processes each
28 // instruction individually and believes (a + 2) + b is the best form according
29 // to its rank system.
31 // To address this limitation, NaryReassociate reassociates an expression in a
32 // form that reuses existing instructions. As a result, NaryReassociate can
33 // reassociate (a + 2) + b in the example to (a + b) + 2 because it detects that
34 // (a + b) is computed before.
36 // NaryReassociate works as follows. For every instruction in the form of (a +
37 // b) + c, it checks whether a + c or b + c is already computed by a dominating
38 // instruction. If so, it then reassociates (a + b) + c into (a + c) + b or (b +
39 // c) + a and removes the redundancy accordingly. To efficiently look up whether
40 // an expression is computed before, we store each instruction seen and its SCEV
41 // into an SCEV-to-instruction map.
43 // Although the algorithm pattern-matches only ternary additions, it
44 // automatically handles many >3-ary expressions by walking through the function
45 // in the depth-first order. For example, given
50 // NaryReassociate first rewrites (a + b) + c to (a + c) + b, and then rewrites
51 // ((a + c) + b) + d into ((a + c) + d) + b.
53 // Finally, the above dominator-based algorithm may need to be run multiple
54 // iterations before emitting optimal code. One source of this need is that we
55 // only split an operand when it is used only once. The above algorithm can
56 // eliminate an instruction and decrease the usage count of its operands. As a
57 // result, an instruction that previously had multiple uses may become a
58 // single-use instruction and thus eligible for split consideration. For
67 // In the first iteration, we cannot reassociate abc to ac+b because ab is used
68 // twice. However, we can reassociate ab2c to abc+b in the first iteration. As a
69 // result, ab2 becomes dead and ab will be used only once in the second
72 // Limitations and TODO items:
74 // 1) We only considers n-ary adds for now. This should be extended and
77 // 2) Besides arithmetic operations, similar reassociation can be applied to
78 // GEPs. For example, if
82 // we may rewrite Y into X + b.
84 //===----------------------------------------------------------------------===//
86 #include "llvm/Analysis/ScalarEvolution.h"
87 #include "llvm/Analysis/TargetLibraryInfo.h"
88 #include "llvm/IR/Dominators.h"
89 #include "llvm/IR/Module.h"
90 #include "llvm/IR/PatternMatch.h"
91 #include "llvm/Transforms/Scalar.h"
92 #include "llvm/Transforms/Utils/Local.h"
94 using namespace PatternMatch;
96 #define DEBUG_TYPE "nary-reassociate"
99 class NaryReassociate : public FunctionPass {
103 NaryReassociate(): FunctionPass(ID) {
104 initializeNaryReassociatePass(*PassRegistry::getPassRegistry());
107 bool runOnFunction(Function &F) override;
109 void getAnalysisUsage(AnalysisUsage &AU) const override {
110 AU.addPreserved<DominatorTreeWrapperPass>();
111 AU.addPreserved<ScalarEvolution>();
112 AU.addPreserved<TargetLibraryInfoWrapperPass>();
113 AU.addRequired<DominatorTreeWrapperPass>();
114 AU.addRequired<ScalarEvolution>();
115 AU.addRequired<TargetLibraryInfoWrapperPass>();
116 AU.setPreservesCFG();
120 // Runs only one iteration of the dominator-based algorithm. See the header
121 // comments for why we need multiple iterations.
122 bool doOneIteration(Function &F);
123 // Reasssociates I to a better form.
124 Instruction *tryReassociateAdd(Instruction *I);
125 // A helper function for tryReassociateAdd. LHS and RHS are explicitly passed.
126 Instruction *tryReassociateAdd(Value *LHS, Value *RHS, Instruction *I);
127 // Rewrites I to LHS + RHS if LHS is computed already.
128 Instruction *tryReassociatedAdd(const SCEV *LHS, Value *RHS, Instruction *I);
132 TargetLibraryInfo *TLI;
133 // A lookup table quickly telling which instructions compute the given SCEV.
134 // Note that there can be multiple instructions at different locations
135 // computing to the same SCEV, so we map a SCEV to an instruction list. For
142 DenseMap<const SCEV *, SmallVector<Instruction *, 2>> SeenExprs;
144 } // anonymous namespace
146 char NaryReassociate::ID = 0;
147 INITIALIZE_PASS_BEGIN(NaryReassociate, "nary-reassociate", "Nary reassociation",
149 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
150 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
151 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
152 INITIALIZE_PASS_END(NaryReassociate, "nary-reassociate", "Nary reassociation",
155 FunctionPass *llvm::createNaryReassociatePass() {
156 return new NaryReassociate();
159 bool NaryReassociate::runOnFunction(Function &F) {
160 if (skipOptnoneFunction(F))
163 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
164 SE = &getAnalysis<ScalarEvolution>();
165 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
167 bool Changed = false, ChangedInThisIteration;
169 ChangedInThisIteration = doOneIteration(F);
170 Changed |= ChangedInThisIteration;
171 } while (ChangedInThisIteration);
175 bool NaryReassociate::doOneIteration(Function &F) {
176 bool Changed = false;
178 // Traverse the dominator tree in the depth-first order. This order makes sure
179 // all bases of a candidate are in Candidates when we process it.
180 for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
181 Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
182 BasicBlock *BB = Node->getBlock();
183 for (auto I = BB->begin(); I != BB->end(); ++I) {
184 // Skip vector types which are not SCEVable.
185 if (I->getOpcode() == Instruction::Add && !I->getType()->isVectorTy()) {
186 if (Instruction *NewI = tryReassociateAdd(I)) {
189 I->replaceAllUsesWith(NewI);
190 RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
193 // We should add the rewritten instruction because tryReassociateAdd may
194 // have invalidated the original one.
195 SeenExprs[SE->getSCEV(I)].push_back(I);
202 Instruction *NaryReassociate::tryReassociateAdd(Instruction *I) {
203 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
204 if (auto *NewI = tryReassociateAdd(LHS, RHS, I))
206 if (auto *NewI = tryReassociateAdd(RHS, LHS, I))
211 Instruction *NaryReassociate::tryReassociateAdd(Value *LHS, Value *RHS,
213 Value *A = nullptr, *B = nullptr;
214 // To be conservative, we reassociate I only when it is the only user of A+B.
215 if (LHS->hasOneUse() && match(LHS, m_Add(m_Value(A), m_Value(B)))) {
217 // = (A + RHS) + B or (B + RHS) + A
218 const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
219 const SCEV *RHSExpr = SE->getSCEV(RHS);
220 if (BExpr != RHSExpr) {
221 if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(AExpr, RHSExpr), B, I))
224 if (AExpr != RHSExpr) {
225 if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(BExpr, RHSExpr), A, I))
232 Instruction *NaryReassociate::tryReassociatedAdd(const SCEV *LHSExpr,
233 Value *RHS, Instruction *I) {
234 auto Pos = SeenExprs.find(LHSExpr);
235 // Bail out if LHSExpr is not previously seen.
236 if (Pos == SeenExprs.end())
239 auto &LHSCandidates = Pos->second;
240 // Look for the closest dominator LHS of I that computes LHSExpr, and replace
243 // Because we traverse the dominator tree in the pre-order, a
244 // candidate that doesn't dominate the current instruction won't dominate any
245 // future instruction either. Therefore, we pop it out of the stack. This
246 // optimization makes the algorithm O(n).
247 while (!LHSCandidates.empty()) {
248 Instruction *LHS = LHSCandidates.back();
249 if (DT->dominates(LHS, I)) {
250 Instruction *NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
254 LHSCandidates.pop_back();