Reassociate.cpp revision 7b4ad94282b94e1827be29b4db73fdf6e241f748
1//===- Reassociate.cpp - Reassociate binary expressions -------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source 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... 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/Function.h" 27#include "llvm/Instructions.h" 28#include "llvm/Pass.h" 29#include "llvm/Type.h" 30#include "llvm/Assembly/Writer.h" 31#include "llvm/Support/CFG.h" 32#include "llvm/Support/Debug.h" 33#include "llvm/ADT/PostOrderIterator.h" 34#include "llvm/ADT/Statistic.h" 35#include <algorithm> 36using namespace llvm; 37 38namespace { 39 Statistic<> NumLinear ("reassociate","Number of insts linearized"); 40 Statistic<> NumChanged("reassociate","Number of insts reassociated"); 41 Statistic<> NumSwapped("reassociate","Number of insts with operands swapped"); 42 Statistic<> NumAnnihil("reassociate","Number of expr tree annihilated"); 43 44 struct ValueEntry { 45 unsigned Rank; 46 Value *Op; 47 ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {} 48 }; 49 inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) { 50 return LHS.Rank > RHS.Rank; // Sort so that highest rank goes to start. 51 } 52 53 class Reassociate : public FunctionPass { 54 std::map<BasicBlock*, unsigned> RankMap; 55 std::map<Value*, unsigned> ValueRankMap; 56 bool MadeChange; 57 public: 58 bool runOnFunction(Function &F); 59 60 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 61 AU.setPreservesCFG(); 62 } 63 private: 64 void BuildRankMap(Function &F); 65 unsigned getRank(Value *V); 66 void RewriteExprTree(BinaryOperator *I, unsigned Idx, 67 std::vector<ValueEntry> &Ops); 68 void OptimizeExpression(unsigned Opcode, std::vector<ValueEntry> &Ops); 69 void LinearizeExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops); 70 void LinearizeExpr(BinaryOperator *I); 71 void ReassociateBB(BasicBlock *BB); 72 }; 73 74 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions"); 75} 76 77// Public interface to the Reassociate pass 78FunctionPass *llvm::createReassociatePass() { return new Reassociate(); } 79 80 81static bool isUnmovableInstruction(Instruction *I) { 82 if (I->getOpcode() == Instruction::PHI || 83 I->getOpcode() == Instruction::Alloca || 84 I->getOpcode() == Instruction::Load || 85 I->getOpcode() == Instruction::Malloc || 86 I->getOpcode() == Instruction::Invoke || 87 I->getOpcode() == Instruction::Call || 88 I->getOpcode() == Instruction::Div || 89 I->getOpcode() == Instruction::Rem) 90 return true; 91 return false; 92} 93 94void Reassociate::BuildRankMap(Function &F) { 95 unsigned i = 2; 96 97 // Assign distinct ranks to function arguments 98 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) 99 ValueRankMap[I] = ++i; 100 101 ReversePostOrderTraversal<Function*> RPOT(&F); 102 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(), 103 E = RPOT.end(); I != E; ++I) { 104 BasicBlock *BB = *I; 105 unsigned BBRank = RankMap[BB] = ++i << 16; 106 107 // Walk the basic block, adding precomputed ranks for any instructions that 108 // we cannot move. This ensures that the ranks for these instructions are 109 // all different in the block. 110 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 111 if (isUnmovableInstruction(I)) 112 ValueRankMap[I] = ++BBRank; 113 } 114} 115 116unsigned Reassociate::getRank(Value *V) { 117 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument... 118 119 Instruction *I = dyn_cast<Instruction>(V); 120 if (I == 0) return 0; // Otherwise it's a global or constant, rank 0. 121 122 unsigned &CachedRank = ValueRankMap[I]; 123 if (CachedRank) return CachedRank; // Rank already known? 124 125 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that 126 // we can reassociate expressions for code motion! Since we do not recurse 127 // for PHI nodes, we cannot have infinite recursion here, because there 128 // cannot be loops in the value graph that do not go through PHI nodes. 129 unsigned Rank = 0, MaxRank = RankMap[I->getParent()]; 130 for (unsigned i = 0, e = I->getNumOperands(); 131 i != e && Rank != MaxRank; ++i) 132 Rank = std::max(Rank, getRank(I->getOperand(i))); 133 134 // If this is a not or neg instruction, do not count it for rank. This 135 // assures us that X and ~X will have the same rank. 136 if (!I->getType()->isIntegral() || 137 (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I))) 138 ++Rank; 139 140 //DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = " 141 //<< Rank << "\n"); 142 143 return CachedRank = Rank; 144} 145 146/// isReassociableOp - Return true if V is an instruction of the specified 147/// opcode and if it only has one use. 148static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) { 149 if (V->hasOneUse() && isa<Instruction>(V) && 150 cast<Instruction>(V)->getOpcode() == Opcode) 151 return cast<BinaryOperator>(V); 152 return 0; 153} 154 155/// LowerNegateToMultiply - Replace 0-X with X*-1. 156/// 157static Instruction *LowerNegateToMultiply(Instruction *Neg) { 158 Constant *Cst; 159 if (Neg->getType()->isFloatingPoint()) 160 Cst = ConstantFP::get(Neg->getType(), -1); 161 else 162 Cst = ConstantInt::getAllOnesValue(Neg->getType()); 163 164 std::string NegName = Neg->getName(); Neg->setName(""); 165 Instruction *Res = BinaryOperator::createMul(Neg->getOperand(1), Cst, NegName, 166 Neg); 167 Neg->replaceAllUsesWith(Res); 168 Neg->eraseFromParent(); 169 return Res; 170} 171 172// Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'. 173// Note that if D is also part of the expression tree that we recurse to 174// linearize it as well. Besides that case, this does not recurse into A,B, or 175// C. 176void Reassociate::LinearizeExpr(BinaryOperator *I) { 177 BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0)); 178 BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1)); 179 assert(isReassociableOp(LHS, I->getOpcode()) && 180 isReassociableOp(RHS, I->getOpcode()) && 181 "Not an expression that needs linearization?"); 182 183 DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I); 184 185 // Move the RHS instruction to live immediately before I, avoiding breaking 186 // dominator properties. 187 RHS->moveBefore(I); 188 189 // Move operands around to do the linearization. 190 I->setOperand(1, RHS->getOperand(0)); 191 RHS->setOperand(0, LHS); 192 I->setOperand(0, RHS); 193 194 ++NumLinear; 195 MadeChange = true; 196 DEBUG(std::cerr << "Linearized: " << *I); 197 198 // If D is part of this expression tree, tail recurse. 199 if (isReassociableOp(I->getOperand(1), I->getOpcode())) 200 LinearizeExpr(I); 201} 202 203 204/// LinearizeExprTree - Given an associative binary expression tree, traverse 205/// all of the uses putting it into canonical form. This forces a left-linear 206/// form of the the expression (((a+b)+c)+d), and collects information about the 207/// rank of the non-tree operands. 208/// 209/// This returns the rank of the RHS operand, which is known to be the highest 210/// rank value in the expression tree. 211/// 212void Reassociate::LinearizeExprTree(BinaryOperator *I, 213 std::vector<ValueEntry> &Ops) { 214 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1); 215 unsigned Opcode = I->getOpcode(); 216 217 // First step, linearize the expression if it is in ((A+B)+(C+D)) form. 218 BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode); 219 BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode); 220 221 // If this is a multiply expression tree and it contains internal negations, 222 // transform them into multiplies by -1 so they can be reassociated. 223 if (I->getOpcode() == Instruction::Mul) { 224 if (!LHSBO && LHS->hasOneUse() && BinaryOperator::isNeg(LHS)) { 225 LHS = LowerNegateToMultiply(cast<Instruction>(LHS)); 226 LHSBO = isReassociableOp(LHS, Opcode); 227 } 228 if (!RHSBO && RHS->hasOneUse() && BinaryOperator::isNeg(RHS)) { 229 RHS = LowerNegateToMultiply(cast<Instruction>(RHS)); 230 RHSBO = isReassociableOp(RHS, Opcode); 231 } 232 } 233 234 if (!LHSBO) { 235 if (!RHSBO) { 236 // Neither the LHS or RHS as part of the tree, thus this is a leaf. As 237 // such, just remember these operands and their rank. 238 Ops.push_back(ValueEntry(getRank(LHS), LHS)); 239 Ops.push_back(ValueEntry(getRank(RHS), RHS)); 240 return; 241 } else { 242 // Turn X+(Y+Z) -> (Y+Z)+X 243 std::swap(LHSBO, RHSBO); 244 std::swap(LHS, RHS); 245 bool Success = !I->swapOperands(); 246 assert(Success && "swapOperands failed"); 247 MadeChange = true; 248 } 249 } else if (RHSBO) { 250 // Turn (A+B)+(C+D) -> (((A+B)+C)+D). This guarantees the the RHS is not 251 // part of the expression tree. 252 LinearizeExpr(I); 253 LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0)); 254 RHS = I->getOperand(1); 255 RHSBO = 0; 256 } 257 258 // Okay, now we know that the LHS is a nested expression and that the RHS is 259 // not. Perform reassociation. 260 assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!"); 261 262 // Move LHS right before I to make sure that the tree expression dominates all 263 // values. 264 LHSBO->moveBefore(I); 265 266 // Linearize the expression tree on the LHS. 267 LinearizeExprTree(LHSBO, Ops); 268 269 // Remember the RHS operand and its rank. 270 Ops.push_back(ValueEntry(getRank(RHS), RHS)); 271} 272 273// RewriteExprTree - Now that the operands for this expression tree are 274// linearized and optimized, emit them in-order. This function is written to be 275// tail recursive. 276void Reassociate::RewriteExprTree(BinaryOperator *I, unsigned i, 277 std::vector<ValueEntry> &Ops) { 278 if (i+2 == Ops.size()) { 279 if (I->getOperand(0) != Ops[i].Op || 280 I->getOperand(1) != Ops[i+1].Op) { 281 DEBUG(std::cerr << "RA: " << *I); 282 I->setOperand(0, Ops[i].Op); 283 I->setOperand(1, Ops[i+1].Op); 284 DEBUG(std::cerr << "TO: " << *I); 285 MadeChange = true; 286 ++NumChanged; 287 } 288 return; 289 } 290 assert(i+2 < Ops.size() && "Ops index out of range!"); 291 292 if (I->getOperand(1) != Ops[i].Op) { 293 DEBUG(std::cerr << "RA: " << *I); 294 I->setOperand(1, Ops[i].Op); 295 DEBUG(std::cerr << "TO: " << *I); 296 MadeChange = true; 297 ++NumChanged; 298 } 299 RewriteExprTree(cast<BinaryOperator>(I->getOperand(0)), i+1, Ops); 300} 301 302 303 304// NegateValue - Insert instructions before the instruction pointed to by BI, 305// that computes the negative version of the value specified. The negative 306// version of the value is returned, and BI is left pointing at the instruction 307// that should be processed next by the reassociation pass. 308// 309static Value *NegateValue(Value *V, Instruction *BI) { 310 // We are trying to expose opportunity for reassociation. One of the things 311 // that we want to do to achieve this is to push a negation as deep into an 312 // expression chain as possible, to expose the add instructions. In practice, 313 // this means that we turn this: 314 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D 315 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate 316 // the constants. We assume that instcombine will clean up the mess later if 317 // we introduce tons of unnecessary negation instructions... 318 // 319 if (Instruction *I = dyn_cast<Instruction>(V)) 320 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) { 321 // Push the negates through the add. 322 I->setOperand(0, NegateValue(I->getOperand(0), BI)); 323 I->setOperand(1, NegateValue(I->getOperand(1), BI)); 324 325 // We must move the add instruction here, because the neg instructions do 326 // not dominate the old add instruction in general. By moving it, we are 327 // assured that the neg instructions we just inserted dominate the 328 // instruction we are about to insert after them. 329 // 330 I->moveBefore(BI); 331 I->setName(I->getName()+".neg"); 332 return I; 333 } 334 335 // Insert a 'neg' instruction that subtracts the value from zero to get the 336 // negation. 337 // 338 return BinaryOperator::createNeg(V, V->getName() + ".neg", BI); 339} 340 341/// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is 342/// only used by an add, transform this into (X+(0-Y)) to promote better 343/// reassociation. 344static Instruction *BreakUpSubtract(Instruction *Sub) { 345 // Don't bother to break this up unless either the LHS is an associable add or 346 // if this is only used by one. 347 if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) && 348 !isReassociableOp(Sub->getOperand(1), Instruction::Add) && 349 !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add))) 350 return 0; 351 352 // Convert a subtract into an add and a neg instruction... so that sub 353 // instructions can be commuted with other add instructions... 354 // 355 // Calculate the negative value of Operand 1 of the sub instruction... 356 // and set it as the RHS of the add instruction we just made... 357 // 358 std::string Name = Sub->getName(); 359 Sub->setName(""); 360 Value *NegVal = NegateValue(Sub->getOperand(1), Sub); 361 Instruction *New = 362 BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub); 363 364 // Everyone now refers to the add instruction. 365 Sub->replaceAllUsesWith(New); 366 Sub->eraseFromParent(); 367 368 DEBUG(std::cerr << "Negated: " << *New); 369 return New; 370} 371 372/// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used 373/// by one, change this into a multiply by a constant to assist with further 374/// reassociation. 375static Instruction *ConvertShiftToMul(Instruction *Shl) { 376 if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) && 377 !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul))) 378 return 0; 379 380 Constant *MulCst = ConstantInt::get(Shl->getType(), 1); 381 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1))); 382 383 std::string Name = Shl->getName(); Shl->setName(""); 384 Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst, 385 Name, Shl); 386 Shl->replaceAllUsesWith(Mul); 387 Shl->eraseFromParent(); 388 return Mul; 389} 390 391// Scan backwards and forwards among values with the same rank as element i to 392// see if X exists. If X does not exist, return i. 393static unsigned FindInOperandList(std::vector<ValueEntry> &Ops, unsigned i, 394 Value *X) { 395 unsigned XRank = Ops[i].Rank; 396 unsigned e = Ops.size(); 397 for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) 398 if (Ops[j].Op == X) 399 return j; 400 // Scan backwards 401 for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) 402 if (Ops[j].Op == X) 403 return j; 404 return i; 405} 406 407void Reassociate::OptimizeExpression(unsigned Opcode, 408 std::vector<ValueEntry> &Ops) { 409 // Now that we have the linearized expression tree, try to optimize it. 410 // Start by folding any constants that we found. 411 bool IterateOptimization = false; 412 if (Ops.size() == 1) return; 413 414 if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op)) 415 if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) { 416 Ops.pop_back(); 417 Ops.back().Op = ConstantExpr::get(Opcode, V1, V2); 418 OptimizeExpression(Opcode, Ops); 419 return; 420 } 421 422 // Check for destructive annihilation due to a constant being used. 423 if (ConstantIntegral *CstVal = dyn_cast<ConstantIntegral>(Ops.back().Op)) 424 switch (Opcode) { 425 default: break; 426 case Instruction::And: 427 if (CstVal->isNullValue()) { // ... & 0 -> 0 428 Ops[0].Op = CstVal; 429 Ops.erase(Ops.begin()+1, Ops.end()); 430 ++NumAnnihil; 431 return; 432 } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ... 433 Ops.pop_back(); 434 } 435 break; 436 case Instruction::Mul: 437 if (CstVal->isNullValue()) { // ... * 0 -> 0 438 Ops[0].Op = CstVal; 439 Ops.erase(Ops.begin()+1, Ops.end()); 440 ++NumAnnihil; 441 return; 442 } else if (cast<ConstantInt>(CstVal)->getRawValue() == 1) { 443 Ops.pop_back(); // ... * 1 -> ... 444 } 445 break; 446 case Instruction::Or: 447 if (CstVal->isAllOnesValue()) { // ... | -1 -> -1 448 Ops[0].Op = CstVal; 449 Ops.erase(Ops.begin()+1, Ops.end()); 450 ++NumAnnihil; 451 return; 452 } 453 // FALLTHROUGH! 454 case Instruction::Add: 455 case Instruction::Xor: 456 if (CstVal->isNullValue()) // ... [|^+] 0 -> ... 457 Ops.pop_back(); 458 break; 459 } 460 if (Ops.size() == 1) return; 461 462 // Handle destructive annihilation do to identities between elements in the 463 // argument list here. 464 switch (Opcode) { 465 default: break; 466 case Instruction::And: 467 case Instruction::Or: 468 case Instruction::Xor: 469 // Scan the operand lists looking for X and ~X pairs, along with X,X pairs. 470 // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1. 471 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 472 // First, check for X and ~X in the operand list. 473 assert(i < Ops.size()); 474 if (BinaryOperator::isNot(Ops[i].Op)) { // Cannot occur for ^. 475 Value *X = BinaryOperator::getNotArgument(Ops[i].Op); 476 unsigned FoundX = FindInOperandList(Ops, i, X); 477 if (FoundX != i) { 478 if (Opcode == Instruction::And) { // ...&X&~X = 0 479 Ops[0].Op = Constant::getNullValue(X->getType()); 480 Ops.erase(Ops.begin()+1, Ops.end()); 481 ++NumAnnihil; 482 return; 483 } else if (Opcode == Instruction::Or) { // ...|X|~X = -1 484 Ops[0].Op = ConstantIntegral::getAllOnesValue(X->getType()); 485 Ops.erase(Ops.begin()+1, Ops.end()); 486 ++NumAnnihil; 487 return; 488 } 489 } 490 } 491 492 // Next, check for duplicate pairs of values, which we assume are next to 493 // each other, due to our sorting criteria. 494 assert(i < Ops.size()); 495 if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) { 496 if (Opcode == Instruction::And || Opcode == Instruction::Or) { 497 // Drop duplicate values. 498 Ops.erase(Ops.begin()+i); 499 --i; --e; 500 IterateOptimization = true; 501 ++NumAnnihil; 502 } else { 503 assert(Opcode == Instruction::Xor); 504 if (e == 2) { 505 Ops[0].Op = Constant::getNullValue(Ops[0].Op->getType()); 506 Ops.erase(Ops.begin()+1, Ops.end()); 507 ++NumAnnihil; 508 return; 509 } 510 // ... X^X -> ... 511 Ops.erase(Ops.begin()+i, Ops.begin()+i+2); 512 i -= 1; e -= 2; 513 IterateOptimization = true; 514 ++NumAnnihil; 515 } 516 } 517 } 518 break; 519 520 case Instruction::Add: 521 // Scan the operand lists looking for X and -X pairs. If we find any, we 522 // can simplify the expression. X+-X == 0 523 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 524 assert(i < Ops.size()); 525 // Check for X and -X in the operand list. 526 if (BinaryOperator::isNeg(Ops[i].Op)) { 527 Value *X = BinaryOperator::getNegArgument(Ops[i].Op); 528 unsigned FoundX = FindInOperandList(Ops, i, X); 529 if (FoundX != i) { 530 // Remove X and -X from the operand list. 531 if (Ops.size() == 2) { 532 Ops[0].Op = Constant::getNullValue(X->getType()); 533 Ops.pop_back(); 534 ++NumAnnihil; 535 return; 536 } else { 537 Ops.erase(Ops.begin()+i); 538 if (i < FoundX) 539 --FoundX; 540 else 541 --i; // Need to back up an extra one. 542 Ops.erase(Ops.begin()+FoundX); 543 IterateOptimization = true; 544 ++NumAnnihil; 545 --i; // Revisit element. 546 e -= 2; // Removed two elements. 547 } 548 } 549 } 550 } 551 break; 552 //case Instruction::Mul: 553 } 554 555 if (IterateOptimization) 556 OptimizeExpression(Opcode, Ops); 557} 558 559/// PrintOps - Print out the expression identified in the Ops list. 560/// 561static void PrintOps(unsigned Opcode, const std::vector<ValueEntry> &Ops, 562 BasicBlock *BB) { 563 Module *M = BB->getParent()->getParent(); 564 std::cerr << Instruction::getOpcodeName(Opcode) << " " 565 << *Ops[0].Op->getType(); 566 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 567 WriteAsOperand(std::cerr << " ", Ops[i].Op, false, true, M) 568 << "," << Ops[i].Rank; 569} 570 571/// ReassociateBB - Inspect all of the instructions in this basic block, 572/// reassociating them as we go. 573void Reassociate::ReassociateBB(BasicBlock *BB) { 574 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) { 575 if (BI->getOpcode() == Instruction::Shl && 576 isa<ConstantInt>(BI->getOperand(1))) 577 if (Instruction *NI = ConvertShiftToMul(BI)) { 578 MadeChange = true; 579 BI = NI; 580 } 581 582 // Reject cases where it is pointless to do this. 583 if (!isa<BinaryOperator>(BI) || BI->getType()->isFloatingPoint()) 584 continue; // Floating point ops are not associative. 585 586 // If this is a subtract instruction which is not already in negate form, 587 // see if we can convert it to X+-Y. 588 if (BI->getOpcode() == Instruction::Sub) { 589 if (!BinaryOperator::isNeg(BI)) { 590 if (Instruction *NI = BreakUpSubtract(BI)) { 591 MadeChange = true; 592 BI = NI; 593 } 594 } else { 595 // Otherwise, this is a negation. See if the operand is a multiply tree 596 // and if this is not an inner node of a multiply tree. 597 if (isReassociableOp(BI->getOperand(1), Instruction::Mul) && 598 (!BI->hasOneUse() || 599 !isReassociableOp(BI->use_back(), Instruction::Mul))) { 600 BI = LowerNegateToMultiply(BI); 601 MadeChange = true; 602 } 603 } 604 } 605 606 // If this instruction is a commutative binary operator, process it. 607 if (!BI->isAssociative()) continue; 608 BinaryOperator *I = cast<BinaryOperator>(BI); 609 610 // If this is an interior node of a reassociable tree, ignore it until we 611 // get to the root of the tree, to avoid N^2 analysis. 612 if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode())) 613 continue; 614 615 // If this is an add tree that is used by a sub instruction, ignore it 616 // until we process the subtract. 617 if (I->hasOneUse() && I->getOpcode() == Instruction::Add && 618 cast<Instruction>(I->use_back())->getOpcode() == Instruction::Sub) 619 continue; 620 621 // First, walk the expression tree, linearizing the tree, collecting 622 std::vector<ValueEntry> Ops; 623 LinearizeExprTree(I, Ops); 624 625 DEBUG(std::cerr << "RAIn:\t"; PrintOps(I->getOpcode(), Ops, BB); 626 std::cerr << "\n"); 627 628 // Now that we have linearized the tree to a list and have gathered all of 629 // the operands and their ranks, sort the operands by their rank. Use a 630 // stable_sort so that values with equal ranks will have their relative 631 // positions maintained (and so the compiler is deterministic). Note that 632 // this sorts so that the highest ranking values end up at the beginning of 633 // the vector. 634 std::stable_sort(Ops.begin(), Ops.end()); 635 636 // OptimizeExpression - Now that we have the expression tree in a convenient 637 // sorted form, optimize it globally if possible. 638 OptimizeExpression(I->getOpcode(), Ops); 639 640 // We want to sink immediates as deeply as possible except in the case where 641 // this is a multiply tree used only by an add, and the immediate is a -1. 642 // In this case we reassociate to put the negation on the outside so that we 643 // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y 644 if (I->getOpcode() == Instruction::Mul && I->hasOneUse() && 645 cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add && 646 isa<ConstantInt>(Ops.back().Op) && 647 cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) { 648 Ops.insert(Ops.begin(), Ops.back()); 649 Ops.pop_back(); 650 } 651 652 DEBUG(std::cerr << "RAOut:\t"; PrintOps(I->getOpcode(), Ops, BB); 653 std::cerr << "\n"); 654 655 if (Ops.size() == 1) { 656 // This expression tree simplified to something that isn't a tree, 657 // eliminate it. 658 I->replaceAllUsesWith(Ops[0].Op); 659 } else { 660 // Now that we ordered and optimized the expressions, splat them back into 661 // the expression tree, removing any unneeded nodes. 662 RewriteExprTree(I, 0, Ops); 663 } 664 } 665} 666 667 668bool Reassociate::runOnFunction(Function &F) { 669 // Recalculate the rank map for F 670 BuildRankMap(F); 671 672 MadeChange = false; 673 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) 674 ReassociateBB(FI); 675 676 // We are done with the rank map... 677 RankMap.clear(); 678 ValueRankMap.clear(); 679 return MadeChange; 680} 681 682