blob: 275d19adbc10256e36f91af40afd99dfe4892fc8 [file] [log] [blame]
Chris Lattner4fd56002002-05-08 22:19:27 +00001//===- Reassociate.cpp - Reassociate binary expressions -------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4fd56002002-05-08 22:19:27 +00009//
10// This pass reassociates commutative expressions in an order that is designed
Chris Lattner90461932010-01-01 00:04:26 +000011// to promote better constant propagation, GCSE, LICM, PRE, etc.
Chris Lattner4fd56002002-05-08 22:19:27 +000012//
13// For example: 4 + (x + 5) -> x + (4 + 5)
14//
Chris Lattner4fd56002002-05-08 22:19:27 +000015// In the implementation of this algorithm, constants are assigned rank = 0,
16// function arguments are rank = 1, and other values are assigned ranks
17// corresponding to the reverse post order traversal of current function
18// (starting at 2), which effectively gives values in deep loops higher rank
19// than values not in loops.
20//
21//===----------------------------------------------------------------------===//
22
Chris Lattner08b43922005-05-07 04:08:02 +000023#define DEBUG_TYPE "reassociate"
Chris Lattner4fd56002002-05-08 22:19:27 +000024#include "llvm/Transforms/Scalar.h"
Dan Gohmanfa0e6fa2011-03-10 19:51:54 +000025#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0975ed52005-05-07 04:24:13 +000026#include "llvm/Constants.h"
Chris Lattnerae74f552006-04-28 04:14:49 +000027#include "llvm/DerivedTypes.h"
Chris Lattner4fd56002002-05-08 22:19:27 +000028#include "llvm/Function.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000029#include "llvm/Instructions.h"
Dale Johannesen03afd022009-03-06 01:41:59 +000030#include "llvm/IntrinsicInst.h"
Chris Lattner4fd56002002-05-08 22:19:27 +000031#include "llvm/Pass.h"
Chris Lattnerc9fd0972005-05-08 20:09:57 +000032#include "llvm/Assembly/Writer.h"
Chris Lattner4fd56002002-05-08 22:19:27 +000033#include "llvm/Support/CFG.h"
Chandler Carruth464bda32012-04-26 05:30:30 +000034#include "llvm/Support/IRBuilder.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/Support/Debug.h"
Chris Lattnerd3c7b732009-03-31 22:13:29 +000036#include "llvm/Support/ValueHandle.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000037#include "llvm/Support/raw_ostream.h"
Duncan Sands0fd120b2012-05-25 12:03:02 +000038#include "llvm/ADT/DenseMap.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/PostOrderIterator.h"
Duncan Sands841f4262012-06-08 20:15:33 +000040#include "llvm/ADT/SetVector.h"
Duncan Sands0fd120b2012-05-25 12:03:02 +000041#include "llvm/ADT/SmallMap.h"
Chandler Carruth464bda32012-04-26 05:30:30 +000042#include "llvm/ADT/STLExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000043#include "llvm/ADT/Statistic.h"
Chris Lattnerc0649ac2005-05-07 21:59:39 +000044#include <algorithm>
Chris Lattnerd7456022004-01-09 06:02:20 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Chris Lattner0e5f4992006-12-19 21:40:18 +000047STATISTIC(NumChanged, "Number of insts reassociated");
48STATISTIC(NumAnnihil, "Number of expr tree annihilated");
49STATISTIC(NumFactor , "Number of multiplies factored");
Chris Lattnera92f6962002-10-01 22:38:41 +000050
Chris Lattner0e5f4992006-12-19 21:40:18 +000051namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000052 struct ValueEntry {
Chris Lattnerc0649ac2005-05-07 21:59:39 +000053 unsigned Rank;
54 Value *Op;
55 ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
56 };
57 inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
58 return LHS.Rank > RHS.Rank; // Sort so that highest rank goes to start.
59 }
Chris Lattnere5022fe2006-03-04 09:31:13 +000060}
Chris Lattnerc0649ac2005-05-07 21:59:39 +000061
Devang Patel50cacb22008-11-21 21:00:20 +000062#ifndef NDEBUG
Chris Lattnere5022fe2006-03-04 09:31:13 +000063/// PrintOps - Print out the expression identified in the Ops list.
64///
Chris Lattner9f7b7082009-12-31 18:40:32 +000065static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
Chris Lattnere5022fe2006-03-04 09:31:13 +000066 Module *M = I->getParent()->getParent()->getParent();
David Greenea1fa76c2010-01-05 01:27:24 +000067 dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " "
Chris Lattner1befe642009-12-31 07:17:37 +000068 << *Ops[0].Op->getType() << '\t';
Chris Lattner7de3b5d2008-08-19 04:45:19 +000069 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
David Greenea1fa76c2010-01-05 01:27:24 +000070 dbgs() << "[ ";
71 WriteAsOperand(dbgs(), Ops[i].Op, false, M);
72 dbgs() << ", #" << Ops[i].Rank << "] ";
Chris Lattner7de3b5d2008-08-19 04:45:19 +000073 }
Chris Lattnere5022fe2006-03-04 09:31:13 +000074}
Devang Patel59500c82008-11-21 20:00:59 +000075#endif
Bill Wendlinge8cd3f22012-05-02 23:43:23 +000076
Dan Gohman844731a2008-05-13 00:00:25 +000077namespace {
Chandler Carruth464bda32012-04-26 05:30:30 +000078 /// \brief Utility class representing a base and exponent pair which form one
79 /// factor of some product.
80 struct Factor {
81 Value *Base;
82 unsigned Power;
83
84 Factor(Value *Base, unsigned Power) : Base(Base), Power(Power) {}
85
86 /// \brief Sort factors by their Base.
87 struct BaseSorter {
88 bool operator()(const Factor &LHS, const Factor &RHS) {
89 return LHS.Base < RHS.Base;
90 }
91 };
92
93 /// \brief Compare factors for equal bases.
94 struct BaseEqual {
95 bool operator()(const Factor &LHS, const Factor &RHS) {
96 return LHS.Base == RHS.Base;
97 }
98 };
99
100 /// \brief Sort factors in descending order by their power.
101 struct PowerDescendingSorter {
102 bool operator()(const Factor &LHS, const Factor &RHS) {
103 return LHS.Power > RHS.Power;
104 }
105 };
106
107 /// \brief Compare factors for equal powers.
108 struct PowerEqual {
109 bool operator()(const Factor &LHS, const Factor &RHS) {
110 return LHS.Power == RHS.Power;
111 }
112 };
113 };
114}
115
116namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000117 class Reassociate : public FunctionPass {
Chris Lattnerf55e7f52010-01-01 00:01:34 +0000118 DenseMap<BasicBlock*, unsigned> RankMap;
Craig Topperf1d0f772012-03-26 06:58:25 +0000119 DenseMap<AssertingVH<Value>, unsigned> ValueRankMap;
Duncan Sands841f4262012-06-08 20:15:33 +0000120 SetVector<AssertingVH<Instruction> > RedoInsts;
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000121 bool MadeChange;
Chris Lattner4fd56002002-05-08 22:19:27 +0000122 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000123 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000124 Reassociate() : FunctionPass(ID) {
125 initializeReassociatePass(*PassRegistry::getPassRegistry());
126 }
Devang Patel794fd752007-05-01 21:15:47 +0000127
Chris Lattner7e708292002-06-25 16:13:24 +0000128 bool runOnFunction(Function &F);
Chris Lattner4fd56002002-05-08 22:19:27 +0000129
130 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnercb2610e2002-10-21 20:00:28 +0000131 AU.setPreservesCFG();
Chris Lattner4fd56002002-05-08 22:19:27 +0000132 }
133 private:
Chris Lattner7e708292002-06-25 16:13:24 +0000134 void BuildRankMap(Function &F);
Chris Lattner4fd56002002-05-08 22:19:27 +0000135 unsigned getRank(Value *V);
Chris Lattner69e98e22009-12-31 19:24:52 +0000136 Value *ReassociateExpression(BinaryOperator *I);
Duncan Sands0fd120b2012-05-25 12:03:02 +0000137 void RewriteExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
Chris Lattner9f7b7082009-12-31 18:40:32 +0000138 Value *OptimizeExpression(BinaryOperator *I,
139 SmallVectorImpl<ValueEntry> &Ops);
140 Value *OptimizeAdd(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
Chandler Carruth464bda32012-04-26 05:30:30 +0000141 bool collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
142 SmallVectorImpl<Factor> &Factors);
143 Value *buildMinimalMultiplyDAG(IRBuilder<> &Builder,
144 SmallVectorImpl<Factor> &Factors);
145 Value *OptimizeMul(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
Chris Lattner9f7b7082009-12-31 18:40:32 +0000146 void LinearizeExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
Chris Lattnere5022fe2006-03-04 09:31:13 +0000147 Value *RemoveFactorFromExpression(Value *V, Value *Factor);
Duncan Sands841f4262012-06-08 20:15:33 +0000148 void EraseInst(Instruction *I);
149 void OptimizeInst(Instruction *I);
Chris Lattner4fd56002002-05-08 22:19:27 +0000150 };
151}
152
Dan Gohman844731a2008-05-13 00:00:25 +0000153char Reassociate::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000154INITIALIZE_PASS(Reassociate, "reassociate",
Owen Andersonce665bd2010-10-07 22:25:06 +0000155 "Reassociate expressions", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000156
Brian Gaeked0fde302003-11-11 22:41:34 +0000157// Public interface to the Reassociate pass
Chris Lattnerd7456022004-01-09 06:02:20 +0000158FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
Chris Lattner4fd56002002-05-08 22:19:27 +0000159
Duncan Sands0fd120b2012-05-25 12:03:02 +0000160/// isReassociableOp - Return true if V is an instruction of the specified
161/// opcode and if it only has one use.
162static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
163 if (V->hasOneUse() && isa<Instruction>(V) &&
164 cast<Instruction>(V)->getOpcode() == Opcode)
165 return cast<BinaryOperator>(V);
166 return 0;
167}
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000168
Chris Lattner9c723192005-05-08 20:57:04 +0000169static bool isUnmovableInstruction(Instruction *I) {
170 if (I->getOpcode() == Instruction::PHI ||
Bill Wendling98bda3d2012-05-04 04:22:32 +0000171 I->getOpcode() == Instruction::LandingPad ||
Chris Lattner9c723192005-05-08 20:57:04 +0000172 I->getOpcode() == Instruction::Alloca ||
173 I->getOpcode() == Instruction::Load ||
Chris Lattner9c723192005-05-08 20:57:04 +0000174 I->getOpcode() == Instruction::Invoke ||
Dale Johannesen03afd022009-03-06 01:41:59 +0000175 (I->getOpcode() == Instruction::Call &&
176 !isa<DbgInfoIntrinsic>(I)) ||
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000177 I->getOpcode() == Instruction::UDiv ||
Reid Spencer1628cec2006-10-26 06:15:43 +0000178 I->getOpcode() == Instruction::SDiv ||
179 I->getOpcode() == Instruction::FDiv ||
Reid Spencer0a783f72006-11-02 01:53:59 +0000180 I->getOpcode() == Instruction::URem ||
181 I->getOpcode() == Instruction::SRem ||
182 I->getOpcode() == Instruction::FRem)
Chris Lattner9c723192005-05-08 20:57:04 +0000183 return true;
184 return false;
185}
186
Chris Lattner7e708292002-06-25 16:13:24 +0000187void Reassociate::BuildRankMap(Function &F) {
Chris Lattner6007cb62003-08-12 20:14:27 +0000188 unsigned i = 2;
Chris Lattnerfb5be092003-08-13 16:16:26 +0000189
190 // Assign distinct ranks to function arguments
Chris Lattnere4d5c442005-03-15 04:54:21 +0000191 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattnerd3c7b732009-03-31 22:13:29 +0000192 ValueRankMap[&*I] = ++i;
Chris Lattnerfb5be092003-08-13 16:16:26 +0000193
Chris Lattner7e708292002-06-25 16:13:24 +0000194 ReversePostOrderTraversal<Function*> RPOT(&F);
Chris Lattner4fd56002002-05-08 22:19:27 +0000195 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
Chris Lattner9c723192005-05-08 20:57:04 +0000196 E = RPOT.end(); I != E; ++I) {
197 BasicBlock *BB = *I;
198 unsigned BBRank = RankMap[BB] = ++i << 16;
199
200 // Walk the basic block, adding precomputed ranks for any instructions that
201 // we cannot move. This ensures that the ranks for these instructions are
202 // all different in the block.
203 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
204 if (isUnmovableInstruction(I))
Chris Lattnerd3c7b732009-03-31 22:13:29 +0000205 ValueRankMap[&*I] = ++BBRank;
Chris Lattner9c723192005-05-08 20:57:04 +0000206 }
Chris Lattner4fd56002002-05-08 22:19:27 +0000207}
208
209unsigned Reassociate::getRank(Value *V) {
Chris Lattner08b43922005-05-07 04:08:02 +0000210 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerf55e7f52010-01-01 00:01:34 +0000211 if (I == 0) {
212 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument.
213 return 0; // Otherwise it's a global or constant, rank 0.
214 }
Chris Lattner4fd56002002-05-08 22:19:27 +0000215
Chris Lattnerf55e7f52010-01-01 00:01:34 +0000216 if (unsigned Rank = ValueRankMap[I])
217 return Rank; // Rank already known?
Jeff Cohen00b168892005-07-27 06:12:32 +0000218
Chris Lattner08b43922005-05-07 04:08:02 +0000219 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
220 // we can reassociate expressions for code motion! Since we do not recurse
221 // for PHI nodes, we cannot have infinite recursion here, because there
222 // cannot be loops in the value graph that do not go through PHI nodes.
Chris Lattner08b43922005-05-07 04:08:02 +0000223 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
224 for (unsigned i = 0, e = I->getNumOperands();
225 i != e && Rank != MaxRank; ++i)
226 Rank = std::max(Rank, getRank(I->getOperand(i)));
Jeff Cohen00b168892005-07-27 06:12:32 +0000227
Chris Lattnercc8a2b92005-05-08 00:08:33 +0000228 // If this is a not or neg instruction, do not count it for rank. This
229 // assures us that X and ~X will have the same rank.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000230 if (!I->getType()->isIntegerTy() ||
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000231 (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
Chris Lattnercc8a2b92005-05-08 00:08:33 +0000232 ++Rank;
233
David Greenea1fa76c2010-01-05 01:27:24 +0000234 //DEBUG(dbgs() << "Calculated Rank[" << V->getName() << "] = "
Chris Lattnerbdff5482009-08-23 04:37:46 +0000235 // << Rank << "\n");
Jeff Cohen00b168892005-07-27 06:12:32 +0000236
Chris Lattnerf55e7f52010-01-01 00:01:34 +0000237 return ValueRankMap[I] = Rank;
Chris Lattner4fd56002002-05-08 22:19:27 +0000238}
239
Chris Lattnerf33151a2005-05-08 21:28:52 +0000240/// LowerNegateToMultiply - Replace 0-X with X*-1.
241///
Duncan Sands841f4262012-06-08 20:15:33 +0000242static BinaryOperator *LowerNegateToMultiply(Instruction *Neg) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000243 Constant *Cst = Constant::getAllOnesValue(Neg->getType());
Chris Lattnerf33151a2005-05-08 21:28:52 +0000244
Duncan Sands0fd120b2012-05-25 12:03:02 +0000245 BinaryOperator *Res =
246 BinaryOperator::CreateMul(Neg->getOperand(1), Cst, "",Neg);
Duncan Sands841f4262012-06-08 20:15:33 +0000247 Neg->setOperand(1, Constant::getNullValue(Neg->getType())); // Drop use of op.
Chris Lattner6934a042007-02-11 01:23:03 +0000248 Res->takeName(Neg);
Chris Lattnerf33151a2005-05-08 21:28:52 +0000249 Neg->replaceAllUsesWith(Res);
Devang Patel5367b232011-04-28 22:48:14 +0000250 Res->setDebugLoc(Neg->getDebugLoc());
Chris Lattnerf33151a2005-05-08 21:28:52 +0000251 return Res;
252}
253
Duncan Sands0fd120b2012-05-25 12:03:02 +0000254/// LinearizeExprTree - Given an associative binary expression, return the leaf
255/// nodes in Ops. The original expression is the same as Ops[0] op ... Ops[N].
256/// Note that a node may occur multiple times in Ops, but if so all occurrences
257/// are consecutive in the vector.
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000258///
Duncan Sands0fd120b2012-05-25 12:03:02 +0000259/// A leaf node is either not a binary operation of the same kind as the root
260/// node 'I' (i.e. is not a binary operator at all, or is, but with a different
261/// opcode), or is the same kind of binary operator but has a use which either
262/// does not belong to the expression, or does belong to the expression but is
263/// a leaf node. Every leaf node has at least one use that is a non-leaf node
264/// of the expression, while for non-leaf nodes (except for the root 'I') every
265/// use is a non-leaf node of the expression.
266///
267/// For example:
268/// expression graph node names
269///
270/// + | I
271/// / \ |
272/// + + | A, B
273/// / \ / \ |
274/// * + * | C, D, E
275/// / \ / \ / \ |
276/// + * | F, G
277///
278/// The leaf nodes are C, E, F and G. The Ops array will contain (maybe not in
279/// that order) C, E, F, F, G, G.
280///
281/// The expression is maximal: if some instruction is a binary operator of the
282/// same kind as 'I', and all of its uses are non-leaf nodes of the expression,
283/// then the instruction also belongs to the expression, is not a leaf node of
284/// it, and its operands also belong to the expression (but may be leaf nodes).
285///
286/// NOTE: This routine will set operands of non-leaf non-root nodes to undef in
287/// order to ensure that every non-root node in the expression has *exactly one*
288/// use by a non-leaf node of the expression. This destruction means that the
Duncan Sandseacc31a2012-05-26 16:42:52 +0000289/// caller MUST either replace 'I' with a new expression or use something like
290/// RewriteExprTree to put the values back in.
Chris Lattnere9efecb2006-03-14 16:04:29 +0000291///
Duncan Sands0fd120b2012-05-25 12:03:02 +0000292/// In the above example either the right operand of A or the left operand of B
293/// will be replaced by undef. If it is B's operand then this gives:
294///
295/// + | I
296/// / \ |
297/// + + | A, B - operand of B replaced with undef
298/// / \ \ |
299/// * + * | C, D, E
300/// / \ / \ / \ |
301/// + * | F, G
302///
Duncan Sandseacc31a2012-05-26 16:42:52 +0000303/// Note that such undef operands can only be reached by passing through 'I'.
304/// For example, if you visit operands recursively starting from a leaf node
305/// then you will never see such an undef operand unless you get back to 'I',
Duncan Sands0fd120b2012-05-25 12:03:02 +0000306/// which requires passing through a phi node.
307///
308/// Note that this routine may also mutate binary operators of the wrong type
309/// that have all uses inside the expression (i.e. only used by non-leaf nodes
310/// of the expression) if it can turn them into binary operators of the right
311/// type and thus make the expression bigger.
312
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000313void Reassociate::LinearizeExprTree(BinaryOperator *I,
Chris Lattner9f7b7082009-12-31 18:40:32 +0000314 SmallVectorImpl<ValueEntry> &Ops) {
Duncan Sands0fd120b2012-05-25 12:03:02 +0000315 DEBUG(dbgs() << "LINEARIZE: " << *I << '\n');
316
317 // Visit all operands of the expression, keeping track of their weight (the
318 // number of paths from the expression root to the operand, or if you like
319 // the number of times that operand occurs in the linearized expression).
320 // For example, if I = X + A, where X = A + B, then I, X and B have weight 1
321 // while A has weight two.
322
323 // Worklist of non-leaf nodes (their operands are in the expression too) along
324 // with their weights, representing a certain number of paths to the operator.
325 // If an operator occurs in the worklist multiple times then we found multiple
326 // ways to get to it.
327 SmallVector<std::pair<BinaryOperator*, unsigned>, 8> Worklist; // (Op, Weight)
328 Worklist.push_back(std::make_pair(I, 1));
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000329 unsigned Opcode = I->getOpcode();
330
Duncan Sands0fd120b2012-05-25 12:03:02 +0000331 // Leaves of the expression are values that either aren't the right kind of
332 // operation (eg: a constant, or a multiply in an add tree), or are, but have
333 // some uses that are not inside the expression. For example, in I = X + X,
334 // X = A + B, the value X has two uses (by I) that are in the expression. If
335 // X has any other uses, for example in a return instruction, then we consider
336 // X to be a leaf, and won't analyze it further. When we first visit a value,
337 // if it has more than one use then at first we conservatively consider it to
338 // be a leaf. Later, as the expression is explored, we may discover some more
339 // uses of the value from inside the expression. If all uses turn out to be
340 // from within the expression (and the value is a binary operator of the right
341 // kind) then the value is no longer considered to be a leaf, and its operands
342 // are explored.
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000343
Duncan Sands0fd120b2012-05-25 12:03:02 +0000344 // Leaves - Keeps track of the set of putative leaves as well as the number of
345 // paths to each leaf seen so far.
346 typedef SmallMap<Value*, unsigned, 8> LeafMap;
347 LeafMap Leaves; // Leaf -> Total weight so far.
348 SmallVector<Value*, 8> LeafOrder; // Ensure deterministic leaf output order.
349
350#ifndef NDEBUG
351 SmallPtrSet<Value*, 8> Visited; // For sanity checking the iteration scheme.
352#endif
353 while (!Worklist.empty()) {
354 std::pair<BinaryOperator*, unsigned> P = Worklist.pop_back_val();
355 I = P.first; // We examine the operands of this binary operator.
356 assert(P.second >= 1 && "No paths to here, so how did we get here?!");
357
358 for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx) { // Visit operands.
359 Value *Op = I->getOperand(OpIdx);
360 unsigned Weight = P.second; // Number of paths to this operand.
361 DEBUG(dbgs() << "OPERAND: " << *Op << " (" << Weight << ")\n");
362 assert(!Op->use_empty() && "No uses, so how did we get to it?!");
363
364 // If this is a binary operation of the right kind with only one use then
365 // add its operands to the expression.
366 if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
367 assert(Visited.insert(Op) && "Not first visit!");
368 DEBUG(dbgs() << "DIRECT ADD: " << *Op << " (" << Weight << ")\n");
369 Worklist.push_back(std::make_pair(BO, Weight));
370 continue;
371 }
372
373 // Appears to be a leaf. Is the operand already in the set of leaves?
374 LeafMap::iterator It = Leaves.find(Op);
375 if (It == Leaves.end()) {
376 // Not in the leaf map. Must be the first time we saw this operand.
377 assert(Visited.insert(Op) && "Not first visit!");
378 if (!Op->hasOneUse()) {
379 // This value has uses not accounted for by the expression, so it is
380 // not safe to modify. Mark it as being a leaf.
381 DEBUG(dbgs() << "ADD USES LEAF: " << *Op << " (" << Weight << ")\n");
382 LeafOrder.push_back(Op);
383 Leaves[Op] = Weight;
384 continue;
385 }
386 // No uses outside the expression, try morphing it.
387 } else if (It != Leaves.end()) {
388 // Already in the leaf map.
389 assert(Visited.count(Op) && "In leaf map but not visited!");
390
391 // Update the number of paths to the leaf.
392 It->second += Weight;
393
394 // The leaf already has one use from inside the expression. As we want
395 // exactly one such use, drop this new use of the leaf.
396 assert(!Op->hasOneUse() && "Only one use, but we got here twice!");
397 I->setOperand(OpIdx, UndefValue::get(I->getType()));
398 MadeChange = true;
399
400 // If the leaf is a binary operation of the right kind and we now see
401 // that its multiple original uses were in fact all by nodes belonging
402 // to the expression, then no longer consider it to be a leaf and add
403 // its operands to the expression.
404 if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
405 DEBUG(dbgs() << "UNLEAF: " << *Op << " (" << It->second << ")\n");
406 Worklist.push_back(std::make_pair(BO, It->second));
407 Leaves.erase(It);
408 continue;
409 }
410
411 // If we still have uses that are not accounted for by the expression
412 // then it is not safe to modify the value.
413 if (!Op->hasOneUse())
414 continue;
415
416 // No uses outside the expression, try morphing it.
417 Weight = It->second;
418 Leaves.erase(It); // Since the value may be morphed below.
419 }
420
421 // At this point we have a value which, first of all, is not a binary
422 // expression of the right kind, and secondly, is only used inside the
423 // expression. This means that it can safely be modified. See if we
424 // can usefully morph it into an expression of the right kind.
425 assert((!isa<Instruction>(Op) ||
426 cast<Instruction>(Op)->getOpcode() != Opcode) &&
427 "Should have been handled above!");
428 assert(Op->hasOneUse() && "Has uses outside the expression tree!");
429
430 // If this is a multiply expression, turn any internal negations into
431 // multiplies by -1 so they can be reassociated.
432 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op);
433 if (Opcode == Instruction::Mul && BO && BinaryOperator::isNeg(BO)) {
434 DEBUG(dbgs() << "MORPH LEAF: " << *Op << " (" << Weight << ") TO ");
Duncan Sands841f4262012-06-08 20:15:33 +0000435 BO = LowerNegateToMultiply(BO);
Duncan Sands0fd120b2012-05-25 12:03:02 +0000436 DEBUG(dbgs() << *BO << 'n');
437 Worklist.push_back(std::make_pair(BO, Weight));
438 MadeChange = true;
439 continue;
440 }
441
442 // Failed to morph into an expression of the right type. This really is
443 // a leaf.
444 DEBUG(dbgs() << "ADD LEAF: " << *Op << " (" << Weight << ")\n");
445 assert(!isReassociableOp(Op, Opcode) && "Value was morphed?");
446 LeafOrder.push_back(Op);
447 Leaves[Op] = Weight;
Chris Lattnerf33151a2005-05-08 21:28:52 +0000448 }
449 }
450
Duncan Sands0fd120b2012-05-25 12:03:02 +0000451 // The leaves, repeated according to their weights, represent the linearized
452 // form of the expression.
453 for (unsigned i = 0, e = LeafOrder.size(); i != e; ++i) {
454 Value *V = LeafOrder[i];
455 LeafMap::iterator It = Leaves.find(V);
456 if (It == Leaves.end())
457 // Leaf already output, or node initially thought to be a leaf wasn't.
458 continue;
459 assert(!isReassociableOp(V, Opcode) && "Shouldn't be a leaf!");
460 unsigned Weight = It->second;
461 assert(Weight > 0 && "No paths to this value!");
462 // FIXME: Rather than repeating values Weight times, use a vector of
463 // (ValueEntry, multiplicity) pairs.
464 Ops.append(Weight, ValueEntry(getRank(V), V));
465 // Ensure the leaf is only output once.
466 Leaves.erase(It);
Chris Lattner4fd56002002-05-08 22:19:27 +0000467 }
Chris Lattner4fd56002002-05-08 22:19:27 +0000468}
469
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000470// RewriteExprTree - Now that the operands for this expression tree are
Duncan Sands0fd120b2012-05-25 12:03:02 +0000471// linearized and optimized, emit them in-order.
Chris Lattnere9efecb2006-03-14 16:04:29 +0000472void Reassociate::RewriteExprTree(BinaryOperator *I,
Duncan Sands0fd120b2012-05-25 12:03:02 +0000473 SmallVectorImpl<ValueEntry> &Ops) {
474 assert(Ops.size() > 1 && "Single values should be used directly!");
Dan Gohman46985a12011-02-02 02:02:34 +0000475
Duncan Sands0fd120b2012-05-25 12:03:02 +0000476 // Since our optimizations never increase the number of operations, the new
477 // expression can always be written by reusing the existing binary operators
478 // from the original expression tree, without creating any new instructions,
479 // though the rewritten expression may have a completely different topology.
480 // We take care to not change anything if the new expression will be the same
481 // as the original. If more than trivial changes (like commuting operands)
482 // were made then we are obliged to clear out any optional subclass data like
483 // nsw flags.
Dan Gohman46985a12011-02-02 02:02:34 +0000484
Duncan Sands0fd120b2012-05-25 12:03:02 +0000485 /// NodesToRewrite - Nodes from the original expression available for writing
486 /// the new expression into.
487 SmallVector<BinaryOperator*, 8> NodesToRewrite;
488 unsigned Opcode = I->getOpcode();
489 NodesToRewrite.push_back(I);
490
Duncan Sandseacc31a2012-05-26 16:42:52 +0000491 // ExpressionChanged - Non-null if the rewritten expression differs from the
492 // original in some non-trivial way, requiring the clearing of optional flags.
493 // Flags are cleared from the operator in ExpressionChanged up to I inclusive.
494 BinaryOperator *ExpressionChanged = 0;
Duncan Sands0fd120b2012-05-25 12:03:02 +0000495 BinaryOperator *Previous;
496 BinaryOperator *Op = 0;
497 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
498 assert(!NodesToRewrite.empty() &&
499 "Optimized expressions has more nodes than original!");
500 Previous = Op; Op = NodesToRewrite.pop_back_val();
Duncan Sandseacc31a2012-05-26 16:42:52 +0000501 if (ExpressionChanged)
502 // Compactify the tree instructions together with each other to guarantee
503 // that the expression tree is dominated by all of Ops.
Duncan Sands0fd120b2012-05-25 12:03:02 +0000504 Op->moveBefore(Previous);
505
506 // The last operation (which comes earliest in the IR) is special as both
507 // operands will come from Ops, rather than just one with the other being
508 // a subexpression.
509 if (i+2 == Ops.size()) {
510 Value *NewLHS = Ops[i].Op;
511 Value *NewRHS = Ops[i+1].Op;
512 Value *OldLHS = Op->getOperand(0);
513 Value *OldRHS = Op->getOperand(1);
514
515 if (NewLHS == OldLHS && NewRHS == OldRHS)
516 // Nothing changed, leave it alone.
517 break;
518
519 if (NewLHS == OldRHS && NewRHS == OldLHS) {
520 // The order of the operands was reversed. Swap them.
521 DEBUG(dbgs() << "RA: " << *Op << '\n');
522 Op->swapOperands();
523 DEBUG(dbgs() << "TO: " << *Op << '\n');
524 MadeChange = true;
525 ++NumChanged;
526 break;
527 }
528
529 // The new operation differs non-trivially from the original. Overwrite
530 // the old operands with the new ones.
531 DEBUG(dbgs() << "RA: " << *Op << '\n');
532 if (NewLHS != OldLHS) {
533 if (BinaryOperator *BO = isReassociableOp(OldLHS, Opcode))
534 NodesToRewrite.push_back(BO);
535 Op->setOperand(0, NewLHS);
536 }
537 if (NewRHS != OldRHS) {
538 if (BinaryOperator *BO = isReassociableOp(OldRHS, Opcode))
539 NodesToRewrite.push_back(BO);
540 Op->setOperand(1, NewRHS);
541 }
542 DEBUG(dbgs() << "TO: " << *Op << '\n');
543
Duncan Sandseacc31a2012-05-26 16:42:52 +0000544 ExpressionChanged = Op;
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000545 MadeChange = true;
546 ++NumChanged;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000547
Duncan Sands0fd120b2012-05-25 12:03:02 +0000548 break;
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000549 }
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000550
Duncan Sands0fd120b2012-05-25 12:03:02 +0000551 // Not the last operation. The left-hand side will be a sub-expression
552 // while the right-hand side will be the current element of Ops.
553 Value *NewRHS = Ops[i].Op;
554 if (NewRHS != Op->getOperand(1)) {
555 DEBUG(dbgs() << "RA: " << *Op << '\n');
556 if (NewRHS == Op->getOperand(0)) {
557 // The new right-hand side was already present as the left operand. If
558 // we are lucky then swapping the operands will sort out both of them.
559 Op->swapOperands();
560 } else {
561 // Overwrite with the new right-hand side.
562 if (BinaryOperator *BO = isReassociableOp(Op->getOperand(1), Opcode))
563 NodesToRewrite.push_back(BO);
564 Op->setOperand(1, NewRHS);
Duncan Sandseacc31a2012-05-26 16:42:52 +0000565 ExpressionChanged = Op;
Duncan Sands0fd120b2012-05-25 12:03:02 +0000566 }
567 DEBUG(dbgs() << "TO: " << *Op << '\n');
568 MadeChange = true;
569 ++NumChanged;
570 }
Dan Gohman46985a12011-02-02 02:02:34 +0000571
Duncan Sands0fd120b2012-05-25 12:03:02 +0000572 // Now deal with the left-hand side. If this is already an operation node
573 // from the original expression then just rewrite the rest of the expression
574 // into it.
575 if (BinaryOperator *BO = isReassociableOp(Op->getOperand(0), Opcode)) {
576 NodesToRewrite.push_back(BO);
577 continue;
578 }
Dan Gohman46985a12011-02-02 02:02:34 +0000579
Duncan Sands0fd120b2012-05-25 12:03:02 +0000580 // Otherwise, grab a spare node from the original expression and use that as
581 // the left-hand side.
582 assert(!NodesToRewrite.empty() &&
583 "Optimized expressions has more nodes than original!");
584 DEBUG(dbgs() << "RA: " << *Op << '\n');
585 Op->setOperand(0, NodesToRewrite.back());
586 DEBUG(dbgs() << "TO: " << *Op << '\n');
Duncan Sandseacc31a2012-05-26 16:42:52 +0000587 ExpressionChanged = Op;
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000588 MadeChange = true;
589 ++NumChanged;
590 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000591
Duncan Sandseacc31a2012-05-26 16:42:52 +0000592 // If the expression changed non-trivially then clear out all subclass data
593 // starting from the operator specified in ExpressionChanged.
Duncan Sands0fd120b2012-05-25 12:03:02 +0000594 if (ExpressionChanged) {
595 do {
Duncan Sandseacc31a2012-05-26 16:42:52 +0000596 ExpressionChanged->clearSubclassOptionalData();
597 if (ExpressionChanged == I)
Duncan Sands0fd120b2012-05-25 12:03:02 +0000598 break;
Duncan Sandseacc31a2012-05-26 16:42:52 +0000599 ExpressionChanged = cast<BinaryOperator>(*ExpressionChanged->use_begin());
Duncan Sands0fd120b2012-05-25 12:03:02 +0000600 } while (1);
601 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000602
Duncan Sands0fd120b2012-05-25 12:03:02 +0000603 // Throw away any left over nodes from the original expression.
604 for (unsigned i = 0, e = NodesToRewrite.size(); i != e; ++i)
Duncan Sands841f4262012-06-08 20:15:33 +0000605 RedoInsts.insert(NodesToRewrite[i]);
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000606}
607
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000608/// NegateValue - Insert instructions before the instruction pointed to by BI,
609/// that computes the negative version of the value specified. The negative
610/// version of the value is returned, and BI is left pointing at the instruction
611/// that should be processed next by the reassociation pass.
Nick Lewyckye79fdde2009-11-14 07:25:54 +0000612static Value *NegateValue(Value *V, Instruction *BI) {
Chris Lattner35239932009-12-31 20:34:32 +0000613 if (Constant *C = dyn_cast<Constant>(V))
614 return ConstantExpr::getNeg(C);
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000615
Chris Lattnera36e6c82002-05-16 04:37:07 +0000616 // We are trying to expose opportunity for reassociation. One of the things
617 // that we want to do to achieve this is to push a negation as deep into an
618 // expression chain as possible, to expose the add instructions. In practice,
619 // this means that we turn this:
620 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
621 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
622 // the constants. We assume that instcombine will clean up the mess later if
Chris Lattner90461932010-01-01 00:04:26 +0000623 // we introduce tons of unnecessary negation instructions.
Chris Lattnera36e6c82002-05-16 04:37:07 +0000624 //
Duncan Sands0fd120b2012-05-25 12:03:02 +0000625 if (BinaryOperator *I = isReassociableOp(V, Instruction::Add)) {
626 // Push the negates through the add.
627 I->setOperand(0, NegateValue(I->getOperand(0), BI));
628 I->setOperand(1, NegateValue(I->getOperand(1), BI));
Chris Lattnera36e6c82002-05-16 04:37:07 +0000629
Duncan Sands0fd120b2012-05-25 12:03:02 +0000630 // We must move the add instruction here, because the neg instructions do
631 // not dominate the old add instruction in general. By moving it, we are
632 // assured that the neg instructions we just inserted dominate the
633 // instruction we are about to insert after them.
634 //
635 I->moveBefore(BI);
636 I->setName(I->getName()+".neg");
637 return I;
638 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000639
Chris Lattner35239932009-12-31 20:34:32 +0000640 // Okay, we need to materialize a negated version of V with an instruction.
641 // Scan the use lists of V to see if we have one already.
642 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Gabor Greif110b75a2010-07-12 12:03:02 +0000643 User *U = *UI;
644 if (!BinaryOperator::isNeg(U)) continue;
Chris Lattner35239932009-12-31 20:34:32 +0000645
646 // We found one! Now we have to make sure that the definition dominates
647 // this use. We do this by moving it to the entry block (if it is a
648 // non-instruction value) or right after the definition. These negates will
649 // be zapped by reassociate later, so we don't need much finesse here.
Gabor Greif110b75a2010-07-12 12:03:02 +0000650 BinaryOperator *TheNeg = cast<BinaryOperator>(U);
Chris Lattner1c91fae2010-01-02 21:46:33 +0000651
652 // Verify that the negate is in this function, V might be a constant expr.
653 if (TheNeg->getParent()->getParent() != BI->getParent()->getParent())
654 continue;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000655
Chris Lattner35239932009-12-31 20:34:32 +0000656 BasicBlock::iterator InsertPt;
657 if (Instruction *InstInput = dyn_cast<Instruction>(V)) {
658 if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
659 InsertPt = II->getNormalDest()->begin();
660 } else {
661 InsertPt = InstInput;
662 ++InsertPt;
663 }
664 while (isa<PHINode>(InsertPt)) ++InsertPt;
665 } else {
666 InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
667 }
668 TheNeg->moveBefore(InsertPt);
669 return TheNeg;
670 }
Chris Lattnera36e6c82002-05-16 04:37:07 +0000671
672 // Insert a 'neg' instruction that subtracts the value from zero to get the
673 // negation.
Dan Gohman4ae51262009-08-12 16:23:25 +0000674 return BinaryOperator::CreateNeg(V, V->getName() + ".neg", BI);
Chris Lattner08b43922005-05-07 04:08:02 +0000675}
676
Chris Lattner9bc5ed72008-02-17 20:44:51 +0000677/// ShouldBreakUpSubtract - Return true if we should break up this subtract of
678/// X-Y into (X + -Y).
Nick Lewyckye79fdde2009-11-14 07:25:54 +0000679static bool ShouldBreakUpSubtract(Instruction *Sub) {
Chris Lattner9bc5ed72008-02-17 20:44:51 +0000680 // If this is a negation, we can't split it up!
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000681 if (BinaryOperator::isNeg(Sub))
Chris Lattner9bc5ed72008-02-17 20:44:51 +0000682 return false;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000683
Chris Lattner9bc5ed72008-02-17 20:44:51 +0000684 // Don't bother to break this up unless either the LHS is an associable add or
Chris Lattner0b0803a2008-02-17 20:51:26 +0000685 // subtract or if this is only used by one.
686 if (isReassociableOp(Sub->getOperand(0), Instruction::Add) ||
687 isReassociableOp(Sub->getOperand(0), Instruction::Sub))
Chris Lattner9bc5ed72008-02-17 20:44:51 +0000688 return true;
Chris Lattner0b0803a2008-02-17 20:51:26 +0000689 if (isReassociableOp(Sub->getOperand(1), Instruction::Add) ||
Chris Lattner5329bb22008-02-17 20:54:40 +0000690 isReassociableOp(Sub->getOperand(1), Instruction::Sub))
Chris Lattner9bc5ed72008-02-17 20:44:51 +0000691 return true;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000692 if (Sub->hasOneUse() &&
Chris Lattner0b0803a2008-02-17 20:51:26 +0000693 (isReassociableOp(Sub->use_back(), Instruction::Add) ||
694 isReassociableOp(Sub->use_back(), Instruction::Sub)))
Chris Lattner9bc5ed72008-02-17 20:44:51 +0000695 return true;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000696
Chris Lattner9bc5ed72008-02-17 20:44:51 +0000697 return false;
698}
699
Chris Lattner08b43922005-05-07 04:08:02 +0000700/// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
701/// only used by an add, transform this into (X+(0-Y)) to promote better
702/// reassociation.
Duncan Sands841f4262012-06-08 20:15:33 +0000703static BinaryOperator *BreakUpSubtract(Instruction *Sub) {
Chris Lattner90461932010-01-01 00:04:26 +0000704 // Convert a subtract into an add and a neg instruction. This allows sub
705 // instructions to be commuted with other add instructions.
Chris Lattner08b43922005-05-07 04:08:02 +0000706 //
Chris Lattner90461932010-01-01 00:04:26 +0000707 // Calculate the negative value of Operand 1 of the sub instruction,
708 // and set it as the RHS of the add instruction we just made.
Chris Lattner08b43922005-05-07 04:08:02 +0000709 //
Nick Lewyckye79fdde2009-11-14 07:25:54 +0000710 Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
Duncan Sands841f4262012-06-08 20:15:33 +0000711 BinaryOperator *New =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000712 BinaryOperator::CreateAdd(Sub->getOperand(0), NegVal, "", Sub);
Duncan Sands841f4262012-06-08 20:15:33 +0000713 Sub->setOperand(0, Constant::getNullValue(Sub->getType())); // Drop use of op.
714 Sub->setOperand(1, Constant::getNullValue(Sub->getType())); // Drop use of op.
Chris Lattner6934a042007-02-11 01:23:03 +0000715 New->takeName(Sub);
Chris Lattner08b43922005-05-07 04:08:02 +0000716
717 // Everyone now refers to the add instruction.
718 Sub->replaceAllUsesWith(New);
Devang Patel5367b232011-04-28 22:48:14 +0000719 New->setDebugLoc(Sub->getDebugLoc());
Jeff Cohen00b168892005-07-27 06:12:32 +0000720
David Greenea1fa76c2010-01-05 01:27:24 +0000721 DEBUG(dbgs() << "Negated: " << *New << '\n');
Chris Lattner08b43922005-05-07 04:08:02 +0000722 return New;
Chris Lattnera36e6c82002-05-16 04:37:07 +0000723}
724
Chris Lattner0975ed52005-05-07 04:24:13 +0000725/// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
726/// by one, change this into a multiply by a constant to assist with further
727/// reassociation.
Duncan Sands841f4262012-06-08 20:15:33 +0000728static BinaryOperator *ConvertShiftToMul(Instruction *Shl) {
729 Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
730 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000731
Duncan Sands841f4262012-06-08 20:15:33 +0000732 BinaryOperator *Mul =
733 BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, "", Shl);
734 Shl->setOperand(0, UndefValue::get(Shl->getType())); // Drop use of op.
735 Mul->takeName(Shl);
736 Shl->replaceAllUsesWith(Mul);
737 Mul->setDebugLoc(Shl->getDebugLoc());
738 return Mul;
Chris Lattner0975ed52005-05-07 04:24:13 +0000739}
740
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000741/// FindInOperandList - Scan backwards and forwards among values with the same
742/// rank as element i to see if X exists. If X does not exist, return i. This
743/// is useful when scanning for 'x' when we see '-x' because they both get the
744/// same rank.
Chris Lattner9f7b7082009-12-31 18:40:32 +0000745static unsigned FindInOperandList(SmallVectorImpl<ValueEntry> &Ops, unsigned i,
Chris Lattner109d34d2005-05-08 18:59:37 +0000746 Value *X) {
747 unsigned XRank = Ops[i].Rank;
748 unsigned e = Ops.size();
749 for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
750 if (Ops[j].Op == X)
751 return j;
Chris Lattner9506c932010-01-01 01:13:15 +0000752 // Scan backwards.
Chris Lattner109d34d2005-05-08 18:59:37 +0000753 for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
754 if (Ops[j].Op == X)
755 return j;
756 return i;
757}
758
Chris Lattnere5022fe2006-03-04 09:31:13 +0000759/// EmitAddTreeOfValues - Emit a tree of add instructions, summing Ops together
760/// and returning the result. Insert the tree before I.
Bill Wendling55e70982012-05-02 09:59:45 +0000761static Value *EmitAddTreeOfValues(Instruction *I,
762 SmallVectorImpl<WeakVH> &Ops){
Chris Lattnere5022fe2006-03-04 09:31:13 +0000763 if (Ops.size() == 1) return Ops.back();
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000764
Chris Lattnere5022fe2006-03-04 09:31:13 +0000765 Value *V1 = Ops.back();
766 Ops.pop_back();
767 Value *V2 = EmitAddTreeOfValues(I, Ops);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000768 return BinaryOperator::CreateAdd(V2, V1, "tmp", I);
Chris Lattnere5022fe2006-03-04 09:31:13 +0000769}
770
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000771/// RemoveFactorFromExpression - If V is an expression tree that is a
Chris Lattnere5022fe2006-03-04 09:31:13 +0000772/// multiplication sequence, and if this sequence contains a multiply by Factor,
773/// remove Factor from the tree and return the new tree.
774Value *Reassociate::RemoveFactorFromExpression(Value *V, Value *Factor) {
775 BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
776 if (!BO) return 0;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000777
Chris Lattner9f7b7082009-12-31 18:40:32 +0000778 SmallVector<ValueEntry, 8> Factors;
Chris Lattnere5022fe2006-03-04 09:31:13 +0000779 LinearizeExprTree(BO, Factors);
780
781 bool FoundFactor = false;
Chris Lattner9506c932010-01-01 01:13:15 +0000782 bool NeedsNegate = false;
783 for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
Chris Lattnere5022fe2006-03-04 09:31:13 +0000784 if (Factors[i].Op == Factor) {
785 FoundFactor = true;
786 Factors.erase(Factors.begin()+i);
787 break;
788 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000789
Chris Lattner9506c932010-01-01 01:13:15 +0000790 // If this is a negative version of this factor, remove it.
791 if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor))
792 if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
793 if (FC1->getValue() == -FC2->getValue()) {
794 FoundFactor = NeedsNegate = true;
795 Factors.erase(Factors.begin()+i);
796 break;
797 }
798 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000799
Chris Lattnere9efecb2006-03-14 16:04:29 +0000800 if (!FoundFactor) {
801 // Make sure to restore the operands to the expression tree.
802 RewriteExprTree(BO, Factors);
803 return 0;
804 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000805
Chris Lattner9506c932010-01-01 01:13:15 +0000806 BasicBlock::iterator InsertPt = BO; ++InsertPt;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000807
Chris Lattner1e7558b2009-12-31 19:34:45 +0000808 // If this was just a single multiply, remove the multiply and return the only
809 // remaining operand.
810 if (Factors.size() == 1) {
Duncan Sands841f4262012-06-08 20:15:33 +0000811 RedoInsts.insert(BO);
Chris Lattner9506c932010-01-01 01:13:15 +0000812 V = Factors[0].Op;
813 } else {
814 RewriteExprTree(BO, Factors);
815 V = BO;
Chris Lattner1e7558b2009-12-31 19:34:45 +0000816 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000817
Chris Lattner9506c932010-01-01 01:13:15 +0000818 if (NeedsNegate)
819 V = BinaryOperator::CreateNeg(V, "neg", InsertPt);
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000820
Chris Lattner9506c932010-01-01 01:13:15 +0000821 return V;
Chris Lattnere5022fe2006-03-04 09:31:13 +0000822}
823
Chris Lattnere9efecb2006-03-14 16:04:29 +0000824/// FindSingleUseMultiplyFactors - If V is a single-use multiply, recursively
825/// add its operands as factors, otherwise add V to the list of factors.
Chris Lattner893075f2010-03-05 07:18:54 +0000826///
827/// Ops is the top-level list of add operands we're trying to factor.
Chris Lattnere9efecb2006-03-14 16:04:29 +0000828static void FindSingleUseMultiplyFactors(Value *V,
Chris Lattner893075f2010-03-05 07:18:54 +0000829 SmallVectorImpl<Value*> &Factors,
Duncan Sands0fd120b2012-05-25 12:03:02 +0000830 const SmallVectorImpl<ValueEntry> &Ops) {
831 BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
832 if (!BO) {
Chris Lattnere9efecb2006-03-14 16:04:29 +0000833 Factors.push_back(V);
834 return;
835 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000836
Chris Lattnere9efecb2006-03-14 16:04:29 +0000837 // Otherwise, add the LHS and RHS to the list of factors.
Duncan Sands0fd120b2012-05-25 12:03:02 +0000838 FindSingleUseMultiplyFactors(BO->getOperand(1), Factors, Ops);
839 FindSingleUseMultiplyFactors(BO->getOperand(0), Factors, Ops);
Chris Lattnere9efecb2006-03-14 16:04:29 +0000840}
841
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000842/// OptimizeAndOrXor - Optimize a series of operands to an 'and', 'or', or 'xor'
843/// instruction. This optimizes based on identities. If it can be reduced to
844/// a single Value, it is returned, otherwise the Ops list is mutated as
845/// necessary.
Chris Lattner9f7b7082009-12-31 18:40:32 +0000846static Value *OptimizeAndOrXor(unsigned Opcode,
847 SmallVectorImpl<ValueEntry> &Ops) {
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000848 // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
849 // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
850 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
851 // First, check for X and ~X in the operand list.
852 assert(i < Ops.size());
853 if (BinaryOperator::isNot(Ops[i].Op)) { // Cannot occur for ^.
854 Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
855 unsigned FoundX = FindInOperandList(Ops, i, X);
856 if (FoundX != i) {
Chris Lattner9fdaefa2009-12-31 17:51:05 +0000857 if (Opcode == Instruction::And) // ...&X&~X = 0
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000858 return Constant::getNullValue(X->getType());
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000859
Chris Lattner9fdaefa2009-12-31 17:51:05 +0000860 if (Opcode == Instruction::Or) // ...|X|~X = -1
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000861 return Constant::getAllOnesValue(X->getType());
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000862 }
863 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000864
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000865 // Next, check for duplicate pairs of values, which we assume are next to
866 // each other, due to our sorting criteria.
867 assert(i < Ops.size());
868 if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
869 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
Chris Lattnerf31e2e92009-12-31 19:49:01 +0000870 // Drop duplicate values for And and Or.
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000871 Ops.erase(Ops.begin()+i);
872 --i; --e;
873 ++NumAnnihil;
Chris Lattnerf31e2e92009-12-31 19:49:01 +0000874 continue;
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000875 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000876
Chris Lattnerf31e2e92009-12-31 19:49:01 +0000877 // Drop pairs of values for Xor.
878 assert(Opcode == Instruction::Xor);
879 if (e == 2)
880 return Constant::getNullValue(Ops[0].Op->getType());
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000881
Chris Lattner90461932010-01-01 00:04:26 +0000882 // Y ^ X^X -> Y
Chris Lattnerf31e2e92009-12-31 19:49:01 +0000883 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
884 i -= 1; e -= 2;
885 ++NumAnnihil;
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000886 }
887 }
888 return 0;
889}
Chris Lattnere9efecb2006-03-14 16:04:29 +0000890
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000891/// OptimizeAdd - Optimize a series of operands to an 'add' instruction. This
892/// optimizes based on identities. If it can be reduced to a single Value, it
893/// is returned, otherwise the Ops list is mutated as necessary.
Chris Lattner9f7b7082009-12-31 18:40:32 +0000894Value *Reassociate::OptimizeAdd(Instruction *I,
895 SmallVectorImpl<ValueEntry> &Ops) {
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000896 // Scan the operand lists looking for X and -X pairs. If we find any, we
Chris Lattner69e98e22009-12-31 19:24:52 +0000897 // can simplify the expression. X+-X == 0. While we're at it, scan for any
898 // duplicates. We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
Chris Lattner9506c932010-01-01 01:13:15 +0000899 //
900 // TODO: We could handle "X + ~X" -> "-1" if we wanted, since "-X = ~X+1".
901 //
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000902 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Chris Lattner69e98e22009-12-31 19:24:52 +0000903 Value *TheOp = Ops[i].Op;
904 // Check to see if we've seen this operand before. If so, we factor all
Chris Lattnerf31e2e92009-12-31 19:49:01 +0000905 // instances of the operand together. Due to our sorting criteria, we know
906 // that these need to be next to each other in the vector.
907 if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
908 // Rescan the list, remove all instances of this operand from the expr.
Chris Lattner69e98e22009-12-31 19:24:52 +0000909 unsigned NumFound = 0;
Chris Lattnerf31e2e92009-12-31 19:49:01 +0000910 do {
911 Ops.erase(Ops.begin()+i);
Chris Lattner69e98e22009-12-31 19:24:52 +0000912 ++NumFound;
Chris Lattnerf31e2e92009-12-31 19:49:01 +0000913 } while (i != Ops.size() && Ops[i].Op == TheOp);
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000914
Chris Lattnerf8a447d2009-12-31 19:25:19 +0000915 DEBUG(errs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n');
Chris Lattner69e98e22009-12-31 19:24:52 +0000916 ++NumFactor;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000917
Chris Lattner69e98e22009-12-31 19:24:52 +0000918 // Insert a new multiply.
919 Value *Mul = ConstantInt::get(cast<IntegerType>(I->getType()), NumFound);
920 Mul = BinaryOperator::CreateMul(TheOp, Mul, "factor", I);
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000921
Chris Lattner69e98e22009-12-31 19:24:52 +0000922 // Now that we have inserted a multiply, optimize it. This allows us to
923 // handle cases that require multiple factoring steps, such as this:
924 // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
Duncan Sands841f4262012-06-08 20:15:33 +0000925 RedoInsts.insert(cast<Instruction>(Mul));
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000926
Chris Lattner69e98e22009-12-31 19:24:52 +0000927 // If every add operand was a duplicate, return the multiply.
928 if (Ops.empty())
929 return Mul;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000930
Chris Lattner69e98e22009-12-31 19:24:52 +0000931 // Otherwise, we had some input that didn't have the dupe, such as
932 // "A + A + B" -> "A*2 + B". Add the new multiply to the list of
933 // things being added by this operation.
934 Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul));
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000935
Chris Lattnerf31e2e92009-12-31 19:49:01 +0000936 --i;
937 e = Ops.size();
938 continue;
Chris Lattner69e98e22009-12-31 19:24:52 +0000939 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000940
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000941 // Check for X and -X in the operand list.
Chris Lattner69e98e22009-12-31 19:24:52 +0000942 if (!BinaryOperator::isNeg(TheOp))
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000943 continue;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000944
Chris Lattner69e98e22009-12-31 19:24:52 +0000945 Value *X = BinaryOperator::getNegArgument(TheOp);
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000946 unsigned FoundX = FindInOperandList(Ops, i, X);
947 if (FoundX == i)
948 continue;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000949
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000950 // Remove X and -X from the operand list.
Chris Lattner9fdaefa2009-12-31 17:51:05 +0000951 if (Ops.size() == 2)
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000952 return Constant::getNullValue(X->getType());
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000953
Chris Lattnerf3f55a92009-12-31 07:59:34 +0000954 Ops.erase(Ops.begin()+i);
955 if (i < FoundX)
956 --FoundX;
957 else
958 --i; // Need to back up an extra one.
959 Ops.erase(Ops.begin()+FoundX);
960 ++NumAnnihil;
961 --i; // Revisit element.
962 e -= 2; // Removed two elements.
963 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000964
Chris Lattner94285e62009-12-31 18:17:13 +0000965 // Scan the operand list, checking to see if there are any common factors
966 // between operands. Consider something like A*A+A*B*C+D. We would like to
967 // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
968 // To efficiently find this, we count the number of times a factor occurs
969 // for any ADD operands that are MULs.
970 DenseMap<Value*, unsigned> FactorOccurrences;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000971
Chris Lattner94285e62009-12-31 18:17:13 +0000972 // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
973 // where they are actually the same multiply.
Chris Lattner94285e62009-12-31 18:17:13 +0000974 unsigned MaxOcc = 0;
975 Value *MaxOccVal = 0;
976 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Duncan Sands0fd120b2012-05-25 12:03:02 +0000977 BinaryOperator *BOp = isReassociableOp(Ops[i].Op, Instruction::Mul);
978 if (!BOp)
Chris Lattner94285e62009-12-31 18:17:13 +0000979 continue;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000980
Chris Lattner94285e62009-12-31 18:17:13 +0000981 // Compute all of the factors of this added value.
982 SmallVector<Value*, 8> Factors;
Duncan Sands0fd120b2012-05-25 12:03:02 +0000983 FindSingleUseMultiplyFactors(BOp, Factors, Ops);
Chris Lattner94285e62009-12-31 18:17:13 +0000984 assert(Factors.size() > 1 && "Bad linearize!");
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000985
Chris Lattner94285e62009-12-31 18:17:13 +0000986 // Add one to FactorOccurrences for each unique factor in this op.
Chris Lattner9506c932010-01-01 01:13:15 +0000987 SmallPtrSet<Value*, 8> Duplicates;
988 for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
989 Value *Factor = Factors[i];
990 if (!Duplicates.insert(Factor)) continue;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000991
Chris Lattner9506c932010-01-01 01:13:15 +0000992 unsigned Occ = ++FactorOccurrences[Factor];
993 if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +0000994
Chris Lattner9506c932010-01-01 01:13:15 +0000995 // If Factor is a negative constant, add the negated value as a factor
996 // because we can percolate the negate out. Watch for minint, which
997 // cannot be positivified.
998 if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor))
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000999 if (CI->isNegative() && !CI->isMinValue(true)) {
Chris Lattner9506c932010-01-01 01:13:15 +00001000 Factor = ConstantInt::get(CI->getContext(), -CI->getValue());
1001 assert(!Duplicates.count(Factor) &&
1002 "Shouldn't have two constant factors, missed a canonicalize");
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001003
Chris Lattner9506c932010-01-01 01:13:15 +00001004 unsigned Occ = ++FactorOccurrences[Factor];
1005 if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
1006 }
Chris Lattner94285e62009-12-31 18:17:13 +00001007 }
1008 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001009
Chris Lattner94285e62009-12-31 18:17:13 +00001010 // If any factor occurred more than one time, we can pull it out.
1011 if (MaxOcc > 1) {
Chris Lattner69e98e22009-12-31 19:24:52 +00001012 DEBUG(errs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << '\n');
Chris Lattner94285e62009-12-31 18:17:13 +00001013 ++NumFactor;
1014
1015 // Create a new instruction that uses the MaxOccVal twice. If we don't do
1016 // this, we could otherwise run into situations where removing a factor
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001017 // from an expression will drop a use of maxocc, and this can cause
Chris Lattner94285e62009-12-31 18:17:13 +00001018 // RemoveFactorFromExpression on successive values to behave differently.
1019 Instruction *DummyInst = BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal);
Bill Wendling55e70982012-05-02 09:59:45 +00001020 SmallVector<WeakVH, 4> NewMulOps;
Duncan Sands37f87c72011-01-26 10:08:38 +00001021 for (unsigned i = 0; i != Ops.size(); ++i) {
Chris Lattnerc2d1b692010-01-09 06:01:36 +00001022 // Only try to remove factors from expressions we're allowed to.
Duncan Sands0fd120b2012-05-25 12:03:02 +00001023 BinaryOperator *BOp = isReassociableOp(Ops[i].Op, Instruction::Mul);
1024 if (!BOp)
Chris Lattnerc2d1b692010-01-09 06:01:36 +00001025 continue;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001026
Chris Lattner94285e62009-12-31 18:17:13 +00001027 if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
Duncan Sands37f87c72011-01-26 10:08:38 +00001028 // The factorized operand may occur several times. Convert them all in
1029 // one fell swoop.
1030 for (unsigned j = Ops.size(); j != i;) {
1031 --j;
1032 if (Ops[j].Op == Ops[i].Op) {
1033 NewMulOps.push_back(V);
1034 Ops.erase(Ops.begin()+j);
1035 }
1036 }
1037 --i;
Chris Lattner94285e62009-12-31 18:17:13 +00001038 }
1039 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001040
Chris Lattner94285e62009-12-31 18:17:13 +00001041 // No need for extra uses anymore.
1042 delete DummyInst;
Duncan Sands54a57042010-01-08 17:51:48 +00001043
Chris Lattner94285e62009-12-31 18:17:13 +00001044 unsigned NumAddedValues = NewMulOps.size();
1045 Value *V = EmitAddTreeOfValues(I, NewMulOps);
Duncan Sands54a57042010-01-08 17:51:48 +00001046
Chris Lattner69e98e22009-12-31 19:24:52 +00001047 // Now that we have inserted the add tree, optimize it. This allows us to
1048 // handle cases that require multiple factoring steps, such as this:
Chris Lattner94285e62009-12-31 18:17:13 +00001049 // A*A*B + A*A*C --> A*(A*B+A*C) --> A*(A*(B+C))
Chris Lattner9cd1bc42009-12-31 18:18:46 +00001050 assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
Duncan Sands54a57042010-01-08 17:51:48 +00001051 (void)NumAddedValues;
Duncan Sands841f4262012-06-08 20:15:33 +00001052 if (Instruction *VI = dyn_cast<Instruction>(V))
1053 RedoInsts.insert(VI);
Chris Lattner69e98e22009-12-31 19:24:52 +00001054
1055 // Create the multiply.
Duncan Sands841f4262012-06-08 20:15:33 +00001056 Instruction *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I);
Chris Lattner69e98e22009-12-31 19:24:52 +00001057
Chris Lattnerf31e2e92009-12-31 19:49:01 +00001058 // Rerun associate on the multiply in case the inner expression turned into
1059 // a multiply. We want to make sure that we keep things in canonical form.
Duncan Sands841f4262012-06-08 20:15:33 +00001060 RedoInsts.insert(V2);
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001061
Chris Lattner94285e62009-12-31 18:17:13 +00001062 // If every add operand included the factor (e.g. "A*B + A*C"), then the
1063 // entire result expression is just the multiply "A*(B+C)".
1064 if (Ops.empty())
1065 return V2;
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001066
Chris Lattner9cd1bc42009-12-31 18:18:46 +00001067 // Otherwise, we had some input that didn't have the factor, such as
Chris Lattner94285e62009-12-31 18:17:13 +00001068 // "A*B + A*C + D" -> "A*(B+C) + D". Add the new multiply to the list of
Chris Lattner9cd1bc42009-12-31 18:18:46 +00001069 // things being added by this operation.
Chris Lattner94285e62009-12-31 18:17:13 +00001070 Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
1071 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001072
Chris Lattnerf3f55a92009-12-31 07:59:34 +00001073 return 0;
1074}
Chris Lattnere5022fe2006-03-04 09:31:13 +00001075
Chandler Carruth464bda32012-04-26 05:30:30 +00001076namespace {
1077 /// \brief Predicate tests whether a ValueEntry's op is in a map.
1078 struct IsValueInMap {
1079 const DenseMap<Value *, unsigned> &Map;
1080
1081 IsValueInMap(const DenseMap<Value *, unsigned> &Map) : Map(Map) {}
1082
1083 bool operator()(const ValueEntry &Entry) {
1084 return Map.find(Entry.Op) != Map.end();
1085 }
1086 };
1087}
1088
1089/// \brief Build up a vector of value/power pairs factoring a product.
1090///
1091/// Given a series of multiplication operands, build a vector of factors and
1092/// the powers each is raised to when forming the final product. Sort them in
1093/// the order of descending power.
1094///
1095/// (x*x) -> [(x, 2)]
1096/// ((x*x)*x) -> [(x, 3)]
1097/// ((((x*y)*x)*y)*x) -> [(x, 3), (y, 2)]
1098///
1099/// \returns Whether any factors have a power greater than one.
1100bool Reassociate::collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
1101 SmallVectorImpl<Factor> &Factors) {
Duncan Sands0fd120b2012-05-25 12:03:02 +00001102 // FIXME: Have Ops be (ValueEntry, Multiplicity) pairs, simplifying this.
1103 // Compute the sum of powers of simplifiable factors.
Chandler Carruth464bda32012-04-26 05:30:30 +00001104 unsigned FactorPowerSum = 0;
Duncan Sands0fd120b2012-05-25 12:03:02 +00001105 for (unsigned Idx = 1, Size = Ops.size(); Idx < Size; ++Idx) {
1106 Value *Op = Ops[Idx-1].Op;
1107
1108 // Count the number of occurrences of this value.
1109 unsigned Count = 1;
1110 for (; Idx < Size && Ops[Idx].Op == Op; ++Idx)
1111 ++Count;
Chandler Carruth464bda32012-04-26 05:30:30 +00001112 // Track for simplification all factors which occur 2 or more times.
Duncan Sands0fd120b2012-05-25 12:03:02 +00001113 if (Count > 1)
1114 FactorPowerSum += Count;
Chandler Carruth464bda32012-04-26 05:30:30 +00001115 }
Duncan Sands0fd120b2012-05-25 12:03:02 +00001116
Chandler Carruth464bda32012-04-26 05:30:30 +00001117 // We can only simplify factors if the sum of the powers of our simplifiable
1118 // factors is 4 or higher. When that is the case, we will *always* have
1119 // a simplification. This is an important invariant to prevent cyclicly
1120 // trying to simplify already minimal formations.
1121 if (FactorPowerSum < 4)
1122 return false;
1123
Duncan Sands0fd120b2012-05-25 12:03:02 +00001124 // Now gather the simplifiable factors, removing them from Ops.
1125 FactorPowerSum = 0;
1126 for (unsigned Idx = 1; Idx < Ops.size(); ++Idx) {
1127 Value *Op = Ops[Idx-1].Op;
Chandler Carruth464bda32012-04-26 05:30:30 +00001128
Duncan Sands0fd120b2012-05-25 12:03:02 +00001129 // Count the number of occurrences of this value.
1130 unsigned Count = 1;
1131 for (; Idx < Ops.size() && Ops[Idx].Op == Op; ++Idx)
1132 ++Count;
1133 if (Count == 1)
1134 continue;
Benjamin Kramerd9b0b022012-06-02 10:20:22 +00001135 // Move an even number of occurrences to Factors.
Duncan Sands0fd120b2012-05-25 12:03:02 +00001136 Count &= ~1U;
1137 Idx -= Count;
1138 FactorPowerSum += Count;
1139 Factors.push_back(Factor(Op, Count));
1140 Ops.erase(Ops.begin()+Idx, Ops.begin()+Idx+Count);
Chandler Carruth464bda32012-04-26 05:30:30 +00001141 }
Duncan Sands0fd120b2012-05-25 12:03:02 +00001142
Chandler Carruth464bda32012-04-26 05:30:30 +00001143 // None of the adjustments above should have reduced the sum of factor powers
1144 // below our mininum of '4'.
1145 assert(FactorPowerSum >= 4);
1146
Chandler Carruth464bda32012-04-26 05:30:30 +00001147 std::sort(Factors.begin(), Factors.end(), Factor::PowerDescendingSorter());
1148 return true;
1149}
1150
1151/// \brief Build a tree of multiplies, computing the product of Ops.
1152static Value *buildMultiplyTree(IRBuilder<> &Builder,
1153 SmallVectorImpl<Value*> &Ops) {
1154 if (Ops.size() == 1)
1155 return Ops.back();
1156
1157 Value *LHS = Ops.pop_back_val();
1158 do {
1159 LHS = Builder.CreateMul(LHS, Ops.pop_back_val());
1160 } while (!Ops.empty());
1161
1162 return LHS;
1163}
1164
1165/// \brief Build a minimal multiplication DAG for (a^x)*(b^y)*(c^z)*...
1166///
1167/// Given a vector of values raised to various powers, where no two values are
1168/// equal and the powers are sorted in decreasing order, compute the minimal
1169/// DAG of multiplies to compute the final product, and return that product
1170/// value.
1171Value *Reassociate::buildMinimalMultiplyDAG(IRBuilder<> &Builder,
1172 SmallVectorImpl<Factor> &Factors) {
1173 assert(Factors[0].Power);
1174 SmallVector<Value *, 4> OuterProduct;
1175 for (unsigned LastIdx = 0, Idx = 1, Size = Factors.size();
1176 Idx < Size && Factors[Idx].Power > 0; ++Idx) {
1177 if (Factors[Idx].Power != Factors[LastIdx].Power) {
1178 LastIdx = Idx;
1179 continue;
1180 }
1181
1182 // We want to multiply across all the factors with the same power so that
1183 // we can raise them to that power as a single entity. Build a mini tree
1184 // for that.
1185 SmallVector<Value *, 4> InnerProduct;
1186 InnerProduct.push_back(Factors[LastIdx].Base);
1187 do {
1188 InnerProduct.push_back(Factors[Idx].Base);
1189 ++Idx;
1190 } while (Idx < Size && Factors[Idx].Power == Factors[LastIdx].Power);
1191
1192 // Reset the base value of the first factor to the new expression tree.
1193 // We'll remove all the factors with the same power in a second pass.
Duncan Sands841f4262012-06-08 20:15:33 +00001194 Value *M = Factors[LastIdx].Base = buildMultiplyTree(Builder, InnerProduct);
1195 if (Instruction *MI = dyn_cast<Instruction>(M))
1196 RedoInsts.insert(MI);
Chandler Carruth464bda32012-04-26 05:30:30 +00001197
1198 LastIdx = Idx;
1199 }
1200 // Unique factors with equal powers -- we've folded them into the first one's
1201 // base.
1202 Factors.erase(std::unique(Factors.begin(), Factors.end(),
1203 Factor::PowerEqual()),
1204 Factors.end());
1205
1206 // Iteratively collect the base of each factor with an add power into the
1207 // outer product, and halve each power in preparation for squaring the
1208 // expression.
1209 for (unsigned Idx = 0, Size = Factors.size(); Idx != Size; ++Idx) {
1210 if (Factors[Idx].Power & 1)
1211 OuterProduct.push_back(Factors[Idx].Base);
1212 Factors[Idx].Power >>= 1;
1213 }
1214 if (Factors[0].Power) {
1215 Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
1216 OuterProduct.push_back(SquareRoot);
1217 OuterProduct.push_back(SquareRoot);
1218 }
1219 if (OuterProduct.size() == 1)
1220 return OuterProduct.front();
1221
Duncan Sandsa3370102012-05-08 12:16:05 +00001222 Value *V = buildMultiplyTree(Builder, OuterProduct);
Duncan Sandsa3370102012-05-08 12:16:05 +00001223 return V;
Chandler Carruth464bda32012-04-26 05:30:30 +00001224}
1225
1226Value *Reassociate::OptimizeMul(BinaryOperator *I,
1227 SmallVectorImpl<ValueEntry> &Ops) {
1228 // We can only optimize the multiplies when there is a chain of more than
1229 // three, such that a balanced tree might require fewer total multiplies.
1230 if (Ops.size() < 4)
1231 return 0;
1232
1233 // Try to turn linear trees of multiplies without other uses of the
1234 // intermediate stages into minimal multiply DAGs with perfect sub-expression
1235 // re-use.
1236 SmallVector<Factor, 4> Factors;
1237 if (!collectMultiplyFactors(Ops, Factors))
1238 return 0; // All distinct factors, so nothing left for us to do.
1239
1240 IRBuilder<> Builder(I);
1241 Value *V = buildMinimalMultiplyDAG(Builder, Factors);
1242 if (Ops.empty())
1243 return V;
1244
1245 ValueEntry NewEntry = ValueEntry(getRank(V), V);
1246 Ops.insert(std::lower_bound(Ops.begin(), Ops.end(), NewEntry), NewEntry);
1247 return 0;
1248}
1249
Chris Lattnere5022fe2006-03-04 09:31:13 +00001250Value *Reassociate::OptimizeExpression(BinaryOperator *I,
Chris Lattner9f7b7082009-12-31 18:40:32 +00001251 SmallVectorImpl<ValueEntry> &Ops) {
Chris Lattner46900102005-05-08 00:19:31 +00001252 // Now that we have the linearized expression tree, try to optimize it.
1253 // Start by folding any constants that we found.
Chris Lattnere5022fe2006-03-04 09:31:13 +00001254 if (Ops.size() == 1) return Ops[0].Op;
Chris Lattner46900102005-05-08 00:19:31 +00001255
Chris Lattnere5022fe2006-03-04 09:31:13 +00001256 unsigned Opcode = I->getOpcode();
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001257
Chris Lattner46900102005-05-08 00:19:31 +00001258 if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
1259 if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
1260 Ops.pop_back();
Owen Andersonbaf3c402009-07-29 18:55:55 +00001261 Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
Chris Lattnere5022fe2006-03-04 09:31:13 +00001262 return OptimizeExpression(I, Ops);
Chris Lattner46900102005-05-08 00:19:31 +00001263 }
1264
1265 // Check for destructive annihilation due to a constant being used.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001266 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(Ops.back().Op))
Chris Lattner46900102005-05-08 00:19:31 +00001267 switch (Opcode) {
1268 default: break;
1269 case Instruction::And:
Chris Lattner90461932010-01-01 00:04:26 +00001270 if (CstVal->isZero()) // X & 0 -> 0
Chris Lattnere5022fe2006-03-04 09:31:13 +00001271 return CstVal;
Chris Lattner90461932010-01-01 00:04:26 +00001272 if (CstVal->isAllOnesValue()) // X & -1 -> X
Chris Lattner8d93b252009-12-31 07:48:51 +00001273 Ops.pop_back();
Chris Lattner46900102005-05-08 00:19:31 +00001274 break;
1275 case Instruction::Mul:
Chris Lattner90461932010-01-01 00:04:26 +00001276 if (CstVal->isZero()) { // X * 0 -> 0
Chris Lattner109d34d2005-05-08 18:59:37 +00001277 ++NumAnnihil;
Chris Lattnere5022fe2006-03-04 09:31:13 +00001278 return CstVal;
Chris Lattner46900102005-05-08 00:19:31 +00001279 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001280
Chris Lattner8d93b252009-12-31 07:48:51 +00001281 if (cast<ConstantInt>(CstVal)->isOne())
Chris Lattner90461932010-01-01 00:04:26 +00001282 Ops.pop_back(); // X * 1 -> X
Chris Lattner46900102005-05-08 00:19:31 +00001283 break;
1284 case Instruction::Or:
Chris Lattner90461932010-01-01 00:04:26 +00001285 if (CstVal->isAllOnesValue()) // X | -1 -> -1
Chris Lattnere5022fe2006-03-04 09:31:13 +00001286 return CstVal;
Chris Lattner46900102005-05-08 00:19:31 +00001287 // FALLTHROUGH!
1288 case Instruction::Add:
1289 case Instruction::Xor:
Chris Lattner90461932010-01-01 00:04:26 +00001290 if (CstVal->isZero()) // X [|^+] 0 -> X
Chris Lattner46900102005-05-08 00:19:31 +00001291 Ops.pop_back();
1292 break;
1293 }
Chris Lattnere5022fe2006-03-04 09:31:13 +00001294 if (Ops.size() == 1) return Ops[0].Op;
Chris Lattner46900102005-05-08 00:19:31 +00001295
Chris Lattnerec531232009-12-31 07:33:14 +00001296 // Handle destructive annihilation due to identities between elements in the
Chris Lattner46900102005-05-08 00:19:31 +00001297 // argument list here.
Chandler Carruth464bda32012-04-26 05:30:30 +00001298 unsigned NumOps = Ops.size();
Chris Lattner109d34d2005-05-08 18:59:37 +00001299 switch (Opcode) {
1300 default: break;
1301 case Instruction::And:
1302 case Instruction::Or:
Chandler Carruth464bda32012-04-26 05:30:30 +00001303 case Instruction::Xor:
Chris Lattnerf3f55a92009-12-31 07:59:34 +00001304 if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
1305 return Result;
Chris Lattner109d34d2005-05-08 18:59:37 +00001306 break;
1307
Chandler Carruth464bda32012-04-26 05:30:30 +00001308 case Instruction::Add:
Chris Lattner94285e62009-12-31 18:17:13 +00001309 if (Value *Result = OptimizeAdd(I, Ops))
Chris Lattnerf3f55a92009-12-31 07:59:34 +00001310 return Result;
Chris Lattner109d34d2005-05-08 18:59:37 +00001311 break;
Chandler Carruth464bda32012-04-26 05:30:30 +00001312
1313 case Instruction::Mul:
1314 if (Value *Result = OptimizeMul(I, Ops))
1315 return Result;
1316 break;
Chris Lattner109d34d2005-05-08 18:59:37 +00001317 }
1318
Duncan Sands841f4262012-06-08 20:15:33 +00001319 if (Ops.size() != NumOps)
Chris Lattnere5022fe2006-03-04 09:31:13 +00001320 return OptimizeExpression(I, Ops);
1321 return 0;
Chris Lattner46900102005-05-08 00:19:31 +00001322}
1323
Duncan Sands841f4262012-06-08 20:15:33 +00001324/// EraseInst - Zap the given instruction, adding interesting operands to the
1325/// work list.
1326void Reassociate::EraseInst(Instruction *I) {
1327 assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
1328 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
1329 // Erase the dead instruction.
1330 ValueRankMap.erase(I);
1331 I->eraseFromParent();
1332 // Optimize its operands.
1333 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1334 if (Instruction *Op = dyn_cast<Instruction>(Ops[i])) {
1335 // If this is a node in an expression tree, climb to the expression root
1336 // and add that since that's where optimization actually happens.
1337 unsigned Opcode = Op->getOpcode();
1338 while (Op->hasOneUse() && Op->use_back()->getOpcode() == Opcode)
1339 Op = Op->use_back();
1340 RedoInsts.insert(Op);
1341 }
1342}
1343
1344/// OptimizeInst - Inspect and optimize the given instruction. Note that erasing
1345/// instructions is not allowed.
1346void Reassociate::OptimizeInst(Instruction *I) {
1347 // Only consider operations that we understand.
1348 if (!isa<BinaryOperator>(I))
1349 return;
1350
1351 if (I->getOpcode() == Instruction::Shl &&
1352 isa<ConstantInt>(I->getOperand(1)))
1353 // If an operand of this shift is a reassociable multiply, or if the shift
1354 // is used by a reassociable multiply or add, turn into a multiply.
1355 if (isReassociableOp(I->getOperand(0), Instruction::Mul) ||
1356 (I->hasOneUse() &&
1357 (isReassociableOp(I->use_back(), Instruction::Mul) ||
1358 isReassociableOp(I->use_back(), Instruction::Add)))) {
1359 Instruction *NI = ConvertShiftToMul(I);
1360 RedoInsts.insert(I);
Dan Gohmandac5dba2011-04-12 00:11:56 +00001361 MadeChange = true;
Duncan Sands841f4262012-06-08 20:15:33 +00001362 I = NI;
Chris Lattnerf33151a2005-05-08 21:28:52 +00001363 }
Chris Lattnere4b73042002-10-31 17:12:59 +00001364
Owen Anderson423f19f2012-05-07 20:47:23 +00001365 // Floating point binary operators are not associative, but we can still
1366 // commute (some) of them, to canonicalize the order of their operands.
1367 // This can potentially expose more CSE opportunities, and makes writing
1368 // other transformations simpler.
Duncan Sands841f4262012-06-08 20:15:33 +00001369 if ((I->getType()->isFloatingPointTy() || I->getType()->isVectorTy())) {
Owen Anderson423f19f2012-05-07 20:47:23 +00001370 // FAdd and FMul can be commuted.
Duncan Sands841f4262012-06-08 20:15:33 +00001371 if (I->getOpcode() != Instruction::FMul &&
1372 I->getOpcode() != Instruction::FAdd)
Owen Anderson423f19f2012-05-07 20:47:23 +00001373 return;
1374
Duncan Sands841f4262012-06-08 20:15:33 +00001375 Value *LHS = I->getOperand(0);
1376 Value *RHS = I->getOperand(1);
Owen Anderson423f19f2012-05-07 20:47:23 +00001377 unsigned LHSRank = getRank(LHS);
1378 unsigned RHSRank = getRank(RHS);
1379
1380 // Sort the operands by rank.
1381 if (RHSRank < LHSRank) {
Duncan Sands841f4262012-06-08 20:15:33 +00001382 I->setOperand(0, RHS);
1383 I->setOperand(1, LHS);
Owen Anderson423f19f2012-05-07 20:47:23 +00001384 }
1385
1386 return;
1387 }
1388
Dan Gohmandac5dba2011-04-12 00:11:56 +00001389 // Do not reassociate boolean (i1) expressions. We want to preserve the
1390 // original order of evaluation for short-circuited comparisons that
1391 // SimplifyCFG has folded to AND/OR expressions. If the expression
1392 // is not further optimized, it is likely to be transformed back to a
1393 // short-circuited form for code gen, and the source order may have been
1394 // optimized for the most likely conditions.
Duncan Sands841f4262012-06-08 20:15:33 +00001395 if (I->getType()->isIntegerTy(1))
Dan Gohmandac5dba2011-04-12 00:11:56 +00001396 return;
Chris Lattnera36e6c82002-05-16 04:37:07 +00001397
Dan Gohmandac5dba2011-04-12 00:11:56 +00001398 // If this is a subtract instruction which is not already in negate form,
1399 // see if we can convert it to X+-Y.
Duncan Sands841f4262012-06-08 20:15:33 +00001400 if (I->getOpcode() == Instruction::Sub) {
1401 if (ShouldBreakUpSubtract(I)) {
1402 Instruction *NI = BreakUpSubtract(I);
1403 RedoInsts.insert(I);
Dan Gohmandac5dba2011-04-12 00:11:56 +00001404 MadeChange = true;
Duncan Sands841f4262012-06-08 20:15:33 +00001405 I = NI;
1406 } else if (BinaryOperator::isNeg(I)) {
Dan Gohmandac5dba2011-04-12 00:11:56 +00001407 // Otherwise, this is a negation. See if the operand is a multiply tree
1408 // and if this is not an inner node of a multiply tree.
Duncan Sands841f4262012-06-08 20:15:33 +00001409 if (isReassociableOp(I->getOperand(1), Instruction::Mul) &&
1410 (!I->hasOneUse() ||
1411 !isReassociableOp(I->use_back(), Instruction::Mul))) {
1412 Instruction *NI = LowerNegateToMultiply(I);
1413 RedoInsts.insert(I);
Dan Gohmandac5dba2011-04-12 00:11:56 +00001414 MadeChange = true;
Duncan Sands841f4262012-06-08 20:15:33 +00001415 I = NI;
Dan Gohmandac5dba2011-04-12 00:11:56 +00001416 }
1417 }
Chris Lattner895b3922006-03-14 07:11:11 +00001418 }
Dan Gohmandac5dba2011-04-12 00:11:56 +00001419
Duncan Sands841f4262012-06-08 20:15:33 +00001420 // If this instruction is an associative binary operator, process it.
1421 if (!I->isAssociative()) return;
1422 BinaryOperator *BO = cast<BinaryOperator>(I);
Dan Gohmandac5dba2011-04-12 00:11:56 +00001423
1424 // If this is an interior node of a reassociable tree, ignore it until we
1425 // get to the root of the tree, to avoid N^2 analysis.
Duncan Sands841f4262012-06-08 20:15:33 +00001426 if (BO->hasOneUse() && BO->use_back()->getOpcode() == BO->getOpcode())
Dan Gohmandac5dba2011-04-12 00:11:56 +00001427 return;
1428
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001429 // If this is an add tree that is used by a sub instruction, ignore it
Dan Gohmandac5dba2011-04-12 00:11:56 +00001430 // until we process the subtract.
Duncan Sands841f4262012-06-08 20:15:33 +00001431 if (BO->hasOneUse() && BO->getOpcode() == Instruction::Add &&
1432 cast<Instruction>(BO->use_back())->getOpcode() == Instruction::Sub)
Dan Gohmandac5dba2011-04-12 00:11:56 +00001433 return;
1434
Duncan Sands841f4262012-06-08 20:15:33 +00001435 ReassociateExpression(BO);
Chris Lattner895b3922006-03-14 07:11:11 +00001436}
Chris Lattnerc0649ac2005-05-07 21:59:39 +00001437
Chris Lattner69e98e22009-12-31 19:24:52 +00001438Value *Reassociate::ReassociateExpression(BinaryOperator *I) {
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001439
Chris Lattner69e98e22009-12-31 19:24:52 +00001440 // First, walk the expression tree, linearizing the tree, collecting the
1441 // operand information.
Chris Lattner9f7b7082009-12-31 18:40:32 +00001442 SmallVector<ValueEntry, 8> Ops;
Chris Lattner895b3922006-03-14 07:11:11 +00001443 LinearizeExprTree(I, Ops);
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001444
Duncan Sands24dfa522012-05-26 07:47:48 +00001445 DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n');
1446
Chris Lattner895b3922006-03-14 07:11:11 +00001447 // Now that we have linearized the tree to a list and have gathered all of
1448 // the operands and their ranks, sort the operands by their rank. Use a
1449 // stable_sort so that values with equal ranks will have their relative
1450 // positions maintained (and so the compiler is deterministic). Note that
1451 // this sorts so that the highest ranking values end up at the beginning of
1452 // the vector.
1453 std::stable_sort(Ops.begin(), Ops.end());
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001454
Chris Lattner895b3922006-03-14 07:11:11 +00001455 // OptimizeExpression - Now that we have the expression tree in a convenient
1456 // sorted form, optimize it globally if possible.
1457 if (Value *V = OptimizeExpression(I, Ops)) {
1458 // This expression tree simplified to something that isn't a tree,
1459 // eliminate it.
David Greenea1fa76c2010-01-05 01:27:24 +00001460 DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n');
Chris Lattner895b3922006-03-14 07:11:11 +00001461 I->replaceAllUsesWith(V);
Devang Patel5367b232011-04-28 22:48:14 +00001462 if (Instruction *VI = dyn_cast<Instruction>(V))
1463 VI->setDebugLoc(I->getDebugLoc());
Duncan Sands841f4262012-06-08 20:15:33 +00001464 RedoInsts.insert(I);
Chris Lattner9fdaefa2009-12-31 17:51:05 +00001465 ++NumAnnihil;
Chris Lattner69e98e22009-12-31 19:24:52 +00001466 return V;
Chris Lattner895b3922006-03-14 07:11:11 +00001467 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001468
Chris Lattner895b3922006-03-14 07:11:11 +00001469 // We want to sink immediates as deeply as possible except in the case where
1470 // this is a multiply tree used only by an add, and the immediate is a -1.
1471 // In this case we reassociate to put the negation on the outside so that we
1472 // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
1473 if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
1474 cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add &&
1475 isa<ConstantInt>(Ops.back().Op) &&
1476 cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
Chris Lattner9f7b7082009-12-31 18:40:32 +00001477 ValueEntry Tmp = Ops.pop_back_val();
1478 Ops.insert(Ops.begin(), Tmp);
Chris Lattner895b3922006-03-14 07:11:11 +00001479 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001480
David Greenea1fa76c2010-01-05 01:27:24 +00001481 DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n');
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001482
Chris Lattner895b3922006-03-14 07:11:11 +00001483 if (Ops.size() == 1) {
1484 // This expression tree simplified to something that isn't a tree,
1485 // eliminate it.
1486 I->replaceAllUsesWith(Ops[0].Op);
Devang Patel5367b232011-04-28 22:48:14 +00001487 if (Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
1488 OI->setDebugLoc(I->getDebugLoc());
Duncan Sands841f4262012-06-08 20:15:33 +00001489 RedoInsts.insert(I);
Chris Lattner69e98e22009-12-31 19:24:52 +00001490 return Ops[0].Op;
Chris Lattner4fd56002002-05-08 22:19:27 +00001491 }
Bill Wendlinge8cd3f22012-05-02 23:43:23 +00001492
Chris Lattner69e98e22009-12-31 19:24:52 +00001493 // Now that we ordered and optimized the expressions, splat them back into
1494 // the expression tree, removing any unneeded nodes.
1495 RewriteExprTree(I, Ops);
1496 return I;
Chris Lattner4fd56002002-05-08 22:19:27 +00001497}
1498
Chris Lattner7e708292002-06-25 16:13:24 +00001499bool Reassociate::runOnFunction(Function &F) {
Duncan Sands841f4262012-06-08 20:15:33 +00001500 // Calculate the rank map for F
Chris Lattner4fd56002002-05-08 22:19:27 +00001501 BuildRankMap(F);
1502
Chris Lattnerc0649ac2005-05-07 21:59:39 +00001503 MadeChange = false;
Duncan Sands841f4262012-06-08 20:15:33 +00001504 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1505 // Optimize every instruction in the basic block.
1506 for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE; )
1507 if (isInstructionTriviallyDead(II)) {
1508 EraseInst(II++);
1509 } else {
1510 OptimizeInst(II);
1511 assert(II->getParent() == BI && "Moved to a different block!");
1512 ++II;
1513 }
Duncan Sands69938a82012-06-08 13:37:30 +00001514
Duncan Sands841f4262012-06-08 20:15:33 +00001515 // If this produced extra instructions to optimize, handle them now.
1516 while (!RedoInsts.empty()) {
1517 Instruction *I = RedoInsts.pop_back_val();
1518 if (isInstructionTriviallyDead(I))
1519 EraseInst(I);
1520 else
1521 OptimizeInst(I);
Dan Gohmandac5dba2011-04-12 00:11:56 +00001522 }
Duncan Sands841f4262012-06-08 20:15:33 +00001523 }
Chris Lattner4fd56002002-05-08 22:19:27 +00001524
Duncan Sands0fd120b2012-05-25 12:03:02 +00001525 // We are done with the rank map.
1526 RankMap.clear();
1527 ValueRankMap.clear();
1528
Chris Lattnerc0649ac2005-05-07 21:59:39 +00001529 return MadeChange;
Chris Lattner4fd56002002-05-08 22:19:27 +00001530}