NaryReassociate.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. //===- NaryReassociate.cpp - Reassociate n-ary expressions ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass reassociates n-ary add expressions and eliminates the redundancy
  11. // exposed by the reassociation.
  12. //
  13. // A motivating example:
  14. //
  15. // void foo(int a, int b) {
  16. // bar(a + b);
  17. // bar((a + 2) + b);
  18. // }
  19. //
  20. // An ideal compiler should reassociate (a + 2) + b to (a + b) + 2 and simplify
  21. // the above code to
  22. //
  23. // int t = a + b;
  24. // bar(t);
  25. // bar(t + 2);
  26. //
  27. // However, the Reassociate pass is unable to do that because it processes each
  28. // instruction individually and believes (a + 2) + b is the best form according
  29. // to its rank system.
  30. //
  31. // To address this limitation, NaryReassociate reassociates an expression in a
  32. // form that reuses existing instructions. As a result, NaryReassociate can
  33. // reassociate (a + 2) + b in the example to (a + b) + 2 because it detects that
  34. // (a + b) is computed before.
  35. //
  36. // NaryReassociate works as follows. For every instruction in the form of (a +
  37. // b) + c, it checks whether a + c or b + c is already computed by a dominating
  38. // instruction. If so, it then reassociates (a + b) + c into (a + c) + b or (b +
  39. // c) + a and removes the redundancy accordingly. To efficiently look up whether
  40. // an expression is computed before, we store each instruction seen and its SCEV
  41. // into an SCEV-to-instruction map.
  42. //
  43. // Although the algorithm pattern-matches only ternary additions, it
  44. // automatically handles many >3-ary expressions by walking through the function
  45. // in the depth-first order. For example, given
  46. //
  47. // (a + c) + d
  48. // ((a + b) + c) + d
  49. //
  50. // NaryReassociate first rewrites (a + b) + c to (a + c) + b, and then rewrites
  51. // ((a + c) + b) + d into ((a + c) + d) + b.
  52. //
  53. // Finally, the above dominator-based algorithm may need to be run multiple
  54. // iterations before emitting optimal code. One source of this need is that we
  55. // only split an operand when it is used only once. The above algorithm can
  56. // eliminate an instruction and decrease the usage count of its operands. As a
  57. // result, an instruction that previously had multiple uses may become a
  58. // single-use instruction and thus eligible for split consideration. For
  59. // example,
  60. //
  61. // ac = a + c
  62. // ab = a + b
  63. // abc = ab + c
  64. // ab2 = ab + b
  65. // ab2c = ab2 + c
  66. //
  67. // In the first iteration, we cannot reassociate abc to ac+b because ab is used
  68. // twice. However, we can reassociate ab2c to abc+b in the first iteration. As a
  69. // result, ab2 becomes dead and ab will be used only once in the second
  70. // iteration.
  71. //
  72. // Limitations and TODO items:
  73. //
  74. // 1) We only considers n-ary adds for now. This should be extended and
  75. // generalized.
  76. //
  77. //===----------------------------------------------------------------------===//
  78. #include "llvm/Analysis/AssumptionCache.h"
  79. #include "llvm/Analysis/ScalarEvolution.h"
  80. #include "llvm/Analysis/TargetLibraryInfo.h"
  81. #include "llvm/Analysis/TargetTransformInfo.h"
  82. #include "llvm/Analysis/ValueTracking.h"
  83. #include "llvm/IR/Dominators.h"
  84. #include "llvm/IR/Module.h"
  85. #include "llvm/IR/PatternMatch.h"
  86. #include "llvm/Support/Debug.h"
  87. #include "llvm/Support/raw_ostream.h"
  88. #include "llvm/Transforms/Scalar.h"
  89. #include "llvm/Transforms/Utils/Local.h"
  90. using namespace llvm;
  91. using namespace PatternMatch;
  92. #define DEBUG_TYPE "nary-reassociate"
  93. namespace {
  94. class NaryReassociate : public FunctionPass {
  95. public:
  96. static char ID;
  97. NaryReassociate(): FunctionPass(ID) {
  98. initializeNaryReassociatePass(*PassRegistry::getPassRegistry());
  99. }
  100. bool doInitialization(Module &M) override {
  101. DL = &M.getDataLayout();
  102. return false;
  103. }
  104. bool runOnFunction(Function &F) override;
  105. void getAnalysisUsage(AnalysisUsage &AU) const override {
  106. AU.addPreserved<DominatorTreeWrapperPass>();
  107. AU.addPreserved<ScalarEvolution>();
  108. AU.addPreserved<TargetLibraryInfoWrapperPass>();
  109. AU.addRequired<AssumptionCacheTracker>();
  110. AU.addRequired<DominatorTreeWrapperPass>();
  111. AU.addRequired<ScalarEvolution>();
  112. AU.addRequired<TargetLibraryInfoWrapperPass>();
  113. AU.addRequired<TargetTransformInfoWrapperPass>();
  114. AU.setPreservesCFG();
  115. }
  116. private:
  117. // Runs only one iteration of the dominator-based algorithm. See the header
  118. // comments for why we need multiple iterations.
  119. bool doOneIteration(Function &F);
  120. // Reassociates I for better CSE.
  121. Instruction *tryReassociate(Instruction *I);
  122. // Reassociate GEP for better CSE.
  123. Instruction *tryReassociateGEP(GetElementPtrInst *GEP);
  124. // Try splitting GEP at the I-th index and see whether either part can be
  125. // CSE'ed. This is a helper function for tryReassociateGEP.
  126. //
  127. // \p IndexedType The element type indexed by GEP's I-th index. This is
  128. // equivalent to
  129. // GEP->getIndexedType(GEP->getPointerOperand(), 0-th index,
  130. // ..., i-th index).
  131. GetElementPtrInst *tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
  132. unsigned I, Type *IndexedType);
  133. // Given GEP's I-th index = LHS + RHS, see whether &Base[..][LHS][..] or
  134. // &Base[..][RHS][..] can be CSE'ed and rewrite GEP accordingly.
  135. GetElementPtrInst *tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
  136. unsigned I, Value *LHS,
  137. Value *RHS, Type *IndexedType);
  138. // Reassociate Add for better CSE.
  139. Instruction *tryReassociateAdd(BinaryOperator *I);
  140. // A helper function for tryReassociateAdd. LHS and RHS are explicitly passed.
  141. Instruction *tryReassociateAdd(Value *LHS, Value *RHS, Instruction *I);
  142. // Rewrites I to LHS + RHS if LHS is computed already.
  143. Instruction *tryReassociatedAdd(const SCEV *LHS, Value *RHS, Instruction *I);
  144. // Returns the closest dominator of \c Dominatee that computes
  145. // \c CandidateExpr. Returns null if not found.
  146. Instruction *findClosestMatchingDominator(const SCEV *CandidateExpr,
  147. Instruction *Dominatee);
  148. // GetElementPtrInst implicitly sign-extends an index if the index is shorter
  149. // than the pointer size. This function returns whether Index is shorter than
  150. // GEP's pointer size, i.e., whether Index needs to be sign-extended in order
  151. // to be an index of GEP.
  152. bool requiresSignExtension(Value *Index, GetElementPtrInst *GEP);
  153. // Returns whether V is known to be non-negative at context \c Ctxt.
  154. bool isKnownNonNegative(Value *V, Instruction *Ctxt);
  155. // Returns whether AO may sign overflow at context \c Ctxt. It computes a
  156. // conservative result -- it answers true when not sure.
  157. bool maySignOverflow(AddOperator *AO, Instruction *Ctxt);
  158. AssumptionCache *AC;
  159. const DataLayout *DL;
  160. DominatorTree *DT;
  161. ScalarEvolution *SE;
  162. TargetLibraryInfo *TLI;
  163. TargetTransformInfo *TTI;
  164. // A lookup table quickly telling which instructions compute the given SCEV.
  165. // Note that there can be multiple instructions at different locations
  166. // computing to the same SCEV, so we map a SCEV to an instruction list. For
  167. // example,
  168. //
  169. // if (p1)
  170. // foo(a + b);
  171. // if (p2)
  172. // bar(a + b);
  173. DenseMap<const SCEV *, SmallVector<Instruction *, 2>> SeenExprs;
  174. };
  175. } // anonymous namespace
  176. char NaryReassociate::ID = 0;
  177. INITIALIZE_PASS_BEGIN(NaryReassociate, "nary-reassociate", "Nary reassociation",
  178. false, false)
  179. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  180. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  181. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  182. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  183. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  184. INITIALIZE_PASS_END(NaryReassociate, "nary-reassociate", "Nary reassociation",
  185. false, false)
  186. FunctionPass *llvm::createNaryReassociatePass() {
  187. return new NaryReassociate();
  188. }
  189. bool NaryReassociate::runOnFunction(Function &F) {
  190. if (skipOptnoneFunction(F))
  191. return false;
  192. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  193. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  194. SE = &getAnalysis<ScalarEvolution>();
  195. TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  196. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  197. bool Changed = false, ChangedInThisIteration;
  198. do {
  199. ChangedInThisIteration = doOneIteration(F);
  200. Changed |= ChangedInThisIteration;
  201. } while (ChangedInThisIteration);
  202. return Changed;
  203. }
  204. // Whitelist the instruction types NaryReassociate handles for now.
  205. static bool isPotentiallyNaryReassociable(Instruction *I) {
  206. switch (I->getOpcode()) {
  207. case Instruction::Add:
  208. case Instruction::GetElementPtr:
  209. return true;
  210. default:
  211. return false;
  212. }
  213. }
  214. bool NaryReassociate::doOneIteration(Function &F) {
  215. bool Changed = false;
  216. SeenExprs.clear();
  217. // Process the basic blocks in pre-order of the dominator tree. This order
  218. // ensures that all bases of a candidate are in Candidates when we process it.
  219. for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
  220. Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
  221. BasicBlock *BB = Node->getBlock();
  222. for (auto I = BB->begin(); I != BB->end(); ++I) {
  223. if (SE->isSCEVable(I->getType()) && isPotentiallyNaryReassociable(I)) {
  224. const SCEV *OldSCEV = SE->getSCEV(I);
  225. if (Instruction *NewI = tryReassociate(I)) {
  226. Changed = true;
  227. SE->forgetValue(I);
  228. I->replaceAllUsesWith(NewI);
  229. RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  230. I = NewI;
  231. }
  232. // Add the rewritten instruction to SeenExprs; the original instruction
  233. // is deleted.
  234. const SCEV *NewSCEV = SE->getSCEV(I);
  235. SeenExprs[NewSCEV].push_back(I);
  236. // Ideally, NewSCEV should equal OldSCEV because tryReassociate(I)
  237. // is equivalent to I. However, ScalarEvolution::getSCEV may
  238. // weaken nsw causing NewSCEV not to equal OldSCEV. For example, suppose
  239. // we reassociate
  240. // I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4
  241. // to
  242. // NewI = &a[sext(i)] + sext(j).
  243. //
  244. // ScalarEvolution computes
  245. // getSCEV(I) = a + 4 * sext(i + j)
  246. // getSCEV(newI) = a + 4 * sext(i) + 4 * sext(j)
  247. // which are different SCEVs.
  248. //
  249. // To alleviate this issue of ScalarEvolution not always capturing
  250. // equivalence, we add I to SeenExprs[OldSCEV] as well so that we can
  251. // map both SCEV before and after tryReassociate(I) to I.
  252. //
  253. // This improvement is exercised in @reassociate_gep_nsw in nary-gep.ll.
  254. if (NewSCEV != OldSCEV)
  255. SeenExprs[OldSCEV].push_back(I);
  256. }
  257. }
  258. }
  259. return Changed;
  260. }
  261. Instruction *NaryReassociate::tryReassociate(Instruction *I) {
  262. switch (I->getOpcode()) {
  263. case Instruction::Add:
  264. return tryReassociateAdd(cast<BinaryOperator>(I));
  265. case Instruction::GetElementPtr:
  266. return tryReassociateGEP(cast<GetElementPtrInst>(I));
  267. default:
  268. llvm_unreachable("should be filtered out by isPotentiallyNaryReassociable");
  269. }
  270. }
  271. // FIXME: extract this method into TTI->getGEPCost.
  272. static bool isGEPFoldable(GetElementPtrInst *GEP,
  273. const TargetTransformInfo *TTI,
  274. const DataLayout *DL) {
  275. GlobalVariable *BaseGV = nullptr;
  276. int64_t BaseOffset = 0;
  277. bool HasBaseReg = false;
  278. int64_t Scale = 0;
  279. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand()))
  280. BaseGV = GV;
  281. else
  282. HasBaseReg = true;
  283. gep_type_iterator GTI = gep_type_begin(GEP);
  284. for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I, ++GTI) {
  285. if (isa<SequentialType>(*GTI)) {
  286. int64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
  287. if (ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) {
  288. BaseOffset += ConstIdx->getSExtValue() * ElementSize;
  289. } else {
  290. // Needs scale register.
  291. if (Scale != 0) {
  292. // No addressing mode takes two scale registers.
  293. return false;
  294. }
  295. Scale = ElementSize;
  296. }
  297. } else {
  298. StructType *STy = cast<StructType>(*GTI);
  299. uint64_t Field = cast<ConstantInt>(*I)->getZExtValue();
  300. BaseOffset += DL->getStructLayout(STy)->getElementOffset(Field);
  301. }
  302. }
  303. unsigned AddrSpace = GEP->getPointerAddressSpace();
  304. return TTI->isLegalAddressingMode(GEP->getType()->getElementType(), BaseGV,
  305. BaseOffset, HasBaseReg, Scale, AddrSpace);
  306. }
  307. Instruction *NaryReassociate::tryReassociateGEP(GetElementPtrInst *GEP) {
  308. // Not worth reassociating GEP if it is foldable.
  309. if (isGEPFoldable(GEP, TTI, DL))
  310. return nullptr;
  311. gep_type_iterator GTI = gep_type_begin(*GEP);
  312. for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) {
  313. if (isa<SequentialType>(*GTI++)) {
  314. if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1, *GTI)) {
  315. return NewGEP;
  316. }
  317. }
  318. }
  319. return nullptr;
  320. }
  321. bool NaryReassociate::requiresSignExtension(Value *Index,
  322. GetElementPtrInst *GEP) {
  323. unsigned PointerSizeInBits =
  324. DL->getPointerSizeInBits(GEP->getType()->getPointerAddressSpace());
  325. return cast<IntegerType>(Index->getType())->getBitWidth() < PointerSizeInBits;
  326. }
  327. bool NaryReassociate::isKnownNonNegative(Value *V, Instruction *Ctxt) {
  328. bool NonNegative, Negative;
  329. // TODO: ComputeSignBits is expensive. Consider caching the results.
  330. ComputeSignBit(V, NonNegative, Negative, *DL, 0, AC, Ctxt, DT);
  331. return NonNegative;
  332. }
  333. bool NaryReassociate::maySignOverflow(AddOperator *AO, Instruction *Ctxt) {
  334. if (AO->hasNoSignedWrap())
  335. return false;
  336. Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1);
  337. // If LHS or RHS has the same sign as the sum, AO doesn't sign overflow.
  338. // TODO: handle the negative case as well.
  339. if (isKnownNonNegative(AO, Ctxt) &&
  340. (isKnownNonNegative(LHS, Ctxt) || isKnownNonNegative(RHS, Ctxt)))
  341. return false;
  342. return true;
  343. }
  344. GetElementPtrInst *
  345. NaryReassociate::tryReassociateGEPAtIndex(GetElementPtrInst *GEP, unsigned I,
  346. Type *IndexedType) {
  347. Value *IndexToSplit = GEP->getOperand(I + 1);
  348. if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit)) {
  349. IndexToSplit = SExt->getOperand(0);
  350. } else if (ZExtInst *ZExt = dyn_cast<ZExtInst>(IndexToSplit)) {
  351. // zext can be treated as sext if the source is non-negative.
  352. if (isKnownNonNegative(ZExt->getOperand(0), GEP))
  353. IndexToSplit = ZExt->getOperand(0);
  354. }
  355. if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) {
  356. // If the I-th index needs sext and the underlying add is not equipped with
  357. // nsw, we cannot split the add because
  358. // sext(LHS + RHS) != sext(LHS) + sext(RHS).
  359. if (requiresSignExtension(IndexToSplit, GEP) && maySignOverflow(AO, GEP))
  360. return nullptr;
  361. Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1);
  362. // IndexToSplit = LHS + RHS.
  363. if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType))
  364. return NewGEP;
  365. // Symmetrically, try IndexToSplit = RHS + LHS.
  366. if (LHS != RHS) {
  367. if (auto *NewGEP =
  368. tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType))
  369. return NewGEP;
  370. }
  371. }
  372. return nullptr;
  373. }
  374. GetElementPtrInst *NaryReassociate::tryReassociateGEPAtIndex(
  375. GetElementPtrInst *GEP, unsigned I, Value *LHS, Value *RHS,
  376. Type *IndexedType) {
  377. // Look for GEP's closest dominator that has the same SCEV as GEP except that
  378. // the I-th index is replaced with LHS.
  379. SmallVector<const SCEV *, 4> IndexExprs;
  380. for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
  381. IndexExprs.push_back(SE->getSCEV(*Index));
  382. // Replace the I-th index with LHS.
  383. IndexExprs[I] = SE->getSCEV(LHS);
  384. if (isKnownNonNegative(LHS, GEP) &&
  385. DL->getTypeSizeInBits(LHS->getType()) <
  386. DL->getTypeSizeInBits(GEP->getOperand(I)->getType())) {
  387. // Zero-extend LHS if it is non-negative. InstCombine canonicalizes sext to
  388. // zext if the source operand is proved non-negative. We should do that
  389. // consistently so that CandidateExpr more likely appears before. See
  390. // @reassociate_gep_assume for an example of this canonicalization.
  391. IndexExprs[I] =
  392. SE->getZeroExtendExpr(IndexExprs[I], GEP->getOperand(I)->getType());
  393. }
  394. const SCEV *CandidateExpr = SE->getGEPExpr(
  395. GEP->getSourceElementType(), SE->getSCEV(GEP->getPointerOperand()),
  396. IndexExprs, GEP->isInBounds());
  397. auto *Candidate = findClosestMatchingDominator(CandidateExpr, GEP);
  398. if (Candidate == nullptr)
  399. return nullptr;
  400. PointerType *TypeOfCandidate = dyn_cast<PointerType>(Candidate->getType());
  401. // Pretty rare but theoretically possible when a numeric value happens to
  402. // share CandidateExpr.
  403. if (TypeOfCandidate == nullptr)
  404. return nullptr;
  405. // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType)
  406. uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType);
  407. Type *ElementType = TypeOfCandidate->getElementType();
  408. uint64_t ElementSize = DL->getTypeAllocSize(ElementType);
  409. // Another less rare case: because I is not necessarily the last index of the
  410. // GEP, the size of the type at the I-th index (IndexedSize) is not
  411. // necessarily divisible by ElementSize. For example,
  412. //
  413. // #pragma pack(1)
  414. // struct S {
  415. // int a[3];
  416. // int64 b[8];
  417. // };
  418. // #pragma pack()
  419. //
  420. // sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
  421. //
  422. // TODO: bail out on this case for now. We could emit uglygep.
  423. if (IndexedSize % ElementSize != 0)
  424. return nullptr;
  425. // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
  426. IRBuilder<> Builder(GEP);
  427. Type *IntPtrTy = DL->getIntPtrType(TypeOfCandidate);
  428. if (RHS->getType() != IntPtrTy)
  429. RHS = Builder.CreateSExtOrTrunc(RHS, IntPtrTy);
  430. if (IndexedSize != ElementSize) {
  431. RHS = Builder.CreateMul(
  432. RHS, ConstantInt::get(IntPtrTy, IndexedSize / ElementSize));
  433. }
  434. GetElementPtrInst *NewGEP =
  435. cast<GetElementPtrInst>(Builder.CreateGEP(Candidate, RHS));
  436. NewGEP->setIsInBounds(GEP->isInBounds());
  437. NewGEP->takeName(GEP);
  438. return NewGEP;
  439. }
  440. Instruction *NaryReassociate::tryReassociateAdd(BinaryOperator *I) {
  441. Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
  442. if (auto *NewI = tryReassociateAdd(LHS, RHS, I))
  443. return NewI;
  444. if (auto *NewI = tryReassociateAdd(RHS, LHS, I))
  445. return NewI;
  446. return nullptr;
  447. }
  448. Instruction *NaryReassociate::tryReassociateAdd(Value *LHS, Value *RHS,
  449. Instruction *I) {
  450. Value *A = nullptr, *B = nullptr;
  451. // To be conservative, we reassociate I only when it is the only user of A+B.
  452. if (LHS->hasOneUse() && match(LHS, m_Add(m_Value(A), m_Value(B)))) {
  453. // I = (A + B) + RHS
  454. // = (A + RHS) + B or (B + RHS) + A
  455. const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
  456. const SCEV *RHSExpr = SE->getSCEV(RHS);
  457. if (BExpr != RHSExpr) {
  458. if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(AExpr, RHSExpr), B, I))
  459. return NewI;
  460. }
  461. if (AExpr != RHSExpr) {
  462. if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(BExpr, RHSExpr), A, I))
  463. return NewI;
  464. }
  465. }
  466. return nullptr;
  467. }
  468. Instruction *NaryReassociate::tryReassociatedAdd(const SCEV *LHSExpr,
  469. Value *RHS, Instruction *I) {
  470. auto Pos = SeenExprs.find(LHSExpr);
  471. // Bail out if LHSExpr is not previously seen.
  472. if (Pos == SeenExprs.end())
  473. return nullptr;
  474. // Look for the closest dominator LHS of I that computes LHSExpr, and replace
  475. // I with LHS + RHS.
  476. auto *LHS = findClosestMatchingDominator(LHSExpr, I);
  477. if (LHS == nullptr)
  478. return nullptr;
  479. Instruction *NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
  480. NewI->takeName(I);
  481. return NewI;
  482. }
  483. Instruction *
  484. NaryReassociate::findClosestMatchingDominator(const SCEV *CandidateExpr,
  485. Instruction *Dominatee) {
  486. auto Pos = SeenExprs.find(CandidateExpr);
  487. if (Pos == SeenExprs.end())
  488. return nullptr;
  489. auto &Candidates = Pos->second;
  490. // Because we process the basic blocks in pre-order of the dominator tree, a
  491. // candidate that doesn't dominate the current instruction won't dominate any
  492. // future instruction either. Therefore, we pop it out of the stack. This
  493. // optimization makes the algorithm O(n).
  494. while (!Candidates.empty()) {
  495. Instruction *Candidate = Candidates.back();
  496. if (DT->dominates(Candidate, Dominatee))
  497. return Candidate;
  498. Candidates.pop_back();
  499. }
  500. return nullptr;
  501. }