~ubuntu-branches/ubuntu/wily/clamav/wily-proposed

« back to all changes in this revision

Viewing changes to libclamav/c++/llvm/lib/Transforms/Scalar/Reassociate.cpp

  • Committer: Package Import Robot
  • Author(s): Scott Kitterman, Sebastian Andrzej Siewior, Andreas Cadhalpun, Scott Kitterman, Javier Fernández-Sanguino
  • Date: 2015-01-28 00:25:13 UTC
  • mfrom: (0.48.14 sid)
  • Revision ID: package-import@ubuntu.com-20150128002513-lil2oi74cooy4lzr
Tags: 0.98.6+dfsg-1
[ Sebastian Andrzej Siewior ]
* update "fix-ssize_t-size_t-off_t-printf-modifier", include of misc.h was
  missing but was pulled in via the systemd patch.
* Don't leak return codes from libmspack to clamav API. (Closes: #774686).

[ Andreas Cadhalpun ]
* Add patch to avoid emitting incremental progress messages when not
  outputting to a terminal. (Closes: #767350)
* Update lintian-overrides for unused-file-paragraph-in-dep5-copyright.
* clamav-base.postinst: always chown /var/log/clamav and /var/lib/clamav
  to clamav:clamav, not only on fresh installations. (Closes: #775400)
* Adapt the clamav-daemon and clamav-freshclam logrotate scripts,
  so that they correctly work under systemd.
* Move the PidFile variable from the clamd/freshclam configuration files
  to the init scripts. This makes the init scripts more robust against
  misconfiguration and avoids error messages with systemd. (Closes: #767353)
* debian/copyright: drop files from Files-Excluded only present in github
  tarballs
* Drop Workaround-a-bug-in-libc-on-Hurd.patch, because hurd got fixed.
  (see #752237)
* debian/rules: Remove useless --with-system-tommath --without-included-ltdl
  configure options.

[ Scott Kitterman ]
* Stop stripping llvm when repacking the tarball as the system llvm on some
  releases is too old to use
* New upstream bugfix release
  - Library shared object revisions.
  - Includes a patch from Sebastian Andrzej Siewior making ClamAV pid files
    compatible with systemd.
  - Fix a heap out of bounds condition with crafted Yoda's crypter files.
    This issue was discovered by Felix Groebert of the Google Security Team.
  - Fix a heap out of bounds condition with crafted mew packer files. This
    issue was discovered by Felix Groebert of the Google Security Team.
  - Fix a heap out of bounds condition with crafted upx packer files. This
    issue was discovered by Kevin Szkudlapski of Quarkslab.
  - Fix a heap out of bounds condition with crafted upack packer files. This
    issue was discovered by Sebastian Andrzej Siewior. CVE-2014-9328.
  - Compensate a crash due to incorrect compiler optimization when handling
    crafted petite packer files. This issue was discovered by Sebastian
    Andrzej Siewior.
* Update lintian override for embedded zlib to match new so version

[ Javier Fernández-Sanguino ]
* Updated Spanish Debconf template translation (Closes: #773563)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
//===- Reassociate.cpp - Reassociate binary expressions -------------------===//
 
2
//
 
3
//                     The LLVM Compiler Infrastructure
 
4
//
 
5
// This file is distributed under the University of Illinois Open Source
 
6
// License. See LICENSE.TXT for details.
 
7
//
 
8
//===----------------------------------------------------------------------===//
 
9
//
 
10
// This pass reassociates commutative expressions in an order that is designed
 
11
// to promote better constant propagation, GCSE, LICM, PRE, etc.
 
12
//
 
13
// For example: 4 + (x + 5) -> x + (4 + 5)
 
14
//
 
15
// 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
 
 
23
#define DEBUG_TYPE "reassociate"
 
24
#include "llvm/Transforms/Scalar.h"
 
25
#include "llvm/Constants.h"
 
26
#include "llvm/DerivedTypes.h"
 
27
#include "llvm/Function.h"
 
28
#include "llvm/Instructions.h"
 
29
#include "llvm/IntrinsicInst.h"
 
30
#include "llvm/Pass.h"
 
31
#include "llvm/Assembly/Writer.h"
 
32
#include "llvm/Support/CFG.h"
 
33
#include "llvm/Support/Debug.h"
 
34
#include "llvm/Support/ValueHandle.h"
 
35
#include "llvm/Support/raw_ostream.h"
 
36
#include "llvm/ADT/PostOrderIterator.h"
 
37
#include "llvm/ADT/Statistic.h"
 
38
#include "llvm/ADT/DenseMap.h"
 
39
#include <algorithm>
 
40
using namespace llvm;
 
41
 
 
42
STATISTIC(NumLinear , "Number of insts linearized");
 
43
STATISTIC(NumChanged, "Number of insts reassociated");
 
44
STATISTIC(NumAnnihil, "Number of expr tree annihilated");
 
45
STATISTIC(NumFactor , "Number of multiplies factored");
 
46
 
 
47
namespace {
 
48
  struct ValueEntry {
 
49
    unsigned Rank;
 
50
    Value *Op;
 
51
    ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
 
52
  };
 
53
  inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
 
54
    return LHS.Rank > RHS.Rank;   // Sort so that highest rank goes to start.
 
55
  }
 
56
}
 
57
 
 
58
#ifndef NDEBUG
 
59
/// PrintOps - Print out the expression identified in the Ops list.
 
60
///
 
61
static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
 
62
  Module *M = I->getParent()->getParent()->getParent();
 
63
  dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " "
 
64
       << *Ops[0].Op->getType() << '\t';
 
65
  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
 
66
    dbgs() << "[ ";
 
67
    WriteAsOperand(dbgs(), Ops[i].Op, false, M);
 
68
    dbgs() << ", #" << Ops[i].Rank << "] ";
 
69
  }
 
70
}
 
71
#endif
 
72
  
 
73
namespace {
 
74
  class Reassociate : public FunctionPass {
 
75
    DenseMap<BasicBlock*, unsigned> RankMap;
 
76
    DenseMap<AssertingVH<>, unsigned> ValueRankMap;
 
77
    bool MadeChange;
 
78
  public:
 
79
    static char ID; // Pass identification, replacement for typeid
 
80
    Reassociate() : FunctionPass(ID) {}
 
81
 
 
82
    bool runOnFunction(Function &F);
 
83
 
 
84
    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
 
85
      AU.setPreservesCFG();
 
86
    }
 
87
  private:
 
88
    void BuildRankMap(Function &F);
 
89
    unsigned getRank(Value *V);
 
90
    Value *ReassociateExpression(BinaryOperator *I);
 
91
    void RewriteExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops,
 
92
                         unsigned Idx = 0);
 
93
    Value *OptimizeExpression(BinaryOperator *I,
 
94
                              SmallVectorImpl<ValueEntry> &Ops);
 
95
    Value *OptimizeAdd(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
 
96
    void LinearizeExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
 
97
    void LinearizeExpr(BinaryOperator *I);
 
98
    Value *RemoveFactorFromExpression(Value *V, Value *Factor);
 
99
    void ReassociateBB(BasicBlock *BB);
 
100
    
 
101
    void RemoveDeadBinaryOp(Value *V);
 
102
  };
 
103
}
 
104
 
 
105
char Reassociate::ID = 0;
 
106
INITIALIZE_PASS(Reassociate, "reassociate",
 
107
                "Reassociate expressions", false, false);
 
108
 
 
109
// Public interface to the Reassociate pass
 
110
FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
 
111
 
 
112
void Reassociate::RemoveDeadBinaryOp(Value *V) {
 
113
  Instruction *Op = dyn_cast<Instruction>(V);
 
114
  if (!Op || !isa<BinaryOperator>(Op) || !Op->use_empty())
 
115
    return;
 
116
  
 
117
  Value *LHS = Op->getOperand(0), *RHS = Op->getOperand(1);
 
118
  
 
119
  ValueRankMap.erase(Op);
 
120
  Op->eraseFromParent();
 
121
  RemoveDeadBinaryOp(LHS);
 
122
  RemoveDeadBinaryOp(RHS);
 
123
}
 
124
 
 
125
 
 
126
static bool isUnmovableInstruction(Instruction *I) {
 
127
  if (I->getOpcode() == Instruction::PHI ||
 
128
      I->getOpcode() == Instruction::Alloca ||
 
129
      I->getOpcode() == Instruction::Load ||
 
130
      I->getOpcode() == Instruction::Invoke ||
 
131
      (I->getOpcode() == Instruction::Call &&
 
132
       !isa<DbgInfoIntrinsic>(I)) ||
 
133
      I->getOpcode() == Instruction::UDiv || 
 
134
      I->getOpcode() == Instruction::SDiv ||
 
135
      I->getOpcode() == Instruction::FDiv ||
 
136
      I->getOpcode() == Instruction::URem ||
 
137
      I->getOpcode() == Instruction::SRem ||
 
138
      I->getOpcode() == Instruction::FRem)
 
139
    return true;
 
140
  return false;
 
141
}
 
142
 
 
143
void Reassociate::BuildRankMap(Function &F) {
 
144
  unsigned i = 2;
 
145
 
 
146
  // Assign distinct ranks to function arguments
 
147
  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
 
148
    ValueRankMap[&*I] = ++i;
 
149
 
 
150
  ReversePostOrderTraversal<Function*> RPOT(&F);
 
151
  for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
 
152
         E = RPOT.end(); I != E; ++I) {
 
153
    BasicBlock *BB = *I;
 
154
    unsigned BBRank = RankMap[BB] = ++i << 16;
 
155
 
 
156
    // Walk the basic block, adding precomputed ranks for any instructions that
 
157
    // we cannot move.  This ensures that the ranks for these instructions are
 
158
    // all different in the block.
 
159
    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
 
160
      if (isUnmovableInstruction(I))
 
161
        ValueRankMap[&*I] = ++BBRank;
 
162
  }
 
163
}
 
164
 
 
165
unsigned Reassociate::getRank(Value *V) {
 
166
  Instruction *I = dyn_cast<Instruction>(V);
 
167
  if (I == 0) {
 
168
    if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument.
 
169
    return 0;  // Otherwise it's a global or constant, rank 0.
 
170
  }
 
171
 
 
172
  if (unsigned Rank = ValueRankMap[I])
 
173
    return Rank;    // Rank already known?
 
174
 
 
175
  // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
 
176
  // we can reassociate expressions for code motion!  Since we do not recurse
 
177
  // for PHI nodes, we cannot have infinite recursion here, because there
 
178
  // cannot be loops in the value graph that do not go through PHI nodes.
 
179
  unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
 
180
  for (unsigned i = 0, e = I->getNumOperands();
 
181
       i != e && Rank != MaxRank; ++i)
 
182
    Rank = std::max(Rank, getRank(I->getOperand(i)));
 
183
 
 
184
  // If this is a not or neg instruction, do not count it for rank.  This
 
185
  // assures us that X and ~X will have the same rank.
 
186
  if (!I->getType()->isIntegerTy() ||
 
187
      (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
 
188
    ++Rank;
 
189
 
 
190
  //DEBUG(dbgs() << "Calculated Rank[" << V->getName() << "] = "
 
191
  //     << Rank << "\n");
 
192
 
 
193
  return ValueRankMap[I] = Rank;
 
194
}
 
195
 
 
196
/// isReassociableOp - Return true if V is an instruction of the specified
 
197
/// opcode and if it only has one use.
 
198
static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
 
199
  if ((V->hasOneUse() || V->use_empty()) && isa<Instruction>(V) &&
 
200
      cast<Instruction>(V)->getOpcode() == Opcode)
 
201
    return cast<BinaryOperator>(V);
 
202
  return 0;
 
203
}
 
204
 
 
205
/// LowerNegateToMultiply - Replace 0-X with X*-1.
 
206
///
 
207
static Instruction *LowerNegateToMultiply(Instruction *Neg,
 
208
                              DenseMap<AssertingVH<>, unsigned> &ValueRankMap) {
 
209
  Constant *Cst = Constant::getAllOnesValue(Neg->getType());
 
210
 
 
211
  Instruction *Res = BinaryOperator::CreateMul(Neg->getOperand(1), Cst, "",Neg);
 
212
  ValueRankMap.erase(Neg);
 
213
  Res->takeName(Neg);
 
214
  Neg->replaceAllUsesWith(Res);
 
215
  Neg->eraseFromParent();
 
216
  return Res;
 
217
}
 
218
 
 
219
// Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'.
 
220
// Note that if D is also part of the expression tree that we recurse to
 
221
// linearize it as well.  Besides that case, this does not recurse into A,B, or
 
222
// C.
 
223
void Reassociate::LinearizeExpr(BinaryOperator *I) {
 
224
  BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
 
225
  BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
 
226
  assert(isReassociableOp(LHS, I->getOpcode()) &&
 
227
         isReassociableOp(RHS, I->getOpcode()) &&
 
228
         "Not an expression that needs linearization?");
 
229
 
 
230
  DEBUG(dbgs() << "Linear" << *LHS << '\n' << *RHS << '\n' << *I << '\n');
 
231
 
 
232
  // Move the RHS instruction to live immediately before I, avoiding breaking
 
233
  // dominator properties.
 
234
  RHS->moveBefore(I);
 
235
 
 
236
  // Move operands around to do the linearization.
 
237
  I->setOperand(1, RHS->getOperand(0));
 
238
  RHS->setOperand(0, LHS);
 
239
  I->setOperand(0, RHS);
 
240
 
 
241
  ++NumLinear;
 
242
  MadeChange = true;
 
243
  DEBUG(dbgs() << "Linearized: " << *I << '\n');
 
244
 
 
245
  // If D is part of this expression tree, tail recurse.
 
246
  if (isReassociableOp(I->getOperand(1), I->getOpcode()))
 
247
    LinearizeExpr(I);
 
248
}
 
249
 
 
250
 
 
251
/// LinearizeExprTree - Given an associative binary expression tree, traverse
 
252
/// all of the uses putting it into canonical form.  This forces a left-linear
 
253
/// form of the expression (((a+b)+c)+d), and collects information about the
 
254
/// rank of the non-tree operands.
 
255
///
 
256
/// NOTE: These intentionally destroys the expression tree operands (turning
 
257
/// them into undef values) to reduce #uses of the values.  This means that the
 
258
/// caller MUST use something like RewriteExprTree to put the values back in.
 
259
///
 
260
void Reassociate::LinearizeExprTree(BinaryOperator *I,
 
261
                                    SmallVectorImpl<ValueEntry> &Ops) {
 
262
  Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
 
263
  unsigned Opcode = I->getOpcode();
 
264
 
 
265
  // First step, linearize the expression if it is in ((A+B)+(C+D)) form.
 
266
  BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode);
 
267
  BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode);
 
268
 
 
269
  // If this is a multiply expression tree and it contains internal negations,
 
270
  // transform them into multiplies by -1 so they can be reassociated.
 
271
  if (I->getOpcode() == Instruction::Mul) {
 
272
    if (!LHSBO && LHS->hasOneUse() && BinaryOperator::isNeg(LHS)) {
 
273
      LHS = LowerNegateToMultiply(cast<Instruction>(LHS), ValueRankMap);
 
274
      LHSBO = isReassociableOp(LHS, Opcode);
 
275
    }
 
276
    if (!RHSBO && RHS->hasOneUse() && BinaryOperator::isNeg(RHS)) {
 
277
      RHS = LowerNegateToMultiply(cast<Instruction>(RHS), ValueRankMap);
 
278
      RHSBO = isReassociableOp(RHS, Opcode);
 
279
    }
 
280
  }
 
281
 
 
282
  if (!LHSBO) {
 
283
    if (!RHSBO) {
 
284
      // Neither the LHS or RHS as part of the tree, thus this is a leaf.  As
 
285
      // such, just remember these operands and their rank.
 
286
      Ops.push_back(ValueEntry(getRank(LHS), LHS));
 
287
      Ops.push_back(ValueEntry(getRank(RHS), RHS));
 
288
      
 
289
      // Clear the leaves out.
 
290
      I->setOperand(0, UndefValue::get(I->getType()));
 
291
      I->setOperand(1, UndefValue::get(I->getType()));
 
292
      return;
 
293
    }
 
294
    
 
295
    // Turn X+(Y+Z) -> (Y+Z)+X
 
296
    std::swap(LHSBO, RHSBO);
 
297
    std::swap(LHS, RHS);
 
298
    bool Success = !I->swapOperands();
 
299
    assert(Success && "swapOperands failed");
 
300
    Success = false;
 
301
    MadeChange = true;
 
302
  } else if (RHSBO) {
 
303
    // Turn (A+B)+(C+D) -> (((A+B)+C)+D).  This guarantees the RHS is not
 
304
    // part of the expression tree.
 
305
    LinearizeExpr(I);
 
306
    LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
 
307
    RHS = I->getOperand(1);
 
308
    RHSBO = 0;
 
309
  }
 
310
 
 
311
  // Okay, now we know that the LHS is a nested expression and that the RHS is
 
312
  // not.  Perform reassociation.
 
313
  assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!");
 
314
 
 
315
  // Move LHS right before I to make sure that the tree expression dominates all
 
316
  // values.
 
317
  LHSBO->moveBefore(I);
 
318
 
 
319
  // Linearize the expression tree on the LHS.
 
320
  LinearizeExprTree(LHSBO, Ops);
 
321
 
 
322
  // Remember the RHS operand and its rank.
 
323
  Ops.push_back(ValueEntry(getRank(RHS), RHS));
 
324
  
 
325
  // Clear the RHS leaf out.
 
326
  I->setOperand(1, UndefValue::get(I->getType()));
 
327
}
 
328
 
 
329
// RewriteExprTree - Now that the operands for this expression tree are
 
330
// linearized and optimized, emit them in-order.  This function is written to be
 
331
// tail recursive.
 
332
void Reassociate::RewriteExprTree(BinaryOperator *I,
 
333
                                  SmallVectorImpl<ValueEntry> &Ops,
 
334
                                  unsigned i) {
 
335
  if (i+2 == Ops.size()) {
 
336
    if (I->getOperand(0) != Ops[i].Op ||
 
337
        I->getOperand(1) != Ops[i+1].Op) {
 
338
      Value *OldLHS = I->getOperand(0);
 
339
      DEBUG(dbgs() << "RA: " << *I << '\n');
 
340
      I->setOperand(0, Ops[i].Op);
 
341
      I->setOperand(1, Ops[i+1].Op);
 
342
      DEBUG(dbgs() << "TO: " << *I << '\n');
 
343
      MadeChange = true;
 
344
      ++NumChanged;
 
345
      
 
346
      // If we reassociated a tree to fewer operands (e.g. (1+a+2) -> (a+3)
 
347
      // delete the extra, now dead, nodes.
 
348
      RemoveDeadBinaryOp(OldLHS);
 
349
    }
 
350
    return;
 
351
  }
 
352
  assert(i+2 < Ops.size() && "Ops index out of range!");
 
353
 
 
354
  if (I->getOperand(1) != Ops[i].Op) {
 
355
    DEBUG(dbgs() << "RA: " << *I << '\n');
 
356
    I->setOperand(1, Ops[i].Op);
 
357
    DEBUG(dbgs() << "TO: " << *I << '\n');
 
358
    MadeChange = true;
 
359
    ++NumChanged;
 
360
  }
 
361
  
 
362
  BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
 
363
  assert(LHS->getOpcode() == I->getOpcode() &&
 
364
         "Improper expression tree!");
 
365
  
 
366
  // Compactify the tree instructions together with each other to guarantee
 
367
  // that the expression tree is dominated by all of Ops.
 
368
  LHS->moveBefore(I);
 
369
  RewriteExprTree(LHS, Ops, i+1);
 
370
}
 
371
 
 
372
 
 
373
 
 
374
// NegateValue - Insert instructions before the instruction pointed to by BI,
 
375
// that computes the negative version of the value specified.  The negative
 
376
// version of the value is returned, and BI is left pointing at the instruction
 
377
// that should be processed next by the reassociation pass.
 
378
//
 
379
static Value *NegateValue(Value *V, Instruction *BI) {
 
380
  if (Constant *C = dyn_cast<Constant>(V))
 
381
    return ConstantExpr::getNeg(C);
 
382
  
 
383
  // We are trying to expose opportunity for reassociation.  One of the things
 
384
  // that we want to do to achieve this is to push a negation as deep into an
 
385
  // expression chain as possible, to expose the add instructions.  In practice,
 
386
  // this means that we turn this:
 
387
  //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
 
388
  // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
 
389
  // the constants.  We assume that instcombine will clean up the mess later if
 
390
  // we introduce tons of unnecessary negation instructions.
 
391
  //
 
392
  if (Instruction *I = dyn_cast<Instruction>(V))
 
393
    if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
 
394
      // Push the negates through the add.
 
395
      I->setOperand(0, NegateValue(I->getOperand(0), BI));
 
396
      I->setOperand(1, NegateValue(I->getOperand(1), BI));
 
397
 
 
398
      // We must move the add instruction here, because the neg instructions do
 
399
      // not dominate the old add instruction in general.  By moving it, we are
 
400
      // assured that the neg instructions we just inserted dominate the 
 
401
      // instruction we are about to insert after them.
 
402
      //
 
403
      I->moveBefore(BI);
 
404
      I->setName(I->getName()+".neg");
 
405
      return I;
 
406
    }
 
407
  
 
408
  // Okay, we need to materialize a negated version of V with an instruction.
 
409
  // Scan the use lists of V to see if we have one already.
 
410
  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
 
411
    User *U = *UI;
 
412
    if (!BinaryOperator::isNeg(U)) continue;
 
413
 
 
414
    // We found one!  Now we have to make sure that the definition dominates
 
415
    // this use.  We do this by moving it to the entry block (if it is a
 
416
    // non-instruction value) or right after the definition.  These negates will
 
417
    // be zapped by reassociate later, so we don't need much finesse here.
 
418
    BinaryOperator *TheNeg = cast<BinaryOperator>(U);
 
419
 
 
420
    // Verify that the negate is in this function, V might be a constant expr.
 
421
    if (TheNeg->getParent()->getParent() != BI->getParent()->getParent())
 
422
      continue;
 
423
    
 
424
    BasicBlock::iterator InsertPt;
 
425
    if (Instruction *InstInput = dyn_cast<Instruction>(V)) {
 
426
      if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
 
427
        InsertPt = II->getNormalDest()->begin();
 
428
      } else {
 
429
        InsertPt = InstInput;
 
430
        ++InsertPt;
 
431
      }
 
432
      while (isa<PHINode>(InsertPt)) ++InsertPt;
 
433
    } else {
 
434
      InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
 
435
    }
 
436
    TheNeg->moveBefore(InsertPt);
 
437
    return TheNeg;
 
438
  }
 
439
 
 
440
  // Insert a 'neg' instruction that subtracts the value from zero to get the
 
441
  // negation.
 
442
  return BinaryOperator::CreateNeg(V, V->getName() + ".neg", BI);
 
443
}
 
444
 
 
445
/// ShouldBreakUpSubtract - Return true if we should break up this subtract of
 
446
/// X-Y into (X + -Y).
 
447
static bool ShouldBreakUpSubtract(Instruction *Sub) {
 
448
  // If this is a negation, we can't split it up!
 
449
  if (BinaryOperator::isNeg(Sub))
 
450
    return false;
 
451
  
 
452
  // Don't bother to break this up unless either the LHS is an associable add or
 
453
  // subtract or if this is only used by one.
 
454
  if (isReassociableOp(Sub->getOperand(0), Instruction::Add) ||
 
455
      isReassociableOp(Sub->getOperand(0), Instruction::Sub))
 
456
    return true;
 
457
  if (isReassociableOp(Sub->getOperand(1), Instruction::Add) ||
 
458
      isReassociableOp(Sub->getOperand(1), Instruction::Sub))
 
459
    return true;
 
460
  if (Sub->hasOneUse() && 
 
461
      (isReassociableOp(Sub->use_back(), Instruction::Add) ||
 
462
       isReassociableOp(Sub->use_back(), Instruction::Sub)))
 
463
    return true;
 
464
    
 
465
  return false;
 
466
}
 
467
 
 
468
/// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
 
469
/// only used by an add, transform this into (X+(0-Y)) to promote better
 
470
/// reassociation.
 
471
static Instruction *BreakUpSubtract(Instruction *Sub,
 
472
                              DenseMap<AssertingVH<>, unsigned> &ValueRankMap) {
 
473
  // Convert a subtract into an add and a neg instruction. This allows sub
 
474
  // instructions to be commuted with other add instructions.
 
475
  //
 
476
  // Calculate the negative value of Operand 1 of the sub instruction,
 
477
  // and set it as the RHS of the add instruction we just made.
 
478
  //
 
479
  Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
 
480
  Instruction *New =
 
481
    BinaryOperator::CreateAdd(Sub->getOperand(0), NegVal, "", Sub);
 
482
  New->takeName(Sub);
 
483
 
 
484
  // Everyone now refers to the add instruction.
 
485
  ValueRankMap.erase(Sub);
 
486
  Sub->replaceAllUsesWith(New);
 
487
  Sub->eraseFromParent();
 
488
 
 
489
  DEBUG(dbgs() << "Negated: " << *New << '\n');
 
490
  return New;
 
491
}
 
492
 
 
493
/// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
 
494
/// by one, change this into a multiply by a constant to assist with further
 
495
/// reassociation.
 
496
static Instruction *ConvertShiftToMul(Instruction *Shl, 
 
497
                              DenseMap<AssertingVH<>, unsigned> &ValueRankMap) {
 
498
  // If an operand of this shift is a reassociable multiply, or if the shift
 
499
  // is used by a reassociable multiply or add, turn into a multiply.
 
500
  if (isReassociableOp(Shl->getOperand(0), Instruction::Mul) ||
 
501
      (Shl->hasOneUse() && 
 
502
       (isReassociableOp(Shl->use_back(), Instruction::Mul) ||
 
503
        isReassociableOp(Shl->use_back(), Instruction::Add)))) {
 
504
    Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
 
505
    MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
 
506
    
 
507
    Instruction *Mul =
 
508
      BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, "", Shl);
 
509
    ValueRankMap.erase(Shl);
 
510
    Mul->takeName(Shl);
 
511
    Shl->replaceAllUsesWith(Mul);
 
512
    Shl->eraseFromParent();
 
513
    return Mul;
 
514
  }
 
515
  return 0;
 
516
}
 
517
 
 
518
// Scan backwards and forwards among values with the same rank as element i to
 
519
// see if X exists.  If X does not exist, return i.  This is useful when
 
520
// scanning for 'x' when we see '-x' because they both get the same rank.
 
521
static unsigned FindInOperandList(SmallVectorImpl<ValueEntry> &Ops, unsigned i,
 
522
                                  Value *X) {
 
523
  unsigned XRank = Ops[i].Rank;
 
524
  unsigned e = Ops.size();
 
525
  for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
 
526
    if (Ops[j].Op == X)
 
527
      return j;
 
528
  // Scan backwards.
 
529
  for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
 
530
    if (Ops[j].Op == X)
 
531
      return j;
 
532
  return i;
 
533
}
 
534
 
 
535
/// EmitAddTreeOfValues - Emit a tree of add instructions, summing Ops together
 
536
/// and returning the result.  Insert the tree before I.
 
537
static Value *EmitAddTreeOfValues(Instruction *I, SmallVectorImpl<Value*> &Ops){
 
538
  if (Ops.size() == 1) return Ops.back();
 
539
  
 
540
  Value *V1 = Ops.back();
 
541
  Ops.pop_back();
 
542
  Value *V2 = EmitAddTreeOfValues(I, Ops);
 
543
  return BinaryOperator::CreateAdd(V2, V1, "tmp", I);
 
544
}
 
545
 
 
546
/// RemoveFactorFromExpression - If V is an expression tree that is a 
 
547
/// multiplication sequence, and if this sequence contains a multiply by Factor,
 
548
/// remove Factor from the tree and return the new tree.
 
549
Value *Reassociate::RemoveFactorFromExpression(Value *V, Value *Factor) {
 
550
  BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
 
551
  if (!BO) return 0;
 
552
  
 
553
  SmallVector<ValueEntry, 8> Factors;
 
554
  LinearizeExprTree(BO, Factors);
 
555
 
 
556
  bool FoundFactor = false;
 
557
  bool NeedsNegate = false;
 
558
  for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
 
559
    if (Factors[i].Op == Factor) {
 
560
      FoundFactor = true;
 
561
      Factors.erase(Factors.begin()+i);
 
562
      break;
 
563
    }
 
564
    
 
565
    // If this is a negative version of this factor, remove it.
 
566
    if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor))
 
567
      if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
 
568
        if (FC1->getValue() == -FC2->getValue()) {
 
569
          FoundFactor = NeedsNegate = true;
 
570
          Factors.erase(Factors.begin()+i);
 
571
          break;
 
572
        }
 
573
  }
 
574
  
 
575
  if (!FoundFactor) {
 
576
    // Make sure to restore the operands to the expression tree.
 
577
    RewriteExprTree(BO, Factors);
 
578
    return 0;
 
579
  }
 
580
  
 
581
  BasicBlock::iterator InsertPt = BO; ++InsertPt;
 
582
  
 
583
  // If this was just a single multiply, remove the multiply and return the only
 
584
  // remaining operand.
 
585
  if (Factors.size() == 1) {
 
586
    ValueRankMap.erase(BO);
 
587
    BO->eraseFromParent();
 
588
    V = Factors[0].Op;
 
589
  } else {
 
590
    RewriteExprTree(BO, Factors);
 
591
    V = BO;
 
592
  }
 
593
  
 
594
  if (NeedsNegate)
 
595
    V = BinaryOperator::CreateNeg(V, "neg", InsertPt);
 
596
  
 
597
  return V;
 
598
}
 
599
 
 
600
/// FindSingleUseMultiplyFactors - If V is a single-use multiply, recursively
 
601
/// add its operands as factors, otherwise add V to the list of factors.
 
602
///
 
603
/// Ops is the top-level list of add operands we're trying to factor.
 
604
static void FindSingleUseMultiplyFactors(Value *V,
 
605
                                         SmallVectorImpl<Value*> &Factors,
 
606
                                       const SmallVectorImpl<ValueEntry> &Ops,
 
607
                                         bool IsRoot) {
 
608
  BinaryOperator *BO;
 
609
  if (!(V->hasOneUse() || V->use_empty()) || // More than one use.
 
610
      !(BO = dyn_cast<BinaryOperator>(V)) ||
 
611
      BO->getOpcode() != Instruction::Mul) {
 
612
    Factors.push_back(V);
 
613
    return;
 
614
  }
 
615
  
 
616
  // If this value has a single use because it is another input to the add
 
617
  // tree we're reassociating and we dropped its use, it actually has two
 
618
  // uses and we can't factor it.
 
619
  if (!IsRoot) {
 
620
    for (unsigned i = 0, e = Ops.size(); i != e; ++i)
 
621
      if (Ops[i].Op == V) {
 
622
        Factors.push_back(V);
 
623
        return;
 
624
      }
 
625
  }
 
626
  
 
627
  
 
628
  // Otherwise, add the LHS and RHS to the list of factors.
 
629
  FindSingleUseMultiplyFactors(BO->getOperand(1), Factors, Ops, false);
 
630
  FindSingleUseMultiplyFactors(BO->getOperand(0), Factors, Ops, false);
 
631
}
 
632
 
 
633
/// OptimizeAndOrXor - Optimize a series of operands to an 'and', 'or', or 'xor'
 
634
/// instruction.  This optimizes based on identities.  If it can be reduced to
 
635
/// a single Value, it is returned, otherwise the Ops list is mutated as
 
636
/// necessary.
 
637
static Value *OptimizeAndOrXor(unsigned Opcode,
 
638
                               SmallVectorImpl<ValueEntry> &Ops) {
 
639
  // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
 
640
  // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
 
641
  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
 
642
    // First, check for X and ~X in the operand list.
 
643
    assert(i < Ops.size());
 
644
    if (BinaryOperator::isNot(Ops[i].Op)) {    // Cannot occur for ^.
 
645
      Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
 
646
      unsigned FoundX = FindInOperandList(Ops, i, X);
 
647
      if (FoundX != i) {
 
648
        if (Opcode == Instruction::And)   // ...&X&~X = 0
 
649
          return Constant::getNullValue(X->getType());
 
650
        
 
651
        if (Opcode == Instruction::Or)    // ...|X|~X = -1
 
652
          return Constant::getAllOnesValue(X->getType());
 
653
      }
 
654
    }
 
655
    
 
656
    // Next, check for duplicate pairs of values, which we assume are next to
 
657
    // each other, due to our sorting criteria.
 
658
    assert(i < Ops.size());
 
659
    if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
 
660
      if (Opcode == Instruction::And || Opcode == Instruction::Or) {
 
661
        // Drop duplicate values for And and Or.
 
662
        Ops.erase(Ops.begin()+i);
 
663
        --i; --e;
 
664
        ++NumAnnihil;
 
665
        continue;
 
666
      }
 
667
      
 
668
      // Drop pairs of values for Xor.
 
669
      assert(Opcode == Instruction::Xor);
 
670
      if (e == 2)
 
671
        return Constant::getNullValue(Ops[0].Op->getType());
 
672
      
 
673
      // Y ^ X^X -> Y
 
674
      Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
 
675
      i -= 1; e -= 2;
 
676
      ++NumAnnihil;
 
677
    }
 
678
  }
 
679
  return 0;
 
680
}
 
681
 
 
682
/// OptimizeAdd - Optimize a series of operands to an 'add' instruction.  This
 
683
/// optimizes based on identities.  If it can be reduced to a single Value, it
 
684
/// is returned, otherwise the Ops list is mutated as necessary.
 
685
Value *Reassociate::OptimizeAdd(Instruction *I,
 
686
                                SmallVectorImpl<ValueEntry> &Ops) {
 
687
  // Scan the operand lists looking for X and -X pairs.  If we find any, we
 
688
  // can simplify the expression. X+-X == 0.  While we're at it, scan for any
 
689
  // duplicates.  We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
 
690
  //
 
691
  // TODO: We could handle "X + ~X" -> "-1" if we wanted, since "-X = ~X+1".
 
692
  //
 
693
  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
 
694
    Value *TheOp = Ops[i].Op;
 
695
    // Check to see if we've seen this operand before.  If so, we factor all
 
696
    // instances of the operand together.  Due to our sorting criteria, we know
 
697
    // that these need to be next to each other in the vector.
 
698
    if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
 
699
      // Rescan the list, remove all instances of this operand from the expr.
 
700
      unsigned NumFound = 0;
 
701
      do {
 
702
        Ops.erase(Ops.begin()+i);
 
703
        ++NumFound;
 
704
      } while (i != Ops.size() && Ops[i].Op == TheOp);
 
705
      
 
706
      DEBUG(errs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n');
 
707
      ++NumFactor;
 
708
      
 
709
      // Insert a new multiply.
 
710
      Value *Mul = ConstantInt::get(cast<IntegerType>(I->getType()), NumFound);
 
711
      Mul = BinaryOperator::CreateMul(TheOp, Mul, "factor", I);
 
712
      
 
713
      // Now that we have inserted a multiply, optimize it. This allows us to
 
714
      // handle cases that require multiple factoring steps, such as this:
 
715
      // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
 
716
      Mul = ReassociateExpression(cast<BinaryOperator>(Mul));
 
717
      
 
718
      // If every add operand was a duplicate, return the multiply.
 
719
      if (Ops.empty())
 
720
        return Mul;
 
721
      
 
722
      // Otherwise, we had some input that didn't have the dupe, such as
 
723
      // "A + A + B" -> "A*2 + B".  Add the new multiply to the list of
 
724
      // things being added by this operation.
 
725
      Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul));
 
726
      
 
727
      --i;
 
728
      e = Ops.size();
 
729
      continue;
 
730
    }
 
731
    
 
732
    // Check for X and -X in the operand list.
 
733
    if (!BinaryOperator::isNeg(TheOp))
 
734
      continue;
 
735
    
 
736
    Value *X = BinaryOperator::getNegArgument(TheOp);
 
737
    unsigned FoundX = FindInOperandList(Ops, i, X);
 
738
    if (FoundX == i)
 
739
      continue;
 
740
    
 
741
    // Remove X and -X from the operand list.
 
742
    if (Ops.size() == 2)
 
743
      return Constant::getNullValue(X->getType());
 
744
    
 
745
    Ops.erase(Ops.begin()+i);
 
746
    if (i < FoundX)
 
747
      --FoundX;
 
748
    else
 
749
      --i;   // Need to back up an extra one.
 
750
    Ops.erase(Ops.begin()+FoundX);
 
751
    ++NumAnnihil;
 
752
    --i;     // Revisit element.
 
753
    e -= 2;  // Removed two elements.
 
754
  }
 
755
  
 
756
  // Scan the operand list, checking to see if there are any common factors
 
757
  // between operands.  Consider something like A*A+A*B*C+D.  We would like to
 
758
  // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
 
759
  // To efficiently find this, we count the number of times a factor occurs
 
760
  // for any ADD operands that are MULs.
 
761
  DenseMap<Value*, unsigned> FactorOccurrences;
 
762
  
 
763
  // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
 
764
  // where they are actually the same multiply.
 
765
  unsigned MaxOcc = 0;
 
766
  Value *MaxOccVal = 0;
 
767
  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
 
768
    BinaryOperator *BOp = dyn_cast<BinaryOperator>(Ops[i].Op);
 
769
    if (BOp == 0 || BOp->getOpcode() != Instruction::Mul || !BOp->use_empty())
 
770
      continue;
 
771
    
 
772
    // Compute all of the factors of this added value.
 
773
    SmallVector<Value*, 8> Factors;
 
774
    FindSingleUseMultiplyFactors(BOp, Factors, Ops, true);
 
775
    assert(Factors.size() > 1 && "Bad linearize!");
 
776
    
 
777
    // Add one to FactorOccurrences for each unique factor in this op.
 
778
    SmallPtrSet<Value*, 8> Duplicates;
 
779
    for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
 
780
      Value *Factor = Factors[i];
 
781
      if (!Duplicates.insert(Factor)) continue;
 
782
      
 
783
      unsigned Occ = ++FactorOccurrences[Factor];
 
784
      if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
 
785
      
 
786
      // If Factor is a negative constant, add the negated value as a factor
 
787
      // because we can percolate the negate out.  Watch for minint, which
 
788
      // cannot be positivified.
 
789
      if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor))
 
790
        if (CI->getValue().isNegative() && !CI->getValue().isMinSignedValue()) {
 
791
          Factor = ConstantInt::get(CI->getContext(), -CI->getValue());
 
792
          assert(!Duplicates.count(Factor) &&
 
793
                 "Shouldn't have two constant factors, missed a canonicalize");
 
794
          
 
795
          unsigned Occ = ++FactorOccurrences[Factor];
 
796
          if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
 
797
        }
 
798
    }
 
799
  }
 
800
  
 
801
  // If any factor occurred more than one time, we can pull it out.
 
802
  if (MaxOcc > 1) {
 
803
    DEBUG(errs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << '\n');
 
804
    ++NumFactor;
 
805
 
 
806
    // Create a new instruction that uses the MaxOccVal twice.  If we don't do
 
807
    // this, we could otherwise run into situations where removing a factor
 
808
    // from an expression will drop a use of maxocc, and this can cause 
 
809
    // RemoveFactorFromExpression on successive values to behave differently.
 
810
    Instruction *DummyInst = BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal);
 
811
    SmallVector<Value*, 4> NewMulOps;
 
812
    for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
 
813
      // Only try to remove factors from expressions we're allowed to.
 
814
      BinaryOperator *BOp = dyn_cast<BinaryOperator>(Ops[i].Op);
 
815
      if (BOp == 0 || BOp->getOpcode() != Instruction::Mul || !BOp->use_empty())
 
816
        continue;
 
817
      
 
818
      if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
 
819
        NewMulOps.push_back(V);
 
820
        Ops.erase(Ops.begin()+i);
 
821
        --i; --e;
 
822
      }
 
823
    }
 
824
    
 
825
    // No need for extra uses anymore.
 
826
    delete DummyInst;
 
827
 
 
828
    unsigned NumAddedValues = NewMulOps.size();
 
829
    Value *V = EmitAddTreeOfValues(I, NewMulOps);
 
830
 
 
831
    // Now that we have inserted the add tree, optimize it. This allows us to
 
832
    // handle cases that require multiple factoring steps, such as this:
 
833
    // A*A*B + A*A*C   -->   A*(A*B+A*C)   -->   A*(A*(B+C))
 
834
    assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
 
835
    (void)NumAddedValues;
 
836
    V = ReassociateExpression(cast<BinaryOperator>(V));
 
837
 
 
838
    // Create the multiply.
 
839
    Value *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I);
 
840
 
 
841
    // Rerun associate on the multiply in case the inner expression turned into
 
842
    // a multiply.  We want to make sure that we keep things in canonical form.
 
843
    V2 = ReassociateExpression(cast<BinaryOperator>(V2));
 
844
    
 
845
    // If every add operand included the factor (e.g. "A*B + A*C"), then the
 
846
    // entire result expression is just the multiply "A*(B+C)".
 
847
    if (Ops.empty())
 
848
      return V2;
 
849
    
 
850
    // Otherwise, we had some input that didn't have the factor, such as
 
851
    // "A*B + A*C + D" -> "A*(B+C) + D".  Add the new multiply to the list of
 
852
    // things being added by this operation.
 
853
    Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
 
854
  }
 
855
  
 
856
  return 0;
 
857
}
 
858
 
 
859
Value *Reassociate::OptimizeExpression(BinaryOperator *I,
 
860
                                       SmallVectorImpl<ValueEntry> &Ops) {
 
861
  // Now that we have the linearized expression tree, try to optimize it.
 
862
  // Start by folding any constants that we found.
 
863
  bool IterateOptimization = false;
 
864
  if (Ops.size() == 1) return Ops[0].Op;
 
865
 
 
866
  unsigned Opcode = I->getOpcode();
 
867
  
 
868
  if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
 
869
    if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
 
870
      Ops.pop_back();
 
871
      Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
 
872
      return OptimizeExpression(I, Ops);
 
873
    }
 
874
 
 
875
  // Check for destructive annihilation due to a constant being used.
 
876
  if (ConstantInt *CstVal = dyn_cast<ConstantInt>(Ops.back().Op))
 
877
    switch (Opcode) {
 
878
    default: break;
 
879
    case Instruction::And:
 
880
      if (CstVal->isZero())                  // X & 0 -> 0
 
881
        return CstVal;
 
882
      if (CstVal->isAllOnesValue())          // X & -1 -> X
 
883
        Ops.pop_back();
 
884
      break;
 
885
    case Instruction::Mul:
 
886
      if (CstVal->isZero()) {                // X * 0 -> 0
 
887
        ++NumAnnihil;
 
888
        return CstVal;
 
889
      }
 
890
        
 
891
      if (cast<ConstantInt>(CstVal)->isOne())
 
892
        Ops.pop_back();                      // X * 1 -> X
 
893
      break;
 
894
    case Instruction::Or:
 
895
      if (CstVal->isAllOnesValue())          // X | -1 -> -1
 
896
        return CstVal;
 
897
      // FALLTHROUGH!
 
898
    case Instruction::Add:
 
899
    case Instruction::Xor:
 
900
      if (CstVal->isZero())                  // X [|^+] 0 -> X
 
901
        Ops.pop_back();
 
902
      break;
 
903
    }
 
904
  if (Ops.size() == 1) return Ops[0].Op;
 
905
 
 
906
  // Handle destructive annihilation due to identities between elements in the
 
907
  // argument list here.
 
908
  switch (Opcode) {
 
909
  default: break;
 
910
  case Instruction::And:
 
911
  case Instruction::Or:
 
912
  case Instruction::Xor: {
 
913
    unsigned NumOps = Ops.size();
 
914
    if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
 
915
      return Result;
 
916
    IterateOptimization |= Ops.size() != NumOps;
 
917
    break;
 
918
  }
 
919
 
 
920
  case Instruction::Add: {
 
921
    unsigned NumOps = Ops.size();
 
922
    if (Value *Result = OptimizeAdd(I, Ops))
 
923
      return Result;
 
924
    IterateOptimization |= Ops.size() != NumOps;
 
925
  }
 
926
 
 
927
    break;
 
928
  //case Instruction::Mul:
 
929
  }
 
930
 
 
931
  if (IterateOptimization)
 
932
    return OptimizeExpression(I, Ops);
 
933
  return 0;
 
934
}
 
935
 
 
936
 
 
937
/// ReassociateBB - Inspect all of the instructions in this basic block,
 
938
/// reassociating them as we go.
 
939
void Reassociate::ReassociateBB(BasicBlock *BB) {
 
940
  for (BasicBlock::iterator BBI = BB->begin(); BBI != BB->end(); ) {
 
941
    Instruction *BI = BBI++;
 
942
    if (BI->getOpcode() == Instruction::Shl &&
 
943
        isa<ConstantInt>(BI->getOperand(1)))
 
944
      if (Instruction *NI = ConvertShiftToMul(BI, ValueRankMap)) {
 
945
        MadeChange = true;
 
946
        BI = NI;
 
947
      }
 
948
 
 
949
    // Reject cases where it is pointless to do this.
 
950
    if (!isa<BinaryOperator>(BI) || BI->getType()->isFloatingPointTy() || 
 
951
        BI->getType()->isVectorTy())
 
952
      continue;  // Floating point ops are not associative.
 
953
 
 
954
    // Do not reassociate boolean (i1) expressions.  We want to preserve the
 
955
    // original order of evaluation for short-circuited comparisons that
 
956
    // SimplifyCFG has folded to AND/OR expressions.  If the expression
 
957
    // is not further optimized, it is likely to be transformed back to a
 
958
    // short-circuited form for code gen, and the source order may have been
 
959
    // optimized for the most likely conditions.
 
960
    if (BI->getType()->isIntegerTy(1))
 
961
      continue;
 
962
 
 
963
    // If this is a subtract instruction which is not already in negate form,
 
964
    // see if we can convert it to X+-Y.
 
965
    if (BI->getOpcode() == Instruction::Sub) {
 
966
      if (ShouldBreakUpSubtract(BI)) {
 
967
        BI = BreakUpSubtract(BI, ValueRankMap);
 
968
        // Reset the BBI iterator in case BreakUpSubtract changed the
 
969
        // instruction it points to.
 
970
        BBI = BI;
 
971
        ++BBI;
 
972
        MadeChange = true;
 
973
      } else if (BinaryOperator::isNeg(BI)) {
 
974
        // Otherwise, this is a negation.  See if the operand is a multiply tree
 
975
        // and if this is not an inner node of a multiply tree.
 
976
        if (isReassociableOp(BI->getOperand(1), Instruction::Mul) &&
 
977
            (!BI->hasOneUse() ||
 
978
             !isReassociableOp(BI->use_back(), Instruction::Mul))) {
 
979
          BI = LowerNegateToMultiply(BI, ValueRankMap);
 
980
          MadeChange = true;
 
981
        }
 
982
      }
 
983
    }
 
984
 
 
985
    // If this instruction is a commutative binary operator, process it.
 
986
    if (!BI->isAssociative()) continue;
 
987
    BinaryOperator *I = cast<BinaryOperator>(BI);
 
988
 
 
989
    // If this is an interior node of a reassociable tree, ignore it until we
 
990
    // get to the root of the tree, to avoid N^2 analysis.
 
991
    if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
 
992
      continue;
 
993
 
 
994
    // If this is an add tree that is used by a sub instruction, ignore it 
 
995
    // until we process the subtract.
 
996
    if (I->hasOneUse() && I->getOpcode() == Instruction::Add &&
 
997
        cast<Instruction>(I->use_back())->getOpcode() == Instruction::Sub)
 
998
      continue;
 
999
 
 
1000
    ReassociateExpression(I);
 
1001
  }
 
1002
}
 
1003
 
 
1004
Value *Reassociate::ReassociateExpression(BinaryOperator *I) {
 
1005
  
 
1006
  // First, walk the expression tree, linearizing the tree, collecting the
 
1007
  // operand information.
 
1008
  SmallVector<ValueEntry, 8> Ops;
 
1009
  LinearizeExprTree(I, Ops);
 
1010
  
 
1011
  DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n');
 
1012
  
 
1013
  // Now that we have linearized the tree to a list and have gathered all of
 
1014
  // the operands and their ranks, sort the operands by their rank.  Use a
 
1015
  // stable_sort so that values with equal ranks will have their relative
 
1016
  // positions maintained (and so the compiler is deterministic).  Note that
 
1017
  // this sorts so that the highest ranking values end up at the beginning of
 
1018
  // the vector.
 
1019
  std::stable_sort(Ops.begin(), Ops.end());
 
1020
  
 
1021
  // OptimizeExpression - Now that we have the expression tree in a convenient
 
1022
  // sorted form, optimize it globally if possible.
 
1023
  if (Value *V = OptimizeExpression(I, Ops)) {
 
1024
    // This expression tree simplified to something that isn't a tree,
 
1025
    // eliminate it.
 
1026
    DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n');
 
1027
    I->replaceAllUsesWith(V);
 
1028
    RemoveDeadBinaryOp(I);
 
1029
    ++NumAnnihil;
 
1030
    return V;
 
1031
  }
 
1032
  
 
1033
  // We want to sink immediates as deeply as possible except in the case where
 
1034
  // this is a multiply tree used only by an add, and the immediate is a -1.
 
1035
  // In this case we reassociate to put the negation on the outside so that we
 
1036
  // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
 
1037
  if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
 
1038
      cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add &&
 
1039
      isa<ConstantInt>(Ops.back().Op) &&
 
1040
      cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
 
1041
    ValueEntry Tmp = Ops.pop_back_val();
 
1042
    Ops.insert(Ops.begin(), Tmp);
 
1043
  }
 
1044
  
 
1045
  DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n');
 
1046
  
 
1047
  if (Ops.size() == 1) {
 
1048
    // This expression tree simplified to something that isn't a tree,
 
1049
    // eliminate it.
 
1050
    I->replaceAllUsesWith(Ops[0].Op);
 
1051
    RemoveDeadBinaryOp(I);
 
1052
    return Ops[0].Op;
 
1053
  }
 
1054
  
 
1055
  // Now that we ordered and optimized the expressions, splat them back into
 
1056
  // the expression tree, removing any unneeded nodes.
 
1057
  RewriteExprTree(I, Ops);
 
1058
  return I;
 
1059
}
 
1060
 
 
1061
 
 
1062
bool Reassociate::runOnFunction(Function &F) {
 
1063
  // Recalculate the rank map for F
 
1064
  BuildRankMap(F);
 
1065
 
 
1066
  MadeChange = false;
 
1067
  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
 
1068
    ReassociateBB(FI);
 
1069
 
 
1070
  // We are done with the rank map.
 
1071
  RankMap.clear();
 
1072
  ValueRankMap.clear();
 
1073
  return MadeChange;
 
1074
}
 
1075