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 respectively. To efficiently look up whether an expression is
40 // computed before, we store each instruction seen and its SCEV into an
41 // 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 // Limitations and TODO items:
55 // 1) We only considers n-ary adds for now. This should be extended and
58 // 2) Besides arithmetic operations, similar reassociation can be applied to
59 // GEPs. For example, if
63 // we may rewrite Y into X + b.
65 //===----------------------------------------------------------------------===//
67 #include "llvm/Analysis/ScalarEvolution.h"
68 #include "llvm/IR/Dominators.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/PatternMatch.h"
71 #include "llvm/Transforms/Scalar.h"
73 using namespace PatternMatch;
75 #define DEBUG_TYPE "nary-reassociate"
78 class NaryReassociate : public FunctionPass {
82 NaryReassociate(): FunctionPass(ID) {
83 initializeNaryReassociatePass(*PassRegistry::getPassRegistry());
86 bool runOnFunction(Function &F) override;
88 void getAnalysisUsage(AnalysisUsage &AU) const override {
89 AU.addPreserved<DominatorTreeWrapperPass>();
90 AU.addRequired<DominatorTreeWrapperPass>();
91 // TODO: can we preserve ScalarEvolution?
92 AU.addRequired<ScalarEvolution>();
97 // Reasssociates I to a better form.
98 Instruction *tryReassociateAdd(Instruction *I);
99 // A helper function for tryReassociateAdd. LHS and RHS are explicitly passed.
100 Instruction *tryReassociateAdd(Value *LHS, Value *RHS, Instruction *I);
101 // Rewrites I to LHS + RHS if LHS is computed already.
102 Instruction *tryReassociatedAdd(const SCEV *LHS, Value *RHS, Instruction *I);
106 // A lookup table quickly telling which instructions compute the given SCEV.
107 // Note that there can be multiple instructions at different locations
108 // computing to the same SCEV, so we map a SCEV to an instruction list. For
115 DenseMap<const SCEV *, SmallVector<Instruction *, 2>> SeenExprs;
117 } // anonymous namespace
119 char NaryReassociate::ID = 0;
120 INITIALIZE_PASS_BEGIN(NaryReassociate, "nary-reassociate", "Nary reassociation",
122 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
123 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
124 INITIALIZE_PASS_END(NaryReassociate, "nary-reassociate", "Nary reassociation",
127 FunctionPass *llvm::createNaryReassociatePass() {
128 return new NaryReassociate();
131 bool NaryReassociate::runOnFunction(Function &F) {
132 if (skipOptnoneFunction(F))
135 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
136 SE = &getAnalysis<ScalarEvolution>();
138 // Traverse the dominator tree in the depth-first order. This order makes sure
139 // all bases of a candidate are in Candidates when we process it.
140 bool Changed = false;
142 for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
143 Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
144 BasicBlock *BB = Node->getBlock();
145 for (auto I = BB->begin(); I != BB->end(); ++I) {
146 if (I->getOpcode() == Instruction::Add) {
147 if (Instruction *NewI = tryReassociateAdd(I)) {
148 I->replaceAllUsesWith(NewI);
149 I->eraseFromParent();
152 // We should add the rewritten instruction because tryReassociateAdd may
153 // have invalidated the original one.
154 SeenExprs[SE->getSCEV(I)].push_back(I);
161 Instruction *NaryReassociate::tryReassociateAdd(Instruction *I) {
162 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
163 if (auto *NewI = tryReassociateAdd(LHS, RHS, I))
165 if (auto *NewI = tryReassociateAdd(RHS, LHS, I))
170 Instruction *NaryReassociate::tryReassociateAdd(Value *LHS, Value *RHS,
172 Value *A = nullptr, *B = nullptr;
173 // To be conservative, we reassociate I only when it is the only user of A+B.
174 if (LHS->hasOneUse() && match(LHS, m_Add(m_Value(A), m_Value(B)))) {
176 // = (A + RHS) + B or (B + RHS) + A
177 const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
178 const SCEV *RHSExpr = SE->getSCEV(RHS);
179 if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(AExpr, RHSExpr), B, I))
181 if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(BExpr, RHSExpr), A, I))
187 Instruction *NaryReassociate::tryReassociatedAdd(const SCEV *LHSExpr,
188 Value *RHS, Instruction *I) {
189 auto Pos = SeenExprs.find(LHSExpr);
190 // Bail out if LHSExpr is not previously seen.
191 if (Pos == SeenExprs.end())
194 auto &LHSCandidates = Pos->second;
195 // Look for the closest dominator LHS of I that computes LHSExpr, and replace
198 // Because we traverse the dominator tree in the pre-order, a
199 // candidate that doesn't dominate the current instruction won't dominate any
200 // future instruction either. Therefore, we pop it out of the stack. This
201 // optimization makes the algorithm O(n).
202 while (!LHSCandidates.empty()) {
203 Instruction *LHS = LHSCandidates.back();
204 if (DT->dominates(LHS, I)) {
205 Instruction *NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
209 LHSCandidates.pop_back();