LLVM API Documentation
00001 //===- Reassociate.cpp - Reassociate binary expressions -------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file was developed by the LLVM research group and is distributed under 00006 // the University of Illinois Open Source License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This pass reassociates commutative expressions in an order that is designed 00011 // to promote better constant propagation, GCSE, LICM, PRE... 00012 // 00013 // For example: 4 + (x + 5) -> x + (4 + 5) 00014 // 00015 // In the implementation of this algorithm, constants are assigned rank = 0, 00016 // function arguments are rank = 1, and other values are assigned ranks 00017 // corresponding to the reverse post order traversal of current function 00018 // (starting at 2), which effectively gives values in deep loops higher rank 00019 // than values not in loops. 00020 // 00021 //===----------------------------------------------------------------------===// 00022 00023 #define DEBUG_TYPE "reassociate" 00024 #include "llvm/Transforms/Scalar.h" 00025 #include "llvm/Constants.h" 00026 #include "llvm/DerivedTypes.h" 00027 #include "llvm/Function.h" 00028 #include "llvm/Instructions.h" 00029 #include "llvm/Pass.h" 00030 #include "llvm/Assembly/Writer.h" 00031 #include "llvm/Support/CFG.h" 00032 #include "llvm/Support/Debug.h" 00033 #include "llvm/ADT/PostOrderIterator.h" 00034 #include "llvm/ADT/Statistic.h" 00035 #include <algorithm> 00036 #include <iostream> 00037 using namespace llvm; 00038 00039 namespace { 00040 Statistic<> NumLinear ("reassociate","Number of insts linearized"); 00041 Statistic<> NumChanged("reassociate","Number of insts reassociated"); 00042 Statistic<> NumSwapped("reassociate","Number of insts with operands swapped"); 00043 Statistic<> NumAnnihil("reassociate","Number of expr tree annihilated"); 00044 Statistic<> NumFactor ("reassociate","Number of multiplies factored"); 00045 00046 struct ValueEntry { 00047 unsigned Rank; 00048 Value *Op; 00049 ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {} 00050 }; 00051 inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) { 00052 return LHS.Rank > RHS.Rank; // Sort so that highest rank goes to start. 00053 } 00054 } 00055 00056 /// PrintOps - Print out the expression identified in the Ops list. 00057 /// 00058 static void PrintOps(Instruction *I, const std::vector<ValueEntry> &Ops) { 00059 Module *M = I->getParent()->getParent()->getParent(); 00060 std::cerr << Instruction::getOpcodeName(I->getOpcode()) << " " 00061 << *Ops[0].Op->getType(); 00062 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 00063 WriteAsOperand(std::cerr << " ", Ops[i].Op, false, true, M) 00064 << "," << Ops[i].Rank; 00065 } 00066 00067 namespace { 00068 class Reassociate : public FunctionPass { 00069 std::map<BasicBlock*, unsigned> RankMap; 00070 std::map<Value*, unsigned> ValueRankMap; 00071 bool MadeChange; 00072 public: 00073 bool runOnFunction(Function &F); 00074 00075 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00076 AU.setPreservesCFG(); 00077 } 00078 private: 00079 void BuildRankMap(Function &F); 00080 unsigned getRank(Value *V); 00081 void ReassociateExpression(BinaryOperator *I); 00082 void RewriteExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops, 00083 unsigned Idx = 0); 00084 Value *OptimizeExpression(BinaryOperator *I, std::vector<ValueEntry> &Ops); 00085 void LinearizeExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops); 00086 void LinearizeExpr(BinaryOperator *I); 00087 Value *RemoveFactorFromExpression(Value *V, Value *Factor); 00088 void ReassociateBB(BasicBlock *BB); 00089 00090 void RemoveDeadBinaryOp(Value *V); 00091 }; 00092 00093 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions"); 00094 } 00095 00096 // Public interface to the Reassociate pass 00097 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); } 00098 00099 void Reassociate::RemoveDeadBinaryOp(Value *V) { 00100 BinaryOperator *BOp = dyn_cast<BinaryOperator>(V); 00101 if (!BOp || !BOp->use_empty()) return; 00102 00103 Value *LHS = BOp->getOperand(0), *RHS = BOp->getOperand(1); 00104 RemoveDeadBinaryOp(LHS); 00105 RemoveDeadBinaryOp(RHS); 00106 } 00107 00108 00109 static bool isUnmovableInstruction(Instruction *I) { 00110 if (I->getOpcode() == Instruction::PHI || 00111 I->getOpcode() == Instruction::Alloca || 00112 I->getOpcode() == Instruction::Load || 00113 I->getOpcode() == Instruction::Malloc || 00114 I->getOpcode() == Instruction::Invoke || 00115 I->getOpcode() == Instruction::Call || 00116 I->getOpcode() == Instruction::Div || 00117 I->getOpcode() == Instruction::Rem) 00118 return true; 00119 return false; 00120 } 00121 00122 void Reassociate::BuildRankMap(Function &F) { 00123 unsigned i = 2; 00124 00125 // Assign distinct ranks to function arguments 00126 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) 00127 ValueRankMap[I] = ++i; 00128 00129 ReversePostOrderTraversal<Function*> RPOT(&F); 00130 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(), 00131 E = RPOT.end(); I != E; ++I) { 00132 BasicBlock *BB = *I; 00133 unsigned BBRank = RankMap[BB] = ++i << 16; 00134 00135 // Walk the basic block, adding precomputed ranks for any instructions that 00136 // we cannot move. This ensures that the ranks for these instructions are 00137 // all different in the block. 00138 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 00139 if (isUnmovableInstruction(I)) 00140 ValueRankMap[I] = ++BBRank; 00141 } 00142 } 00143 00144 unsigned Reassociate::getRank(Value *V) { 00145 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument... 00146 00147 Instruction *I = dyn_cast<Instruction>(V); 00148 if (I == 0) return 0; // Otherwise it's a global or constant, rank 0. 00149 00150 unsigned &CachedRank = ValueRankMap[I]; 00151 if (CachedRank) return CachedRank; // Rank already known? 00152 00153 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that 00154 // we can reassociate expressions for code motion! Since we do not recurse 00155 // for PHI nodes, we cannot have infinite recursion here, because there 00156 // cannot be loops in the value graph that do not go through PHI nodes. 00157 unsigned Rank = 0, MaxRank = RankMap[I->getParent()]; 00158 for (unsigned i = 0, e = I->getNumOperands(); 00159 i != e && Rank != MaxRank; ++i) 00160 Rank = std::max(Rank, getRank(I->getOperand(i))); 00161 00162 // If this is a not or neg instruction, do not count it for rank. This 00163 // assures us that X and ~X will have the same rank. 00164 if (!I->getType()->isIntegral() || 00165 (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I))) 00166 ++Rank; 00167 00168 //DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = " 00169 //<< Rank << "\n"); 00170 00171 return CachedRank = Rank; 00172 } 00173 00174 /// isReassociableOp - Return true if V is an instruction of the specified 00175 /// opcode and if it only has one use. 00176 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) { 00177 if ((V->hasOneUse() || V->use_empty()) && isa<Instruction>(V) && 00178 cast<Instruction>(V)->getOpcode() == Opcode) 00179 return cast<BinaryOperator>(V); 00180 return 0; 00181 } 00182 00183 /// LowerNegateToMultiply - Replace 0-X with X*-1. 00184 /// 00185 static Instruction *LowerNegateToMultiply(Instruction *Neg) { 00186 Constant *Cst; 00187 if (Neg->getType()->isFloatingPoint()) 00188 Cst = ConstantFP::get(Neg->getType(), -1); 00189 else 00190 Cst = ConstantInt::getAllOnesValue(Neg->getType()); 00191 00192 std::string NegName = Neg->getName(); Neg->setName(""); 00193 Instruction *Res = BinaryOperator::createMul(Neg->getOperand(1), Cst, NegName, 00194 Neg); 00195 Neg->replaceAllUsesWith(Res); 00196 Neg->eraseFromParent(); 00197 return Res; 00198 } 00199 00200 // Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'. 00201 // Note that if D is also part of the expression tree that we recurse to 00202 // linearize it as well. Besides that case, this does not recurse into A,B, or 00203 // C. 00204 void Reassociate::LinearizeExpr(BinaryOperator *I) { 00205 BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0)); 00206 BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1)); 00207 assert(isReassociableOp(LHS, I->getOpcode()) && 00208 isReassociableOp(RHS, I->getOpcode()) && 00209 "Not an expression that needs linearization?"); 00210 00211 DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I); 00212 00213 // Move the RHS instruction to live immediately before I, avoiding breaking 00214 // dominator properties. 00215 RHS->moveBefore(I); 00216 00217 // Move operands around to do the linearization. 00218 I->setOperand(1, RHS->getOperand(0)); 00219 RHS->setOperand(0, LHS); 00220 I->setOperand(0, RHS); 00221 00222 ++NumLinear; 00223 MadeChange = true; 00224 DEBUG(std::cerr << "Linearized: " << *I); 00225 00226 // If D is part of this expression tree, tail recurse. 00227 if (isReassociableOp(I->getOperand(1), I->getOpcode())) 00228 LinearizeExpr(I); 00229 } 00230 00231 00232 /// LinearizeExprTree - Given an associative binary expression tree, traverse 00233 /// all of the uses putting it into canonical form. This forces a left-linear 00234 /// form of the the expression (((a+b)+c)+d), and collects information about the 00235 /// rank of the non-tree operands. 00236 /// 00237 /// NOTE: These intentionally destroys the expression tree operands (turning 00238 /// them into undef values) to reduce #uses of the values. This means that the 00239 /// caller MUST use something like RewriteExprTree to put the values back in. 00240 /// 00241 void Reassociate::LinearizeExprTree(BinaryOperator *I, 00242 std::vector<ValueEntry> &Ops) { 00243 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1); 00244 unsigned Opcode = I->getOpcode(); 00245 00246 // First step, linearize the expression if it is in ((A+B)+(C+D)) form. 00247 BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode); 00248 BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode); 00249 00250 // If this is a multiply expression tree and it contains internal negations, 00251 // transform them into multiplies by -1 so they can be reassociated. 00252 if (I->getOpcode() == Instruction::Mul) { 00253 if (!LHSBO && LHS->hasOneUse() && BinaryOperator::isNeg(LHS)) { 00254 LHS = LowerNegateToMultiply(cast<Instruction>(LHS)); 00255 LHSBO = isReassociableOp(LHS, Opcode); 00256 } 00257 if (!RHSBO && RHS->hasOneUse() && BinaryOperator::isNeg(RHS)) { 00258 RHS = LowerNegateToMultiply(cast<Instruction>(RHS)); 00259 RHSBO = isReassociableOp(RHS, Opcode); 00260 } 00261 } 00262 00263 if (!LHSBO) { 00264 if (!RHSBO) { 00265 // Neither the LHS or RHS as part of the tree, thus this is a leaf. As 00266 // such, just remember these operands and their rank. 00267 Ops.push_back(ValueEntry(getRank(LHS), LHS)); 00268 Ops.push_back(ValueEntry(getRank(RHS), RHS)); 00269 00270 // Clear the leaves out. 00271 I->setOperand(0, UndefValue::get(I->getType())); 00272 I->setOperand(1, UndefValue::get(I->getType())); 00273 return; 00274 } else { 00275 // Turn X+(Y+Z) -> (Y+Z)+X 00276 std::swap(LHSBO, RHSBO); 00277 std::swap(LHS, RHS); 00278 bool Success = !I->swapOperands(); 00279 assert(Success && "swapOperands failed"); 00280 MadeChange = true; 00281 } 00282 } else if (RHSBO) { 00283 // Turn (A+B)+(C+D) -> (((A+B)+C)+D). This guarantees the the RHS is not 00284 // part of the expression tree. 00285 LinearizeExpr(I); 00286 LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0)); 00287 RHS = I->getOperand(1); 00288 RHSBO = 0; 00289 } 00290 00291 // Okay, now we know that the LHS is a nested expression and that the RHS is 00292 // not. Perform reassociation. 00293 assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!"); 00294 00295 // Move LHS right before I to make sure that the tree expression dominates all 00296 // values. 00297 LHSBO->moveBefore(I); 00298 00299 // Linearize the expression tree on the LHS. 00300 LinearizeExprTree(LHSBO, Ops); 00301 00302 // Remember the RHS operand and its rank. 00303 Ops.push_back(ValueEntry(getRank(RHS), RHS)); 00304 00305 // Clear the RHS leaf out. 00306 I->setOperand(1, UndefValue::get(I->getType())); 00307 } 00308 00309 // RewriteExprTree - Now that the operands for this expression tree are 00310 // linearized and optimized, emit them in-order. This function is written to be 00311 // tail recursive. 00312 void Reassociate::RewriteExprTree(BinaryOperator *I, 00313 std::vector<ValueEntry> &Ops, 00314 unsigned i) { 00315 if (i+2 == Ops.size()) { 00316 if (I->getOperand(0) != Ops[i].Op || 00317 I->getOperand(1) != Ops[i+1].Op) { 00318 Value *OldLHS = I->getOperand(0); 00319 DEBUG(std::cerr << "RA: " << *I); 00320 I->setOperand(0, Ops[i].Op); 00321 I->setOperand(1, Ops[i+1].Op); 00322 DEBUG(std::cerr << "TO: " << *I); 00323 MadeChange = true; 00324 ++NumChanged; 00325 00326 // If we reassociated a tree to fewer operands (e.g. (1+a+2) -> (a+3) 00327 // delete the extra, now dead, nodes. 00328 RemoveDeadBinaryOp(OldLHS); 00329 } 00330 return; 00331 } 00332 assert(i+2 < Ops.size() && "Ops index out of range!"); 00333 00334 if (I->getOperand(1) != Ops[i].Op) { 00335 DEBUG(std::cerr << "RA: " << *I); 00336 I->setOperand(1, Ops[i].Op); 00337 DEBUG(std::cerr << "TO: " << *I); 00338 MadeChange = true; 00339 ++NumChanged; 00340 } 00341 00342 BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0)); 00343 assert(LHS->getOpcode() == I->getOpcode() && 00344 "Improper expression tree!"); 00345 00346 // Compactify the tree instructions together with each other to guarantee 00347 // that the expression tree is dominated by all of Ops. 00348 LHS->moveBefore(I); 00349 RewriteExprTree(LHS, Ops, i+1); 00350 } 00351 00352 00353 00354 // NegateValue - Insert instructions before the instruction pointed to by BI, 00355 // that computes the negative version of the value specified. The negative 00356 // version of the value is returned, and BI is left pointing at the instruction 00357 // that should be processed next by the reassociation pass. 00358 // 00359 static Value *NegateValue(Value *V, Instruction *BI) { 00360 // We are trying to expose opportunity for reassociation. One of the things 00361 // that we want to do to achieve this is to push a negation as deep into an 00362 // expression chain as possible, to expose the add instructions. In practice, 00363 // this means that we turn this: 00364 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D 00365 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate 00366 // the constants. We assume that instcombine will clean up the mess later if 00367 // we introduce tons of unnecessary negation instructions... 00368 // 00369 if (Instruction *I = dyn_cast<Instruction>(V)) 00370 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) { 00371 // Push the negates through the add. 00372 I->setOperand(0, NegateValue(I->getOperand(0), BI)); 00373 I->setOperand(1, NegateValue(I->getOperand(1), BI)); 00374 00375 // We must move the add instruction here, because the neg instructions do 00376 // not dominate the old add instruction in general. By moving it, we are 00377 // assured that the neg instructions we just inserted dominate the 00378 // instruction we are about to insert after them. 00379 // 00380 I->moveBefore(BI); 00381 I->setName(I->getName()+".neg"); 00382 return I; 00383 } 00384 00385 // Insert a 'neg' instruction that subtracts the value from zero to get the 00386 // negation. 00387 // 00388 return BinaryOperator::createNeg(V, V->getName() + ".neg", BI); 00389 } 00390 00391 /// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is 00392 /// only used by an add, transform this into (X+(0-Y)) to promote better 00393 /// reassociation. 00394 static Instruction *BreakUpSubtract(Instruction *Sub) { 00395 // Don't bother to break this up unless either the LHS is an associable add or 00396 // if this is only used by one. 00397 if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) && 00398 !isReassociableOp(Sub->getOperand(1), Instruction::Add) && 00399 !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add))) 00400 return 0; 00401 00402 // Convert a subtract into an add and a neg instruction... so that sub 00403 // instructions can be commuted with other add instructions... 00404 // 00405 // Calculate the negative value of Operand 1 of the sub instruction... 00406 // and set it as the RHS of the add instruction we just made... 00407 // 00408 std::string Name = Sub->getName(); 00409 Sub->setName(""); 00410 Value *NegVal = NegateValue(Sub->getOperand(1), Sub); 00411 Instruction *New = 00412 BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub); 00413 00414 // Everyone now refers to the add instruction. 00415 Sub->replaceAllUsesWith(New); 00416 Sub->eraseFromParent(); 00417 00418 DEBUG(std::cerr << "Negated: " << *New); 00419 return New; 00420 } 00421 00422 /// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used 00423 /// by one, change this into a multiply by a constant to assist with further 00424 /// reassociation. 00425 static Instruction *ConvertShiftToMul(Instruction *Shl) { 00426 // If an operand of this shift is a reassociable multiply, or if the shift 00427 // is used by a reassociable multiply or add, turn into a multiply. 00428 if (isReassociableOp(Shl->getOperand(0), Instruction::Mul) || 00429 (Shl->hasOneUse() && 00430 (isReassociableOp(Shl->use_back(), Instruction::Mul) || 00431 isReassociableOp(Shl->use_back(), Instruction::Add)))) { 00432 Constant *MulCst = ConstantInt::get(Shl->getType(), 1); 00433 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1))); 00434 00435 std::string Name = Shl->getName(); Shl->setName(""); 00436 Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst, 00437 Name, Shl); 00438 Shl->replaceAllUsesWith(Mul); 00439 Shl->eraseFromParent(); 00440 return Mul; 00441 } 00442 return 0; 00443 } 00444 00445 // Scan backwards and forwards among values with the same rank as element i to 00446 // see if X exists. If X does not exist, return i. 00447 static unsigned FindInOperandList(std::vector<ValueEntry> &Ops, unsigned i, 00448 Value *X) { 00449 unsigned XRank = Ops[i].Rank; 00450 unsigned e = Ops.size(); 00451 for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) 00452 if (Ops[j].Op == X) 00453 return j; 00454 // Scan backwards 00455 for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) 00456 if (Ops[j].Op == X) 00457 return j; 00458 return i; 00459 } 00460 00461 /// EmitAddTreeOfValues - Emit a tree of add instructions, summing Ops together 00462 /// and returning the result. Insert the tree before I. 00463 static Value *EmitAddTreeOfValues(Instruction *I, std::vector<Value*> &Ops) { 00464 if (Ops.size() == 1) return Ops.back(); 00465 00466 Value *V1 = Ops.back(); 00467 Ops.pop_back(); 00468 Value *V2 = EmitAddTreeOfValues(I, Ops); 00469 return BinaryOperator::createAdd(V2, V1, "tmp", I); 00470 } 00471 00472 /// RemoveFactorFromExpression - If V is an expression tree that is a 00473 /// multiplication sequence, and if this sequence contains a multiply by Factor, 00474 /// remove Factor from the tree and return the new tree. 00475 Value *Reassociate::RemoveFactorFromExpression(Value *V, Value *Factor) { 00476 BinaryOperator *BO = isReassociableOp(V, Instruction::Mul); 00477 if (!BO) return 0; 00478 00479 std::vector<ValueEntry> Factors; 00480 LinearizeExprTree(BO, Factors); 00481 00482 bool FoundFactor = false; 00483 for (unsigned i = 0, e = Factors.size(); i != e; ++i) 00484 if (Factors[i].Op == Factor) { 00485 FoundFactor = true; 00486 Factors.erase(Factors.begin()+i); 00487 break; 00488 } 00489 if (!FoundFactor) { 00490 // Make sure to restore the operands to the expression tree. 00491 RewriteExprTree(BO, Factors); 00492 return 0; 00493 } 00494 00495 if (Factors.size() == 1) return Factors[0].Op; 00496 00497 RewriteExprTree(BO, Factors); 00498 return BO; 00499 } 00500 00501 /// FindSingleUseMultiplyFactors - If V is a single-use multiply, recursively 00502 /// add its operands as factors, otherwise add V to the list of factors. 00503 static void FindSingleUseMultiplyFactors(Value *V, 00504 std::vector<Value*> &Factors) { 00505 BinaryOperator *BO; 00506 if ((!V->hasOneUse() && !V->use_empty()) || 00507 !(BO = dyn_cast<BinaryOperator>(V)) || 00508 BO->getOpcode() != Instruction::Mul) { 00509 Factors.push_back(V); 00510 return; 00511 } 00512 00513 // Otherwise, add the LHS and RHS to the list of factors. 00514 FindSingleUseMultiplyFactors(BO->getOperand(1), Factors); 00515 FindSingleUseMultiplyFactors(BO->getOperand(0), Factors); 00516 } 00517 00518 00519 00520 Value *Reassociate::OptimizeExpression(BinaryOperator *I, 00521 std::vector<ValueEntry> &Ops) { 00522 // Now that we have the linearized expression tree, try to optimize it. 00523 // Start by folding any constants that we found. 00524 bool IterateOptimization = false; 00525 if (Ops.size() == 1) return Ops[0].Op; 00526 00527 unsigned Opcode = I->getOpcode(); 00528 00529 if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op)) 00530 if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) { 00531 Ops.pop_back(); 00532 Ops.back().Op = ConstantExpr::get(Opcode, V1, V2); 00533 return OptimizeExpression(I, Ops); 00534 } 00535 00536 // Check for destructive annihilation due to a constant being used. 00537 if (ConstantIntegral *CstVal = dyn_cast<ConstantIntegral>(Ops.back().Op)) 00538 switch (Opcode) { 00539 default: break; 00540 case Instruction::And: 00541 if (CstVal->isNullValue()) { // ... & 0 -> 0 00542 ++NumAnnihil; 00543 return CstVal; 00544 } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ... 00545 Ops.pop_back(); 00546 } 00547 break; 00548 case Instruction::Mul: 00549 if (CstVal->isNullValue()) { // ... * 0 -> 0 00550 ++NumAnnihil; 00551 return CstVal; 00552 } else if (cast<ConstantInt>(CstVal)->getRawValue() == 1) { 00553 Ops.pop_back(); // ... * 1 -> ... 00554 } 00555 break; 00556 case Instruction::Or: 00557 if (CstVal->isAllOnesValue()) { // ... | -1 -> -1 00558 ++NumAnnihil; 00559 return CstVal; 00560 } 00561 // FALLTHROUGH! 00562 case Instruction::Add: 00563 case Instruction::Xor: 00564 if (CstVal->isNullValue()) // ... [|^+] 0 -> ... 00565 Ops.pop_back(); 00566 break; 00567 } 00568 if (Ops.size() == 1) return Ops[0].Op; 00569 00570 // Handle destructive annihilation do to identities between elements in the 00571 // argument list here. 00572 switch (Opcode) { 00573 default: break; 00574 case Instruction::And: 00575 case Instruction::Or: 00576 case Instruction::Xor: 00577 // Scan the operand lists looking for X and ~X pairs, along with X,X pairs. 00578 // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1. 00579 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 00580 // First, check for X and ~X in the operand list. 00581 assert(i < Ops.size()); 00582 if (BinaryOperator::isNot(Ops[i].Op)) { // Cannot occur for ^. 00583 Value *X = BinaryOperator::getNotArgument(Ops[i].Op); 00584 unsigned FoundX = FindInOperandList(Ops, i, X); 00585 if (FoundX != i) { 00586 if (Opcode == Instruction::And) { // ...&X&~X = 0 00587 ++NumAnnihil; 00588 return Constant::getNullValue(X->getType()); 00589 } else if (Opcode == Instruction::Or) { // ...|X|~X = -1 00590 ++NumAnnihil; 00591 return ConstantIntegral::getAllOnesValue(X->getType()); 00592 } 00593 } 00594 } 00595 00596 // Next, check for duplicate pairs of values, which we assume are next to 00597 // each other, due to our sorting criteria. 00598 assert(i < Ops.size()); 00599 if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) { 00600 if (Opcode == Instruction::And || Opcode == Instruction::Or) { 00601 // Drop duplicate values. 00602 Ops.erase(Ops.begin()+i); 00603 --i; --e; 00604 IterateOptimization = true; 00605 ++NumAnnihil; 00606 } else { 00607 assert(Opcode == Instruction::Xor); 00608 if (e == 2) { 00609 ++NumAnnihil; 00610 return Constant::getNullValue(Ops[0].Op->getType()); 00611 } 00612 // ... X^X -> ... 00613 Ops.erase(Ops.begin()+i, Ops.begin()+i+2); 00614 i -= 1; e -= 2; 00615 IterateOptimization = true; 00616 ++NumAnnihil; 00617 } 00618 } 00619 } 00620 break; 00621 00622 case Instruction::Add: 00623 // Scan the operand lists looking for X and -X pairs. If we find any, we 00624 // can simplify the expression. X+-X == 0. 00625 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 00626 assert(i < Ops.size()); 00627 // Check for X and -X in the operand list. 00628 if (BinaryOperator::isNeg(Ops[i].Op)) { 00629 Value *X = BinaryOperator::getNegArgument(Ops[i].Op); 00630 unsigned FoundX = FindInOperandList(Ops, i, X); 00631 if (FoundX != i) { 00632 // Remove X and -X from the operand list. 00633 if (Ops.size() == 2) { 00634 ++NumAnnihil; 00635 return Constant::getNullValue(X->getType()); 00636 } else { 00637 Ops.erase(Ops.begin()+i); 00638 if (i < FoundX) 00639 --FoundX; 00640 else 00641 --i; // Need to back up an extra one. 00642 Ops.erase(Ops.begin()+FoundX); 00643 IterateOptimization = true; 00644 ++NumAnnihil; 00645 --i; // Revisit element. 00646 e -= 2; // Removed two elements. 00647 } 00648 } 00649 } 00650 } 00651 00652 00653 // Scan the operand list, checking to see if there are any common factors 00654 // between operands. Consider something like A*A+A*B*C+D. We would like to 00655 // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies. 00656 // To efficiently find this, we count the number of times a factor occurs 00657 // for any ADD operands that are MULs. 00658 std::map<Value*, unsigned> FactorOccurrences; 00659 unsigned MaxOcc = 0; 00660 Value *MaxOccVal = 0; 00661 if (!I->getType()->isFloatingPoint()) { 00662 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 00663 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Ops[i].Op)) 00664 if (BOp->getOpcode() == Instruction::Mul && BOp->use_empty()) { 00665 // Compute all of the factors of this added value. 00666 std::vector<Value*> Factors; 00667 FindSingleUseMultiplyFactors(BOp, Factors); 00668 assert(Factors.size() > 1 && "Bad linearize!"); 00669 00670 // Add one to FactorOccurrences for each unique factor in this op. 00671 if (Factors.size() == 2) { 00672 unsigned Occ = ++FactorOccurrences[Factors[0]]; 00673 if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[0]; } 00674 if (Factors[0] != Factors[1]) { // Don't double count A*A. 00675 Occ = ++FactorOccurrences[Factors[1]]; 00676 if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[1]; } 00677 } 00678 } else { 00679 std::set<Value*> Duplicates; 00680 for (unsigned i = 0, e = Factors.size(); i != e; ++i) 00681 if (Duplicates.insert(Factors[i]).second) { 00682 unsigned Occ = ++FactorOccurrences[Factors[i]]; 00683 if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[i]; } 00684 } 00685 } 00686 } 00687 } 00688 } 00689 00690 // If any factor occurred more than one time, we can pull it out. 00691 if (MaxOcc > 1) { 00692 DEBUG(std::cerr << "\nFACTORING [" << MaxOcc << "]: " 00693 << *MaxOccVal << "\n"); 00694 00695 // Create a new instruction that uses the MaxOccVal twice. If we don't do 00696 // this, we could otherwise run into situations where removing a factor 00697 // from an expression will drop a use of maxocc, and this can cause 00698 // RemoveFactorFromExpression on successive values to behave differently. 00699 Instruction *DummyInst = BinaryOperator::createAdd(MaxOccVal, MaxOccVal); 00700 std::vector<Value*> NewMulOps; 00701 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 00702 if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) { 00703 NewMulOps.push_back(V); 00704 Ops.erase(Ops.begin()+i); 00705 --i; --e; 00706 } 00707 } 00708 00709 // No need for extra uses anymore. 00710 delete DummyInst; 00711 00712 unsigned NumAddedValues = NewMulOps.size(); 00713 Value *V = EmitAddTreeOfValues(I, NewMulOps); 00714 Value *V2 = BinaryOperator::createMul(V, MaxOccVal, "tmp", I); 00715 00716 // Now that we have inserted V and its sole use, optimize it. This allows 00717 // us to handle cases that require multiple factoring steps, such as this: 00718 // A*A*B + A*A*C --> A*(A*B+A*C) --> A*(A*(B+C)) 00719 if (NumAddedValues > 1) 00720 ReassociateExpression(cast<BinaryOperator>(V)); 00721 00722 ++NumFactor; 00723 00724 if (Ops.size() == 0) 00725 return V2; 00726 00727 // Add the new value to the list of things being added. 00728 Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2)); 00729 00730 // Rewrite the tree so that there is now a use of V. 00731 RewriteExprTree(I, Ops); 00732 return OptimizeExpression(I, Ops); 00733 } 00734 break; 00735 //case Instruction::Mul: 00736 } 00737 00738 if (IterateOptimization) 00739 return OptimizeExpression(I, Ops); 00740 return 0; 00741 } 00742 00743 00744 /// ReassociateBB - Inspect all of the instructions in this basic block, 00745 /// reassociating them as we go. 00746 void Reassociate::ReassociateBB(BasicBlock *BB) { 00747 for (BasicBlock::iterator BBI = BB->begin(); BBI != BB->end(); ) { 00748 Instruction *BI = BBI++; 00749 if (BI->getOpcode() == Instruction::Shl && 00750 isa<ConstantInt>(BI->getOperand(1))) 00751 if (Instruction *NI = ConvertShiftToMul(BI)) { 00752 MadeChange = true; 00753 BI = NI; 00754 } 00755 00756 // Reject cases where it is pointless to do this. 00757 if (!isa<BinaryOperator>(BI) || BI->getType()->isFloatingPoint() || 00758 isa<PackedType>(BI->getType())) 00759 continue; // Floating point ops are not associative. 00760 00761 // If this is a subtract instruction which is not already in negate form, 00762 // see if we can convert it to X+-Y. 00763 if (BI->getOpcode() == Instruction::Sub) { 00764 if (!BinaryOperator::isNeg(BI)) { 00765 if (Instruction *NI = BreakUpSubtract(BI)) { 00766 MadeChange = true; 00767 BI = NI; 00768 } 00769 } else { 00770 // Otherwise, this is a negation. See if the operand is a multiply tree 00771 // and if this is not an inner node of a multiply tree. 00772 if (isReassociableOp(BI->getOperand(1), Instruction::Mul) && 00773 (!BI->hasOneUse() || 00774 !isReassociableOp(BI->use_back(), Instruction::Mul))) { 00775 BI = LowerNegateToMultiply(BI); 00776 MadeChange = true; 00777 } 00778 } 00779 } 00780 00781 // If this instruction is a commutative binary operator, process it. 00782 if (!BI->isAssociative()) continue; 00783 BinaryOperator *I = cast<BinaryOperator>(BI); 00784 00785 // If this is an interior node of a reassociable tree, ignore it until we 00786 // get to the root of the tree, to avoid N^2 analysis. 00787 if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode())) 00788 continue; 00789 00790 // If this is an add tree that is used by a sub instruction, ignore it 00791 // until we process the subtract. 00792 if (I->hasOneUse() && I->getOpcode() == Instruction::Add && 00793 cast<Instruction>(I->use_back())->getOpcode() == Instruction::Sub) 00794 continue; 00795 00796 ReassociateExpression(I); 00797 } 00798 } 00799 00800 void Reassociate::ReassociateExpression(BinaryOperator *I) { 00801 00802 // First, walk the expression tree, linearizing the tree, collecting 00803 std::vector<ValueEntry> Ops; 00804 LinearizeExprTree(I, Ops); 00805 00806 DEBUG(std::cerr << "RAIn:\t"; PrintOps(I, Ops); 00807 std::cerr << "\n"); 00808 00809 // Now that we have linearized the tree to a list and have gathered all of 00810 // the operands and their ranks, sort the operands by their rank. Use a 00811 // stable_sort so that values with equal ranks will have their relative 00812 // positions maintained (and so the compiler is deterministic). Note that 00813 // this sorts so that the highest ranking values end up at the beginning of 00814 // the vector. 00815 std::stable_sort(Ops.begin(), Ops.end()); 00816 00817 // OptimizeExpression - Now that we have the expression tree in a convenient 00818 // sorted form, optimize it globally if possible. 00819 if (Value *V = OptimizeExpression(I, Ops)) { 00820 // This expression tree simplified to something that isn't a tree, 00821 // eliminate it. 00822 DEBUG(std::cerr << "Reassoc to scalar: " << *V << "\n"); 00823 I->replaceAllUsesWith(V); 00824 RemoveDeadBinaryOp(I); 00825 return; 00826 } 00827 00828 // We want to sink immediates as deeply as possible except in the case where 00829 // this is a multiply tree used only by an add, and the immediate is a -1. 00830 // In this case we reassociate to put the negation on the outside so that we 00831 // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y 00832 if (I->getOpcode() == Instruction::Mul && I->hasOneUse() && 00833 cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add && 00834 isa<ConstantInt>(Ops.back().Op) && 00835 cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) { 00836 Ops.insert(Ops.begin(), Ops.back()); 00837 Ops.pop_back(); 00838 } 00839 00840 DEBUG(std::cerr << "RAOut:\t"; PrintOps(I, Ops); 00841 std::cerr << "\n"); 00842 00843 if (Ops.size() == 1) { 00844 // This expression tree simplified to something that isn't a tree, 00845 // eliminate it. 00846 I->replaceAllUsesWith(Ops[0].Op); 00847 RemoveDeadBinaryOp(I); 00848 } else { 00849 // Now that we ordered and optimized the expressions, splat them back into 00850 // the expression tree, removing any unneeded nodes. 00851 RewriteExprTree(I, Ops); 00852 } 00853 } 00854 00855 00856 bool Reassociate::runOnFunction(Function &F) { 00857 // Recalculate the rank map for F 00858 BuildRankMap(F); 00859 00860 MadeChange = false; 00861 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) 00862 ReassociateBB(FI); 00863 00864 // We are done with the rank map... 00865 RankMap.clear(); 00866 ValueRankMap.clear(); 00867 return MadeChange; 00868 } 00869