1 //===- Reassociate.cpp - Reassociate binary expressions -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass reassociates commutative expressions in an order that is designed 10 // to promote better constant propagation, GCSE, LICM, PRE, etc. 11 // 12 // For example: 4 + (x + 5) -> x + (4 + 5) 13 // 14 // In the implementation of this algorithm, constants are assigned rank = 0, 15 // function arguments are rank = 1, and other values are assigned ranks 16 // corresponding to the reverse post order traversal of current function 17 // (starting at 2), which effectively gives values in deep loops higher rank 18 // than values not in loops. 19 // 20 //===----------------------------------------------------------------------===// 21 22 #include "llvm/Transforms/Scalar/Reassociate.h" 23 #include "llvm/ADT/APFloat.h" 24 #include "llvm/ADT/APInt.h" 25 #include "llvm/ADT/DenseMap.h" 26 #include "llvm/ADT/PostOrderIterator.h" 27 #include "llvm/ADT/SmallPtrSet.h" 28 #include "llvm/ADT/SmallSet.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/ADT/Statistic.h" 31 #include "llvm/Analysis/BasicAliasAnalysis.h" 32 #include "llvm/Analysis/ConstantFolding.h" 33 #include "llvm/Analysis/GlobalsModRef.h" 34 #include "llvm/Analysis/ValueTracking.h" 35 #include "llvm/IR/Argument.h" 36 #include "llvm/IR/BasicBlock.h" 37 #include "llvm/IR/CFG.h" 38 #include "llvm/IR/Constant.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/IRBuilder.h" 42 #include "llvm/IR/InstrTypes.h" 43 #include "llvm/IR/Instruction.h" 44 #include "llvm/IR/Instructions.h" 45 #include "llvm/IR/Operator.h" 46 #include "llvm/IR/PassManager.h" 47 #include "llvm/IR/PatternMatch.h" 48 #include "llvm/IR/Type.h" 49 #include "llvm/IR/User.h" 50 #include "llvm/IR/Value.h" 51 #include "llvm/IR/ValueHandle.h" 52 #include "llvm/InitializePasses.h" 53 #include "llvm/Pass.h" 54 #include "llvm/Support/Casting.h" 55 #include "llvm/Support/CommandLine.h" 56 #include "llvm/Support/Debug.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include "llvm/Transforms/Scalar.h" 59 #include "llvm/Transforms/Utils/Local.h" 60 #include <algorithm> 61 #include <cassert> 62 #include <utility> 63 64 using namespace llvm; 65 using namespace reassociate; 66 using namespace PatternMatch; 67 68 #define DEBUG_TYPE "reassociate" 69 70 STATISTIC(NumChanged, "Number of insts reassociated"); 71 STATISTIC(NumAnnihil, "Number of expr tree annihilated"); 72 STATISTIC(NumFactor , "Number of multiplies factored"); 73 74 static cl::opt<bool> 75 UseCSELocalOpt(DEBUG_TYPE "-use-cse-local", 76 cl::desc("Only reorder expressions within a basic block " 77 "when exposing CSE opportunities"), 78 cl::init(true), cl::Hidden); 79 80 #ifndef NDEBUG 81 /// Print out the expression identified in the Ops list. 82 static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) { 83 Module *M = I->getModule(); 84 dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " " 85 << *Ops[0].Op->getType() << '\t'; 86 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 87 dbgs() << "[ "; 88 Ops[i].Op->printAsOperand(dbgs(), false, M); 89 dbgs() << ", #" << Ops[i].Rank << "] "; 90 } 91 } 92 #endif 93 94 /// Utility class representing a non-constant Xor-operand. We classify 95 /// non-constant Xor-Operands into two categories: 96 /// C1) The operand is in the form "X & C", where C is a constant and C != ~0 97 /// C2) 98 /// C2.1) The operand is in the form of "X | C", where C is a non-zero 99 /// constant. 100 /// C2.2) Any operand E which doesn't fall into C1 and C2.1, we view this 101 /// operand as "E | 0" 102 class llvm::reassociate::XorOpnd { 103 public: 104 XorOpnd(Value *V); 105 106 bool isInvalid() const { return SymbolicPart == nullptr; } 107 bool isOrExpr() const { return isOr; } 108 Value *getValue() const { return OrigVal; } 109 Value *getSymbolicPart() const { return SymbolicPart; } 110 unsigned getSymbolicRank() const { return SymbolicRank; } 111 const APInt &getConstPart() const { return ConstPart; } 112 113 void Invalidate() { SymbolicPart = OrigVal = nullptr; } 114 void setSymbolicRank(unsigned R) { SymbolicRank = R; } 115 116 private: 117 Value *OrigVal; 118 Value *SymbolicPart; 119 APInt ConstPart; 120 unsigned SymbolicRank; 121 bool isOr; 122 }; 123 124 XorOpnd::XorOpnd(Value *V) { 125 assert(!isa<ConstantInt>(V) && "No ConstantInt"); 126 OrigVal = V; 127 Instruction *I = dyn_cast<Instruction>(V); 128 SymbolicRank = 0; 129 130 if (I && (I->getOpcode() == Instruction::Or || 131 I->getOpcode() == Instruction::And)) { 132 Value *V0 = I->getOperand(0); 133 Value *V1 = I->getOperand(1); 134 const APInt *C; 135 if (match(V0, m_APInt(C))) 136 std::swap(V0, V1); 137 138 if (match(V1, m_APInt(C))) { 139 ConstPart = *C; 140 SymbolicPart = V0; 141 isOr = (I->getOpcode() == Instruction::Or); 142 return; 143 } 144 } 145 146 // view the operand as "V | 0" 147 SymbolicPart = V; 148 ConstPart = APInt::getZero(V->getType()->getScalarSizeInBits()); 149 isOr = true; 150 } 151 152 /// Return true if I is an instruction with the FastMathFlags that are needed 153 /// for general reassociation set. This is not the same as testing 154 /// Instruction::isAssociative() because it includes operations like fsub. 155 /// (This routine is only intended to be called for floating-point operations.) 156 static bool hasFPAssociativeFlags(Instruction *I) { 157 assert(I && isa<FPMathOperator>(I) && "Should only check FP ops"); 158 return I->hasAllowReassoc() && I->hasNoSignedZeros(); 159 } 160 161 /// Return true if V is an instruction of the specified opcode and if it 162 /// only has one use. 163 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) { 164 auto *BO = dyn_cast<BinaryOperator>(V); 165 if (BO && BO->hasOneUse() && BO->getOpcode() == Opcode) 166 if (!isa<FPMathOperator>(BO) || hasFPAssociativeFlags(BO)) 167 return BO; 168 return nullptr; 169 } 170 171 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode1, 172 unsigned Opcode2) { 173 auto *BO = dyn_cast<BinaryOperator>(V); 174 if (BO && BO->hasOneUse() && 175 (BO->getOpcode() == Opcode1 || BO->getOpcode() == Opcode2)) 176 if (!isa<FPMathOperator>(BO) || hasFPAssociativeFlags(BO)) 177 return BO; 178 return nullptr; 179 } 180 181 void ReassociatePass::BuildRankMap(Function &F, 182 ReversePostOrderTraversal<Function*> &RPOT) { 183 unsigned Rank = 2; 184 185 // Assign distinct ranks to function arguments. 186 for (auto &Arg : F.args()) { 187 ValueRankMap[&Arg] = ++Rank; 188 LLVM_DEBUG(dbgs() << "Calculated Rank[" << Arg.getName() << "] = " << Rank 189 << "\n"); 190 } 191 192 // Traverse basic blocks in ReversePostOrder. 193 for (BasicBlock *BB : RPOT) { 194 unsigned BBRank = RankMap[BB] = ++Rank << 16; 195 196 // Walk the basic block, adding precomputed ranks for any instructions that 197 // we cannot move. This ensures that the ranks for these instructions are 198 // all different in the block. 199 for (Instruction &I : *BB) 200 if (mayHaveNonDefUseDependency(I)) 201 ValueRankMap[&I] = ++BBRank; 202 } 203 } 204 205 unsigned ReassociatePass::getRank(Value *V) { 206 Instruction *I = dyn_cast<Instruction>(V); 207 if (!I) { 208 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument. 209 return 0; // Otherwise it's a global or constant, rank 0. 210 } 211 212 if (unsigned Rank = ValueRankMap[I]) 213 return Rank; // Rank already known? 214 215 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that 216 // we can reassociate expressions for code motion! Since we do not recurse 217 // for PHI nodes, we cannot have infinite recursion here, because there 218 // cannot be loops in the value graph that do not go through PHI nodes. 219 unsigned Rank = 0, MaxRank = RankMap[I->getParent()]; 220 for (unsigned i = 0, e = I->getNumOperands(); i != e && Rank != MaxRank; ++i) 221 Rank = std::max(Rank, getRank(I->getOperand(i))); 222 223 // If this is a 'not' or 'neg' instruction, do not count it for rank. This 224 // assures us that X and ~X will have the same rank. 225 if (!match(I, m_Not(m_Value())) && !match(I, m_Neg(m_Value())) && 226 !match(I, m_FNeg(m_Value()))) 227 ++Rank; 228 229 LLVM_DEBUG(dbgs() << "Calculated Rank[" << V->getName() << "] = " << Rank 230 << "\n"); 231 232 return ValueRankMap[I] = Rank; 233 } 234 235 // Canonicalize constants to RHS. Otherwise, sort the operands by rank. 236 void ReassociatePass::canonicalizeOperands(Instruction *I) { 237 assert(isa<BinaryOperator>(I) && "Expected binary operator."); 238 assert(I->isCommutative() && "Expected commutative operator."); 239 240 Value *LHS = I->getOperand(0); 241 Value *RHS = I->getOperand(1); 242 if (LHS == RHS || isa<Constant>(RHS)) 243 return; 244 if (isa<Constant>(LHS) || getRank(RHS) < getRank(LHS)) 245 cast<BinaryOperator>(I)->swapOperands(); 246 } 247 248 static BinaryOperator *CreateAdd(Value *S1, Value *S2, const Twine &Name, 249 BasicBlock::iterator InsertBefore, 250 Value *FlagsOp) { 251 if (S1->getType()->isIntOrIntVectorTy()) 252 return BinaryOperator::CreateAdd(S1, S2, Name, InsertBefore); 253 else { 254 BinaryOperator *Res = 255 BinaryOperator::CreateFAdd(S1, S2, Name, InsertBefore); 256 Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags()); 257 return Res; 258 } 259 } 260 261 static BinaryOperator *CreateMul(Value *S1, Value *S2, const Twine &Name, 262 BasicBlock::iterator InsertBefore, 263 Value *FlagsOp) { 264 if (S1->getType()->isIntOrIntVectorTy()) 265 return BinaryOperator::CreateMul(S1, S2, Name, InsertBefore); 266 else { 267 BinaryOperator *Res = 268 BinaryOperator::CreateFMul(S1, S2, Name, InsertBefore); 269 Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags()); 270 return Res; 271 } 272 } 273 274 static Instruction *CreateNeg(Value *S1, const Twine &Name, 275 BasicBlock::iterator InsertBefore, 276 Value *FlagsOp) { 277 if (S1->getType()->isIntOrIntVectorTy()) 278 return BinaryOperator::CreateNeg(S1, Name, InsertBefore); 279 280 if (auto *FMFSource = dyn_cast<Instruction>(FlagsOp)) 281 return UnaryOperator::CreateFNegFMF(S1, FMFSource, Name, InsertBefore); 282 283 return UnaryOperator::CreateFNeg(S1, Name, InsertBefore); 284 } 285 286 /// Replace 0-X with X*-1. 287 static BinaryOperator *LowerNegateToMultiply(Instruction *Neg) { 288 assert((isa<UnaryOperator>(Neg) || isa<BinaryOperator>(Neg)) && 289 "Expected a Negate!"); 290 // FIXME: It's not safe to lower a unary FNeg into a FMul by -1.0. 291 unsigned OpNo = isa<BinaryOperator>(Neg) ? 1 : 0; 292 Type *Ty = Neg->getType(); 293 Constant *NegOne = Ty->isIntOrIntVectorTy() ? 294 ConstantInt::getAllOnesValue(Ty) : ConstantFP::get(Ty, -1.0); 295 296 BinaryOperator *Res = 297 CreateMul(Neg->getOperand(OpNo), NegOne, "", Neg->getIterator(), Neg); 298 Neg->setOperand(OpNo, Constant::getNullValue(Ty)); // Drop use of op. 299 Res->takeName(Neg); 300 Neg->replaceAllUsesWith(Res); 301 Res->setDebugLoc(Neg->getDebugLoc()); 302 return Res; 303 } 304 305 using RepeatedValue = std::pair<Value*, APInt>; 306 307 /// Given an associative binary expression, return the leaf 308 /// nodes in Ops along with their weights (how many times the leaf occurs). The 309 /// original expression is the same as 310 /// (Ops[0].first op Ops[0].first op ... Ops[0].first) <- Ops[0].second times 311 /// op 312 /// (Ops[1].first op Ops[1].first op ... Ops[1].first) <- Ops[1].second times 313 /// op 314 /// ... 315 /// op 316 /// (Ops[N].first op Ops[N].first op ... Ops[N].first) <- Ops[N].second times 317 /// 318 /// Note that the values Ops[0].first, ..., Ops[N].first are all distinct. 319 /// 320 /// This routine may modify the function, in which case it returns 'true'. The 321 /// changes it makes may well be destructive, changing the value computed by 'I' 322 /// to something completely different. Thus if the routine returns 'true' then 323 /// you MUST either replace I with a new expression computed from the Ops array, 324 /// or use RewriteExprTree to put the values back in. 325 /// 326 /// A leaf node is either not a binary operation of the same kind as the root 327 /// node 'I' (i.e. is not a binary operator at all, or is, but with a different 328 /// opcode), or is the same kind of binary operator but has a use which either 329 /// does not belong to the expression, or does belong to the expression but is 330 /// a leaf node. Every leaf node has at least one use that is a non-leaf node 331 /// of the expression, while for non-leaf nodes (except for the root 'I') every 332 /// use is a non-leaf node of the expression. 333 /// 334 /// For example: 335 /// expression graph node names 336 /// 337 /// + | I 338 /// / \ | 339 /// + + | A, B 340 /// / \ / \ | 341 /// * + * | C, D, E 342 /// / \ / \ / \ | 343 /// + * | F, G 344 /// 345 /// The leaf nodes are C, E, F and G. The Ops array will contain (maybe not in 346 /// that order) (C, 1), (E, 1), (F, 2), (G, 2). 347 /// 348 /// The expression is maximal: if some instruction is a binary operator of the 349 /// same kind as 'I', and all of its uses are non-leaf nodes of the expression, 350 /// then the instruction also belongs to the expression, is not a leaf node of 351 /// it, and its operands also belong to the expression (but may be leaf nodes). 352 /// 353 /// NOTE: This routine will set operands of non-leaf non-root nodes to undef in 354 /// order to ensure that every non-root node in the expression has *exactly one* 355 /// use by a non-leaf node of the expression. This destruction means that the 356 /// caller MUST either replace 'I' with a new expression or use something like 357 /// RewriteExprTree to put the values back in if the routine indicates that it 358 /// made a change by returning 'true'. 359 /// 360 /// In the above example either the right operand of A or the left operand of B 361 /// will be replaced by undef. If it is B's operand then this gives: 362 /// 363 /// + | I 364 /// / \ | 365 /// + + | A, B - operand of B replaced with undef 366 /// / \ \ | 367 /// * + * | C, D, E 368 /// / \ / \ / \ | 369 /// + * | F, G 370 /// 371 /// Note that such undef operands can only be reached by passing through 'I'. 372 /// For example, if you visit operands recursively starting from a leaf node 373 /// then you will never see such an undef operand unless you get back to 'I', 374 /// which requires passing through a phi node. 375 /// 376 /// Note that this routine may also mutate binary operators of the wrong type 377 /// that have all uses inside the expression (i.e. only used by non-leaf nodes 378 /// of the expression) if it can turn them into binary operators of the right 379 /// type and thus make the expression bigger. 380 static bool LinearizeExprTree(Instruction *I, 381 SmallVectorImpl<RepeatedValue> &Ops, 382 ReassociatePass::OrderedSet &ToRedo, 383 reassociate::OverflowTracking &Flags) { 384 assert((isa<UnaryOperator>(I) || isa<BinaryOperator>(I)) && 385 "Expected a UnaryOperator or BinaryOperator!"); 386 LLVM_DEBUG(dbgs() << "LINEARIZE: " << *I << '\n'); 387 unsigned Bitwidth = I->getType()->getScalarType()->getPrimitiveSizeInBits(); 388 unsigned Opcode = I->getOpcode(); 389 assert(I->isAssociative() && I->isCommutative() && 390 "Expected an associative and commutative operation!"); 391 392 // Visit all operands of the expression, keeping track of their weight (the 393 // number of paths from the expression root to the operand, or if you like 394 // the number of times that operand occurs in the linearized expression). 395 // For example, if I = X + A, where X = A + B, then I, X and B have weight 1 396 // while A has weight two. 397 398 // Worklist of non-leaf nodes (their operands are in the expression too) along 399 // with their weights, representing a certain number of paths to the operator. 400 // If an operator occurs in the worklist multiple times then we found multiple 401 // ways to get to it. 402 SmallVector<std::pair<Instruction*, APInt>, 8> Worklist; // (Op, Weight) 403 Worklist.push_back(std::make_pair(I, APInt(Bitwidth, 1))); 404 bool Changed = false; 405 406 // Leaves of the expression are values that either aren't the right kind of 407 // operation (eg: a constant, or a multiply in an add tree), or are, but have 408 // some uses that are not inside the expression. For example, in I = X + X, 409 // X = A + B, the value X has two uses (by I) that are in the expression. If 410 // X has any other uses, for example in a return instruction, then we consider 411 // X to be a leaf, and won't analyze it further. When we first visit a value, 412 // if it has more than one use then at first we conservatively consider it to 413 // be a leaf. Later, as the expression is explored, we may discover some more 414 // uses of the value from inside the expression. If all uses turn out to be 415 // from within the expression (and the value is a binary operator of the right 416 // kind) then the value is no longer considered to be a leaf, and its operands 417 // are explored. 418 419 // Leaves - Keeps track of the set of putative leaves as well as the number of 420 // paths to each leaf seen so far. 421 using LeafMap = DenseMap<Value *, APInt>; 422 LeafMap Leaves; // Leaf -> Total weight so far. 423 SmallVector<Value *, 8> LeafOrder; // Ensure deterministic leaf output order. 424 const DataLayout DL = I->getModule()->getDataLayout(); 425 426 #ifndef NDEBUG 427 SmallPtrSet<Value *, 8> Visited; // For checking the iteration scheme. 428 #endif 429 while (!Worklist.empty()) { 430 std::pair<Instruction*, APInt> P = Worklist.pop_back_val(); 431 I = P.first; // We examine the operands of this binary operator. 432 433 if (isa<OverflowingBinaryOperator>(I)) { 434 Flags.HasNUW &= I->hasNoUnsignedWrap(); 435 Flags.HasNSW &= I->hasNoSignedWrap(); 436 } 437 438 for (unsigned OpIdx = 0; OpIdx < I->getNumOperands(); ++OpIdx) { // Visit operands. 439 Value *Op = I->getOperand(OpIdx); 440 APInt Weight = P.second; // Number of paths to this operand. 441 LLVM_DEBUG(dbgs() << "OPERAND: " << *Op << " (" << Weight << ")\n"); 442 assert(!Op->use_empty() && "No uses, so how did we get to it?!"); 443 444 // If this is a binary operation of the right kind with only one use then 445 // add its operands to the expression. 446 if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) { 447 assert(Visited.insert(Op).second && "Not first visit!"); 448 LLVM_DEBUG(dbgs() << "DIRECT ADD: " << *Op << " (" << Weight << ")\n"); 449 Worklist.push_back(std::make_pair(BO, Weight)); 450 continue; 451 } 452 453 // Appears to be a leaf. Is the operand already in the set of leaves? 454 LeafMap::iterator It = Leaves.find(Op); 455 if (It == Leaves.end()) { 456 // Not in the leaf map. Must be the first time we saw this operand. 457 assert(Visited.insert(Op).second && "Not first visit!"); 458 if (!Op->hasOneUse()) { 459 // This value has uses not accounted for by the expression, so it is 460 // not safe to modify. Mark it as being a leaf. 461 LLVM_DEBUG(dbgs() 462 << "ADD USES LEAF: " << *Op << " (" << Weight << ")\n"); 463 LeafOrder.push_back(Op); 464 Leaves[Op] = Weight; 465 continue; 466 } 467 // No uses outside the expression, try morphing it. 468 } else { 469 // Already in the leaf map. 470 assert(It != Leaves.end() && Visited.count(Op) && 471 "In leaf map but not visited!"); 472 473 // Update the number of paths to the leaf. 474 It->second += Weight; 475 476 // If we still have uses that are not accounted for by the expression 477 // then it is not safe to modify the value. 478 if (!Op->hasOneUse()) 479 continue; 480 481 // No uses outside the expression, try morphing it. 482 Weight = It->second; 483 Leaves.erase(It); // Since the value may be morphed below. 484 } 485 486 // At this point we have a value which, first of all, is not a binary 487 // expression of the right kind, and secondly, is only used inside the 488 // expression. This means that it can safely be modified. See if we 489 // can usefully morph it into an expression of the right kind. 490 assert((!isa<Instruction>(Op) || 491 cast<Instruction>(Op)->getOpcode() != Opcode 492 || (isa<FPMathOperator>(Op) && 493 !hasFPAssociativeFlags(cast<Instruction>(Op)))) && 494 "Should have been handled above!"); 495 assert(Op->hasOneUse() && "Has uses outside the expression tree!"); 496 497 // If this is a multiply expression, turn any internal negations into 498 // multiplies by -1 so they can be reassociated. Add any users of the 499 // newly created multiplication by -1 to the redo list, so any 500 // reassociation opportunities that are exposed will be reassociated 501 // further. 502 Instruction *Neg; 503 if (((Opcode == Instruction::Mul && match(Op, m_Neg(m_Value()))) || 504 (Opcode == Instruction::FMul && match(Op, m_FNeg(m_Value())))) && 505 match(Op, m_Instruction(Neg))) { 506 LLVM_DEBUG(dbgs() 507 << "MORPH LEAF: " << *Op << " (" << Weight << ") TO "); 508 Instruction *Mul = LowerNegateToMultiply(Neg); 509 LLVM_DEBUG(dbgs() << *Mul << '\n'); 510 Worklist.push_back(std::make_pair(Mul, Weight)); 511 for (User *U : Mul->users()) { 512 if (BinaryOperator *UserBO = dyn_cast<BinaryOperator>(U)) 513 ToRedo.insert(UserBO); 514 } 515 ToRedo.insert(Neg); 516 Changed = true; 517 continue; 518 } 519 520 // Failed to morph into an expression of the right type. This really is 521 // a leaf. 522 LLVM_DEBUG(dbgs() << "ADD LEAF: " << *Op << " (" << Weight << ")\n"); 523 assert(!isReassociableOp(Op, Opcode) && "Value was morphed?"); 524 LeafOrder.push_back(Op); 525 Leaves[Op] = Weight; 526 } 527 } 528 529 // The leaves, repeated according to their weights, represent the linearized 530 // form of the expression. 531 for (Value *V : LeafOrder) { 532 LeafMap::iterator It = Leaves.find(V); 533 if (It == Leaves.end()) 534 // Node initially thought to be a leaf wasn't. 535 continue; 536 assert(!isReassociableOp(V, Opcode) && "Shouldn't be a leaf!"); 537 APInt Weight = It->second; 538 if (Weight.isMinValue()) 539 // Leaf already output or weight reduction eliminated it. 540 continue; 541 // Ensure the leaf is only output once. 542 It->second = 0; 543 Ops.push_back(std::make_pair(V, Weight)); 544 if (Opcode == Instruction::Add && Flags.AllKnownNonNegative && Flags.HasNSW) 545 Flags.AllKnownNonNegative &= isKnownNonNegative(V, SimplifyQuery(DL)); 546 } 547 548 // For nilpotent operations or addition there may be no operands, for example 549 // because the expression was "X xor X" or consisted of 2^Bitwidth additions: 550 // in both cases the weight reduces to 0 causing the value to be skipped. 551 if (Ops.empty()) { 552 Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, I->getType()); 553 assert(Identity && "Associative operation without identity!"); 554 Ops.emplace_back(Identity, APInt(Bitwidth, 1)); 555 } 556 557 return Changed; 558 } 559 560 /// Now that the operands for this expression tree are 561 /// linearized and optimized, emit them in-order. 562 void ReassociatePass::RewriteExprTree(BinaryOperator *I, 563 SmallVectorImpl<ValueEntry> &Ops, 564 OverflowTracking Flags) { 565 assert(Ops.size() > 1 && "Single values should be used directly!"); 566 567 // Since our optimizations should never increase the number of operations, the 568 // new expression can usually be written reusing the existing binary operators 569 // from the original expression tree, without creating any new instructions, 570 // though the rewritten expression may have a completely different topology. 571 // We take care to not change anything if the new expression will be the same 572 // as the original. If more than trivial changes (like commuting operands) 573 // were made then we are obliged to clear out any optional subclass data like 574 // nsw flags. 575 576 /// NodesToRewrite - Nodes from the original expression available for writing 577 /// the new expression into. 578 SmallVector<BinaryOperator*, 8> NodesToRewrite; 579 unsigned Opcode = I->getOpcode(); 580 BinaryOperator *Op = I; 581 582 /// NotRewritable - The operands being written will be the leaves of the new 583 /// expression and must not be used as inner nodes (via NodesToRewrite) by 584 /// mistake. Inner nodes are always reassociable, and usually leaves are not 585 /// (if they were they would have been incorporated into the expression and so 586 /// would not be leaves), so most of the time there is no danger of this. But 587 /// in rare cases a leaf may become reassociable if an optimization kills uses 588 /// of it, or it may momentarily become reassociable during rewriting (below) 589 /// due it being removed as an operand of one of its uses. Ensure that misuse 590 /// of leaf nodes as inner nodes cannot occur by remembering all of the future 591 /// leaves and refusing to reuse any of them as inner nodes. 592 SmallPtrSet<Value*, 8> NotRewritable; 593 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 594 NotRewritable.insert(Ops[i].Op); 595 596 // ExpressionChangedStart - Non-null if the rewritten expression differs from 597 // the original in some non-trivial way, requiring the clearing of optional 598 // flags. Flags are cleared from the operator in ExpressionChangedStart up to 599 // ExpressionChangedEnd inclusive. 600 BinaryOperator *ExpressionChangedStart = nullptr, 601 *ExpressionChangedEnd = nullptr; 602 for (unsigned i = 0; ; ++i) { 603 // The last operation (which comes earliest in the IR) is special as both 604 // operands will come from Ops, rather than just one with the other being 605 // a subexpression. 606 if (i+2 == Ops.size()) { 607 Value *NewLHS = Ops[i].Op; 608 Value *NewRHS = Ops[i+1].Op; 609 Value *OldLHS = Op->getOperand(0); 610 Value *OldRHS = Op->getOperand(1); 611 612 if (NewLHS == OldLHS && NewRHS == OldRHS) 613 // Nothing changed, leave it alone. 614 break; 615 616 if (NewLHS == OldRHS && NewRHS == OldLHS) { 617 // The order of the operands was reversed. Swap them. 618 LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n'); 619 Op->swapOperands(); 620 LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n'); 621 MadeChange = true; 622 ++NumChanged; 623 break; 624 } 625 626 // The new operation differs non-trivially from the original. Overwrite 627 // the old operands with the new ones. 628 LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n'); 629 if (NewLHS != OldLHS) { 630 BinaryOperator *BO = isReassociableOp(OldLHS, Opcode); 631 if (BO && !NotRewritable.count(BO)) 632 NodesToRewrite.push_back(BO); 633 Op->setOperand(0, NewLHS); 634 } 635 if (NewRHS != OldRHS) { 636 BinaryOperator *BO = isReassociableOp(OldRHS, Opcode); 637 if (BO && !NotRewritable.count(BO)) 638 NodesToRewrite.push_back(BO); 639 Op->setOperand(1, NewRHS); 640 } 641 LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n'); 642 643 ExpressionChangedStart = Op; 644 if (!ExpressionChangedEnd) 645 ExpressionChangedEnd = Op; 646 MadeChange = true; 647 ++NumChanged; 648 649 break; 650 } 651 652 // Not the last operation. The left-hand side will be a sub-expression 653 // while the right-hand side will be the current element of Ops. 654 Value *NewRHS = Ops[i].Op; 655 if (NewRHS != Op->getOperand(1)) { 656 LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n'); 657 if (NewRHS == Op->getOperand(0)) { 658 // The new right-hand side was already present as the left operand. If 659 // we are lucky then swapping the operands will sort out both of them. 660 Op->swapOperands(); 661 } else { 662 // Overwrite with the new right-hand side. 663 BinaryOperator *BO = isReassociableOp(Op->getOperand(1), Opcode); 664 if (BO && !NotRewritable.count(BO)) 665 NodesToRewrite.push_back(BO); 666 Op->setOperand(1, NewRHS); 667 ExpressionChangedStart = Op; 668 if (!ExpressionChangedEnd) 669 ExpressionChangedEnd = Op; 670 } 671 LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n'); 672 MadeChange = true; 673 ++NumChanged; 674 } 675 676 // Now deal with the left-hand side. If this is already an operation node 677 // from the original expression then just rewrite the rest of the expression 678 // into it. 679 BinaryOperator *BO = isReassociableOp(Op->getOperand(0), Opcode); 680 if (BO && !NotRewritable.count(BO)) { 681 Op = BO; 682 continue; 683 } 684 685 // Otherwise, grab a spare node from the original expression and use that as 686 // the left-hand side. If there are no nodes left then the optimizers made 687 // an expression with more nodes than the original! This usually means that 688 // they did something stupid but it might mean that the problem was just too 689 // hard (finding the mimimal number of multiplications needed to realize a 690 // multiplication expression is NP-complete). Whatever the reason, smart or 691 // stupid, create a new node if there are none left. 692 BinaryOperator *NewOp; 693 if (NodesToRewrite.empty()) { 694 Constant *Undef = UndefValue::get(I->getType()); 695 NewOp = BinaryOperator::Create(Instruction::BinaryOps(Opcode), Undef, 696 Undef, "", I->getIterator()); 697 if (isa<FPMathOperator>(NewOp)) 698 NewOp->setFastMathFlags(I->getFastMathFlags()); 699 } else { 700 NewOp = NodesToRewrite.pop_back_val(); 701 } 702 703 LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n'); 704 Op->setOperand(0, NewOp); 705 LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n'); 706 ExpressionChangedStart = Op; 707 if (!ExpressionChangedEnd) 708 ExpressionChangedEnd = Op; 709 MadeChange = true; 710 ++NumChanged; 711 Op = NewOp; 712 } 713 714 // If the expression changed non-trivially then clear out all subclass data 715 // starting from the operator specified in ExpressionChanged, and compactify 716 // the operators to just before the expression root to guarantee that the 717 // expression tree is dominated by all of Ops. 718 if (ExpressionChangedStart) { 719 bool ClearFlags = true; 720 do { 721 // Preserve flags. 722 if (ClearFlags) { 723 if (isa<FPMathOperator>(I)) { 724 FastMathFlags Flags = I->getFastMathFlags(); 725 ExpressionChangedStart->clearSubclassOptionalData(); 726 ExpressionChangedStart->setFastMathFlags(Flags); 727 } else { 728 ExpressionChangedStart->clearSubclassOptionalData(); 729 // Note that it doesn't hold for mul if one of the operands is zero. 730 // TODO: We can preserve NUW flag if we prove that all mul operands 731 // are non-zero. 732 if (ExpressionChangedStart->getOpcode() == Instruction::Add) { 733 if (Flags.HasNUW) 734 ExpressionChangedStart->setHasNoUnsignedWrap(); 735 if (Flags.HasNSW && (Flags.AllKnownNonNegative || Flags.HasNUW)) 736 ExpressionChangedStart->setHasNoSignedWrap(); 737 } 738 } 739 } 740 741 if (ExpressionChangedStart == ExpressionChangedEnd) 742 ClearFlags = false; 743 if (ExpressionChangedStart == I) 744 break; 745 746 // Discard any debug info related to the expressions that has changed (we 747 // can leave debug info related to the root and any operation that didn't 748 // change, since the result of the expression tree should be the same 749 // even after reassociation). 750 if (ClearFlags) 751 replaceDbgUsesWithUndef(ExpressionChangedStart); 752 753 ExpressionChangedStart->moveBefore(I); 754 ExpressionChangedStart = 755 cast<BinaryOperator>(*ExpressionChangedStart->user_begin()); 756 } while (true); 757 } 758 759 // Throw away any left over nodes from the original expression. 760 for (unsigned i = 0, e = NodesToRewrite.size(); i != e; ++i) 761 RedoInsts.insert(NodesToRewrite[i]); 762 } 763 764 /// Insert instructions before the instruction pointed to by BI, 765 /// that computes the negative version of the value specified. The negative 766 /// version of the value is returned, and BI is left pointing at the instruction 767 /// that should be processed next by the reassociation pass. 768 /// Also add intermediate instructions to the redo list that are modified while 769 /// pushing the negates through adds. These will be revisited to see if 770 /// additional opportunities have been exposed. 771 static Value *NegateValue(Value *V, Instruction *BI, 772 ReassociatePass::OrderedSet &ToRedo) { 773 if (auto *C = dyn_cast<Constant>(V)) { 774 const DataLayout &DL = BI->getModule()->getDataLayout(); 775 Constant *Res = C->getType()->isFPOrFPVectorTy() 776 ? ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL) 777 : ConstantExpr::getNeg(C); 778 if (Res) 779 return Res; 780 } 781 782 // We are trying to expose opportunity for reassociation. One of the things 783 // that we want to do to achieve this is to push a negation as deep into an 784 // expression chain as possible, to expose the add instructions. In practice, 785 // this means that we turn this: 786 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D 787 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate 788 // the constants. We assume that instcombine will clean up the mess later if 789 // we introduce tons of unnecessary negation instructions. 790 // 791 if (BinaryOperator *I = 792 isReassociableOp(V, Instruction::Add, Instruction::FAdd)) { 793 // Push the negates through the add. 794 I->setOperand(0, NegateValue(I->getOperand(0), BI, ToRedo)); 795 I->setOperand(1, NegateValue(I->getOperand(1), BI, ToRedo)); 796 if (I->getOpcode() == Instruction::Add) { 797 I->setHasNoUnsignedWrap(false); 798 I->setHasNoSignedWrap(false); 799 } 800 801 // We must move the add instruction here, because the neg instructions do 802 // not dominate the old add instruction in general. By moving it, we are 803 // assured that the neg instructions we just inserted dominate the 804 // instruction we are about to insert after them. 805 // 806 I->moveBefore(BI); 807 I->setName(I->getName()+".neg"); 808 809 // Add the intermediate negates to the redo list as processing them later 810 // could expose more reassociating opportunities. 811 ToRedo.insert(I); 812 return I; 813 } 814 815 // Okay, we need to materialize a negated version of V with an instruction. 816 // Scan the use lists of V to see if we have one already. 817 for (User *U : V->users()) { 818 if (!match(U, m_Neg(m_Value())) && !match(U, m_FNeg(m_Value()))) 819 continue; 820 821 // We found one! Now we have to make sure that the definition dominates 822 // this use. We do this by moving it to the entry block (if it is a 823 // non-instruction value) or right after the definition. These negates will 824 // be zapped by reassociate later, so we don't need much finesse here. 825 Instruction *TheNeg = dyn_cast<Instruction>(U); 826 827 // We can't safely propagate a vector zero constant with poison/undef lanes. 828 Constant *C; 829 if (match(TheNeg, m_BinOp(m_Constant(C), m_Value())) && 830 C->containsUndefOrPoisonElement()) 831 continue; 832 833 // Verify that the negate is in this function, V might be a constant expr. 834 if (!TheNeg || 835 TheNeg->getParent()->getParent() != BI->getParent()->getParent()) 836 continue; 837 838 BasicBlock::iterator InsertPt; 839 if (Instruction *InstInput = dyn_cast<Instruction>(V)) { 840 auto InsertPtOpt = InstInput->getInsertionPointAfterDef(); 841 if (!InsertPtOpt) 842 continue; 843 InsertPt = *InsertPtOpt; 844 } else { 845 InsertPt = TheNeg->getFunction() 846 ->getEntryBlock() 847 .getFirstNonPHIOrDbg() 848 ->getIterator(); 849 } 850 851 TheNeg->moveBefore(*InsertPt->getParent(), InsertPt); 852 if (TheNeg->getOpcode() == Instruction::Sub) { 853 TheNeg->setHasNoUnsignedWrap(false); 854 TheNeg->setHasNoSignedWrap(false); 855 } else { 856 TheNeg->andIRFlags(BI); 857 } 858 ToRedo.insert(TheNeg); 859 return TheNeg; 860 } 861 862 // Insert a 'neg' instruction that subtracts the value from zero to get the 863 // negation. 864 Instruction *NewNeg = 865 CreateNeg(V, V->getName() + ".neg", BI->getIterator(), BI); 866 ToRedo.insert(NewNeg); 867 return NewNeg; 868 } 869 870 // See if this `or` looks like an load widening reduction, i.e. that it 871 // consists of an `or`/`shl`/`zext`/`load` nodes only. Note that we don't 872 // ensure that the pattern is *really* a load widening reduction, 873 // we do not ensure that it can really be replaced with a widened load, 874 // only that it mostly looks like one. 875 static bool isLoadCombineCandidate(Instruction *Or) { 876 SmallVector<Instruction *, 8> Worklist; 877 SmallSet<Instruction *, 8> Visited; 878 879 auto Enqueue = [&](Value *V) { 880 auto *I = dyn_cast<Instruction>(V); 881 // Each node of an `or` reduction must be an instruction, 882 if (!I) 883 return false; // Node is certainly not part of an `or` load reduction. 884 // Only process instructions we have never processed before. 885 if (Visited.insert(I).second) 886 Worklist.emplace_back(I); 887 return true; // Will need to look at parent nodes. 888 }; 889 890 if (!Enqueue(Or)) 891 return false; // Not an `or` reduction pattern. 892 893 while (!Worklist.empty()) { 894 auto *I = Worklist.pop_back_val(); 895 896 // Okay, which instruction is this node? 897 switch (I->getOpcode()) { 898 case Instruction::Or: 899 // Got an `or` node. That's fine, just recurse into it's operands. 900 for (Value *Op : I->operands()) 901 if (!Enqueue(Op)) 902 return false; // Not an `or` reduction pattern. 903 continue; 904 905 case Instruction::Shl: 906 case Instruction::ZExt: 907 // `shl`/`zext` nodes are fine, just recurse into their base operand. 908 if (!Enqueue(I->getOperand(0))) 909 return false; // Not an `or` reduction pattern. 910 continue; 911 912 case Instruction::Load: 913 // Perfect, `load` node means we've reached an edge of the graph. 914 continue; 915 916 default: // Unknown node. 917 return false; // Not an `or` reduction pattern. 918 } 919 } 920 921 return true; 922 } 923 924 /// Return true if it may be profitable to convert this (X|Y) into (X+Y). 925 static bool shouldConvertOrWithNoCommonBitsToAdd(Instruction *Or) { 926 // Don't bother to convert this up unless either the LHS is an associable add 927 // or subtract or mul or if this is only used by one of the above. 928 // This is only a compile-time improvement, it is not needed for correctness! 929 auto isInteresting = [](Value *V) { 930 for (auto Op : {Instruction::Add, Instruction::Sub, Instruction::Mul, 931 Instruction::Shl}) 932 if (isReassociableOp(V, Op)) 933 return true; 934 return false; 935 }; 936 937 if (any_of(Or->operands(), isInteresting)) 938 return true; 939 940 Value *VB = Or->user_back(); 941 if (Or->hasOneUse() && isInteresting(VB)) 942 return true; 943 944 return false; 945 } 946 947 /// If we have (X|Y), and iff X and Y have no common bits set, 948 /// transform this into (X+Y) to allow arithmetics reassociation. 949 static BinaryOperator *convertOrWithNoCommonBitsToAdd(Instruction *Or) { 950 // Convert an or into an add. 951 BinaryOperator *New = CreateAdd(Or->getOperand(0), Or->getOperand(1), "", 952 Or->getIterator(), Or); 953 New->setHasNoSignedWrap(); 954 New->setHasNoUnsignedWrap(); 955 New->takeName(Or); 956 957 // Everyone now refers to the add instruction. 958 Or->replaceAllUsesWith(New); 959 New->setDebugLoc(Or->getDebugLoc()); 960 961 LLVM_DEBUG(dbgs() << "Converted or into an add: " << *New << '\n'); 962 return New; 963 } 964 965 /// Return true if we should break up this subtract of X-Y into (X + -Y). 966 static bool ShouldBreakUpSubtract(Instruction *Sub) { 967 // If this is a negation, we can't split it up! 968 if (match(Sub, m_Neg(m_Value())) || match(Sub, m_FNeg(m_Value()))) 969 return false; 970 971 // Don't breakup X - undef. 972 if (isa<UndefValue>(Sub->getOperand(1))) 973 return false; 974 975 // Don't bother to break this up unless either the LHS is an associable add or 976 // subtract or if this is only used by one. 977 Value *V0 = Sub->getOperand(0); 978 if (isReassociableOp(V0, Instruction::Add, Instruction::FAdd) || 979 isReassociableOp(V0, Instruction::Sub, Instruction::FSub)) 980 return true; 981 Value *V1 = Sub->getOperand(1); 982 if (isReassociableOp(V1, Instruction::Add, Instruction::FAdd) || 983 isReassociableOp(V1, Instruction::Sub, Instruction::FSub)) 984 return true; 985 Value *VB = Sub->user_back(); 986 if (Sub->hasOneUse() && 987 (isReassociableOp(VB, Instruction::Add, Instruction::FAdd) || 988 isReassociableOp(VB, Instruction::Sub, Instruction::FSub))) 989 return true; 990 991 return false; 992 } 993 994 /// If we have (X-Y), and if either X is an add, or if this is only used by an 995 /// add, transform this into (X+(0-Y)) to promote better reassociation. 996 static BinaryOperator *BreakUpSubtract(Instruction *Sub, 997 ReassociatePass::OrderedSet &ToRedo) { 998 // Convert a subtract into an add and a neg instruction. This allows sub 999 // instructions to be commuted with other add instructions. 1000 // 1001 // Calculate the negative value of Operand 1 of the sub instruction, 1002 // and set it as the RHS of the add instruction we just made. 1003 Value *NegVal = NegateValue(Sub->getOperand(1), Sub, ToRedo); 1004 BinaryOperator *New = 1005 CreateAdd(Sub->getOperand(0), NegVal, "", Sub->getIterator(), Sub); 1006 Sub->setOperand(0, Constant::getNullValue(Sub->getType())); // Drop use of op. 1007 Sub->setOperand(1, Constant::getNullValue(Sub->getType())); // Drop use of op. 1008 New->takeName(Sub); 1009 1010 // Everyone now refers to the add instruction. 1011 Sub->replaceAllUsesWith(New); 1012 New->setDebugLoc(Sub->getDebugLoc()); 1013 1014 LLVM_DEBUG(dbgs() << "Negated: " << *New << '\n'); 1015 return New; 1016 } 1017 1018 /// If this is a shift of a reassociable multiply or is used by one, change 1019 /// this into a multiply by a constant to assist with further reassociation. 1020 static BinaryOperator *ConvertShiftToMul(Instruction *Shl) { 1021 Constant *MulCst = ConstantInt::get(Shl->getType(), 1); 1022 auto *SA = cast<ConstantInt>(Shl->getOperand(1)); 1023 MulCst = ConstantExpr::getShl(MulCst, SA); 1024 1025 BinaryOperator *Mul = BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, 1026 "", Shl->getIterator()); 1027 Shl->setOperand(0, PoisonValue::get(Shl->getType())); // Drop use of op. 1028 Mul->takeName(Shl); 1029 1030 // Everyone now refers to the mul instruction. 1031 Shl->replaceAllUsesWith(Mul); 1032 Mul->setDebugLoc(Shl->getDebugLoc()); 1033 1034 // We can safely preserve the nuw flag in all cases. It's also safe to turn a 1035 // nuw nsw shl into a nuw nsw mul. However, nsw in isolation requires special 1036 // handling. It can be preserved as long as we're not left shifting by 1037 // bitwidth - 1. 1038 bool NSW = cast<BinaryOperator>(Shl)->hasNoSignedWrap(); 1039 bool NUW = cast<BinaryOperator>(Shl)->hasNoUnsignedWrap(); 1040 unsigned BitWidth = Shl->getType()->getIntegerBitWidth(); 1041 if (NSW && (NUW || SA->getValue().ult(BitWidth - 1))) 1042 Mul->setHasNoSignedWrap(true); 1043 Mul->setHasNoUnsignedWrap(NUW); 1044 return Mul; 1045 } 1046 1047 /// Scan backwards and forwards among values with the same rank as element i 1048 /// to see if X exists. If X does not exist, return i. This is useful when 1049 /// scanning for 'x' when we see '-x' because they both get the same rank. 1050 static unsigned FindInOperandList(const SmallVectorImpl<ValueEntry> &Ops, 1051 unsigned i, Value *X) { 1052 unsigned XRank = Ops[i].Rank; 1053 unsigned e = Ops.size(); 1054 for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) { 1055 if (Ops[j].Op == X) 1056 return j; 1057 if (Instruction *I1 = dyn_cast<Instruction>(Ops[j].Op)) 1058 if (Instruction *I2 = dyn_cast<Instruction>(X)) 1059 if (I1->isIdenticalTo(I2)) 1060 return j; 1061 } 1062 // Scan backwards. 1063 for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) { 1064 if (Ops[j].Op == X) 1065 return j; 1066 if (Instruction *I1 = dyn_cast<Instruction>(Ops[j].Op)) 1067 if (Instruction *I2 = dyn_cast<Instruction>(X)) 1068 if (I1->isIdenticalTo(I2)) 1069 return j; 1070 } 1071 return i; 1072 } 1073 1074 /// Emit a tree of add instructions, summing Ops together 1075 /// and returning the result. Insert the tree before I. 1076 static Value *EmitAddTreeOfValues(BasicBlock::iterator It, 1077 SmallVectorImpl<WeakTrackingVH> &Ops) { 1078 if (Ops.size() == 1) return Ops.back(); 1079 1080 Value *V1 = Ops.pop_back_val(); 1081 Value *V2 = EmitAddTreeOfValues(It, Ops); 1082 return CreateAdd(V2, V1, "reass.add", It, &*It); 1083 } 1084 1085 /// If V is an expression tree that is a multiplication sequence, 1086 /// and if this sequence contains a multiply by Factor, 1087 /// remove Factor from the tree and return the new tree. 1088 Value *ReassociatePass::RemoveFactorFromExpression(Value *V, Value *Factor) { 1089 BinaryOperator *BO = isReassociableOp(V, Instruction::Mul, Instruction::FMul); 1090 if (!BO) 1091 return nullptr; 1092 1093 SmallVector<RepeatedValue, 8> Tree; 1094 OverflowTracking Flags; 1095 MadeChange |= LinearizeExprTree(BO, Tree, RedoInsts, Flags); 1096 SmallVector<ValueEntry, 8> Factors; 1097 Factors.reserve(Tree.size()); 1098 for (unsigned i = 0, e = Tree.size(); i != e; ++i) { 1099 RepeatedValue E = Tree[i]; 1100 Factors.append(E.second.getZExtValue(), 1101 ValueEntry(getRank(E.first), E.first)); 1102 } 1103 1104 bool FoundFactor = false; 1105 bool NeedsNegate = false; 1106 for (unsigned i = 0, e = Factors.size(); i != e; ++i) { 1107 if (Factors[i].Op == Factor) { 1108 FoundFactor = true; 1109 Factors.erase(Factors.begin()+i); 1110 break; 1111 } 1112 1113 // If this is a negative version of this factor, remove it. 1114 if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor)) { 1115 if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op)) 1116 if (FC1->getValue() == -FC2->getValue()) { 1117 FoundFactor = NeedsNegate = true; 1118 Factors.erase(Factors.begin()+i); 1119 break; 1120 } 1121 } else if (ConstantFP *FC1 = dyn_cast<ConstantFP>(Factor)) { 1122 if (ConstantFP *FC2 = dyn_cast<ConstantFP>(Factors[i].Op)) { 1123 const APFloat &F1 = FC1->getValueAPF(); 1124 APFloat F2(FC2->getValueAPF()); 1125 F2.changeSign(); 1126 if (F1 == F2) { 1127 FoundFactor = NeedsNegate = true; 1128 Factors.erase(Factors.begin() + i); 1129 break; 1130 } 1131 } 1132 } 1133 } 1134 1135 if (!FoundFactor) { 1136 // Make sure to restore the operands to the expression tree. 1137 RewriteExprTree(BO, Factors, Flags); 1138 return nullptr; 1139 } 1140 1141 BasicBlock::iterator InsertPt = ++BO->getIterator(); 1142 1143 // If this was just a single multiply, remove the multiply and return the only 1144 // remaining operand. 1145 if (Factors.size() == 1) { 1146 RedoInsts.insert(BO); 1147 V = Factors[0].Op; 1148 } else { 1149 RewriteExprTree(BO, Factors, Flags); 1150 V = BO; 1151 } 1152 1153 if (NeedsNegate) 1154 V = CreateNeg(V, "neg", InsertPt, BO); 1155 1156 return V; 1157 } 1158 1159 /// If V is a single-use multiply, recursively add its operands as factors, 1160 /// otherwise add V to the list of factors. 1161 /// 1162 /// Ops is the top-level list of add operands we're trying to factor. 1163 static void FindSingleUseMultiplyFactors(Value *V, 1164 SmallVectorImpl<Value*> &Factors) { 1165 BinaryOperator *BO = isReassociableOp(V, Instruction::Mul, Instruction::FMul); 1166 if (!BO) { 1167 Factors.push_back(V); 1168 return; 1169 } 1170 1171 // Otherwise, add the LHS and RHS to the list of factors. 1172 FindSingleUseMultiplyFactors(BO->getOperand(1), Factors); 1173 FindSingleUseMultiplyFactors(BO->getOperand(0), Factors); 1174 } 1175 1176 /// Optimize a series of operands to an 'and', 'or', or 'xor' instruction. 1177 /// This optimizes based on identities. If it can be reduced to a single Value, 1178 /// it is returned, otherwise the Ops list is mutated as necessary. 1179 static Value *OptimizeAndOrXor(unsigned Opcode, 1180 SmallVectorImpl<ValueEntry> &Ops) { 1181 // Scan the operand lists looking for X and ~X pairs, along with X,X pairs. 1182 // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1. 1183 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1184 // First, check for X and ~X in the operand list. 1185 assert(i < Ops.size()); 1186 Value *X; 1187 if (match(Ops[i].Op, m_Not(m_Value(X)))) { // Cannot occur for ^. 1188 unsigned FoundX = FindInOperandList(Ops, i, X); 1189 if (FoundX != i) { 1190 if (Opcode == Instruction::And) // ...&X&~X = 0 1191 return Constant::getNullValue(X->getType()); 1192 1193 if (Opcode == Instruction::Or) // ...|X|~X = -1 1194 return Constant::getAllOnesValue(X->getType()); 1195 } 1196 } 1197 1198 // Next, check for duplicate pairs of values, which we assume are next to 1199 // each other, due to our sorting criteria. 1200 assert(i < Ops.size()); 1201 if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) { 1202 if (Opcode == Instruction::And || Opcode == Instruction::Or) { 1203 // Drop duplicate values for And and Or. 1204 Ops.erase(Ops.begin()+i); 1205 --i; --e; 1206 ++NumAnnihil; 1207 continue; 1208 } 1209 1210 // Drop pairs of values for Xor. 1211 assert(Opcode == Instruction::Xor); 1212 if (e == 2) 1213 return Constant::getNullValue(Ops[0].Op->getType()); 1214 1215 // Y ^ X^X -> Y 1216 Ops.erase(Ops.begin()+i, Ops.begin()+i+2); 1217 i -= 1; e -= 2; 1218 ++NumAnnihil; 1219 } 1220 } 1221 return nullptr; 1222 } 1223 1224 /// Helper function of CombineXorOpnd(). It creates a bitwise-and 1225 /// instruction with the given two operands, and return the resulting 1226 /// instruction. There are two special cases: 1) if the constant operand is 0, 1227 /// it will return NULL. 2) if the constant is ~0, the symbolic operand will 1228 /// be returned. 1229 static Value *createAndInstr(BasicBlock::iterator InsertBefore, Value *Opnd, 1230 const APInt &ConstOpnd) { 1231 if (ConstOpnd.isZero()) 1232 return nullptr; 1233 1234 if (ConstOpnd.isAllOnes()) 1235 return Opnd; 1236 1237 Instruction *I = BinaryOperator::CreateAnd( 1238 Opnd, ConstantInt::get(Opnd->getType(), ConstOpnd), "and.ra", 1239 InsertBefore); 1240 I->setDebugLoc(InsertBefore->getDebugLoc()); 1241 return I; 1242 } 1243 1244 // Helper function of OptimizeXor(). It tries to simplify "Opnd1 ^ ConstOpnd" 1245 // into "R ^ C", where C would be 0, and R is a symbolic value. 1246 // 1247 // If it was successful, true is returned, and the "R" and "C" is returned 1248 // via "Res" and "ConstOpnd", respectively; otherwise, false is returned, 1249 // and both "Res" and "ConstOpnd" remain unchanged. 1250 bool ReassociatePass::CombineXorOpnd(BasicBlock::iterator It, XorOpnd *Opnd1, 1251 APInt &ConstOpnd, Value *&Res) { 1252 // Xor-Rule 1: (x | c1) ^ c2 = (x | c1) ^ (c1 ^ c1) ^ c2 1253 // = ((x | c1) ^ c1) ^ (c1 ^ c2) 1254 // = (x & ~c1) ^ (c1 ^ c2) 1255 // It is useful only when c1 == c2. 1256 if (!Opnd1->isOrExpr() || Opnd1->getConstPart().isZero()) 1257 return false; 1258 1259 if (!Opnd1->getValue()->hasOneUse()) 1260 return false; 1261 1262 const APInt &C1 = Opnd1->getConstPart(); 1263 if (C1 != ConstOpnd) 1264 return false; 1265 1266 Value *X = Opnd1->getSymbolicPart(); 1267 Res = createAndInstr(It, X, ~C1); 1268 // ConstOpnd was C2, now C1 ^ C2. 1269 ConstOpnd ^= C1; 1270 1271 if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue())) 1272 RedoInsts.insert(T); 1273 return true; 1274 } 1275 1276 // Helper function of OptimizeXor(). It tries to simplify 1277 // "Opnd1 ^ Opnd2 ^ ConstOpnd" into "R ^ C", where C would be 0, and R is a 1278 // symbolic value. 1279 // 1280 // If it was successful, true is returned, and the "R" and "C" is returned 1281 // via "Res" and "ConstOpnd", respectively (If the entire expression is 1282 // evaluated to a constant, the Res is set to NULL); otherwise, false is 1283 // returned, and both "Res" and "ConstOpnd" remain unchanged. 1284 bool ReassociatePass::CombineXorOpnd(BasicBlock::iterator It, XorOpnd *Opnd1, 1285 XorOpnd *Opnd2, APInt &ConstOpnd, 1286 Value *&Res) { 1287 Value *X = Opnd1->getSymbolicPart(); 1288 if (X != Opnd2->getSymbolicPart()) 1289 return false; 1290 1291 // This many instruction become dead.(At least "Opnd1 ^ Opnd2" will die.) 1292 int DeadInstNum = 1; 1293 if (Opnd1->getValue()->hasOneUse()) 1294 DeadInstNum++; 1295 if (Opnd2->getValue()->hasOneUse()) 1296 DeadInstNum++; 1297 1298 // Xor-Rule 2: 1299 // (x | c1) ^ (x & c2) 1300 // = (x|c1) ^ (x&c2) ^ (c1 ^ c1) = ((x|c1) ^ c1) ^ (x & c2) ^ c1 1301 // = (x & ~c1) ^ (x & c2) ^ c1 // Xor-Rule 1 1302 // = (x & c3) ^ c1, where c3 = ~c1 ^ c2 // Xor-rule 3 1303 // 1304 if (Opnd1->isOrExpr() != Opnd2->isOrExpr()) { 1305 if (Opnd2->isOrExpr()) 1306 std::swap(Opnd1, Opnd2); 1307 1308 const APInt &C1 = Opnd1->getConstPart(); 1309 const APInt &C2 = Opnd2->getConstPart(); 1310 APInt C3((~C1) ^ C2); 1311 1312 // Do not increase code size! 1313 if (!C3.isZero() && !C3.isAllOnes()) { 1314 int NewInstNum = ConstOpnd.getBoolValue() ? 1 : 2; 1315 if (NewInstNum > DeadInstNum) 1316 return false; 1317 } 1318 1319 Res = createAndInstr(It, X, C3); 1320 ConstOpnd ^= C1; 1321 } else if (Opnd1->isOrExpr()) { 1322 // Xor-Rule 3: (x | c1) ^ (x | c2) = (x & c3) ^ c3 where c3 = c1 ^ c2 1323 // 1324 const APInt &C1 = Opnd1->getConstPart(); 1325 const APInt &C2 = Opnd2->getConstPart(); 1326 APInt C3 = C1 ^ C2; 1327 1328 // Do not increase code size 1329 if (!C3.isZero() && !C3.isAllOnes()) { 1330 int NewInstNum = ConstOpnd.getBoolValue() ? 1 : 2; 1331 if (NewInstNum > DeadInstNum) 1332 return false; 1333 } 1334 1335 Res = createAndInstr(It, X, C3); 1336 ConstOpnd ^= C3; 1337 } else { 1338 // Xor-Rule 4: (x & c1) ^ (x & c2) = (x & (c1^c2)) 1339 // 1340 const APInt &C1 = Opnd1->getConstPart(); 1341 const APInt &C2 = Opnd2->getConstPart(); 1342 APInt C3 = C1 ^ C2; 1343 Res = createAndInstr(It, X, C3); 1344 } 1345 1346 // Put the original operands in the Redo list; hope they will be deleted 1347 // as dead code. 1348 if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue())) 1349 RedoInsts.insert(T); 1350 if (Instruction *T = dyn_cast<Instruction>(Opnd2->getValue())) 1351 RedoInsts.insert(T); 1352 1353 return true; 1354 } 1355 1356 /// Optimize a series of operands to an 'xor' instruction. If it can be reduced 1357 /// to a single Value, it is returned, otherwise the Ops list is mutated as 1358 /// necessary. 1359 Value *ReassociatePass::OptimizeXor(Instruction *I, 1360 SmallVectorImpl<ValueEntry> &Ops) { 1361 if (Value *V = OptimizeAndOrXor(Instruction::Xor, Ops)) 1362 return V; 1363 1364 if (Ops.size() == 1) 1365 return nullptr; 1366 1367 SmallVector<XorOpnd, 8> Opnds; 1368 SmallVector<XorOpnd*, 8> OpndPtrs; 1369 Type *Ty = Ops[0].Op->getType(); 1370 APInt ConstOpnd(Ty->getScalarSizeInBits(), 0); 1371 1372 // Step 1: Convert ValueEntry to XorOpnd 1373 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1374 Value *V = Ops[i].Op; 1375 const APInt *C; 1376 // TODO: Support non-splat vectors. 1377 if (match(V, m_APInt(C))) { 1378 ConstOpnd ^= *C; 1379 } else { 1380 XorOpnd O(V); 1381 O.setSymbolicRank(getRank(O.getSymbolicPart())); 1382 Opnds.push_back(O); 1383 } 1384 } 1385 1386 // NOTE: From this point on, do *NOT* add/delete element to/from "Opnds". 1387 // It would otherwise invalidate the "Opnds"'s iterator, and hence invalidate 1388 // the "OpndPtrs" as well. For the similar reason, do not fuse this loop 1389 // with the previous loop --- the iterator of the "Opnds" may be invalidated 1390 // when new elements are added to the vector. 1391 for (unsigned i = 0, e = Opnds.size(); i != e; ++i) 1392 OpndPtrs.push_back(&Opnds[i]); 1393 1394 // Step 2: Sort the Xor-Operands in a way such that the operands containing 1395 // the same symbolic value cluster together. For instance, the input operand 1396 // sequence ("x | 123", "y & 456", "x & 789") will be sorted into: 1397 // ("x | 123", "x & 789", "y & 456"). 1398 // 1399 // The purpose is twofold: 1400 // 1) Cluster together the operands sharing the same symbolic-value. 1401 // 2) Operand having smaller symbolic-value-rank is permuted earlier, which 1402 // could potentially shorten crital path, and expose more loop-invariants. 1403 // Note that values' rank are basically defined in RPO order (FIXME). 1404 // So, if Rank(X) < Rank(Y) < Rank(Z), it means X is defined earlier 1405 // than Y which is defined earlier than Z. Permute "x | 1", "Y & 2", 1406 // "z" in the order of X-Y-Z is better than any other orders. 1407 llvm::stable_sort(OpndPtrs, [](XorOpnd *LHS, XorOpnd *RHS) { 1408 return LHS->getSymbolicRank() < RHS->getSymbolicRank(); 1409 }); 1410 1411 // Step 3: Combine adjacent operands 1412 XorOpnd *PrevOpnd = nullptr; 1413 bool Changed = false; 1414 for (unsigned i = 0, e = Opnds.size(); i < e; i++) { 1415 XorOpnd *CurrOpnd = OpndPtrs[i]; 1416 // The combined value 1417 Value *CV; 1418 1419 // Step 3.1: Try simplifying "CurrOpnd ^ ConstOpnd" 1420 if (!ConstOpnd.isZero() && 1421 CombineXorOpnd(I->getIterator(), CurrOpnd, ConstOpnd, CV)) { 1422 Changed = true; 1423 if (CV) 1424 *CurrOpnd = XorOpnd(CV); 1425 else { 1426 CurrOpnd->Invalidate(); 1427 continue; 1428 } 1429 } 1430 1431 if (!PrevOpnd || CurrOpnd->getSymbolicPart() != PrevOpnd->getSymbolicPart()) { 1432 PrevOpnd = CurrOpnd; 1433 continue; 1434 } 1435 1436 // step 3.2: When previous and current operands share the same symbolic 1437 // value, try to simplify "PrevOpnd ^ CurrOpnd ^ ConstOpnd" 1438 if (CombineXorOpnd(I->getIterator(), CurrOpnd, PrevOpnd, ConstOpnd, CV)) { 1439 // Remove previous operand 1440 PrevOpnd->Invalidate(); 1441 if (CV) { 1442 *CurrOpnd = XorOpnd(CV); 1443 PrevOpnd = CurrOpnd; 1444 } else { 1445 CurrOpnd->Invalidate(); 1446 PrevOpnd = nullptr; 1447 } 1448 Changed = true; 1449 } 1450 } 1451 1452 // Step 4: Reassemble the Ops 1453 if (Changed) { 1454 Ops.clear(); 1455 for (const XorOpnd &O : Opnds) { 1456 if (O.isInvalid()) 1457 continue; 1458 ValueEntry VE(getRank(O.getValue()), O.getValue()); 1459 Ops.push_back(VE); 1460 } 1461 if (!ConstOpnd.isZero()) { 1462 Value *C = ConstantInt::get(Ty, ConstOpnd); 1463 ValueEntry VE(getRank(C), C); 1464 Ops.push_back(VE); 1465 } 1466 unsigned Sz = Ops.size(); 1467 if (Sz == 1) 1468 return Ops.back().Op; 1469 if (Sz == 0) { 1470 assert(ConstOpnd.isZero()); 1471 return ConstantInt::get(Ty, ConstOpnd); 1472 } 1473 } 1474 1475 return nullptr; 1476 } 1477 1478 /// Optimize a series of operands to an 'add' instruction. This 1479 /// optimizes based on identities. If it can be reduced to a single Value, it 1480 /// is returned, otherwise the Ops list is mutated as necessary. 1481 Value *ReassociatePass::OptimizeAdd(Instruction *I, 1482 SmallVectorImpl<ValueEntry> &Ops) { 1483 // Scan the operand lists looking for X and -X pairs. If we find any, we 1484 // can simplify expressions like X+-X == 0 and X+~X ==-1. While we're at it, 1485 // scan for any 1486 // duplicates. We want to canonicalize Y+Y+Y+Z -> 3*Y+Z. 1487 1488 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1489 Value *TheOp = Ops[i].Op; 1490 // Check to see if we've seen this operand before. If so, we factor all 1491 // instances of the operand together. Due to our sorting criteria, we know 1492 // that these need to be next to each other in the vector. 1493 if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) { 1494 // Rescan the list, remove all instances of this operand from the expr. 1495 unsigned NumFound = 0; 1496 do { 1497 Ops.erase(Ops.begin()+i); 1498 ++NumFound; 1499 } while (i != Ops.size() && Ops[i].Op == TheOp); 1500 1501 LLVM_DEBUG(dbgs() << "\nFACTORING [" << NumFound << "]: " << *TheOp 1502 << '\n'); 1503 ++NumFactor; 1504 1505 // Insert a new multiply. 1506 Type *Ty = TheOp->getType(); 1507 Constant *C = Ty->isIntOrIntVectorTy() ? 1508 ConstantInt::get(Ty, NumFound) : ConstantFP::get(Ty, NumFound); 1509 Instruction *Mul = CreateMul(TheOp, C, "factor", I->getIterator(), I); 1510 1511 // Now that we have inserted a multiply, optimize it. This allows us to 1512 // handle cases that require multiple factoring steps, such as this: 1513 // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6 1514 RedoInsts.insert(Mul); 1515 1516 // If every add operand was a duplicate, return the multiply. 1517 if (Ops.empty()) 1518 return Mul; 1519 1520 // Otherwise, we had some input that didn't have the dupe, such as 1521 // "A + A + B" -> "A*2 + B". Add the new multiply to the list of 1522 // things being added by this operation. 1523 Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul)); 1524 1525 --i; 1526 e = Ops.size(); 1527 continue; 1528 } 1529 1530 // Check for X and -X or X and ~X in the operand list. 1531 Value *X; 1532 if (!match(TheOp, m_Neg(m_Value(X))) && !match(TheOp, m_Not(m_Value(X))) && 1533 !match(TheOp, m_FNeg(m_Value(X)))) 1534 continue; 1535 1536 unsigned FoundX = FindInOperandList(Ops, i, X); 1537 if (FoundX == i) 1538 continue; 1539 1540 // Remove X and -X from the operand list. 1541 if (Ops.size() == 2 && 1542 (match(TheOp, m_Neg(m_Value())) || match(TheOp, m_FNeg(m_Value())))) 1543 return Constant::getNullValue(X->getType()); 1544 1545 // Remove X and ~X from the operand list. 1546 if (Ops.size() == 2 && match(TheOp, m_Not(m_Value()))) 1547 return Constant::getAllOnesValue(X->getType()); 1548 1549 Ops.erase(Ops.begin()+i); 1550 if (i < FoundX) 1551 --FoundX; 1552 else 1553 --i; // Need to back up an extra one. 1554 Ops.erase(Ops.begin()+FoundX); 1555 ++NumAnnihil; 1556 --i; // Revisit element. 1557 e -= 2; // Removed two elements. 1558 1559 // if X and ~X we append -1 to the operand list. 1560 if (match(TheOp, m_Not(m_Value()))) { 1561 Value *V = Constant::getAllOnesValue(X->getType()); 1562 Ops.insert(Ops.end(), ValueEntry(getRank(V), V)); 1563 e += 1; 1564 } 1565 } 1566 1567 // Scan the operand list, checking to see if there are any common factors 1568 // between operands. Consider something like A*A+A*B*C+D. We would like to 1569 // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies. 1570 // To efficiently find this, we count the number of times a factor occurs 1571 // for any ADD operands that are MULs. 1572 DenseMap<Value*, unsigned> FactorOccurrences; 1573 1574 // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4) 1575 // where they are actually the same multiply. 1576 unsigned MaxOcc = 0; 1577 Value *MaxOccVal = nullptr; 1578 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1579 BinaryOperator *BOp = 1580 isReassociableOp(Ops[i].Op, Instruction::Mul, Instruction::FMul); 1581 if (!BOp) 1582 continue; 1583 1584 // Compute all of the factors of this added value. 1585 SmallVector<Value*, 8> Factors; 1586 FindSingleUseMultiplyFactors(BOp, Factors); 1587 assert(Factors.size() > 1 && "Bad linearize!"); 1588 1589 // Add one to FactorOccurrences for each unique factor in this op. 1590 SmallPtrSet<Value*, 8> Duplicates; 1591 for (Value *Factor : Factors) { 1592 if (!Duplicates.insert(Factor).second) 1593 continue; 1594 1595 unsigned Occ = ++FactorOccurrences[Factor]; 1596 if (Occ > MaxOcc) { 1597 MaxOcc = Occ; 1598 MaxOccVal = Factor; 1599 } 1600 1601 // If Factor is a negative constant, add the negated value as a factor 1602 // because we can percolate the negate out. Watch for minint, which 1603 // cannot be positivified. 1604 if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor)) { 1605 if (CI->isNegative() && !CI->isMinValue(true)) { 1606 Factor = ConstantInt::get(CI->getContext(), -CI->getValue()); 1607 if (!Duplicates.insert(Factor).second) 1608 continue; 1609 unsigned Occ = ++FactorOccurrences[Factor]; 1610 if (Occ > MaxOcc) { 1611 MaxOcc = Occ; 1612 MaxOccVal = Factor; 1613 } 1614 } 1615 } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Factor)) { 1616 if (CF->isNegative()) { 1617 APFloat F(CF->getValueAPF()); 1618 F.changeSign(); 1619 Factor = ConstantFP::get(CF->getContext(), F); 1620 if (!Duplicates.insert(Factor).second) 1621 continue; 1622 unsigned Occ = ++FactorOccurrences[Factor]; 1623 if (Occ > MaxOcc) { 1624 MaxOcc = Occ; 1625 MaxOccVal = Factor; 1626 } 1627 } 1628 } 1629 } 1630 } 1631 1632 // If any factor occurred more than one time, we can pull it out. 1633 if (MaxOcc > 1) { 1634 LLVM_DEBUG(dbgs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal 1635 << '\n'); 1636 ++NumFactor; 1637 1638 // Create a new instruction that uses the MaxOccVal twice. If we don't do 1639 // this, we could otherwise run into situations where removing a factor 1640 // from an expression will drop a use of maxocc, and this can cause 1641 // RemoveFactorFromExpression on successive values to behave differently. 1642 Instruction *DummyInst = 1643 I->getType()->isIntOrIntVectorTy() 1644 ? BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal) 1645 : BinaryOperator::CreateFAdd(MaxOccVal, MaxOccVal); 1646 1647 SmallVector<WeakTrackingVH, 4> NewMulOps; 1648 for (unsigned i = 0; i != Ops.size(); ++i) { 1649 // Only try to remove factors from expressions we're allowed to. 1650 BinaryOperator *BOp = 1651 isReassociableOp(Ops[i].Op, Instruction::Mul, Instruction::FMul); 1652 if (!BOp) 1653 continue; 1654 1655 if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) { 1656 // The factorized operand may occur several times. Convert them all in 1657 // one fell swoop. 1658 for (unsigned j = Ops.size(); j != i;) { 1659 --j; 1660 if (Ops[j].Op == Ops[i].Op) { 1661 NewMulOps.push_back(V); 1662 Ops.erase(Ops.begin()+j); 1663 } 1664 } 1665 --i; 1666 } 1667 } 1668 1669 // No need for extra uses anymore. 1670 DummyInst->deleteValue(); 1671 1672 unsigned NumAddedValues = NewMulOps.size(); 1673 Value *V = EmitAddTreeOfValues(I->getIterator(), NewMulOps); 1674 1675 // Now that we have inserted the add tree, optimize it. This allows us to 1676 // handle cases that require multiple factoring steps, such as this: 1677 // A*A*B + A*A*C --> A*(A*B+A*C) --> A*(A*(B+C)) 1678 assert(NumAddedValues > 1 && "Each occurrence should contribute a value"); 1679 (void)NumAddedValues; 1680 if (Instruction *VI = dyn_cast<Instruction>(V)) 1681 RedoInsts.insert(VI); 1682 1683 // Create the multiply. 1684 Instruction *V2 = CreateMul(V, MaxOccVal, "reass.mul", I->getIterator(), I); 1685 1686 // Rerun associate on the multiply in case the inner expression turned into 1687 // a multiply. We want to make sure that we keep things in canonical form. 1688 RedoInsts.insert(V2); 1689 1690 // If every add operand included the factor (e.g. "A*B + A*C"), then the 1691 // entire result expression is just the multiply "A*(B+C)". 1692 if (Ops.empty()) 1693 return V2; 1694 1695 // Otherwise, we had some input that didn't have the factor, such as 1696 // "A*B + A*C + D" -> "A*(B+C) + D". Add the new multiply to the list of 1697 // things being added by this operation. 1698 Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2)); 1699 } 1700 1701 return nullptr; 1702 } 1703 1704 /// Build up a vector of value/power pairs factoring a product. 1705 /// 1706 /// Given a series of multiplication operands, build a vector of factors and 1707 /// the powers each is raised to when forming the final product. Sort them in 1708 /// the order of descending power. 1709 /// 1710 /// (x*x) -> [(x, 2)] 1711 /// ((x*x)*x) -> [(x, 3)] 1712 /// ((((x*y)*x)*y)*x) -> [(x, 3), (y, 2)] 1713 /// 1714 /// \returns Whether any factors have a power greater than one. 1715 static bool collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops, 1716 SmallVectorImpl<Factor> &Factors) { 1717 // FIXME: Have Ops be (ValueEntry, Multiplicity) pairs, simplifying this. 1718 // Compute the sum of powers of simplifiable factors. 1719 unsigned FactorPowerSum = 0; 1720 for (unsigned Idx = 1, Size = Ops.size(); Idx < Size; ++Idx) { 1721 Value *Op = Ops[Idx-1].Op; 1722 1723 // Count the number of occurrences of this value. 1724 unsigned Count = 1; 1725 for (; Idx < Size && Ops[Idx].Op == Op; ++Idx) 1726 ++Count; 1727 // Track for simplification all factors which occur 2 or more times. 1728 if (Count > 1) 1729 FactorPowerSum += Count; 1730 } 1731 1732 // We can only simplify factors if the sum of the powers of our simplifiable 1733 // factors is 4 or higher. When that is the case, we will *always* have 1734 // a simplification. This is an important invariant to prevent cyclicly 1735 // trying to simplify already minimal formations. 1736 if (FactorPowerSum < 4) 1737 return false; 1738 1739 // Now gather the simplifiable factors, removing them from Ops. 1740 FactorPowerSum = 0; 1741 for (unsigned Idx = 1; Idx < Ops.size(); ++Idx) { 1742 Value *Op = Ops[Idx-1].Op; 1743 1744 // Count the number of occurrences of this value. 1745 unsigned Count = 1; 1746 for (; Idx < Ops.size() && Ops[Idx].Op == Op; ++Idx) 1747 ++Count; 1748 if (Count == 1) 1749 continue; 1750 // Move an even number of occurrences to Factors. 1751 Count &= ~1U; 1752 Idx -= Count; 1753 FactorPowerSum += Count; 1754 Factors.push_back(Factor(Op, Count)); 1755 Ops.erase(Ops.begin()+Idx, Ops.begin()+Idx+Count); 1756 } 1757 1758 // None of the adjustments above should have reduced the sum of factor powers 1759 // below our mininum of '4'. 1760 assert(FactorPowerSum >= 4); 1761 1762 llvm::stable_sort(Factors, [](const Factor &LHS, const Factor &RHS) { 1763 return LHS.Power > RHS.Power; 1764 }); 1765 return true; 1766 } 1767 1768 /// Build a tree of multiplies, computing the product of Ops. 1769 static Value *buildMultiplyTree(IRBuilderBase &Builder, 1770 SmallVectorImpl<Value*> &Ops) { 1771 if (Ops.size() == 1) 1772 return Ops.back(); 1773 1774 Value *LHS = Ops.pop_back_val(); 1775 do { 1776 if (LHS->getType()->isIntOrIntVectorTy()) 1777 LHS = Builder.CreateMul(LHS, Ops.pop_back_val()); 1778 else 1779 LHS = Builder.CreateFMul(LHS, Ops.pop_back_val()); 1780 } while (!Ops.empty()); 1781 1782 return LHS; 1783 } 1784 1785 /// Build a minimal multiplication DAG for (a^x)*(b^y)*(c^z)*... 1786 /// 1787 /// Given a vector of values raised to various powers, where no two values are 1788 /// equal and the powers are sorted in decreasing order, compute the minimal 1789 /// DAG of multiplies to compute the final product, and return that product 1790 /// value. 1791 Value * 1792 ReassociatePass::buildMinimalMultiplyDAG(IRBuilderBase &Builder, 1793 SmallVectorImpl<Factor> &Factors) { 1794 assert(Factors[0].Power); 1795 SmallVector<Value *, 4> OuterProduct; 1796 for (unsigned LastIdx = 0, Idx = 1, Size = Factors.size(); 1797 Idx < Size && Factors[Idx].Power > 0; ++Idx) { 1798 if (Factors[Idx].Power != Factors[LastIdx].Power) { 1799 LastIdx = Idx; 1800 continue; 1801 } 1802 1803 // We want to multiply across all the factors with the same power so that 1804 // we can raise them to that power as a single entity. Build a mini tree 1805 // for that. 1806 SmallVector<Value *, 4> InnerProduct; 1807 InnerProduct.push_back(Factors[LastIdx].Base); 1808 do { 1809 InnerProduct.push_back(Factors[Idx].Base); 1810 ++Idx; 1811 } while (Idx < Size && Factors[Idx].Power == Factors[LastIdx].Power); 1812 1813 // Reset the base value of the first factor to the new expression tree. 1814 // We'll remove all the factors with the same power in a second pass. 1815 Value *M = Factors[LastIdx].Base = buildMultiplyTree(Builder, InnerProduct); 1816 if (Instruction *MI = dyn_cast<Instruction>(M)) 1817 RedoInsts.insert(MI); 1818 1819 LastIdx = Idx; 1820 } 1821 // Unique factors with equal powers -- we've folded them into the first one's 1822 // base. 1823 Factors.erase(std::unique(Factors.begin(), Factors.end(), 1824 [](const Factor &LHS, const Factor &RHS) { 1825 return LHS.Power == RHS.Power; 1826 }), 1827 Factors.end()); 1828 1829 // Iteratively collect the base of each factor with an add power into the 1830 // outer product, and halve each power in preparation for squaring the 1831 // expression. 1832 for (Factor &F : Factors) { 1833 if (F.Power & 1) 1834 OuterProduct.push_back(F.Base); 1835 F.Power >>= 1; 1836 } 1837 if (Factors[0].Power) { 1838 Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors); 1839 OuterProduct.push_back(SquareRoot); 1840 OuterProduct.push_back(SquareRoot); 1841 } 1842 if (OuterProduct.size() == 1) 1843 return OuterProduct.front(); 1844 1845 Value *V = buildMultiplyTree(Builder, OuterProduct); 1846 return V; 1847 } 1848 1849 Value *ReassociatePass::OptimizeMul(BinaryOperator *I, 1850 SmallVectorImpl<ValueEntry> &Ops) { 1851 // We can only optimize the multiplies when there is a chain of more than 1852 // three, such that a balanced tree might require fewer total multiplies. 1853 if (Ops.size() < 4) 1854 return nullptr; 1855 1856 // Try to turn linear trees of multiplies without other uses of the 1857 // intermediate stages into minimal multiply DAGs with perfect sub-expression 1858 // re-use. 1859 SmallVector<Factor, 4> Factors; 1860 if (!collectMultiplyFactors(Ops, Factors)) 1861 return nullptr; // All distinct factors, so nothing left for us to do. 1862 1863 IRBuilder<> Builder(I); 1864 // The reassociate transformation for FP operations is performed only 1865 // if unsafe algebra is permitted by FastMathFlags. Propagate those flags 1866 // to the newly generated operations. 1867 if (auto FPI = dyn_cast<FPMathOperator>(I)) 1868 Builder.setFastMathFlags(FPI->getFastMathFlags()); 1869 1870 Value *V = buildMinimalMultiplyDAG(Builder, Factors); 1871 if (Ops.empty()) 1872 return V; 1873 1874 ValueEntry NewEntry = ValueEntry(getRank(V), V); 1875 Ops.insert(llvm::lower_bound(Ops, NewEntry), NewEntry); 1876 return nullptr; 1877 } 1878 1879 Value *ReassociatePass::OptimizeExpression(BinaryOperator *I, 1880 SmallVectorImpl<ValueEntry> &Ops) { 1881 // Now that we have the linearized expression tree, try to optimize it. 1882 // Start by folding any constants that we found. 1883 const DataLayout &DL = I->getModule()->getDataLayout(); 1884 Constant *Cst = nullptr; 1885 unsigned Opcode = I->getOpcode(); 1886 while (!Ops.empty()) { 1887 if (auto *C = dyn_cast<Constant>(Ops.back().Op)) { 1888 if (!Cst) { 1889 Ops.pop_back(); 1890 Cst = C; 1891 continue; 1892 } 1893 if (Constant *Res = ConstantFoldBinaryOpOperands(Opcode, C, Cst, DL)) { 1894 Ops.pop_back(); 1895 Cst = Res; 1896 continue; 1897 } 1898 } 1899 break; 1900 } 1901 // If there was nothing but constants then we are done. 1902 if (Ops.empty()) 1903 return Cst; 1904 1905 // Put the combined constant back at the end of the operand list, except if 1906 // there is no point. For example, an add of 0 gets dropped here, while a 1907 // multiplication by zero turns the whole expression into zero. 1908 if (Cst && Cst != ConstantExpr::getBinOpIdentity(Opcode, I->getType())) { 1909 if (Cst == ConstantExpr::getBinOpAbsorber(Opcode, I->getType())) 1910 return Cst; 1911 Ops.push_back(ValueEntry(0, Cst)); 1912 } 1913 1914 if (Ops.size() == 1) return Ops[0].Op; 1915 1916 // Handle destructive annihilation due to identities between elements in the 1917 // argument list here. 1918 unsigned NumOps = Ops.size(); 1919 switch (Opcode) { 1920 default: break; 1921 case Instruction::And: 1922 case Instruction::Or: 1923 if (Value *Result = OptimizeAndOrXor(Opcode, Ops)) 1924 return Result; 1925 break; 1926 1927 case Instruction::Xor: 1928 if (Value *Result = OptimizeXor(I, Ops)) 1929 return Result; 1930 break; 1931 1932 case Instruction::Add: 1933 case Instruction::FAdd: 1934 if (Value *Result = OptimizeAdd(I, Ops)) 1935 return Result; 1936 break; 1937 1938 case Instruction::Mul: 1939 case Instruction::FMul: 1940 if (Value *Result = OptimizeMul(I, Ops)) 1941 return Result; 1942 break; 1943 } 1944 1945 if (Ops.size() != NumOps) 1946 return OptimizeExpression(I, Ops); 1947 return nullptr; 1948 } 1949 1950 // Remove dead instructions and if any operands are trivially dead add them to 1951 // Insts so they will be removed as well. 1952 void ReassociatePass::RecursivelyEraseDeadInsts(Instruction *I, 1953 OrderedSet &Insts) { 1954 assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!"); 1955 SmallVector<Value *, 4> Ops(I->operands()); 1956 ValueRankMap.erase(I); 1957 Insts.remove(I); 1958 RedoInsts.remove(I); 1959 llvm::salvageDebugInfo(*I); 1960 I->eraseFromParent(); 1961 for (auto *Op : Ops) 1962 if (Instruction *OpInst = dyn_cast<Instruction>(Op)) 1963 if (OpInst->use_empty()) 1964 Insts.insert(OpInst); 1965 } 1966 1967 /// Zap the given instruction, adding interesting operands to the work list. 1968 void ReassociatePass::EraseInst(Instruction *I) { 1969 assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!"); 1970 LLVM_DEBUG(dbgs() << "Erasing dead inst: "; I->dump()); 1971 1972 SmallVector<Value *, 8> Ops(I->operands()); 1973 // Erase the dead instruction. 1974 ValueRankMap.erase(I); 1975 RedoInsts.remove(I); 1976 llvm::salvageDebugInfo(*I); 1977 I->eraseFromParent(); 1978 // Optimize its operands. 1979 SmallPtrSet<Instruction *, 8> Visited; // Detect self-referential nodes. 1980 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1981 if (Instruction *Op = dyn_cast<Instruction>(Ops[i])) { 1982 // If this is a node in an expression tree, climb to the expression root 1983 // and add that since that's where optimization actually happens. 1984 unsigned Opcode = Op->getOpcode(); 1985 while (Op->hasOneUse() && Op->user_back()->getOpcode() == Opcode && 1986 Visited.insert(Op).second) 1987 Op = Op->user_back(); 1988 1989 // The instruction we're going to push may be coming from a 1990 // dead block, and Reassociate skips the processing of unreachable 1991 // blocks because it's a waste of time and also because it can 1992 // lead to infinite loop due to LLVM's non-standard definition 1993 // of dominance. 1994 if (ValueRankMap.contains(Op)) 1995 RedoInsts.insert(Op); 1996 } 1997 1998 MadeChange = true; 1999 } 2000 2001 /// Recursively analyze an expression to build a list of instructions that have 2002 /// negative floating-point constant operands. The caller can then transform 2003 /// the list to create positive constants for better reassociation and CSE. 2004 static void getNegatibleInsts(Value *V, 2005 SmallVectorImpl<Instruction *> &Candidates) { 2006 // Handle only one-use instructions. Combining negations does not justify 2007 // replicating instructions. 2008 Instruction *I; 2009 if (!match(V, m_OneUse(m_Instruction(I)))) 2010 return; 2011 2012 // Handle expressions of multiplications and divisions. 2013 // TODO: This could look through floating-point casts. 2014 const APFloat *C; 2015 switch (I->getOpcode()) { 2016 case Instruction::FMul: 2017 // Not expecting non-canonical code here. Bail out and wait. 2018 if (match(I->getOperand(0), m_Constant())) 2019 break; 2020 2021 if (match(I->getOperand(1), m_APFloat(C)) && C->isNegative()) { 2022 Candidates.push_back(I); 2023 LLVM_DEBUG(dbgs() << "FMul with negative constant: " << *I << '\n'); 2024 } 2025 getNegatibleInsts(I->getOperand(0), Candidates); 2026 getNegatibleInsts(I->getOperand(1), Candidates); 2027 break; 2028 case Instruction::FDiv: 2029 // Not expecting non-canonical code here. Bail out and wait. 2030 if (match(I->getOperand(0), m_Constant()) && 2031 match(I->getOperand(1), m_Constant())) 2032 break; 2033 2034 if ((match(I->getOperand(0), m_APFloat(C)) && C->isNegative()) || 2035 (match(I->getOperand(1), m_APFloat(C)) && C->isNegative())) { 2036 Candidates.push_back(I); 2037 LLVM_DEBUG(dbgs() << "FDiv with negative constant: " << *I << '\n'); 2038 } 2039 getNegatibleInsts(I->getOperand(0), Candidates); 2040 getNegatibleInsts(I->getOperand(1), Candidates); 2041 break; 2042 default: 2043 break; 2044 } 2045 } 2046 2047 /// Given an fadd/fsub with an operand that is a one-use instruction 2048 /// (the fadd/fsub), try to change negative floating-point constants into 2049 /// positive constants to increase potential for reassociation and CSE. 2050 Instruction *ReassociatePass::canonicalizeNegFPConstantsForOp(Instruction *I, 2051 Instruction *Op, 2052 Value *OtherOp) { 2053 assert((I->getOpcode() == Instruction::FAdd || 2054 I->getOpcode() == Instruction::FSub) && "Expected fadd/fsub"); 2055 2056 // Collect instructions with negative FP constants from the subtree that ends 2057 // in Op. 2058 SmallVector<Instruction *, 4> Candidates; 2059 getNegatibleInsts(Op, Candidates); 2060 if (Candidates.empty()) 2061 return nullptr; 2062 2063 // Don't canonicalize x + (-Constant * y) -> x - (Constant * y), if the 2064 // resulting subtract will be broken up later. This can get us into an 2065 // infinite loop during reassociation. 2066 bool IsFSub = I->getOpcode() == Instruction::FSub; 2067 bool NeedsSubtract = !IsFSub && Candidates.size() % 2 == 1; 2068 if (NeedsSubtract && ShouldBreakUpSubtract(I)) 2069 return nullptr; 2070 2071 for (Instruction *Negatible : Candidates) { 2072 const APFloat *C; 2073 if (match(Negatible->getOperand(0), m_APFloat(C))) { 2074 assert(!match(Negatible->getOperand(1), m_Constant()) && 2075 "Expecting only 1 constant operand"); 2076 assert(C->isNegative() && "Expected negative FP constant"); 2077 Negatible->setOperand(0, ConstantFP::get(Negatible->getType(), abs(*C))); 2078 MadeChange = true; 2079 } 2080 if (match(Negatible->getOperand(1), m_APFloat(C))) { 2081 assert(!match(Negatible->getOperand(0), m_Constant()) && 2082 "Expecting only 1 constant operand"); 2083 assert(C->isNegative() && "Expected negative FP constant"); 2084 Negatible->setOperand(1, ConstantFP::get(Negatible->getType(), abs(*C))); 2085 MadeChange = true; 2086 } 2087 } 2088 assert(MadeChange == true && "Negative constant candidate was not changed"); 2089 2090 // Negations cancelled out. 2091 if (Candidates.size() % 2 == 0) 2092 return I; 2093 2094 // Negate the final operand in the expression by flipping the opcode of this 2095 // fadd/fsub. 2096 assert(Candidates.size() % 2 == 1 && "Expected odd number"); 2097 IRBuilder<> Builder(I); 2098 Value *NewInst = IsFSub ? Builder.CreateFAddFMF(OtherOp, Op, I) 2099 : Builder.CreateFSubFMF(OtherOp, Op, I); 2100 I->replaceAllUsesWith(NewInst); 2101 RedoInsts.insert(I); 2102 return dyn_cast<Instruction>(NewInst); 2103 } 2104 2105 /// Canonicalize expressions that contain a negative floating-point constant 2106 /// of the following form: 2107 /// OtherOp + (subtree) -> OtherOp {+/-} (canonical subtree) 2108 /// (subtree) + OtherOp -> OtherOp {+/-} (canonical subtree) 2109 /// OtherOp - (subtree) -> OtherOp {+/-} (canonical subtree) 2110 /// 2111 /// The fadd/fsub opcode may be switched to allow folding a negation into the 2112 /// input instruction. 2113 Instruction *ReassociatePass::canonicalizeNegFPConstants(Instruction *I) { 2114 LLVM_DEBUG(dbgs() << "Combine negations for: " << *I << '\n'); 2115 Value *X; 2116 Instruction *Op; 2117 if (match(I, m_FAdd(m_Value(X), m_OneUse(m_Instruction(Op))))) 2118 if (Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, X)) 2119 I = R; 2120 if (match(I, m_FAdd(m_OneUse(m_Instruction(Op)), m_Value(X)))) 2121 if (Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, X)) 2122 I = R; 2123 if (match(I, m_FSub(m_Value(X), m_OneUse(m_Instruction(Op))))) 2124 if (Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, X)) 2125 I = R; 2126 return I; 2127 } 2128 2129 /// Inspect and optimize the given instruction. Note that erasing 2130 /// instructions is not allowed. 2131 void ReassociatePass::OptimizeInst(Instruction *I) { 2132 // Only consider operations that we understand. 2133 if (!isa<UnaryOperator>(I) && !isa<BinaryOperator>(I)) 2134 return; 2135 2136 if (I->getOpcode() == Instruction::Shl && isa<ConstantInt>(I->getOperand(1))) 2137 // If an operand of this shift is a reassociable multiply, or if the shift 2138 // is used by a reassociable multiply or add, turn into a multiply. 2139 if (isReassociableOp(I->getOperand(0), Instruction::Mul) || 2140 (I->hasOneUse() && 2141 (isReassociableOp(I->user_back(), Instruction::Mul) || 2142 isReassociableOp(I->user_back(), Instruction::Add)))) { 2143 Instruction *NI = ConvertShiftToMul(I); 2144 RedoInsts.insert(I); 2145 MadeChange = true; 2146 I = NI; 2147 } 2148 2149 // Commute binary operators, to canonicalize the order of their operands. 2150 // This can potentially expose more CSE opportunities, and makes writing other 2151 // transformations simpler. 2152 if (I->isCommutative()) 2153 canonicalizeOperands(I); 2154 2155 // Canonicalize negative constants out of expressions. 2156 if (Instruction *Res = canonicalizeNegFPConstants(I)) 2157 I = Res; 2158 2159 // Don't optimize floating-point instructions unless they have the 2160 // appropriate FastMathFlags for reassociation enabled. 2161 if (isa<FPMathOperator>(I) && !hasFPAssociativeFlags(I)) 2162 return; 2163 2164 // Do not reassociate boolean (i1) expressions. We want to preserve the 2165 // original order of evaluation for short-circuited comparisons that 2166 // SimplifyCFG has folded to AND/OR expressions. If the expression 2167 // is not further optimized, it is likely to be transformed back to a 2168 // short-circuited form for code gen, and the source order may have been 2169 // optimized for the most likely conditions. 2170 if (I->getType()->isIntegerTy(1)) 2171 return; 2172 2173 // If this is a bitwise or instruction of operands 2174 // with no common bits set, convert it to X+Y. 2175 if (I->getOpcode() == Instruction::Or && 2176 shouldConvertOrWithNoCommonBitsToAdd(I) && !isLoadCombineCandidate(I) && 2177 (cast<PossiblyDisjointInst>(I)->isDisjoint() || 2178 haveNoCommonBitsSet(I->getOperand(0), I->getOperand(1), 2179 SimplifyQuery(I->getModule()->getDataLayout(), 2180 /*DT=*/nullptr, /*AC=*/nullptr, I)))) { 2181 Instruction *NI = convertOrWithNoCommonBitsToAdd(I); 2182 RedoInsts.insert(I); 2183 MadeChange = true; 2184 I = NI; 2185 } 2186 2187 // If this is a subtract instruction which is not already in negate form, 2188 // see if we can convert it to X+-Y. 2189 if (I->getOpcode() == Instruction::Sub) { 2190 if (ShouldBreakUpSubtract(I)) { 2191 Instruction *NI = BreakUpSubtract(I, RedoInsts); 2192 RedoInsts.insert(I); 2193 MadeChange = true; 2194 I = NI; 2195 } else if (match(I, m_Neg(m_Value()))) { 2196 // Otherwise, this is a negation. See if the operand is a multiply tree 2197 // and if this is not an inner node of a multiply tree. 2198 if (isReassociableOp(I->getOperand(1), Instruction::Mul) && 2199 (!I->hasOneUse() || 2200 !isReassociableOp(I->user_back(), Instruction::Mul))) { 2201 Instruction *NI = LowerNegateToMultiply(I); 2202 // If the negate was simplified, revisit the users to see if we can 2203 // reassociate further. 2204 for (User *U : NI->users()) { 2205 if (BinaryOperator *Tmp = dyn_cast<BinaryOperator>(U)) 2206 RedoInsts.insert(Tmp); 2207 } 2208 RedoInsts.insert(I); 2209 MadeChange = true; 2210 I = NI; 2211 } 2212 } 2213 } else if (I->getOpcode() == Instruction::FNeg || 2214 I->getOpcode() == Instruction::FSub) { 2215 if (ShouldBreakUpSubtract(I)) { 2216 Instruction *NI = BreakUpSubtract(I, RedoInsts); 2217 RedoInsts.insert(I); 2218 MadeChange = true; 2219 I = NI; 2220 } else if (match(I, m_FNeg(m_Value()))) { 2221 // Otherwise, this is a negation. See if the operand is a multiply tree 2222 // and if this is not an inner node of a multiply tree. 2223 Value *Op = isa<BinaryOperator>(I) ? I->getOperand(1) : 2224 I->getOperand(0); 2225 if (isReassociableOp(Op, Instruction::FMul) && 2226 (!I->hasOneUse() || 2227 !isReassociableOp(I->user_back(), Instruction::FMul))) { 2228 // If the negate was simplified, revisit the users to see if we can 2229 // reassociate further. 2230 Instruction *NI = LowerNegateToMultiply(I); 2231 for (User *U : NI->users()) { 2232 if (BinaryOperator *Tmp = dyn_cast<BinaryOperator>(U)) 2233 RedoInsts.insert(Tmp); 2234 } 2235 RedoInsts.insert(I); 2236 MadeChange = true; 2237 I = NI; 2238 } 2239 } 2240 } 2241 2242 // If this instruction is an associative binary operator, process it. 2243 if (!I->isAssociative()) return; 2244 BinaryOperator *BO = cast<BinaryOperator>(I); 2245 2246 // If this is an interior node of a reassociable tree, ignore it until we 2247 // get to the root of the tree, to avoid N^2 analysis. 2248 unsigned Opcode = BO->getOpcode(); 2249 if (BO->hasOneUse() && BO->user_back()->getOpcode() == Opcode) { 2250 // During the initial run we will get to the root of the tree. 2251 // But if we get here while we are redoing instructions, there is no 2252 // guarantee that the root will be visited. So Redo later 2253 if (BO->user_back() != BO && 2254 BO->getParent() == BO->user_back()->getParent()) 2255 RedoInsts.insert(BO->user_back()); 2256 return; 2257 } 2258 2259 // If this is an add tree that is used by a sub instruction, ignore it 2260 // until we process the subtract. 2261 if (BO->hasOneUse() && BO->getOpcode() == Instruction::Add && 2262 cast<Instruction>(BO->user_back())->getOpcode() == Instruction::Sub) 2263 return; 2264 if (BO->hasOneUse() && BO->getOpcode() == Instruction::FAdd && 2265 cast<Instruction>(BO->user_back())->getOpcode() == Instruction::FSub) 2266 return; 2267 2268 ReassociateExpression(BO); 2269 } 2270 2271 void ReassociatePass::ReassociateExpression(BinaryOperator *I) { 2272 // First, walk the expression tree, linearizing the tree, collecting the 2273 // operand information. 2274 SmallVector<RepeatedValue, 8> Tree; 2275 OverflowTracking Flags; 2276 MadeChange |= LinearizeExprTree(I, Tree, RedoInsts, Flags); 2277 SmallVector<ValueEntry, 8> Ops; 2278 Ops.reserve(Tree.size()); 2279 for (const RepeatedValue &E : Tree) 2280 Ops.append(E.second.getZExtValue(), ValueEntry(getRank(E.first), E.first)); 2281 2282 LLVM_DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n'); 2283 2284 // Now that we have linearized the tree to a list and have gathered all of 2285 // the operands and their ranks, sort the operands by their rank. Use a 2286 // stable_sort so that values with equal ranks will have their relative 2287 // positions maintained (and so the compiler is deterministic). Note that 2288 // this sorts so that the highest ranking values end up at the beginning of 2289 // the vector. 2290 llvm::stable_sort(Ops); 2291 2292 // Now that we have the expression tree in a convenient 2293 // sorted form, optimize it globally if possible. 2294 if (Value *V = OptimizeExpression(I, Ops)) { 2295 if (V == I) 2296 // Self-referential expression in unreachable code. 2297 return; 2298 // This expression tree simplified to something that isn't a tree, 2299 // eliminate it. 2300 LLVM_DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n'); 2301 I->replaceAllUsesWith(V); 2302 if (Instruction *VI = dyn_cast<Instruction>(V)) 2303 if (I->getDebugLoc()) 2304 VI->setDebugLoc(I->getDebugLoc()); 2305 RedoInsts.insert(I); 2306 ++NumAnnihil; 2307 return; 2308 } 2309 2310 // We want to sink immediates as deeply as possible except in the case where 2311 // this is a multiply tree used only by an add, and the immediate is a -1. 2312 // In this case we reassociate to put the negation on the outside so that we 2313 // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y 2314 if (I->hasOneUse()) { 2315 if (I->getOpcode() == Instruction::Mul && 2316 cast<Instruction>(I->user_back())->getOpcode() == Instruction::Add && 2317 isa<ConstantInt>(Ops.back().Op) && 2318 cast<ConstantInt>(Ops.back().Op)->isMinusOne()) { 2319 ValueEntry Tmp = Ops.pop_back_val(); 2320 Ops.insert(Ops.begin(), Tmp); 2321 } else if (I->getOpcode() == Instruction::FMul && 2322 cast<Instruction>(I->user_back())->getOpcode() == 2323 Instruction::FAdd && 2324 isa<ConstantFP>(Ops.back().Op) && 2325 cast<ConstantFP>(Ops.back().Op)->isExactlyValue(-1.0)) { 2326 ValueEntry Tmp = Ops.pop_back_val(); 2327 Ops.insert(Ops.begin(), Tmp); 2328 } 2329 } 2330 2331 LLVM_DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n'); 2332 2333 if (Ops.size() == 1) { 2334 if (Ops[0].Op == I) 2335 // Self-referential expression in unreachable code. 2336 return; 2337 2338 // This expression tree simplified to something that isn't a tree, 2339 // eliminate it. 2340 I->replaceAllUsesWith(Ops[0].Op); 2341 if (Instruction *OI = dyn_cast<Instruction>(Ops[0].Op)) 2342 OI->setDebugLoc(I->getDebugLoc()); 2343 RedoInsts.insert(I); 2344 return; 2345 } 2346 2347 if (Ops.size() > 2 && Ops.size() <= GlobalReassociateLimit) { 2348 // Find the pair with the highest count in the pairmap and move it to the 2349 // back of the list so that it can later be CSE'd. 2350 // example: 2351 // a*b*c*d*e 2352 // if c*e is the most "popular" pair, we can express this as 2353 // (((c*e)*d)*b)*a 2354 unsigned Max = 1; 2355 unsigned BestRank = 0; 2356 std::pair<unsigned, unsigned> BestPair; 2357 unsigned Idx = I->getOpcode() - Instruction::BinaryOpsBegin; 2358 unsigned LimitIdx = 0; 2359 // With the CSE-driven heuristic, we are about to slap two values at the 2360 // beginning of the expression whereas they could live very late in the CFG. 2361 // When using the CSE-local heuristic we avoid creating dependences from 2362 // completely unrelated part of the CFG by limiting the expression 2363 // reordering on the values that live in the first seen basic block. 2364 // The main idea is that we want to avoid forming expressions that would 2365 // become loop dependent. 2366 if (UseCSELocalOpt) { 2367 const BasicBlock *FirstSeenBB = nullptr; 2368 int StartIdx = Ops.size() - 1; 2369 // Skip the first value of the expression since we need at least two 2370 // values to materialize an expression. I.e., even if this value is 2371 // anchored in a different basic block, the actual first sub expression 2372 // will be anchored on the second value. 2373 for (int i = StartIdx - 1; i != -1; --i) { 2374 const Value *Val = Ops[i].Op; 2375 const auto *CurrLeafInstr = dyn_cast<Instruction>(Val); 2376 const BasicBlock *SeenBB = nullptr; 2377 if (!CurrLeafInstr) { 2378 // The value is free of any CFG dependencies. 2379 // Do as if it lives in the entry block. 2380 // 2381 // We do this to make sure all the values falling on this path are 2382 // seen through the same anchor point. The rationale is these values 2383 // can be combined together to from a sub expression free of any CFG 2384 // dependencies so we want them to stay together. 2385 // We could be cleverer and postpone the anchor down to the first 2386 // anchored value, but that's likely complicated to get right. 2387 // E.g., we wouldn't want to do that if that means being stuck in a 2388 // loop. 2389 // 2390 // For instance, we wouldn't want to change: 2391 // res = arg1 op arg2 op arg3 op ... op loop_val1 op loop_val2 ... 2392 // into 2393 // res = loop_val1 op arg1 op arg2 op arg3 op ... op loop_val2 ... 2394 // Because all the sub expressions with arg2..N would be stuck between 2395 // two loop dependent values. 2396 SeenBB = &I->getParent()->getParent()->getEntryBlock(); 2397 } else { 2398 SeenBB = CurrLeafInstr->getParent(); 2399 } 2400 2401 if (!FirstSeenBB) { 2402 FirstSeenBB = SeenBB; 2403 continue; 2404 } 2405 if (FirstSeenBB != SeenBB) { 2406 // ith value is in a different basic block. 2407 // Rewind the index once to point to the last value on the same basic 2408 // block. 2409 LimitIdx = i + 1; 2410 LLVM_DEBUG(dbgs() << "CSE reordering: Consider values between [" 2411 << LimitIdx << ", " << StartIdx << "]\n"); 2412 break; 2413 } 2414 } 2415 } 2416 for (unsigned i = Ops.size() - 1; i > LimitIdx; --i) { 2417 // We must use int type to go below zero when LimitIdx is 0. 2418 for (int j = i - 1; j >= (int)LimitIdx; --j) { 2419 unsigned Score = 0; 2420 Value *Op0 = Ops[i].Op; 2421 Value *Op1 = Ops[j].Op; 2422 if (std::less<Value *>()(Op1, Op0)) 2423 std::swap(Op0, Op1); 2424 auto it = PairMap[Idx].find({Op0, Op1}); 2425 if (it != PairMap[Idx].end()) { 2426 // Functions like BreakUpSubtract() can erase the Values we're using 2427 // as keys and create new Values after we built the PairMap. There's a 2428 // small chance that the new nodes can have the same address as 2429 // something already in the table. We shouldn't accumulate the stored 2430 // score in that case as it refers to the wrong Value. 2431 if (it->second.isValid()) 2432 Score += it->second.Score; 2433 } 2434 2435 unsigned MaxRank = std::max(Ops[i].Rank, Ops[j].Rank); 2436 2437 // By construction, the operands are sorted in reverse order of their 2438 // topological order. 2439 // So we tend to form (sub) expressions with values that are close to 2440 // each other. 2441 // 2442 // Now to expose more CSE opportunities we want to expose the pair of 2443 // operands that occur the most (as statically computed in 2444 // BuildPairMap.) as the first sub-expression. 2445 // 2446 // If two pairs occur as many times, we pick the one with the 2447 // lowest rank, meaning the one with both operands appearing first in 2448 // the topological order. 2449 if (Score > Max || (Score == Max && MaxRank < BestRank)) { 2450 BestPair = {j, i}; 2451 Max = Score; 2452 BestRank = MaxRank; 2453 } 2454 } 2455 } 2456 if (Max > 1) { 2457 auto Op0 = Ops[BestPair.first]; 2458 auto Op1 = Ops[BestPair.second]; 2459 Ops.erase(&Ops[BestPair.second]); 2460 Ops.erase(&Ops[BestPair.first]); 2461 Ops.push_back(Op0); 2462 Ops.push_back(Op1); 2463 } 2464 } 2465 LLVM_DEBUG(dbgs() << "RAOut after CSE reorder:\t"; PrintOps(I, Ops); 2466 dbgs() << '\n'); 2467 // Now that we ordered and optimized the expressions, splat them back into 2468 // the expression tree, removing any unneeded nodes. 2469 RewriteExprTree(I, Ops, Flags); 2470 } 2471 2472 void 2473 ReassociatePass::BuildPairMap(ReversePostOrderTraversal<Function *> &RPOT) { 2474 // Make a "pairmap" of how often each operand pair occurs. 2475 for (BasicBlock *BI : RPOT) { 2476 for (Instruction &I : *BI) { 2477 if (!I.isAssociative() || !I.isBinaryOp()) 2478 continue; 2479 2480 // Ignore nodes that aren't at the root of trees. 2481 if (I.hasOneUse() && I.user_back()->getOpcode() == I.getOpcode()) 2482 continue; 2483 2484 // Collect all operands in a single reassociable expression. 2485 // Since Reassociate has already been run once, we can assume things 2486 // are already canonical according to Reassociation's regime. 2487 SmallVector<Value *, 8> Worklist = { I.getOperand(0), I.getOperand(1) }; 2488 SmallVector<Value *, 8> Ops; 2489 while (!Worklist.empty() && Ops.size() <= GlobalReassociateLimit) { 2490 Value *Op = Worklist.pop_back_val(); 2491 Instruction *OpI = dyn_cast<Instruction>(Op); 2492 if (!OpI || OpI->getOpcode() != I.getOpcode() || !OpI->hasOneUse()) { 2493 Ops.push_back(Op); 2494 continue; 2495 } 2496 // Be paranoid about self-referencing expressions in unreachable code. 2497 if (OpI->getOperand(0) != OpI) 2498 Worklist.push_back(OpI->getOperand(0)); 2499 if (OpI->getOperand(1) != OpI) 2500 Worklist.push_back(OpI->getOperand(1)); 2501 } 2502 // Skip extremely long expressions. 2503 if (Ops.size() > GlobalReassociateLimit) 2504 continue; 2505 2506 // Add all pairwise combinations of operands to the pair map. 2507 unsigned BinaryIdx = I.getOpcode() - Instruction::BinaryOpsBegin; 2508 SmallSet<std::pair<Value *, Value*>, 32> Visited; 2509 for (unsigned i = 0; i < Ops.size() - 1; ++i) { 2510 for (unsigned j = i + 1; j < Ops.size(); ++j) { 2511 // Canonicalize operand orderings. 2512 Value *Op0 = Ops[i]; 2513 Value *Op1 = Ops[j]; 2514 if (std::less<Value *>()(Op1, Op0)) 2515 std::swap(Op0, Op1); 2516 if (!Visited.insert({Op0, Op1}).second) 2517 continue; 2518 auto res = PairMap[BinaryIdx].insert({{Op0, Op1}, {Op0, Op1, 1}}); 2519 if (!res.second) { 2520 // If either key value has been erased then we've got the same 2521 // address by coincidence. That can't happen here because nothing is 2522 // erasing values but it can happen by the time we're querying the 2523 // map. 2524 assert(res.first->second.isValid() && "WeakVH invalidated"); 2525 ++res.first->second.Score; 2526 } 2527 } 2528 } 2529 } 2530 } 2531 } 2532 2533 PreservedAnalyses ReassociatePass::run(Function &F, FunctionAnalysisManager &) { 2534 // Get the functions basic blocks in Reverse Post Order. This order is used by 2535 // BuildRankMap to pre calculate ranks correctly. It also excludes dead basic 2536 // blocks (it has been seen that the analysis in this pass could hang when 2537 // analysing dead basic blocks). 2538 ReversePostOrderTraversal<Function *> RPOT(&F); 2539 2540 // Calculate the rank map for F. 2541 BuildRankMap(F, RPOT); 2542 2543 // Build the pair map before running reassociate. 2544 // Technically this would be more accurate if we did it after one round 2545 // of reassociation, but in practice it doesn't seem to help much on 2546 // real-world code, so don't waste the compile time running reassociate 2547 // twice. 2548 // If a user wants, they could expicitly run reassociate twice in their 2549 // pass pipeline for further potential gains. 2550 // It might also be possible to update the pair map during runtime, but the 2551 // overhead of that may be large if there's many reassociable chains. 2552 BuildPairMap(RPOT); 2553 2554 MadeChange = false; 2555 2556 // Traverse the same blocks that were analysed by BuildRankMap. 2557 for (BasicBlock *BI : RPOT) { 2558 assert(RankMap.count(&*BI) && "BB should be ranked."); 2559 // Optimize every instruction in the basic block. 2560 for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;) 2561 if (isInstructionTriviallyDead(&*II)) { 2562 EraseInst(&*II++); 2563 } else { 2564 OptimizeInst(&*II); 2565 assert(II->getParent() == &*BI && "Moved to a different block!"); 2566 ++II; 2567 } 2568 2569 // Make a copy of all the instructions to be redone so we can remove dead 2570 // instructions. 2571 OrderedSet ToRedo(RedoInsts); 2572 // Iterate over all instructions to be reevaluated and remove trivially dead 2573 // instructions. If any operand of the trivially dead instruction becomes 2574 // dead mark it for deletion as well. Continue this process until all 2575 // trivially dead instructions have been removed. 2576 while (!ToRedo.empty()) { 2577 Instruction *I = ToRedo.pop_back_val(); 2578 if (isInstructionTriviallyDead(I)) { 2579 RecursivelyEraseDeadInsts(I, ToRedo); 2580 MadeChange = true; 2581 } 2582 } 2583 2584 // Now that we have removed dead instructions, we can reoptimize the 2585 // remaining instructions. 2586 while (!RedoInsts.empty()) { 2587 Instruction *I = RedoInsts.front(); 2588 RedoInsts.erase(RedoInsts.begin()); 2589 if (isInstructionTriviallyDead(I)) 2590 EraseInst(I); 2591 else 2592 OptimizeInst(I); 2593 } 2594 } 2595 2596 // We are done with the rank map and pair map. 2597 RankMap.clear(); 2598 ValueRankMap.clear(); 2599 for (auto &Entry : PairMap) 2600 Entry.clear(); 2601 2602 if (MadeChange) { 2603 PreservedAnalyses PA; 2604 PA.preserveSet<CFGAnalyses>(); 2605 return PA; 2606 } 2607 2608 return PreservedAnalyses::all(); 2609 } 2610 2611 namespace { 2612 2613 class ReassociateLegacyPass : public FunctionPass { 2614 ReassociatePass Impl; 2615 2616 public: 2617 static char ID; // Pass identification, replacement for typeid 2618 2619 ReassociateLegacyPass() : FunctionPass(ID) { 2620 initializeReassociateLegacyPassPass(*PassRegistry::getPassRegistry()); 2621 } 2622 2623 bool runOnFunction(Function &F) override { 2624 if (skipFunction(F)) 2625 return false; 2626 2627 FunctionAnalysisManager DummyFAM; 2628 auto PA = Impl.run(F, DummyFAM); 2629 return !PA.areAllPreserved(); 2630 } 2631 2632 void getAnalysisUsage(AnalysisUsage &AU) const override { 2633 AU.setPreservesCFG(); 2634 AU.addPreserved<AAResultsWrapperPass>(); 2635 AU.addPreserved<BasicAAWrapperPass>(); 2636 AU.addPreserved<GlobalsAAWrapperPass>(); 2637 } 2638 }; 2639 2640 } // end anonymous namespace 2641 2642 char ReassociateLegacyPass::ID = 0; 2643 2644 INITIALIZE_PASS(ReassociateLegacyPass, "reassociate", 2645 "Reassociate expressions", false, false) 2646 2647 // Public interface to the Reassociate pass 2648 FunctionPass *llvm::createReassociatePass() { 2649 return new ReassociateLegacyPass(); 2650 } 2651