diff --git a/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp b/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp --- a/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp +++ b/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp @@ -1964,6 +1964,10 @@ /// SmallDenseSet. SetVector, SmallSet> Factors; + /// Baseline costfor currently used SCEV. Drop the best solution by LSR if the + /// solution is not profitable. + Cost BaselineCost; + /// Interesting use types, to facilitate truncation reuse. SmallSetVector Types; @@ -3288,6 +3292,10 @@ BranchInst *ExitBranch = nullptr; bool SaveCmp = TTI.canSaveCmp(L, &ExitBranch, &SE, &LI, &DT, &AC, &TLI); + // For calculating InitialSolutionCost + SmallPtrSet Regs; + DenseSet VisitedRegs; + for (const IVStrideUse &U : IU) { Instruction *UserInst = U.getUser(); // Skip IV users that are part of profitable IV Chains. @@ -3358,6 +3366,12 @@ int64_t Offset = P.second; LSRUse &LU = Uses[LUIdx]; + // Create initial SCEV as Formula for baseline cost + Formula F; + F.initialMatch(S, L, SE); + if (!BaselineCost.isLoser()) + BaselineCost.RateFormula(F, Regs, VisitedRegs, LU); + // Record the fixup. LSRFixup &LF = LU.getNewFixup(); LF.UserInst = UserInst; @@ -5141,6 +5155,18 @@ }); assert(Solution.size() == Uses.size() && "Malformed solution!"); + + if (!SolutionCost.isLess(const_cast(BaselineCost))) { + LLVM_DEBUG(dbgs() << "\n" + "The baseline solution requires "; + BaselineCost.print(dbgs()); dbgs() << "\n";); + + LLVM_DEBUG( + dbgs() + << "Baseline solution is more profitable than chosen solution.\n"); + LLVM_DEBUG(dbgs() << "Dropping LSR chosen solution.\n"); + Solution.clear(); + } } /// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as @@ -5715,8 +5741,10 @@ const TargetTransformInfo &TTI, AssumptionCache &AC, TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU) : IU(IU), SE(SE), DT(DT), LI(LI), AC(AC), TLI(TLI), TTI(TTI), L(L), - MSSAU(MSSAU), AMK(PreferredAddresingMode.getNumOccurrences() > 0 ? - PreferredAddresingMode : TTI.getPreferredAddressingMode(L, &SE)) { + MSSAU(MSSAU), AMK(PreferredAddresingMode.getNumOccurrences() > 0 + ? PreferredAddresingMode + : TTI.getPreferredAddressingMode(L, &SE)), + BaselineCost(L, SE, TTI, AMK) { // If LoopSimplify form is not available, stay out of trouble. if (!L->isLoopSimplifyForm()) return;