xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Scalar/NaryReassociate.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- NaryReassociate.cpp - Reassociate n-ary expressions ----------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass reassociates n-ary add expressions and eliminates the redundancy
100b57cec5SDimitry Andric // exposed by the reassociation.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // A motivating example:
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric //   void foo(int a, int b) {
150b57cec5SDimitry Andric //     bar(a + b);
160b57cec5SDimitry Andric //     bar((a + 2) + b);
170b57cec5SDimitry Andric //   }
180b57cec5SDimitry Andric //
190b57cec5SDimitry Andric // An ideal compiler should reassociate (a + 2) + b to (a + b) + 2 and simplify
200b57cec5SDimitry Andric // the above code to
210b57cec5SDimitry Andric //
220b57cec5SDimitry Andric //   int t = a + b;
230b57cec5SDimitry Andric //   bar(t);
240b57cec5SDimitry Andric //   bar(t + 2);
250b57cec5SDimitry Andric //
260b57cec5SDimitry Andric // However, the Reassociate pass is unable to do that because it processes each
270b57cec5SDimitry Andric // instruction individually and believes (a + 2) + b is the best form according
280b57cec5SDimitry Andric // to its rank system.
290b57cec5SDimitry Andric //
300b57cec5SDimitry Andric // To address this limitation, NaryReassociate reassociates an expression in a
310b57cec5SDimitry Andric // form that reuses existing instructions. As a result, NaryReassociate can
320b57cec5SDimitry Andric // reassociate (a + 2) + b in the example to (a + b) + 2 because it detects that
330b57cec5SDimitry Andric // (a + b) is computed before.
340b57cec5SDimitry Andric //
350b57cec5SDimitry Andric // NaryReassociate works as follows. For every instruction in the form of (a +
360b57cec5SDimitry Andric // b) + c, it checks whether a + c or b + c is already computed by a dominating
370b57cec5SDimitry Andric // instruction. If so, it then reassociates (a + b) + c into (a + c) + b or (b +
380b57cec5SDimitry Andric // c) + a and removes the redundancy accordingly. To efficiently look up whether
390b57cec5SDimitry Andric // an expression is computed before, we store each instruction seen and its SCEV
400b57cec5SDimitry Andric // into an SCEV-to-instruction map.
410b57cec5SDimitry Andric //
420b57cec5SDimitry Andric // Although the algorithm pattern-matches only ternary additions, it
430b57cec5SDimitry Andric // automatically handles many >3-ary expressions by walking through the function
440b57cec5SDimitry Andric // in the depth-first order. For example, given
450b57cec5SDimitry Andric //
460b57cec5SDimitry Andric //   (a + c) + d
470b57cec5SDimitry Andric //   ((a + b) + c) + d
480b57cec5SDimitry Andric //
490b57cec5SDimitry Andric // NaryReassociate first rewrites (a + b) + c to (a + c) + b, and then rewrites
500b57cec5SDimitry Andric // ((a + c) + b) + d into ((a + c) + d) + b.
510b57cec5SDimitry Andric //
520b57cec5SDimitry Andric // Finally, the above dominator-based algorithm may need to be run multiple
530b57cec5SDimitry Andric // iterations before emitting optimal code. One source of this need is that we
540b57cec5SDimitry Andric // only split an operand when it is used only once. The above algorithm can
550b57cec5SDimitry Andric // eliminate an instruction and decrease the usage count of its operands. As a
560b57cec5SDimitry Andric // result, an instruction that previously had multiple uses may become a
570b57cec5SDimitry Andric // single-use instruction and thus eligible for split consideration. For
580b57cec5SDimitry Andric // example,
590b57cec5SDimitry Andric //
600b57cec5SDimitry Andric //   ac = a + c
610b57cec5SDimitry Andric //   ab = a + b
620b57cec5SDimitry Andric //   abc = ab + c
630b57cec5SDimitry Andric //   ab2 = ab + b
640b57cec5SDimitry Andric //   ab2c = ab2 + c
650b57cec5SDimitry Andric //
660b57cec5SDimitry Andric // In the first iteration, we cannot reassociate abc to ac+b because ab is used
670b57cec5SDimitry Andric // twice. However, we can reassociate ab2c to abc+b in the first iteration. As a
680b57cec5SDimitry Andric // result, ab2 becomes dead and ab will be used only once in the second
690b57cec5SDimitry Andric // iteration.
700b57cec5SDimitry Andric //
710b57cec5SDimitry Andric // Limitations and TODO items:
720b57cec5SDimitry Andric //
730b57cec5SDimitry Andric // 1) We only considers n-ary adds and muls for now. This should be extended
740b57cec5SDimitry Andric // and generalized.
750b57cec5SDimitry Andric //
760b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/NaryReassociate.h"
790b57cec5SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
800b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
810b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
820b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
83fe6060f1SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
840b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
850b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
860b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
870b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
880b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
890b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
900b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
910b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
920b57cec5SDimitry Andric #include "llvm/IR/Function.h"
930b57cec5SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
940b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
950b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
960b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
970b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
980b57cec5SDimitry Andric #include "llvm/IR/Module.h"
990b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
1000b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
1010b57cec5SDimitry Andric #include "llvm/IR/Type.h"
1020b57cec5SDimitry Andric #include "llvm/IR/Value.h"
1030b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
104480093f4SDimitry Andric #include "llvm/InitializePasses.h"
1050b57cec5SDimitry Andric #include "llvm/Pass.h"
1060b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
1070b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
1080b57cec5SDimitry Andric #include "llvm/Transforms/Scalar.h"
109480093f4SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
110fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
1110b57cec5SDimitry Andric #include <cassert>
1120b57cec5SDimitry Andric #include <cstdint>
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric using namespace llvm;
1150b57cec5SDimitry Andric using namespace PatternMatch;
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric #define DEBUG_TYPE "nary-reassociate"
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric namespace {
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric class NaryReassociateLegacyPass : public FunctionPass {
1220b57cec5SDimitry Andric public:
1230b57cec5SDimitry Andric   static char ID;
1240b57cec5SDimitry Andric 
NaryReassociateLegacyPass()1250b57cec5SDimitry Andric   NaryReassociateLegacyPass() : FunctionPass(ID) {
1260b57cec5SDimitry Andric     initializeNaryReassociateLegacyPassPass(*PassRegistry::getPassRegistry());
1270b57cec5SDimitry Andric   }
1280b57cec5SDimitry Andric 
doInitialization(Module & M)1290b57cec5SDimitry Andric   bool doInitialization(Module &M) override {
1300b57cec5SDimitry Andric     return false;
1310b57cec5SDimitry Andric   }
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   bool runOnFunction(Function &F) override;
1340b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const1350b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
1360b57cec5SDimitry Andric     AU.addPreserved<DominatorTreeWrapperPass>();
1370b57cec5SDimitry Andric     AU.addPreserved<ScalarEvolutionWrapperPass>();
1380b57cec5SDimitry Andric     AU.addPreserved<TargetLibraryInfoWrapperPass>();
1390b57cec5SDimitry Andric     AU.addRequired<AssumptionCacheTracker>();
1400b57cec5SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
1410b57cec5SDimitry Andric     AU.addRequired<ScalarEvolutionWrapperPass>();
1420b57cec5SDimitry Andric     AU.addRequired<TargetLibraryInfoWrapperPass>();
1430b57cec5SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
1440b57cec5SDimitry Andric     AU.setPreservesCFG();
1450b57cec5SDimitry Andric   }
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric private:
1480b57cec5SDimitry Andric   NaryReassociatePass Impl;
1490b57cec5SDimitry Andric };
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric } // end anonymous namespace
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric char NaryReassociateLegacyPass::ID = 0;
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(NaryReassociateLegacyPass, "nary-reassociate",
1560b57cec5SDimitry Andric                       "Nary reassociation", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)1570b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1580b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1590b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
1600b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1610b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1620b57cec5SDimitry Andric INITIALIZE_PASS_END(NaryReassociateLegacyPass, "nary-reassociate",
1630b57cec5SDimitry Andric                     "Nary reassociation", false, false)
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric FunctionPass *llvm::createNaryReassociatePass() {
1660b57cec5SDimitry Andric   return new NaryReassociateLegacyPass();
1670b57cec5SDimitry Andric }
1680b57cec5SDimitry Andric 
runOnFunction(Function & F)1690b57cec5SDimitry Andric bool NaryReassociateLegacyPass::runOnFunction(Function &F) {
1700b57cec5SDimitry Andric   if (skipFunction(F))
1710b57cec5SDimitry Andric     return false;
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1740b57cec5SDimitry Andric   auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1750b57cec5SDimitry Andric   auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1768bcb0991SDimitry Andric   auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1770b57cec5SDimitry Andric   auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   return Impl.runImpl(F, AC, DT, SE, TLI, TTI);
1800b57cec5SDimitry Andric }
1810b57cec5SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)1820b57cec5SDimitry Andric PreservedAnalyses NaryReassociatePass::run(Function &F,
1830b57cec5SDimitry Andric                                            FunctionAnalysisManager &AM) {
1840b57cec5SDimitry Andric   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
1850b57cec5SDimitry Andric   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1860b57cec5SDimitry Andric   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
1870b57cec5SDimitry Andric   auto *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
1880b57cec5SDimitry Andric   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   if (!runImpl(F, AC, DT, SE, TLI, TTI))
1910b57cec5SDimitry Andric     return PreservedAnalyses::all();
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   PreservedAnalyses PA;
1940b57cec5SDimitry Andric   PA.preserveSet<CFGAnalyses>();
1950b57cec5SDimitry Andric   PA.preserve<ScalarEvolutionAnalysis>();
1960b57cec5SDimitry Andric   return PA;
1970b57cec5SDimitry Andric }
1980b57cec5SDimitry Andric 
runImpl(Function & F,AssumptionCache * AC_,DominatorTree * DT_,ScalarEvolution * SE_,TargetLibraryInfo * TLI_,TargetTransformInfo * TTI_)1990b57cec5SDimitry Andric bool NaryReassociatePass::runImpl(Function &F, AssumptionCache *AC_,
2000b57cec5SDimitry Andric                                   DominatorTree *DT_, ScalarEvolution *SE_,
2010b57cec5SDimitry Andric                                   TargetLibraryInfo *TLI_,
2020b57cec5SDimitry Andric                                   TargetTransformInfo *TTI_) {
2030b57cec5SDimitry Andric   AC = AC_;
2040b57cec5SDimitry Andric   DT = DT_;
2050b57cec5SDimitry Andric   SE = SE_;
2060b57cec5SDimitry Andric   TLI = TLI_;
2070b57cec5SDimitry Andric   TTI = TTI_;
208*0fca6ea1SDimitry Andric   DL = &F.getDataLayout();
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric   bool Changed = false, ChangedInThisIteration;
2110b57cec5SDimitry Andric   do {
2120b57cec5SDimitry Andric     ChangedInThisIteration = doOneIteration(F);
2130b57cec5SDimitry Andric     Changed |= ChangedInThisIteration;
2140b57cec5SDimitry Andric   } while (ChangedInThisIteration);
2150b57cec5SDimitry Andric   return Changed;
2160b57cec5SDimitry Andric }
2170b57cec5SDimitry Andric 
doOneIteration(Function & F)2180b57cec5SDimitry Andric bool NaryReassociatePass::doOneIteration(Function &F) {
2190b57cec5SDimitry Andric   bool Changed = false;
2200b57cec5SDimitry Andric   SeenExprs.clear();
2210b57cec5SDimitry Andric   // Process the basic blocks in a depth first traversal of the dominator
2220b57cec5SDimitry Andric   // tree. This order ensures that all bases of a candidate are in Candidates
2230b57cec5SDimitry Andric   // when we process it.
224e8d8bef9SDimitry Andric   SmallVector<WeakTrackingVH, 16> DeadInsts;
2250b57cec5SDimitry Andric   for (const auto Node : depth_first(DT)) {
2260b57cec5SDimitry Andric     BasicBlock *BB = Node->getBlock();
227fe6060f1SDimitry Andric     for (Instruction &OrigI : *BB) {
228e8d8bef9SDimitry Andric       const SCEV *OrigSCEV = nullptr;
229fe6060f1SDimitry Andric       if (Instruction *NewI = tryReassociate(&OrigI, OrigSCEV)) {
2300b57cec5SDimitry Andric         Changed = true;
231fe6060f1SDimitry Andric         OrigI.replaceAllUsesWith(NewI);
232e8d8bef9SDimitry Andric 
233e8d8bef9SDimitry Andric         // Add 'OrigI' to the list of dead instructions.
234fe6060f1SDimitry Andric         DeadInsts.push_back(WeakTrackingVH(&OrigI));
235e8d8bef9SDimitry Andric         // Add the rewritten instruction to SeenExprs; the original
236e8d8bef9SDimitry Andric         // instruction is deleted.
237e8d8bef9SDimitry Andric         const SCEV *NewSCEV = SE->getSCEV(NewI);
238e8d8bef9SDimitry Andric         SeenExprs[NewSCEV].push_back(WeakTrackingVH(NewI));
239e8d8bef9SDimitry Andric 
2400b57cec5SDimitry Andric         // Ideally, NewSCEV should equal OldSCEV because tryReassociate(I)
2410b57cec5SDimitry Andric         // is equivalent to I. However, ScalarEvolution::getSCEV may
242e8d8bef9SDimitry Andric         // weaken nsw causing NewSCEV not to equal OldSCEV. For example,
243e8d8bef9SDimitry Andric         // suppose we reassociate
2440b57cec5SDimitry Andric         //   I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4
2450b57cec5SDimitry Andric         // to
2460b57cec5SDimitry Andric         //   NewI = &a[sext(i)] + sext(j).
2470b57cec5SDimitry Andric         //
2480b57cec5SDimitry Andric         // ScalarEvolution computes
2490b57cec5SDimitry Andric         //   getSCEV(I)    = a + 4 * sext(i + j)
2500b57cec5SDimitry Andric         //   getSCEV(newI) = a + 4 * sext(i) + 4 * sext(j)
2510b57cec5SDimitry Andric         // which are different SCEVs.
2520b57cec5SDimitry Andric         //
2530b57cec5SDimitry Andric         // To alleviate this issue of ScalarEvolution not always capturing
2540b57cec5SDimitry Andric         // equivalence, we add I to SeenExprs[OldSCEV] as well so that we can
2550b57cec5SDimitry Andric         // map both SCEV before and after tryReassociate(I) to I.
2560b57cec5SDimitry Andric         //
257e8d8bef9SDimitry Andric         // This improvement is exercised in @reassociate_gep_nsw in
258e8d8bef9SDimitry Andric         // nary-gep.ll.
259e8d8bef9SDimitry Andric         if (NewSCEV != OrigSCEV)
260e8d8bef9SDimitry Andric           SeenExprs[OrigSCEV].push_back(WeakTrackingVH(NewI));
261e8d8bef9SDimitry Andric       } else if (OrigSCEV)
262fe6060f1SDimitry Andric         SeenExprs[OrigSCEV].push_back(WeakTrackingVH(&OrigI));
2630b57cec5SDimitry Andric     }
2640b57cec5SDimitry Andric   }
265e8d8bef9SDimitry Andric   // Delete all dead instructions from 'DeadInsts'.
266e8d8bef9SDimitry Andric   // Please note ScalarEvolution is updated along the way.
267e8d8bef9SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructionsPermissive(
268e8d8bef9SDimitry Andric       DeadInsts, TLI, nullptr, [this](Value *V) { SE->forgetValue(V); });
269e8d8bef9SDimitry Andric 
2700b57cec5SDimitry Andric   return Changed;
2710b57cec5SDimitry Andric }
2720b57cec5SDimitry Andric 
273fe6060f1SDimitry Andric template <typename PredT>
274fe6060f1SDimitry Andric Instruction *
matchAndReassociateMinOrMax(Instruction * I,const SCEV * & OrigSCEV)275fe6060f1SDimitry Andric NaryReassociatePass::matchAndReassociateMinOrMax(Instruction *I,
276fe6060f1SDimitry Andric                                                  const SCEV *&OrigSCEV) {
277fe6060f1SDimitry Andric   Value *LHS = nullptr;
278fe6060f1SDimitry Andric   Value *RHS = nullptr;
279fe6060f1SDimitry Andric 
280fe6060f1SDimitry Andric   auto MinMaxMatcher =
281fe6060f1SDimitry Andric       MaxMin_match<ICmpInst, bind_ty<Value>, bind_ty<Value>, PredT>(
282fe6060f1SDimitry Andric           m_Value(LHS), m_Value(RHS));
283fe6060f1SDimitry Andric   if (match(I, MinMaxMatcher)) {
284fe6060f1SDimitry Andric     OrigSCEV = SE->getSCEV(I);
285349cc55cSDimitry Andric     if (auto *NewMinMax = dyn_cast_or_null<Instruction>(
286349cc55cSDimitry Andric             tryReassociateMinOrMax(I, MinMaxMatcher, LHS, RHS)))
287349cc55cSDimitry Andric       return NewMinMax;
288349cc55cSDimitry Andric     if (auto *NewMinMax = dyn_cast_or_null<Instruction>(
289349cc55cSDimitry Andric             tryReassociateMinOrMax(I, MinMaxMatcher, RHS, LHS)))
290349cc55cSDimitry Andric       return NewMinMax;
291fe6060f1SDimitry Andric   }
292fe6060f1SDimitry Andric   return nullptr;
293fe6060f1SDimitry Andric }
294fe6060f1SDimitry Andric 
tryReassociate(Instruction * I,const SCEV * & OrigSCEV)295e8d8bef9SDimitry Andric Instruction *NaryReassociatePass::tryReassociate(Instruction * I,
296e8d8bef9SDimitry Andric                                                  const SCEV *&OrigSCEV) {
297e8d8bef9SDimitry Andric 
298e8d8bef9SDimitry Andric   if (!SE->isSCEVable(I->getType()))
299e8d8bef9SDimitry Andric     return nullptr;
300e8d8bef9SDimitry Andric 
3010b57cec5SDimitry Andric   switch (I->getOpcode()) {
3020b57cec5SDimitry Andric   case Instruction::Add:
3030b57cec5SDimitry Andric   case Instruction::Mul:
304e8d8bef9SDimitry Andric     OrigSCEV = SE->getSCEV(I);
3050b57cec5SDimitry Andric     return tryReassociateBinaryOp(cast<BinaryOperator>(I));
3060b57cec5SDimitry Andric   case Instruction::GetElementPtr:
307e8d8bef9SDimitry Andric     OrigSCEV = SE->getSCEV(I);
3080b57cec5SDimitry Andric     return tryReassociateGEP(cast<GetElementPtrInst>(I));
3090b57cec5SDimitry Andric   default:
310fe6060f1SDimitry Andric     break;
3110b57cec5SDimitry Andric   }
312e8d8bef9SDimitry Andric 
313fe6060f1SDimitry Andric   // Try to match signed/unsigned Min/Max.
314fe6060f1SDimitry Andric   Instruction *ResI = nullptr;
315fe6060f1SDimitry Andric   // TODO: Currently min/max reassociation is restricted to integer types only
316fe6060f1SDimitry Andric   // due to use of SCEVExpander which my introduce incompatible forms of min/max
317fe6060f1SDimitry Andric   // for pointer types.
318fe6060f1SDimitry Andric   if (I->getType()->isIntegerTy())
319fe6060f1SDimitry Andric     if ((ResI = matchAndReassociateMinOrMax<umin_pred_ty>(I, OrigSCEV)) ||
320fe6060f1SDimitry Andric         (ResI = matchAndReassociateMinOrMax<smin_pred_ty>(I, OrigSCEV)) ||
321fe6060f1SDimitry Andric         (ResI = matchAndReassociateMinOrMax<umax_pred_ty>(I, OrigSCEV)) ||
322fe6060f1SDimitry Andric         (ResI = matchAndReassociateMinOrMax<smax_pred_ty>(I, OrigSCEV)))
323fe6060f1SDimitry Andric       return ResI;
324fe6060f1SDimitry Andric 
325e8d8bef9SDimitry Andric   return nullptr;
3260b57cec5SDimitry Andric }
3270b57cec5SDimitry Andric 
isGEPFoldable(GetElementPtrInst * GEP,const TargetTransformInfo * TTI)3280b57cec5SDimitry Andric static bool isGEPFoldable(GetElementPtrInst *GEP,
3290b57cec5SDimitry Andric                           const TargetTransformInfo *TTI) {
330e8d8bef9SDimitry Andric   SmallVector<const Value *, 4> Indices(GEP->indices());
3310b57cec5SDimitry Andric   return TTI->getGEPCost(GEP->getSourceElementType(), GEP->getPointerOperand(),
3320b57cec5SDimitry Andric                          Indices) == TargetTransformInfo::TCC_Free;
3330b57cec5SDimitry Andric }
3340b57cec5SDimitry Andric 
tryReassociateGEP(GetElementPtrInst * GEP)3350b57cec5SDimitry Andric Instruction *NaryReassociatePass::tryReassociateGEP(GetElementPtrInst *GEP) {
3360b57cec5SDimitry Andric   // Not worth reassociating GEP if it is foldable.
3370b57cec5SDimitry Andric   if (isGEPFoldable(GEP, TTI))
3380b57cec5SDimitry Andric     return nullptr;
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   gep_type_iterator GTI = gep_type_begin(*GEP);
3410b57cec5SDimitry Andric   for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
3420b57cec5SDimitry Andric     if (GTI.isSequential()) {
3430b57cec5SDimitry Andric       if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1,
3440b57cec5SDimitry Andric                                                   GTI.getIndexedType())) {
3450b57cec5SDimitry Andric         return NewGEP;
3460b57cec5SDimitry Andric       }
3470b57cec5SDimitry Andric     }
3480b57cec5SDimitry Andric   }
3490b57cec5SDimitry Andric   return nullptr;
3500b57cec5SDimitry Andric }
3510b57cec5SDimitry Andric 
requiresSignExtension(Value * Index,GetElementPtrInst * GEP)3520b57cec5SDimitry Andric bool NaryReassociatePass::requiresSignExtension(Value *Index,
3530b57cec5SDimitry Andric                                                 GetElementPtrInst *GEP) {
35406c3fb27SDimitry Andric   unsigned IndexSizeInBits =
35506c3fb27SDimitry Andric       DL->getIndexSizeInBits(GEP->getType()->getPointerAddressSpace());
35606c3fb27SDimitry Andric   return cast<IntegerType>(Index->getType())->getBitWidth() < IndexSizeInBits;
3570b57cec5SDimitry Andric }
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric GetElementPtrInst *
tryReassociateGEPAtIndex(GetElementPtrInst * GEP,unsigned I,Type * IndexedType)3600b57cec5SDimitry Andric NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
3610b57cec5SDimitry Andric                                               unsigned I, Type *IndexedType) {
3625f757f3fSDimitry Andric   SimplifyQuery SQ(*DL, DT, AC, GEP);
3630b57cec5SDimitry Andric   Value *IndexToSplit = GEP->getOperand(I + 1);
3640b57cec5SDimitry Andric   if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit)) {
3650b57cec5SDimitry Andric     IndexToSplit = SExt->getOperand(0);
3660b57cec5SDimitry Andric   } else if (ZExtInst *ZExt = dyn_cast<ZExtInst>(IndexToSplit)) {
3670b57cec5SDimitry Andric     // zext can be treated as sext if the source is non-negative.
3685f757f3fSDimitry Andric     if (isKnownNonNegative(ZExt->getOperand(0), SQ))
3690b57cec5SDimitry Andric       IndexToSplit = ZExt->getOperand(0);
3700b57cec5SDimitry Andric   }
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric   if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) {
3730b57cec5SDimitry Andric     // If the I-th index needs sext and the underlying add is not equipped with
3740b57cec5SDimitry Andric     // nsw, we cannot split the add because
3750b57cec5SDimitry Andric     //   sext(LHS + RHS) != sext(LHS) + sext(RHS).
3760b57cec5SDimitry Andric     if (requiresSignExtension(IndexToSplit, GEP) &&
3775f757f3fSDimitry Andric         computeOverflowForSignedAdd(AO, SQ) != OverflowResult::NeverOverflows)
3780b57cec5SDimitry Andric       return nullptr;
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric     Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1);
3810b57cec5SDimitry Andric     // IndexToSplit = LHS + RHS.
3820b57cec5SDimitry Andric     if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType))
3830b57cec5SDimitry Andric       return NewGEP;
3840b57cec5SDimitry Andric     // Symmetrically, try IndexToSplit = RHS + LHS.
3850b57cec5SDimitry Andric     if (LHS != RHS) {
3860b57cec5SDimitry Andric       if (auto *NewGEP =
3870b57cec5SDimitry Andric               tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType))
3880b57cec5SDimitry Andric         return NewGEP;
3890b57cec5SDimitry Andric     }
3900b57cec5SDimitry Andric   }
3910b57cec5SDimitry Andric   return nullptr;
3920b57cec5SDimitry Andric }
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric GetElementPtrInst *
tryReassociateGEPAtIndex(GetElementPtrInst * GEP,unsigned I,Value * LHS,Value * RHS,Type * IndexedType)3950b57cec5SDimitry Andric NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
3960b57cec5SDimitry Andric                                               unsigned I, Value *LHS,
3970b57cec5SDimitry Andric                                               Value *RHS, Type *IndexedType) {
3980b57cec5SDimitry Andric   // Look for GEP's closest dominator that has the same SCEV as GEP except that
3990b57cec5SDimitry Andric   // the I-th index is replaced with LHS.
4000b57cec5SDimitry Andric   SmallVector<const SCEV *, 4> IndexExprs;
401fe6060f1SDimitry Andric   for (Use &Index : GEP->indices())
402fe6060f1SDimitry Andric     IndexExprs.push_back(SE->getSCEV(Index));
4030b57cec5SDimitry Andric   // Replace the I-th index with LHS.
4040b57cec5SDimitry Andric   IndexExprs[I] = SE->getSCEV(LHS);
4055f757f3fSDimitry Andric   if (isKnownNonNegative(LHS, SimplifyQuery(*DL, DT, AC, GEP)) &&
406bdd1243dSDimitry Andric       DL->getTypeSizeInBits(LHS->getType()).getFixedValue() <
407bdd1243dSDimitry Andric           DL->getTypeSizeInBits(GEP->getOperand(I)->getType())
408bdd1243dSDimitry Andric               .getFixedValue()) {
4090b57cec5SDimitry Andric     // Zero-extend LHS if it is non-negative. InstCombine canonicalizes sext to
4100b57cec5SDimitry Andric     // zext if the source operand is proved non-negative. We should do that
4110b57cec5SDimitry Andric     // consistently so that CandidateExpr more likely appears before. See
4120b57cec5SDimitry Andric     // @reassociate_gep_assume for an example of this canonicalization.
4130b57cec5SDimitry Andric     IndexExprs[I] =
4140b57cec5SDimitry Andric         SE->getZeroExtendExpr(IndexExprs[I], GEP->getOperand(I)->getType());
4150b57cec5SDimitry Andric   }
4160b57cec5SDimitry Andric   const SCEV *CandidateExpr = SE->getGEPExpr(cast<GEPOperator>(GEP),
4170b57cec5SDimitry Andric                                              IndexExprs);
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric   Value *Candidate = findClosestMatchingDominator(CandidateExpr, GEP);
4200b57cec5SDimitry Andric   if (Candidate == nullptr)
4210b57cec5SDimitry Andric     return nullptr;
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   IRBuilder<> Builder(GEP);
4240b57cec5SDimitry Andric   // Candidate does not necessarily have the same pointer type as GEP. Use
4250b57cec5SDimitry Andric   // bitcast or pointer cast to make sure they have the same type, so that the
4260b57cec5SDimitry Andric   // later RAUW doesn't complain.
4270b57cec5SDimitry Andric   Candidate = Builder.CreateBitOrPointerCast(Candidate, GEP->getType());
4280b57cec5SDimitry Andric   assert(Candidate->getType() == GEP->getType());
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType)
4310b57cec5SDimitry Andric   uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType);
4320b57cec5SDimitry Andric   Type *ElementType = GEP->getResultElementType();
4330b57cec5SDimitry Andric   uint64_t ElementSize = DL->getTypeAllocSize(ElementType);
4340b57cec5SDimitry Andric   // Another less rare case: because I is not necessarily the last index of the
4350b57cec5SDimitry Andric   // GEP, the size of the type at the I-th index (IndexedSize) is not
4360b57cec5SDimitry Andric   // necessarily divisible by ElementSize. For example,
4370b57cec5SDimitry Andric   //
4380b57cec5SDimitry Andric   // #pragma pack(1)
4390b57cec5SDimitry Andric   // struct S {
4400b57cec5SDimitry Andric   //   int a[3];
4410b57cec5SDimitry Andric   //   int64 b[8];
4420b57cec5SDimitry Andric   // };
4430b57cec5SDimitry Andric   // #pragma pack()
4440b57cec5SDimitry Andric   //
4450b57cec5SDimitry Andric   // sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
4460b57cec5SDimitry Andric   //
4470b57cec5SDimitry Andric   // TODO: bail out on this case for now. We could emit uglygep.
4480b57cec5SDimitry Andric   if (IndexedSize % ElementSize != 0)
4490b57cec5SDimitry Andric     return nullptr;
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric   // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
45206c3fb27SDimitry Andric   Type *PtrIdxTy = DL->getIndexType(GEP->getType());
45306c3fb27SDimitry Andric   if (RHS->getType() != PtrIdxTy)
45406c3fb27SDimitry Andric     RHS = Builder.CreateSExtOrTrunc(RHS, PtrIdxTy);
4550b57cec5SDimitry Andric   if (IndexedSize != ElementSize) {
4560b57cec5SDimitry Andric     RHS = Builder.CreateMul(
45706c3fb27SDimitry Andric         RHS, ConstantInt::get(PtrIdxTy, IndexedSize / ElementSize));
4580b57cec5SDimitry Andric   }
4590b57cec5SDimitry Andric   GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(
4600b57cec5SDimitry Andric       Builder.CreateGEP(GEP->getResultElementType(), Candidate, RHS));
4610b57cec5SDimitry Andric   NewGEP->setIsInBounds(GEP->isInBounds());
4620b57cec5SDimitry Andric   NewGEP->takeName(GEP);
4630b57cec5SDimitry Andric   return NewGEP;
4640b57cec5SDimitry Andric }
4650b57cec5SDimitry Andric 
tryReassociateBinaryOp(BinaryOperator * I)4660b57cec5SDimitry Andric Instruction *NaryReassociatePass::tryReassociateBinaryOp(BinaryOperator *I) {
4670b57cec5SDimitry Andric   Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
4680b57cec5SDimitry Andric   // There is no need to reassociate 0.
4690b57cec5SDimitry Andric   if (SE->getSCEV(I)->isZero())
4700b57cec5SDimitry Andric     return nullptr;
4710b57cec5SDimitry Andric   if (auto *NewI = tryReassociateBinaryOp(LHS, RHS, I))
4720b57cec5SDimitry Andric     return NewI;
4730b57cec5SDimitry Andric   if (auto *NewI = tryReassociateBinaryOp(RHS, LHS, I))
4740b57cec5SDimitry Andric     return NewI;
4750b57cec5SDimitry Andric   return nullptr;
4760b57cec5SDimitry Andric }
4770b57cec5SDimitry Andric 
tryReassociateBinaryOp(Value * LHS,Value * RHS,BinaryOperator * I)4780b57cec5SDimitry Andric Instruction *NaryReassociatePass::tryReassociateBinaryOp(Value *LHS, Value *RHS,
4790b57cec5SDimitry Andric                                                          BinaryOperator *I) {
4800b57cec5SDimitry Andric   Value *A = nullptr, *B = nullptr;
4810b57cec5SDimitry Andric   // To be conservative, we reassociate I only when it is the only user of (A op
4820b57cec5SDimitry Andric   // B).
4830b57cec5SDimitry Andric   if (LHS->hasOneUse() && matchTernaryOp(I, LHS, A, B)) {
4840b57cec5SDimitry Andric     // I = (A op B) op RHS
4850b57cec5SDimitry Andric     //   = (A op RHS) op B or (B op RHS) op A
4860b57cec5SDimitry Andric     const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
4870b57cec5SDimitry Andric     const SCEV *RHSExpr = SE->getSCEV(RHS);
4880b57cec5SDimitry Andric     if (BExpr != RHSExpr) {
4890b57cec5SDimitry Andric       if (auto *NewI =
4900b57cec5SDimitry Andric               tryReassociatedBinaryOp(getBinarySCEV(I, AExpr, RHSExpr), B, I))
4910b57cec5SDimitry Andric         return NewI;
4920b57cec5SDimitry Andric     }
4930b57cec5SDimitry Andric     if (AExpr != RHSExpr) {
4940b57cec5SDimitry Andric       if (auto *NewI =
4950b57cec5SDimitry Andric               tryReassociatedBinaryOp(getBinarySCEV(I, BExpr, RHSExpr), A, I))
4960b57cec5SDimitry Andric         return NewI;
4970b57cec5SDimitry Andric     }
4980b57cec5SDimitry Andric   }
4990b57cec5SDimitry Andric   return nullptr;
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric 
tryReassociatedBinaryOp(const SCEV * LHSExpr,Value * RHS,BinaryOperator * I)5020b57cec5SDimitry Andric Instruction *NaryReassociatePass::tryReassociatedBinaryOp(const SCEV *LHSExpr,
5030b57cec5SDimitry Andric                                                           Value *RHS,
5040b57cec5SDimitry Andric                                                           BinaryOperator *I) {
5050b57cec5SDimitry Andric   // Look for the closest dominator LHS of I that computes LHSExpr, and replace
5060b57cec5SDimitry Andric   // I with LHS op RHS.
5070b57cec5SDimitry Andric   auto *LHS = findClosestMatchingDominator(LHSExpr, I);
5080b57cec5SDimitry Andric   if (LHS == nullptr)
5090b57cec5SDimitry Andric     return nullptr;
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric   Instruction *NewI = nullptr;
5120b57cec5SDimitry Andric   switch (I->getOpcode()) {
5130b57cec5SDimitry Andric   case Instruction::Add:
514*0fca6ea1SDimitry Andric     NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I->getIterator());
5150b57cec5SDimitry Andric     break;
5160b57cec5SDimitry Andric   case Instruction::Mul:
517*0fca6ea1SDimitry Andric     NewI = BinaryOperator::CreateMul(LHS, RHS, "", I->getIterator());
5180b57cec5SDimitry Andric     break;
5190b57cec5SDimitry Andric   default:
5200b57cec5SDimitry Andric     llvm_unreachable("Unexpected instruction.");
5210b57cec5SDimitry Andric   }
522*0fca6ea1SDimitry Andric   NewI->setDebugLoc(I->getDebugLoc());
5230b57cec5SDimitry Andric   NewI->takeName(I);
5240b57cec5SDimitry Andric   return NewI;
5250b57cec5SDimitry Andric }
5260b57cec5SDimitry Andric 
matchTernaryOp(BinaryOperator * I,Value * V,Value * & Op1,Value * & Op2)5270b57cec5SDimitry Andric bool NaryReassociatePass::matchTernaryOp(BinaryOperator *I, Value *V,
5280b57cec5SDimitry Andric                                          Value *&Op1, Value *&Op2) {
5290b57cec5SDimitry Andric   switch (I->getOpcode()) {
5300b57cec5SDimitry Andric   case Instruction::Add:
5310b57cec5SDimitry Andric     return match(V, m_Add(m_Value(Op1), m_Value(Op2)));
5320b57cec5SDimitry Andric   case Instruction::Mul:
5330b57cec5SDimitry Andric     return match(V, m_Mul(m_Value(Op1), m_Value(Op2)));
5340b57cec5SDimitry Andric   default:
5350b57cec5SDimitry Andric     llvm_unreachable("Unexpected instruction.");
5360b57cec5SDimitry Andric   }
5370b57cec5SDimitry Andric   return false;
5380b57cec5SDimitry Andric }
5390b57cec5SDimitry Andric 
getBinarySCEV(BinaryOperator * I,const SCEV * LHS,const SCEV * RHS)5400b57cec5SDimitry Andric const SCEV *NaryReassociatePass::getBinarySCEV(BinaryOperator *I,
5410b57cec5SDimitry Andric                                                const SCEV *LHS,
5420b57cec5SDimitry Andric                                                const SCEV *RHS) {
5430b57cec5SDimitry Andric   switch (I->getOpcode()) {
5440b57cec5SDimitry Andric   case Instruction::Add:
5450b57cec5SDimitry Andric     return SE->getAddExpr(LHS, RHS);
5460b57cec5SDimitry Andric   case Instruction::Mul:
5470b57cec5SDimitry Andric     return SE->getMulExpr(LHS, RHS);
5480b57cec5SDimitry Andric   default:
5490b57cec5SDimitry Andric     llvm_unreachable("Unexpected instruction.");
5500b57cec5SDimitry Andric   }
5510b57cec5SDimitry Andric   return nullptr;
5520b57cec5SDimitry Andric }
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric Instruction *
findClosestMatchingDominator(const SCEV * CandidateExpr,Instruction * Dominatee)5550b57cec5SDimitry Andric NaryReassociatePass::findClosestMatchingDominator(const SCEV *CandidateExpr,
5560b57cec5SDimitry Andric                                                   Instruction *Dominatee) {
5570b57cec5SDimitry Andric   auto Pos = SeenExprs.find(CandidateExpr);
5580b57cec5SDimitry Andric   if (Pos == SeenExprs.end())
5590b57cec5SDimitry Andric     return nullptr;
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric   auto &Candidates = Pos->second;
5620b57cec5SDimitry Andric   // Because we process the basic blocks in pre-order of the dominator tree, a
5630b57cec5SDimitry Andric   // candidate that doesn't dominate the current instruction won't dominate any
5640b57cec5SDimitry Andric   // future instruction either. Therefore, we pop it out of the stack. This
5650b57cec5SDimitry Andric   // optimization makes the algorithm O(n).
5660b57cec5SDimitry Andric   while (!Candidates.empty()) {
5670b57cec5SDimitry Andric     // Candidates stores WeakTrackingVHs, so a candidate can be nullptr if it's
568*0fca6ea1SDimitry Andric     // removed during rewriting.
569*0fca6ea1SDimitry Andric     if (Value *Candidate = Candidates.pop_back_val()) {
5700b57cec5SDimitry Andric       Instruction *CandidateInstruction = cast<Instruction>(Candidate);
571*0fca6ea1SDimitry Andric       if (!DT->dominates(CandidateInstruction, Dominatee))
572*0fca6ea1SDimitry Andric         continue;
573*0fca6ea1SDimitry Andric 
574*0fca6ea1SDimitry Andric       // Make sure that the instruction is safe to reuse without introducing
575*0fca6ea1SDimitry Andric       // poison.
576*0fca6ea1SDimitry Andric       SmallVector<Instruction *> DropPoisonGeneratingInsts;
577*0fca6ea1SDimitry Andric       if (!SE->canReuseInstruction(CandidateExpr, CandidateInstruction,
578*0fca6ea1SDimitry Andric                                    DropPoisonGeneratingInsts))
579*0fca6ea1SDimitry Andric         continue;
580*0fca6ea1SDimitry Andric 
581*0fca6ea1SDimitry Andric       for (Instruction *I : DropPoisonGeneratingInsts)
582*0fca6ea1SDimitry Andric         I->dropPoisonGeneratingAnnotations();
583*0fca6ea1SDimitry Andric 
5840b57cec5SDimitry Andric       return CandidateInstruction;
5850b57cec5SDimitry Andric     }
5860b57cec5SDimitry Andric   }
5870b57cec5SDimitry Andric   return nullptr;
5880b57cec5SDimitry Andric }
589fe6060f1SDimitry Andric 
convertToSCEVype(MaxMinT & MM)590fe6060f1SDimitry Andric template <typename MaxMinT> static SCEVTypes convertToSCEVype(MaxMinT &MM) {
591bdd1243dSDimitry Andric   if (std::is_same_v<smax_pred_ty, typename MaxMinT::PredType>)
592fe6060f1SDimitry Andric     return scSMaxExpr;
593bdd1243dSDimitry Andric   else if (std::is_same_v<umax_pred_ty, typename MaxMinT::PredType>)
594fe6060f1SDimitry Andric     return scUMaxExpr;
595bdd1243dSDimitry Andric   else if (std::is_same_v<smin_pred_ty, typename MaxMinT::PredType>)
596fe6060f1SDimitry Andric     return scSMinExpr;
597bdd1243dSDimitry Andric   else if (std::is_same_v<umin_pred_ty, typename MaxMinT::PredType>)
598fe6060f1SDimitry Andric     return scUMinExpr;
599fe6060f1SDimitry Andric 
600fe6060f1SDimitry Andric   llvm_unreachable("Can't convert MinMax pattern to SCEV type");
601fe6060f1SDimitry Andric   return scUnknown;
602fe6060f1SDimitry Andric }
603fe6060f1SDimitry Andric 
604fe6060f1SDimitry Andric // Parameters:
605fe6060f1SDimitry Andric //  I - instruction matched by MaxMinMatch matcher
606fe6060f1SDimitry Andric //  MaxMinMatch - min/max idiom matcher
607fe6060f1SDimitry Andric //  LHS - first operand of I
608fe6060f1SDimitry Andric //  RHS - second operand of I
609fe6060f1SDimitry Andric template <typename MaxMinT>
tryReassociateMinOrMax(Instruction * I,MaxMinT MaxMinMatch,Value * LHS,Value * RHS)610fe6060f1SDimitry Andric Value *NaryReassociatePass::tryReassociateMinOrMax(Instruction *I,
611fe6060f1SDimitry Andric                                                    MaxMinT MaxMinMatch,
612fe6060f1SDimitry Andric                                                    Value *LHS, Value *RHS) {
613fe6060f1SDimitry Andric   Value *A = nullptr, *B = nullptr;
614fe6060f1SDimitry Andric   MaxMinT m_MaxMin(m_Value(A), m_Value(B));
615fe6060f1SDimitry Andric 
616349cc55cSDimitry Andric   if (LHS->hasNUsesOrMore(3) ||
617fe6060f1SDimitry Andric       // The optimization is profitable only if LHS can be removed in the end.
618fe6060f1SDimitry Andric       // In other words LHS should be used (directly or indirectly) by I only.
619349cc55cSDimitry Andric       llvm::any_of(LHS->users(),
620349cc55cSDimitry Andric                     [&](auto *U) {
621349cc55cSDimitry Andric                       return U != I &&
622349cc55cSDimitry Andric                              !(U->hasOneUser() && *U->users().begin() == I);
623349cc55cSDimitry Andric                     }) ||
624349cc55cSDimitry Andric       !match(LHS, m_MaxMin))
625349cc55cSDimitry Andric     return nullptr;
626fe6060f1SDimitry Andric 
627349cc55cSDimitry Andric   auto tryCombination = [&](Value *A, const SCEV *AExpr, Value *B,
628349cc55cSDimitry Andric                             const SCEV *BExpr, Value *C,
629349cc55cSDimitry Andric                             const SCEV *CExpr) -> Value * {
630fe6060f1SDimitry Andric     SmallVector<const SCEV *, 2> Ops1{BExpr, AExpr};
631fe6060f1SDimitry Andric     const SCEVTypes SCEVType = convertToSCEVype(m_MaxMin);
632fe6060f1SDimitry Andric     const SCEV *R1Expr = SE->getMinMaxExpr(SCEVType, Ops1);
633fe6060f1SDimitry Andric 
634fe6060f1SDimitry Andric     Instruction *R1MinMax = findClosestMatchingDominator(R1Expr, I);
635fe6060f1SDimitry Andric 
636fe6060f1SDimitry Andric     if (!R1MinMax)
637349cc55cSDimitry Andric       return nullptr;
638fe6060f1SDimitry Andric 
639349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "NARY: Found common sub-expr: " << *R1MinMax << "\n");
640fe6060f1SDimitry Andric 
641349cc55cSDimitry Andric     SmallVector<const SCEV *, 2> Ops2{SE->getUnknown(C),
642349cc55cSDimitry Andric                                       SE->getUnknown(R1MinMax)};
643fe6060f1SDimitry Andric     const SCEV *R2Expr = SE->getMinMaxExpr(SCEVType, Ops2);
644fe6060f1SDimitry Andric 
645349cc55cSDimitry Andric     SCEVExpander Expander(*SE, *DL, "nary-reassociate");
646fe6060f1SDimitry Andric     Value *NewMinMax = Expander.expandCodeFor(R2Expr, I->getType(), I);
647fe6060f1SDimitry Andric     NewMinMax->setName(Twine(I->getName()).concat(".nary"));
648fe6060f1SDimitry Andric 
649fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "NARY: Deleting:  " << *I << "\n"
650fe6060f1SDimitry Andric                       << "NARY: Inserting: " << *NewMinMax << "\n");
651fe6060f1SDimitry Andric     return NewMinMax;
652349cc55cSDimitry Andric   };
653349cc55cSDimitry Andric 
654349cc55cSDimitry Andric   const SCEV *AExpr = SE->getSCEV(A);
655349cc55cSDimitry Andric   const SCEV *BExpr = SE->getSCEV(B);
656349cc55cSDimitry Andric   const SCEV *RHSExpr = SE->getSCEV(RHS);
657349cc55cSDimitry Andric 
658349cc55cSDimitry Andric   if (BExpr != RHSExpr) {
659349cc55cSDimitry Andric     // Try (A op RHS) op B
660349cc55cSDimitry Andric     if (auto *NewMinMax = tryCombination(A, AExpr, RHS, RHSExpr, B, BExpr))
661349cc55cSDimitry Andric       return NewMinMax;
662fe6060f1SDimitry Andric   }
663349cc55cSDimitry Andric 
664349cc55cSDimitry Andric   if (AExpr != RHSExpr) {
665349cc55cSDimitry Andric     // Try (RHS op B) op A
666349cc55cSDimitry Andric     if (auto *NewMinMax = tryCombination(RHS, RHSExpr, B, BExpr, A, AExpr))
667349cc55cSDimitry Andric       return NewMinMax;
668fe6060f1SDimitry Andric   }
669349cc55cSDimitry Andric 
670fe6060f1SDimitry Andric   return nullptr;
671fe6060f1SDimitry Andric }
672