10b57cec5SDimitry Andric //===- AggressiveInstCombine.cpp ------------------------------------------===//
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 file implements the aggressive expression pattern combiner classes.
100b57cec5SDimitry Andric // Currently, it handles expression patterns for:
110b57cec5SDimitry Andric //  * Truncate instruction
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
160b57cec5SDimitry Andric #include "AggressiveInstCombineInternal.h"
175ffd83dbSDimitry Andric #include "llvm/ADT/Statistic.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
19349cc55cSDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/BasicAliasAnalysis.h"
2106c3fb27SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
2481ad6265SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
25e8d8bef9SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
26bdd1243dSDimitry Andric #include "llvm/IR/DataLayout.h"
270b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
28e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
290b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
300b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
31972a253aSDimitry Andric #include "llvm/Transforms/Utils/BuildLibCalls.h"
320b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
335ffd83dbSDimitry Andric 
340b57cec5SDimitry Andric using namespace llvm;
350b57cec5SDimitry Andric using namespace PatternMatch;
360b57cec5SDimitry Andric 
370b57cec5SDimitry Andric #define DEBUG_TYPE "aggressive-instcombine"
380b57cec5SDimitry Andric 
395ffd83dbSDimitry Andric STATISTIC(NumAnyOrAllBitsSet, "Number of any/all-bits-set patterns folded");
405ffd83dbSDimitry Andric STATISTIC(NumGuardedRotates,
415ffd83dbSDimitry Andric           "Number of guarded rotates transformed into funnel shifts");
42e8d8bef9SDimitry Andric STATISTIC(NumGuardedFunnelShifts,
43e8d8bef9SDimitry Andric           "Number of guarded funnel shifts transformed into funnel shifts");
445ffd83dbSDimitry Andric STATISTIC(NumPopCountRecognized, "Number of popcount idioms recognized");
455ffd83dbSDimitry Andric 
46bdd1243dSDimitry Andric static cl::opt<unsigned> MaxInstrsToScan(
47bdd1243dSDimitry Andric     "aggressive-instcombine-max-scan-instrs", cl::init(64), cl::Hidden,
48bdd1243dSDimitry Andric     cl::desc("Max number of instructions to scan for aggressive instcombine."));
490b57cec5SDimitry Andric 
50e8d8bef9SDimitry Andric /// Match a pattern for a bitwise funnel/rotate operation that partially guards
51e8d8bef9SDimitry Andric /// against undefined behavior by branching around the funnel-shift/rotation
52e8d8bef9SDimitry Andric /// when the shift amount is 0.
foldGuardedFunnelShift(Instruction & I,const DominatorTree & DT)53e8d8bef9SDimitry Andric static bool foldGuardedFunnelShift(Instruction &I, const DominatorTree &DT) {
540b57cec5SDimitry Andric   if (I.getOpcode() != Instruction::PHI || I.getNumOperands() != 2)
550b57cec5SDimitry Andric     return false;
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric   // As with the one-use checks below, this is not strictly necessary, but we
580b57cec5SDimitry Andric   // are being cautious to avoid potential perf regressions on targets that
59e8d8bef9SDimitry Andric   // do not actually have a funnel/rotate instruction (where the funnel shift
60e8d8bef9SDimitry Andric   // would be expanded back into math/shift/logic ops).
610b57cec5SDimitry Andric   if (!isPowerOf2_32(I.getType()->getScalarSizeInBits()))
620b57cec5SDimitry Andric     return false;
630b57cec5SDimitry Andric 
64e8d8bef9SDimitry Andric   // Match V to funnel shift left/right and capture the source operands and
65e8d8bef9SDimitry Andric   // shift amount.
66e8d8bef9SDimitry Andric   auto matchFunnelShift = [](Value *V, Value *&ShVal0, Value *&ShVal1,
67e8d8bef9SDimitry Andric                              Value *&ShAmt) {
680b57cec5SDimitry Andric     unsigned Width = V->getType()->getScalarSizeInBits();
690b57cec5SDimitry Andric 
70e8d8bef9SDimitry Andric     // fshl(ShVal0, ShVal1, ShAmt)
71e8d8bef9SDimitry Andric     //  == (ShVal0 << ShAmt) | (ShVal1 >> (Width -ShAmt))
72e8d8bef9SDimitry Andric     if (match(V, m_OneUse(m_c_Or(
73e8d8bef9SDimitry Andric                      m_Shl(m_Value(ShVal0), m_Value(ShAmt)),
74e8d8bef9SDimitry Andric                      m_LShr(m_Value(ShVal1),
7506c3fb27SDimitry Andric                             m_Sub(m_SpecificInt(Width), m_Deferred(ShAmt))))))) {
760b57cec5SDimitry Andric         return Intrinsic::fshl;
770b57cec5SDimitry Andric     }
780b57cec5SDimitry Andric 
79e8d8bef9SDimitry Andric     // fshr(ShVal0, ShVal1, ShAmt)
80e8d8bef9SDimitry Andric     //  == (ShVal0 >> ShAmt) | (ShVal1 << (Width - ShAmt))
81e8d8bef9SDimitry Andric     if (match(V,
82e8d8bef9SDimitry Andric               m_OneUse(m_c_Or(m_Shl(m_Value(ShVal0), m_Sub(m_SpecificInt(Width),
8306c3fb27SDimitry Andric                                                            m_Value(ShAmt))),
8406c3fb27SDimitry Andric                               m_LShr(m_Value(ShVal1), m_Deferred(ShAmt)))))) {
850b57cec5SDimitry Andric         return Intrinsic::fshr;
860b57cec5SDimitry Andric     }
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric     return Intrinsic::not_intrinsic;
890b57cec5SDimitry Andric   };
900b57cec5SDimitry Andric 
91e8d8bef9SDimitry Andric   // One phi operand must be a funnel/rotate operation, and the other phi
92e8d8bef9SDimitry Andric   // operand must be the source value of that funnel/rotate operation:
93e8d8bef9SDimitry Andric   // phi [ rotate(RotSrc, ShAmt), FunnelBB ], [ RotSrc, GuardBB ]
94e8d8bef9SDimitry Andric   // phi [ fshl(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal0, GuardBB ]
95e8d8bef9SDimitry Andric   // phi [ fshr(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal1, GuardBB ]
960b57cec5SDimitry Andric   PHINode &Phi = cast<PHINode>(I);
97e8d8bef9SDimitry Andric   unsigned FunnelOp = 0, GuardOp = 1;
980b57cec5SDimitry Andric   Value *P0 = Phi.getOperand(0), *P1 = Phi.getOperand(1);
99e8d8bef9SDimitry Andric   Value *ShVal0, *ShVal1, *ShAmt;
100e8d8bef9SDimitry Andric   Intrinsic::ID IID = matchFunnelShift(P0, ShVal0, ShVal1, ShAmt);
101e8d8bef9SDimitry Andric   if (IID == Intrinsic::not_intrinsic ||
102e8d8bef9SDimitry Andric       (IID == Intrinsic::fshl && ShVal0 != P1) ||
103e8d8bef9SDimitry Andric       (IID == Intrinsic::fshr && ShVal1 != P1)) {
104e8d8bef9SDimitry Andric     IID = matchFunnelShift(P1, ShVal0, ShVal1, ShAmt);
105e8d8bef9SDimitry Andric     if (IID == Intrinsic::not_intrinsic ||
106e8d8bef9SDimitry Andric         (IID == Intrinsic::fshl && ShVal0 != P0) ||
107e8d8bef9SDimitry Andric         (IID == Intrinsic::fshr && ShVal1 != P0))
1080b57cec5SDimitry Andric       return false;
1090b57cec5SDimitry Andric     assert((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
1100b57cec5SDimitry Andric            "Pattern must match funnel shift left or right");
111e8d8bef9SDimitry Andric     std::swap(FunnelOp, GuardOp);
1120b57cec5SDimitry Andric   }
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric   // The incoming block with our source operand must be the "guard" block.
115e8d8bef9SDimitry Andric   // That must contain a cmp+branch to avoid the funnel/rotate when the shift
116e8d8bef9SDimitry Andric   // amount is equal to 0. The other incoming block is the block with the
117e8d8bef9SDimitry Andric   // funnel/rotate.
118e8d8bef9SDimitry Andric   BasicBlock *GuardBB = Phi.getIncomingBlock(GuardOp);
119e8d8bef9SDimitry Andric   BasicBlock *FunnelBB = Phi.getIncomingBlock(FunnelOp);
1200b57cec5SDimitry Andric   Instruction *TermI = GuardBB->getTerminator();
121e8d8bef9SDimitry Andric 
122e8d8bef9SDimitry Andric   // Ensure that the shift values dominate each block.
123e8d8bef9SDimitry Andric   if (!DT.dominates(ShVal0, TermI) || !DT.dominates(ShVal1, TermI))
124e8d8bef9SDimitry Andric     return false;
125e8d8bef9SDimitry Andric 
1260b57cec5SDimitry Andric   ICmpInst::Predicate Pred;
1278bcb0991SDimitry Andric   BasicBlock *PhiBB = Phi.getParent();
128e8d8bef9SDimitry Andric   if (!match(TermI, m_Br(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()),
129e8d8bef9SDimitry Andric                          m_SpecificBB(PhiBB), m_SpecificBB(FunnelBB))))
1300b57cec5SDimitry Andric     return false;
1310b57cec5SDimitry Andric 
1328bcb0991SDimitry Andric   if (Pred != CmpInst::ICMP_EQ)
1330b57cec5SDimitry Andric     return false;
1340b57cec5SDimitry Andric 
135e8d8bef9SDimitry Andric   IRBuilder<> Builder(PhiBB, PhiBB->getFirstInsertionPt());
136e8d8bef9SDimitry Andric 
137e8d8bef9SDimitry Andric   if (ShVal0 == ShVal1)
138e8d8bef9SDimitry Andric     ++NumGuardedRotates;
139e8d8bef9SDimitry Andric   else
140e8d8bef9SDimitry Andric     ++NumGuardedFunnelShifts;
141e8d8bef9SDimitry Andric 
142e8d8bef9SDimitry Andric   // If this is not a rotate then the select was blocking poison from the
143e8d8bef9SDimitry Andric   // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
144e8d8bef9SDimitry Andric   bool IsFshl = IID == Intrinsic::fshl;
145e8d8bef9SDimitry Andric   if (ShVal0 != ShVal1) {
146e8d8bef9SDimitry Andric     if (IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal1))
147e8d8bef9SDimitry Andric       ShVal1 = Builder.CreateFreeze(ShVal1);
148e8d8bef9SDimitry Andric     else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal0))
149e8d8bef9SDimitry Andric       ShVal0 = Builder.CreateFreeze(ShVal0);
150e8d8bef9SDimitry Andric   }
151e8d8bef9SDimitry Andric 
1520b57cec5SDimitry Andric   // We matched a variation of this IR pattern:
1530b57cec5SDimitry Andric   // GuardBB:
154e8d8bef9SDimitry Andric   //   %cmp = icmp eq i32 %ShAmt, 0
155e8d8bef9SDimitry Andric   //   br i1 %cmp, label %PhiBB, label %FunnelBB
156e8d8bef9SDimitry Andric   // FunnelBB:
157e8d8bef9SDimitry Andric   //   %sub = sub i32 32, %ShAmt
158e8d8bef9SDimitry Andric   //   %shr = lshr i32 %ShVal1, %sub
159e8d8bef9SDimitry Andric   //   %shl = shl i32 %ShVal0, %ShAmt
160e8d8bef9SDimitry Andric   //   %fsh = or i32 %shr, %shl
1610b57cec5SDimitry Andric   //   br label %PhiBB
1620b57cec5SDimitry Andric   // PhiBB:
163e8d8bef9SDimitry Andric   //   %cond = phi i32 [ %fsh, %FunnelBB ], [ %ShVal0, %GuardBB ]
1640b57cec5SDimitry Andric   // -->
165e8d8bef9SDimitry Andric   // llvm.fshl.i32(i32 %ShVal0, i32 %ShVal1, i32 %ShAmt)
1660b57cec5SDimitry Andric   Function *F = Intrinsic::getDeclaration(Phi.getModule(), IID, Phi.getType());
167e8d8bef9SDimitry Andric   Phi.replaceAllUsesWith(Builder.CreateCall(F, {ShVal0, ShVal1, ShAmt}));
1680b57cec5SDimitry Andric   return true;
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric /// This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and
1720b57cec5SDimitry Andric /// the bit indexes (Mask) needed by a masked compare. If we're matching a chain
1730b57cec5SDimitry Andric /// of 'and' ops, then we also need to capture the fact that we saw an
1740b57cec5SDimitry Andric /// "and X, 1", so that's an extra return value for that case.
1750b57cec5SDimitry Andric struct MaskOps {
17681ad6265SDimitry Andric   Value *Root = nullptr;
1770b57cec5SDimitry Andric   APInt Mask;
1780b57cec5SDimitry Andric   bool MatchAndChain;
17981ad6265SDimitry Andric   bool FoundAnd1 = false;
1800b57cec5SDimitry Andric 
MaskOpsMaskOps1810b57cec5SDimitry Andric   MaskOps(unsigned BitWidth, bool MatchAnds)
18281ad6265SDimitry Andric       : Mask(APInt::getZero(BitWidth)), MatchAndChain(MatchAnds) {}
1830b57cec5SDimitry Andric };
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric /// This is a recursive helper for foldAnyOrAllBitsSet() that walks through a
1860b57cec5SDimitry Andric /// chain of 'and' or 'or' instructions looking for shift ops of a common source
1870b57cec5SDimitry Andric /// value. Examples:
1880b57cec5SDimitry Andric ///   or (or (or X, (X >> 3)), (X >> 5)), (X >> 8)
1890b57cec5SDimitry Andric /// returns { X, 0x129 }
1900b57cec5SDimitry Andric ///   and (and (X >> 1), 1), (X >> 4)
1910b57cec5SDimitry Andric /// returns { X, 0x12 }
matchAndOrChain(Value * V,MaskOps & MOps)1920b57cec5SDimitry Andric static bool matchAndOrChain(Value *V, MaskOps &MOps) {
1930b57cec5SDimitry Andric   Value *Op0, *Op1;
1940b57cec5SDimitry Andric   if (MOps.MatchAndChain) {
1950b57cec5SDimitry Andric     // Recurse through a chain of 'and' operands. This requires an extra check
1960b57cec5SDimitry Andric     // vs. the 'or' matcher: we must find an "and X, 1" instruction somewhere
1970b57cec5SDimitry Andric     // in the chain to know that all of the high bits are cleared.
1980b57cec5SDimitry Andric     if (match(V, m_And(m_Value(Op0), m_One()))) {
1990b57cec5SDimitry Andric       MOps.FoundAnd1 = true;
2000b57cec5SDimitry Andric       return matchAndOrChain(Op0, MOps);
2010b57cec5SDimitry Andric     }
2020b57cec5SDimitry Andric     if (match(V, m_And(m_Value(Op0), m_Value(Op1))))
2030b57cec5SDimitry Andric       return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
2040b57cec5SDimitry Andric   } else {
2050b57cec5SDimitry Andric     // Recurse through a chain of 'or' operands.
2060b57cec5SDimitry Andric     if (match(V, m_Or(m_Value(Op0), m_Value(Op1))))
2070b57cec5SDimitry Andric       return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
2080b57cec5SDimitry Andric   }
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric   // We need a shift-right or a bare value representing a compare of bit 0 of
2110b57cec5SDimitry Andric   // the original source operand.
2120b57cec5SDimitry Andric   Value *Candidate;
213e8d8bef9SDimitry Andric   const APInt *BitIndex = nullptr;
214e8d8bef9SDimitry Andric   if (!match(V, m_LShr(m_Value(Candidate), m_APInt(BitIndex))))
2150b57cec5SDimitry Andric     Candidate = V;
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric   // Initialize result source operand.
2180b57cec5SDimitry Andric   if (!MOps.Root)
2190b57cec5SDimitry Andric     MOps.Root = Candidate;
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   // The shift constant is out-of-range? This code hasn't been simplified.
222e8d8bef9SDimitry Andric   if (BitIndex && BitIndex->uge(MOps.Mask.getBitWidth()))
2230b57cec5SDimitry Andric     return false;
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric   // Fill in the mask bit derived from the shift constant.
226e8d8bef9SDimitry Andric   MOps.Mask.setBit(BitIndex ? BitIndex->getZExtValue() : 0);
2270b57cec5SDimitry Andric   return MOps.Root == Candidate;
2280b57cec5SDimitry Andric }
2290b57cec5SDimitry Andric 
2300b57cec5SDimitry Andric /// Match patterns that correspond to "any-bits-set" and "all-bits-set".
2310b57cec5SDimitry Andric /// These will include a chain of 'or' or 'and'-shifted bits from a
2320b57cec5SDimitry Andric /// common source value:
2330b57cec5SDimitry Andric /// and (or  (lshr X, C), ...), 1 --> (X & CMask) != 0
2340b57cec5SDimitry Andric /// and (and (lshr X, C), ...), 1 --> (X & CMask) == CMask
2350b57cec5SDimitry Andric /// Note: "any-bits-clear" and "all-bits-clear" are variations of these patterns
2360b57cec5SDimitry Andric /// that differ only with a final 'not' of the result. We expect that final
2370b57cec5SDimitry Andric /// 'not' to be folded with the compare that we create here (invert predicate).
foldAnyOrAllBitsSet(Instruction & I)2380b57cec5SDimitry Andric static bool foldAnyOrAllBitsSet(Instruction &I) {
2390b57cec5SDimitry Andric   // The 'any-bits-set' ('or' chain) pattern is simpler to match because the
2400b57cec5SDimitry Andric   // final "and X, 1" instruction must be the final op in the sequence.
2410b57cec5SDimitry Andric   bool MatchAllBitsSet;
2420b57cec5SDimitry Andric   if (match(&I, m_c_And(m_OneUse(m_And(m_Value(), m_Value())), m_Value())))
2430b57cec5SDimitry Andric     MatchAllBitsSet = true;
2440b57cec5SDimitry Andric   else if (match(&I, m_And(m_OneUse(m_Or(m_Value(), m_Value())), m_One())))
2450b57cec5SDimitry Andric     MatchAllBitsSet = false;
2460b57cec5SDimitry Andric   else
2470b57cec5SDimitry Andric     return false;
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric   MaskOps MOps(I.getType()->getScalarSizeInBits(), MatchAllBitsSet);
2500b57cec5SDimitry Andric   if (MatchAllBitsSet) {
2510b57cec5SDimitry Andric     if (!matchAndOrChain(cast<BinaryOperator>(&I), MOps) || !MOps.FoundAnd1)
2520b57cec5SDimitry Andric       return false;
2530b57cec5SDimitry Andric   } else {
2540b57cec5SDimitry Andric     if (!matchAndOrChain(cast<BinaryOperator>(&I)->getOperand(0), MOps))
2550b57cec5SDimitry Andric       return false;
2560b57cec5SDimitry Andric   }
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric   // The pattern was found. Create a masked compare that replaces all of the
2590b57cec5SDimitry Andric   // shift and logic ops.
2600b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
2610b57cec5SDimitry Andric   Constant *Mask = ConstantInt::get(I.getType(), MOps.Mask);
2620b57cec5SDimitry Andric   Value *And = Builder.CreateAnd(MOps.Root, Mask);
2630b57cec5SDimitry Andric   Value *Cmp = MatchAllBitsSet ? Builder.CreateICmpEQ(And, Mask)
2640b57cec5SDimitry Andric                                : Builder.CreateIsNotNull(And);
2650b57cec5SDimitry Andric   Value *Zext = Builder.CreateZExt(Cmp, I.getType());
2660b57cec5SDimitry Andric   I.replaceAllUsesWith(Zext);
2675ffd83dbSDimitry Andric   ++NumAnyOrAllBitsSet;
2680b57cec5SDimitry Andric   return true;
2690b57cec5SDimitry Andric }
2700b57cec5SDimitry Andric 
2718bcb0991SDimitry Andric // Try to recognize below function as popcount intrinsic.
2728bcb0991SDimitry Andric // This is the "best" algorithm from
2738bcb0991SDimitry Andric // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
2748bcb0991SDimitry Andric // Also used in TargetLowering::expandCTPOP().
2758bcb0991SDimitry Andric //
2768bcb0991SDimitry Andric // int popcount(unsigned int i) {
2778bcb0991SDimitry Andric //   i = i - ((i >> 1) & 0x55555555);
2788bcb0991SDimitry Andric //   i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
2798bcb0991SDimitry Andric //   i = ((i + (i >> 4)) & 0x0F0F0F0F);
2808bcb0991SDimitry Andric //   return (i * 0x01010101) >> 24;
2818bcb0991SDimitry Andric // }
tryToRecognizePopCount(Instruction & I)2828bcb0991SDimitry Andric static bool tryToRecognizePopCount(Instruction &I) {
2838bcb0991SDimitry Andric   if (I.getOpcode() != Instruction::LShr)
2848bcb0991SDimitry Andric     return false;
2858bcb0991SDimitry Andric 
2868bcb0991SDimitry Andric   Type *Ty = I.getType();
2878bcb0991SDimitry Andric   if (!Ty->isIntOrIntVectorTy())
2888bcb0991SDimitry Andric     return false;
2898bcb0991SDimitry Andric 
2908bcb0991SDimitry Andric   unsigned Len = Ty->getScalarSizeInBits();
2918bcb0991SDimitry Andric   // FIXME: fix Len == 8 and other irregular type lengths.
2928bcb0991SDimitry Andric   if (!(Len <= 128 && Len > 8 && Len % 8 == 0))
2938bcb0991SDimitry Andric     return false;
2948bcb0991SDimitry Andric 
2958bcb0991SDimitry Andric   APInt Mask55 = APInt::getSplat(Len, APInt(8, 0x55));
2968bcb0991SDimitry Andric   APInt Mask33 = APInt::getSplat(Len, APInt(8, 0x33));
2978bcb0991SDimitry Andric   APInt Mask0F = APInt::getSplat(Len, APInt(8, 0x0F));
2988bcb0991SDimitry Andric   APInt Mask01 = APInt::getSplat(Len, APInt(8, 0x01));
2998bcb0991SDimitry Andric   APInt MaskShift = APInt(Len, Len - 8);
3008bcb0991SDimitry Andric 
3018bcb0991SDimitry Andric   Value *Op0 = I.getOperand(0);
3028bcb0991SDimitry Andric   Value *Op1 = I.getOperand(1);
3038bcb0991SDimitry Andric   Value *MulOp0;
3048bcb0991SDimitry Andric   // Matching "(i * 0x01010101...) >> 24".
3058bcb0991SDimitry Andric   if ((match(Op0, m_Mul(m_Value(MulOp0), m_SpecificInt(Mask01)))) &&
3068bcb0991SDimitry Andric       match(Op1, m_SpecificInt(MaskShift))) {
3078bcb0991SDimitry Andric     Value *ShiftOp0;
3088bcb0991SDimitry Andric     // Matching "((i + (i >> 4)) & 0x0F0F0F0F...)".
3098bcb0991SDimitry Andric     if (match(MulOp0, m_And(m_c_Add(m_LShr(m_Value(ShiftOp0), m_SpecificInt(4)),
3108bcb0991SDimitry Andric                                     m_Deferred(ShiftOp0)),
3118bcb0991SDimitry Andric                             m_SpecificInt(Mask0F)))) {
3128bcb0991SDimitry Andric       Value *AndOp0;
3138bcb0991SDimitry Andric       // Matching "(i & 0x33333333...) + ((i >> 2) & 0x33333333...)".
3148bcb0991SDimitry Andric       if (match(ShiftOp0,
3158bcb0991SDimitry Andric                 m_c_Add(m_And(m_Value(AndOp0), m_SpecificInt(Mask33)),
3168bcb0991SDimitry Andric                         m_And(m_LShr(m_Deferred(AndOp0), m_SpecificInt(2)),
3178bcb0991SDimitry Andric                               m_SpecificInt(Mask33))))) {
3188bcb0991SDimitry Andric         Value *Root, *SubOp1;
3198bcb0991SDimitry Andric         // Matching "i - ((i >> 1) & 0x55555555...)".
3208bcb0991SDimitry Andric         if (match(AndOp0, m_Sub(m_Value(Root), m_Value(SubOp1))) &&
3218bcb0991SDimitry Andric             match(SubOp1, m_And(m_LShr(m_Specific(Root), m_SpecificInt(1)),
3228bcb0991SDimitry Andric                                 m_SpecificInt(Mask55)))) {
3238bcb0991SDimitry Andric           LLVM_DEBUG(dbgs() << "Recognized popcount intrinsic\n");
3248bcb0991SDimitry Andric           IRBuilder<> Builder(&I);
3258bcb0991SDimitry Andric           Function *Func = Intrinsic::getDeclaration(
3268bcb0991SDimitry Andric               I.getModule(), Intrinsic::ctpop, I.getType());
3278bcb0991SDimitry Andric           I.replaceAllUsesWith(Builder.CreateCall(Func, {Root}));
3285ffd83dbSDimitry Andric           ++NumPopCountRecognized;
3298bcb0991SDimitry Andric           return true;
3308bcb0991SDimitry Andric         }
3318bcb0991SDimitry Andric       }
3328bcb0991SDimitry Andric     }
3338bcb0991SDimitry Andric   }
3348bcb0991SDimitry Andric 
3358bcb0991SDimitry Andric   return false;
3368bcb0991SDimitry Andric }
3378bcb0991SDimitry Andric 
33881ad6265SDimitry Andric /// Fold smin(smax(fptosi(x), C1), C2) to llvm.fptosi.sat(x), providing C1 and
33981ad6265SDimitry Andric /// C2 saturate the value of the fp conversion. The transform is not reversable
34081ad6265SDimitry Andric /// as the fptosi.sat is more defined than the input - all values produce a
34181ad6265SDimitry Andric /// valid value for the fptosi.sat, where as some produce poison for original
34281ad6265SDimitry Andric /// that were out of range of the integer conversion. The reversed pattern may
34381ad6265SDimitry Andric /// use fmax and fmin instead. As we cannot directly reverse the transform, and
34481ad6265SDimitry Andric /// it is not always profitable, we make it conditional on the cost being
34581ad6265SDimitry Andric /// reported as lower by TTI.
tryToFPToSat(Instruction & I,TargetTransformInfo & TTI)34681ad6265SDimitry Andric static bool tryToFPToSat(Instruction &I, TargetTransformInfo &TTI) {
34781ad6265SDimitry Andric   // Look for min(max(fptosi, converting to fptosi_sat.
34881ad6265SDimitry Andric   Value *In;
34981ad6265SDimitry Andric   const APInt *MinC, *MaxC;
35081ad6265SDimitry Andric   if (!match(&I, m_SMax(m_OneUse(m_SMin(m_OneUse(m_FPToSI(m_Value(In))),
35181ad6265SDimitry Andric                                         m_APInt(MinC))),
35281ad6265SDimitry Andric                         m_APInt(MaxC))) &&
35381ad6265SDimitry Andric       !match(&I, m_SMin(m_OneUse(m_SMax(m_OneUse(m_FPToSI(m_Value(In))),
35481ad6265SDimitry Andric                                         m_APInt(MaxC))),
35581ad6265SDimitry Andric                         m_APInt(MinC))))
35681ad6265SDimitry Andric     return false;
35781ad6265SDimitry Andric 
35881ad6265SDimitry Andric   // Check that the constants clamp a saturate.
35981ad6265SDimitry Andric   if (!(*MinC + 1).isPowerOf2() || -*MaxC != *MinC + 1)
36081ad6265SDimitry Andric     return false;
36181ad6265SDimitry Andric 
36281ad6265SDimitry Andric   Type *IntTy = I.getType();
36381ad6265SDimitry Andric   Type *FpTy = In->getType();
36481ad6265SDimitry Andric   Type *SatTy =
36581ad6265SDimitry Andric       IntegerType::get(IntTy->getContext(), (*MinC + 1).exactLogBase2() + 1);
36681ad6265SDimitry Andric   if (auto *VecTy = dyn_cast<VectorType>(IntTy))
36781ad6265SDimitry Andric     SatTy = VectorType::get(SatTy, VecTy->getElementCount());
36881ad6265SDimitry Andric 
36981ad6265SDimitry Andric   // Get the cost of the intrinsic, and check that against the cost of
37081ad6265SDimitry Andric   // fptosi+smin+smax
37181ad6265SDimitry Andric   InstructionCost SatCost = TTI.getIntrinsicInstrCost(
37281ad6265SDimitry Andric       IntrinsicCostAttributes(Intrinsic::fptosi_sat, SatTy, {In}, {FpTy}),
37381ad6265SDimitry Andric       TTI::TCK_RecipThroughput);
3745f757f3fSDimitry Andric   SatCost += TTI.getCastInstrCost(Instruction::SExt, IntTy, SatTy,
37581ad6265SDimitry Andric                                   TTI::CastContextHint::None,
37681ad6265SDimitry Andric                                   TTI::TCK_RecipThroughput);
37781ad6265SDimitry Andric 
37881ad6265SDimitry Andric   InstructionCost MinMaxCost = TTI.getCastInstrCost(
37981ad6265SDimitry Andric       Instruction::FPToSI, IntTy, FpTy, TTI::CastContextHint::None,
38081ad6265SDimitry Andric       TTI::TCK_RecipThroughput);
38181ad6265SDimitry Andric   MinMaxCost += TTI.getIntrinsicInstrCost(
38281ad6265SDimitry Andric       IntrinsicCostAttributes(Intrinsic::smin, IntTy, {IntTy}),
38381ad6265SDimitry Andric       TTI::TCK_RecipThroughput);
38481ad6265SDimitry Andric   MinMaxCost += TTI.getIntrinsicInstrCost(
38581ad6265SDimitry Andric       IntrinsicCostAttributes(Intrinsic::smax, IntTy, {IntTy}),
38681ad6265SDimitry Andric       TTI::TCK_RecipThroughput);
38781ad6265SDimitry Andric 
38881ad6265SDimitry Andric   if (SatCost >= MinMaxCost)
38981ad6265SDimitry Andric     return false;
39081ad6265SDimitry Andric 
39181ad6265SDimitry Andric   IRBuilder<> Builder(&I);
39281ad6265SDimitry Andric   Function *Fn = Intrinsic::getDeclaration(I.getModule(), Intrinsic::fptosi_sat,
39381ad6265SDimitry Andric                                            {SatTy, FpTy});
39481ad6265SDimitry Andric   Value *Sat = Builder.CreateCall(Fn, In);
39581ad6265SDimitry Andric   I.replaceAllUsesWith(Builder.CreateSExt(Sat, IntTy));
39681ad6265SDimitry Andric   return true;
39781ad6265SDimitry Andric }
39881ad6265SDimitry Andric 
3998a4dda33SDimitry Andric /// Try to replace a mathlib call to sqrt with the LLVM intrinsic. This avoids
4008a4dda33SDimitry Andric /// pessimistic codegen that has to account for setting errno and can enable
4018a4dda33SDimitry Andric /// vectorization.
foldSqrt(Instruction & I,TargetTransformInfo & TTI,TargetLibraryInfo & TLI,AssumptionCache & AC,DominatorTree & DT)4028a4dda33SDimitry Andric static bool foldSqrt(Instruction &I, TargetTransformInfo &TTI,
4038a4dda33SDimitry Andric                      TargetLibraryInfo &TLI, AssumptionCache &AC,
4048a4dda33SDimitry Andric                      DominatorTree &DT) {
4058a4dda33SDimitry Andric   // Match a call to sqrt mathlib function.
4068a4dda33SDimitry Andric   auto *Call = dyn_cast<CallInst>(&I);
4078a4dda33SDimitry Andric   if (!Call)
4088a4dda33SDimitry Andric     return false;
4098a4dda33SDimitry Andric 
4108a4dda33SDimitry Andric   Module *M = Call->getModule();
4118a4dda33SDimitry Andric   LibFunc Func;
4128a4dda33SDimitry Andric   if (!TLI.getLibFunc(*Call, Func) || !isLibFuncEmittable(M, &TLI, Func))
4138a4dda33SDimitry Andric     return false;
4148a4dda33SDimitry Andric 
4158a4dda33SDimitry Andric   if (Func != LibFunc_sqrt && Func != LibFunc_sqrtf && Func != LibFunc_sqrtl)
4168a4dda33SDimitry Andric     return false;
4178a4dda33SDimitry Andric 
4188a4dda33SDimitry Andric   // If (1) this is a sqrt libcall, (2) we can assume that NAN is not created
4198a4dda33SDimitry Andric   // (because NNAN or the operand arg must not be less than -0.0) and (2) we
4208a4dda33SDimitry Andric   // would not end up lowering to a libcall anyway (which could change the value
4218a4dda33SDimitry Andric   // of errno), then:
4228a4dda33SDimitry Andric   // (1) errno won't be set.
4238a4dda33SDimitry Andric   // (2) it is safe to convert this to an intrinsic call.
4248a4dda33SDimitry Andric   Type *Ty = Call->getType();
4258a4dda33SDimitry Andric   Value *Arg = Call->getArgOperand(0);
4268a4dda33SDimitry Andric   if (TTI.haveFastSqrt(Ty) &&
4278a4dda33SDimitry Andric       (Call->hasNoNaNs() ||
4288a4dda33SDimitry Andric        cannotBeOrderedLessThanZero(Arg, M->getDataLayout(), &TLI, 0, &AC, &I,
4298a4dda33SDimitry Andric                                    &DT))) {
4308a4dda33SDimitry Andric     IRBuilder<> Builder(&I);
4318a4dda33SDimitry Andric     IRBuilderBase::FastMathFlagGuard Guard(Builder);
4328a4dda33SDimitry Andric     Builder.setFastMathFlags(Call->getFastMathFlags());
4338a4dda33SDimitry Andric 
4348a4dda33SDimitry Andric     Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, Ty);
4358a4dda33SDimitry Andric     Value *NewSqrt = Builder.CreateCall(Sqrt, Arg, "sqrt");
4368a4dda33SDimitry Andric     I.replaceAllUsesWith(NewSqrt);
4378a4dda33SDimitry Andric 
4388a4dda33SDimitry Andric     // Explicitly erase the old call because a call with side effects is not
4398a4dda33SDimitry Andric     // trivially dead.
4408a4dda33SDimitry Andric     I.eraseFromParent();
4418a4dda33SDimitry Andric     return true;
4428a4dda33SDimitry Andric   }
4438a4dda33SDimitry Andric 
4448a4dda33SDimitry Andric   return false;
4458a4dda33SDimitry Andric }
4468a4dda33SDimitry Andric 
447bdd1243dSDimitry Andric // Check if this array of constants represents a cttz table.
448bdd1243dSDimitry Andric // Iterate over the elements from \p Table by trying to find/match all
449bdd1243dSDimitry Andric // the numbers from 0 to \p InputBits that should represent cttz results.
isCTTZTable(const ConstantDataArray & Table,uint64_t Mul,uint64_t Shift,uint64_t InputBits)450bdd1243dSDimitry Andric static bool isCTTZTable(const ConstantDataArray &Table, uint64_t Mul,
451bdd1243dSDimitry Andric                         uint64_t Shift, uint64_t InputBits) {
452bdd1243dSDimitry Andric   unsigned Length = Table.getNumElements();
453bdd1243dSDimitry Andric   if (Length < InputBits || Length > InputBits * 2)
454bdd1243dSDimitry Andric     return false;
455bdd1243dSDimitry Andric 
456bdd1243dSDimitry Andric   APInt Mask = APInt::getBitsSetFrom(InputBits, Shift);
457bdd1243dSDimitry Andric   unsigned Matched = 0;
458bdd1243dSDimitry Andric 
459bdd1243dSDimitry Andric   for (unsigned i = 0; i < Length; i++) {
460bdd1243dSDimitry Andric     uint64_t Element = Table.getElementAsInteger(i);
461bdd1243dSDimitry Andric     if (Element >= InputBits)
462bdd1243dSDimitry Andric       continue;
463bdd1243dSDimitry Andric 
464bdd1243dSDimitry Andric     // Check if \p Element matches a concrete answer. It could fail for some
465bdd1243dSDimitry Andric     // elements that are never accessed, so we keep iterating over each element
466bdd1243dSDimitry Andric     // from the table. The number of matched elements should be equal to the
467bdd1243dSDimitry Andric     // number of potential right answers which is \p InputBits actually.
468bdd1243dSDimitry Andric     if ((((Mul << Element) & Mask.getZExtValue()) >> Shift) == i)
469bdd1243dSDimitry Andric       Matched++;
470bdd1243dSDimitry Andric   }
471bdd1243dSDimitry Andric 
472bdd1243dSDimitry Andric   return Matched == InputBits;
473bdd1243dSDimitry Andric }
474bdd1243dSDimitry Andric 
475bdd1243dSDimitry Andric // Try to recognize table-based ctz implementation.
476bdd1243dSDimitry Andric // E.g., an example in C (for more cases please see the llvm/tests):
477bdd1243dSDimitry Andric // int f(unsigned x) {
478bdd1243dSDimitry Andric //    static const char table[32] =
479bdd1243dSDimitry Andric //      {0, 1, 28, 2, 29, 14, 24, 3, 30,
480bdd1243dSDimitry Andric //       22, 20, 15, 25, 17, 4, 8, 31, 27,
481bdd1243dSDimitry Andric //       13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
482bdd1243dSDimitry Andric //    return table[((unsigned)((x & -x) * 0x077CB531U)) >> 27];
483bdd1243dSDimitry Andric // }
484bdd1243dSDimitry Andric // this can be lowered to `cttz` instruction.
485bdd1243dSDimitry Andric // There is also a special case when the element is 0.
486bdd1243dSDimitry Andric //
487bdd1243dSDimitry Andric // Here are some examples or LLVM IR for a 64-bit target:
488bdd1243dSDimitry Andric //
489bdd1243dSDimitry Andric // CASE 1:
490bdd1243dSDimitry Andric // %sub = sub i32 0, %x
491bdd1243dSDimitry Andric // %and = and i32 %sub, %x
492bdd1243dSDimitry Andric // %mul = mul i32 %and, 125613361
493bdd1243dSDimitry Andric // %shr = lshr i32 %mul, 27
494bdd1243dSDimitry Andric // %idxprom = zext i32 %shr to i64
495bdd1243dSDimitry Andric // %arrayidx = getelementptr inbounds [32 x i8], [32 x i8]* @ctz1.table, i64 0,
4965f757f3fSDimitry Andric //     i64 %idxprom
4975f757f3fSDimitry Andric // %0 = load i8, i8* %arrayidx, align 1, !tbaa !8
498bdd1243dSDimitry Andric //
499bdd1243dSDimitry Andric // CASE 2:
500bdd1243dSDimitry Andric // %sub = sub i32 0, %x
501bdd1243dSDimitry Andric // %and = and i32 %sub, %x
502bdd1243dSDimitry Andric // %mul = mul i32 %and, 72416175
503bdd1243dSDimitry Andric // %shr = lshr i32 %mul, 26
504bdd1243dSDimitry Andric // %idxprom = zext i32 %shr to i64
5055f757f3fSDimitry Andric // %arrayidx = getelementptr inbounds [64 x i16], [64 x i16]* @ctz2.table,
5065f757f3fSDimitry Andric //     i64 0, i64 %idxprom
5075f757f3fSDimitry Andric // %0 = load i16, i16* %arrayidx, align 2, !tbaa !8
508bdd1243dSDimitry Andric //
509bdd1243dSDimitry Andric // CASE 3:
510bdd1243dSDimitry Andric // %sub = sub i32 0, %x
511bdd1243dSDimitry Andric // %and = and i32 %sub, %x
512bdd1243dSDimitry Andric // %mul = mul i32 %and, 81224991
513bdd1243dSDimitry Andric // %shr = lshr i32 %mul, 27
514bdd1243dSDimitry Andric // %idxprom = zext i32 %shr to i64
5155f757f3fSDimitry Andric // %arrayidx = getelementptr inbounds [32 x i32], [32 x i32]* @ctz3.table,
5165f757f3fSDimitry Andric //     i64 0, i64 %idxprom
5175f757f3fSDimitry Andric // %0 = load i32, i32* %arrayidx, align 4, !tbaa !8
518bdd1243dSDimitry Andric //
519bdd1243dSDimitry Andric // CASE 4:
520bdd1243dSDimitry Andric // %sub = sub i64 0, %x
521bdd1243dSDimitry Andric // %and = and i64 %sub, %x
522bdd1243dSDimitry Andric // %mul = mul i64 %and, 283881067100198605
523bdd1243dSDimitry Andric // %shr = lshr i64 %mul, 58
5245f757f3fSDimitry Andric // %arrayidx = getelementptr inbounds [64 x i8], [64 x i8]* @table, i64 0,
5255f757f3fSDimitry Andric //     i64 %shr
5265f757f3fSDimitry Andric // %0 = load i8, i8* %arrayidx, align 1, !tbaa !8
527bdd1243dSDimitry Andric //
528bdd1243dSDimitry Andric // All this can be lowered to @llvm.cttz.i32/64 intrinsic.
tryToRecognizeTableBasedCttz(Instruction & I)529bdd1243dSDimitry Andric static bool tryToRecognizeTableBasedCttz(Instruction &I) {
530bdd1243dSDimitry Andric   LoadInst *LI = dyn_cast<LoadInst>(&I);
531bdd1243dSDimitry Andric   if (!LI)
532bdd1243dSDimitry Andric     return false;
533bdd1243dSDimitry Andric 
534bdd1243dSDimitry Andric   Type *AccessType = LI->getType();
535bdd1243dSDimitry Andric   if (!AccessType->isIntegerTy())
536bdd1243dSDimitry Andric     return false;
537bdd1243dSDimitry Andric 
538bdd1243dSDimitry Andric   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getPointerOperand());
539bdd1243dSDimitry Andric   if (!GEP || !GEP->isInBounds() || GEP->getNumIndices() != 2)
540bdd1243dSDimitry Andric     return false;
541bdd1243dSDimitry Andric 
542bdd1243dSDimitry Andric   if (!GEP->getSourceElementType()->isArrayTy())
543bdd1243dSDimitry Andric     return false;
544bdd1243dSDimitry Andric 
545bdd1243dSDimitry Andric   uint64_t ArraySize = GEP->getSourceElementType()->getArrayNumElements();
546bdd1243dSDimitry Andric   if (ArraySize != 32 && ArraySize != 64)
547bdd1243dSDimitry Andric     return false;
548bdd1243dSDimitry Andric 
549bdd1243dSDimitry Andric   GlobalVariable *GVTable = dyn_cast<GlobalVariable>(GEP->getPointerOperand());
550bdd1243dSDimitry Andric   if (!GVTable || !GVTable->hasInitializer() || !GVTable->isConstant())
551bdd1243dSDimitry Andric     return false;
552bdd1243dSDimitry Andric 
553bdd1243dSDimitry Andric   ConstantDataArray *ConstData =
554bdd1243dSDimitry Andric       dyn_cast<ConstantDataArray>(GVTable->getInitializer());
555bdd1243dSDimitry Andric   if (!ConstData)
556bdd1243dSDimitry Andric     return false;
557bdd1243dSDimitry Andric 
558bdd1243dSDimitry Andric   if (!match(GEP->idx_begin()->get(), m_ZeroInt()))
559bdd1243dSDimitry Andric     return false;
560bdd1243dSDimitry Andric 
561bdd1243dSDimitry Andric   Value *Idx2 = std::next(GEP->idx_begin())->get();
562bdd1243dSDimitry Andric   Value *X1;
563bdd1243dSDimitry Andric   uint64_t MulConst, ShiftConst;
564bdd1243dSDimitry Andric   // FIXME: 64-bit targets have `i64` type for the GEP index, so this match will
565bdd1243dSDimitry Andric   // probably fail for other (e.g. 32-bit) targets.
566bdd1243dSDimitry Andric   if (!match(Idx2, m_ZExtOrSelf(
567bdd1243dSDimitry Andric                        m_LShr(m_Mul(m_c_And(m_Neg(m_Value(X1)), m_Deferred(X1)),
568bdd1243dSDimitry Andric                                     m_ConstantInt(MulConst)),
569bdd1243dSDimitry Andric                               m_ConstantInt(ShiftConst)))))
570bdd1243dSDimitry Andric     return false;
571bdd1243dSDimitry Andric 
572bdd1243dSDimitry Andric   unsigned InputBits = X1->getType()->getScalarSizeInBits();
573bdd1243dSDimitry Andric   if (InputBits != 32 && InputBits != 64)
574bdd1243dSDimitry Andric     return false;
575bdd1243dSDimitry Andric 
576bdd1243dSDimitry Andric   // Shift should extract top 5..7 bits.
577bdd1243dSDimitry Andric   if (InputBits - Log2_32(InputBits) != ShiftConst &&
578bdd1243dSDimitry Andric       InputBits - Log2_32(InputBits) - 1 != ShiftConst)
579bdd1243dSDimitry Andric     return false;
580bdd1243dSDimitry Andric 
581bdd1243dSDimitry Andric   if (!isCTTZTable(*ConstData, MulConst, ShiftConst, InputBits))
582bdd1243dSDimitry Andric     return false;
583bdd1243dSDimitry Andric 
584bdd1243dSDimitry Andric   auto ZeroTableElem = ConstData->getElementAsInteger(0);
585bdd1243dSDimitry Andric   bool DefinedForZero = ZeroTableElem == InputBits;
586bdd1243dSDimitry Andric 
587bdd1243dSDimitry Andric   IRBuilder<> B(LI);
588bdd1243dSDimitry Andric   ConstantInt *BoolConst = B.getInt1(!DefinedForZero);
589bdd1243dSDimitry Andric   Type *XType = X1->getType();
590bdd1243dSDimitry Andric   auto Cttz = B.CreateIntrinsic(Intrinsic::cttz, {XType}, {X1, BoolConst});
591bdd1243dSDimitry Andric   Value *ZExtOrTrunc = nullptr;
592bdd1243dSDimitry Andric 
593bdd1243dSDimitry Andric   if (DefinedForZero) {
594bdd1243dSDimitry Andric     ZExtOrTrunc = B.CreateZExtOrTrunc(Cttz, AccessType);
595bdd1243dSDimitry Andric   } else {
596bdd1243dSDimitry Andric     // If the value in elem 0 isn't the same as InputBits, we still want to
597bdd1243dSDimitry Andric     // produce the value from the table.
598bdd1243dSDimitry Andric     auto Cmp = B.CreateICmpEQ(X1, ConstantInt::get(XType, 0));
599bdd1243dSDimitry Andric     auto Select =
600bdd1243dSDimitry Andric         B.CreateSelect(Cmp, ConstantInt::get(XType, ZeroTableElem), Cttz);
601bdd1243dSDimitry Andric 
602bdd1243dSDimitry Andric     // NOTE: If the table[0] is 0, but the cttz(0) is defined by the Target
603bdd1243dSDimitry Andric     // it should be handled as: `cttz(x) & (typeSize - 1)`.
604bdd1243dSDimitry Andric 
605bdd1243dSDimitry Andric     ZExtOrTrunc = B.CreateZExtOrTrunc(Select, AccessType);
606bdd1243dSDimitry Andric   }
607bdd1243dSDimitry Andric 
608bdd1243dSDimitry Andric   LI->replaceAllUsesWith(ZExtOrTrunc);
609bdd1243dSDimitry Andric 
610bdd1243dSDimitry Andric   return true;
611bdd1243dSDimitry Andric }
612bdd1243dSDimitry Andric 
613bdd1243dSDimitry Andric /// This is used by foldLoadsRecursive() to capture a Root Load node which is
614bdd1243dSDimitry Andric /// of type or(load, load) and recursively build the wide load. Also capture the
615bdd1243dSDimitry Andric /// shift amount, zero extend type and loadSize.
616bdd1243dSDimitry Andric struct LoadOps {
617bdd1243dSDimitry Andric   LoadInst *Root = nullptr;
618bdd1243dSDimitry Andric   LoadInst *RootInsert = nullptr;
619bdd1243dSDimitry Andric   bool FoundRoot = false;
620bdd1243dSDimitry Andric   uint64_t LoadSize = 0;
62106c3fb27SDimitry Andric   const APInt *Shift = nullptr;
622bdd1243dSDimitry Andric   Type *ZextType;
623bdd1243dSDimitry Andric   AAMDNodes AATags;
624bdd1243dSDimitry Andric };
625bdd1243dSDimitry Andric 
626bdd1243dSDimitry Andric // Identify and Merge consecutive loads recursively which is of the form
627bdd1243dSDimitry Andric // (ZExt(L1) << shift1) | (ZExt(L2) << shift2) -> ZExt(L3) << shift1
628bdd1243dSDimitry Andric // (ZExt(L1) << shift1) | ZExt(L2) -> ZExt(L3)
foldLoadsRecursive(Value * V,LoadOps & LOps,const DataLayout & DL,AliasAnalysis & AA)629bdd1243dSDimitry Andric static bool foldLoadsRecursive(Value *V, LoadOps &LOps, const DataLayout &DL,
630bdd1243dSDimitry Andric                                AliasAnalysis &AA) {
63106c3fb27SDimitry Andric   const APInt *ShAmt2 = nullptr;
632bdd1243dSDimitry Andric   Value *X;
633bdd1243dSDimitry Andric   Instruction *L1, *L2;
634bdd1243dSDimitry Andric 
635bdd1243dSDimitry Andric   // Go to the last node with loads.
636bdd1243dSDimitry Andric   if (match(V, m_OneUse(m_c_Or(
637bdd1243dSDimitry Andric                    m_Value(X),
638bdd1243dSDimitry Andric                    m_OneUse(m_Shl(m_OneUse(m_ZExt(m_OneUse(m_Instruction(L2)))),
63906c3fb27SDimitry Andric                                   m_APInt(ShAmt2)))))) ||
640bdd1243dSDimitry Andric       match(V, m_OneUse(m_Or(m_Value(X),
641bdd1243dSDimitry Andric                              m_OneUse(m_ZExt(m_OneUse(m_Instruction(L2)))))))) {
642bdd1243dSDimitry Andric     if (!foldLoadsRecursive(X, LOps, DL, AA) && LOps.FoundRoot)
643bdd1243dSDimitry Andric       // Avoid Partial chain merge.
644bdd1243dSDimitry Andric       return false;
645bdd1243dSDimitry Andric   } else
646bdd1243dSDimitry Andric     return false;
647bdd1243dSDimitry Andric 
648bdd1243dSDimitry Andric   // Check if the pattern has loads
649bdd1243dSDimitry Andric   LoadInst *LI1 = LOps.Root;
65006c3fb27SDimitry Andric   const APInt *ShAmt1 = LOps.Shift;
651bdd1243dSDimitry Andric   if (LOps.FoundRoot == false &&
652bdd1243dSDimitry Andric       (match(X, m_OneUse(m_ZExt(m_Instruction(L1)))) ||
653bdd1243dSDimitry Andric        match(X, m_OneUse(m_Shl(m_OneUse(m_ZExt(m_OneUse(m_Instruction(L1)))),
65406c3fb27SDimitry Andric                                m_APInt(ShAmt1)))))) {
655bdd1243dSDimitry Andric     LI1 = dyn_cast<LoadInst>(L1);
656bdd1243dSDimitry Andric   }
657bdd1243dSDimitry Andric   LoadInst *LI2 = dyn_cast<LoadInst>(L2);
658bdd1243dSDimitry Andric 
659bdd1243dSDimitry Andric   // Check if loads are same, atomic, volatile and having same address space.
660bdd1243dSDimitry Andric   if (LI1 == LI2 || !LI1 || !LI2 || !LI1->isSimple() || !LI2->isSimple() ||
661bdd1243dSDimitry Andric       LI1->getPointerAddressSpace() != LI2->getPointerAddressSpace())
662bdd1243dSDimitry Andric     return false;
663bdd1243dSDimitry Andric 
664bdd1243dSDimitry Andric   // Check if Loads come from same BB.
665bdd1243dSDimitry Andric   if (LI1->getParent() != LI2->getParent())
666bdd1243dSDimitry Andric     return false;
667bdd1243dSDimitry Andric 
668bdd1243dSDimitry Andric   // Find the data layout
669bdd1243dSDimitry Andric   bool IsBigEndian = DL.isBigEndian();
670bdd1243dSDimitry Andric 
671bdd1243dSDimitry Andric   // Check if loads are consecutive and same size.
672bdd1243dSDimitry Andric   Value *Load1Ptr = LI1->getPointerOperand();
673bdd1243dSDimitry Andric   APInt Offset1(DL.getIndexTypeSizeInBits(Load1Ptr->getType()), 0);
674bdd1243dSDimitry Andric   Load1Ptr =
675bdd1243dSDimitry Andric       Load1Ptr->stripAndAccumulateConstantOffsets(DL, Offset1,
676bdd1243dSDimitry Andric                                                   /* AllowNonInbounds */ true);
677bdd1243dSDimitry Andric 
678bdd1243dSDimitry Andric   Value *Load2Ptr = LI2->getPointerOperand();
679bdd1243dSDimitry Andric   APInt Offset2(DL.getIndexTypeSizeInBits(Load2Ptr->getType()), 0);
680bdd1243dSDimitry Andric   Load2Ptr =
681bdd1243dSDimitry Andric       Load2Ptr->stripAndAccumulateConstantOffsets(DL, Offset2,
682bdd1243dSDimitry Andric                                                   /* AllowNonInbounds */ true);
683bdd1243dSDimitry Andric 
684bdd1243dSDimitry Andric   // Verify if both loads have same base pointers and load sizes are same.
685bdd1243dSDimitry Andric   uint64_t LoadSize1 = LI1->getType()->getPrimitiveSizeInBits();
686bdd1243dSDimitry Andric   uint64_t LoadSize2 = LI2->getType()->getPrimitiveSizeInBits();
687bdd1243dSDimitry Andric   if (Load1Ptr != Load2Ptr || LoadSize1 != LoadSize2)
688bdd1243dSDimitry Andric     return false;
689bdd1243dSDimitry Andric 
690bdd1243dSDimitry Andric   // Support Loadsizes greater or equal to 8bits and only power of 2.
691bdd1243dSDimitry Andric   if (LoadSize1 < 8 || !isPowerOf2_64(LoadSize1))
692bdd1243dSDimitry Andric     return false;
693bdd1243dSDimitry Andric 
694bdd1243dSDimitry Andric   // Alias Analysis to check for stores b/w the loads.
695bdd1243dSDimitry Andric   LoadInst *Start = LOps.FoundRoot ? LOps.RootInsert : LI1, *End = LI2;
696bdd1243dSDimitry Andric   MemoryLocation Loc;
697bdd1243dSDimitry Andric   if (!Start->comesBefore(End)) {
698bdd1243dSDimitry Andric     std::swap(Start, End);
699bdd1243dSDimitry Andric     Loc = MemoryLocation::get(End);
700bdd1243dSDimitry Andric     if (LOps.FoundRoot)
701bdd1243dSDimitry Andric       Loc = Loc.getWithNewSize(LOps.LoadSize);
702bdd1243dSDimitry Andric   } else
703bdd1243dSDimitry Andric     Loc = MemoryLocation::get(End);
704bdd1243dSDimitry Andric   unsigned NumScanned = 0;
705bdd1243dSDimitry Andric   for (Instruction &Inst :
706bdd1243dSDimitry Andric        make_range(Start->getIterator(), End->getIterator())) {
707bdd1243dSDimitry Andric     if (Inst.mayWriteToMemory() && isModSet(AA.getModRefInfo(&Inst, Loc)))
708bdd1243dSDimitry Andric       return false;
7095f757f3fSDimitry Andric 
7105f757f3fSDimitry Andric     // Ignore debug info so that's not counted against MaxInstrsToScan.
7115f757f3fSDimitry Andric     // Otherwise debug info could affect codegen.
7125f757f3fSDimitry Andric     if (!isa<DbgInfoIntrinsic>(Inst) && ++NumScanned > MaxInstrsToScan)
713bdd1243dSDimitry Andric       return false;
714bdd1243dSDimitry Andric   }
715bdd1243dSDimitry Andric 
716bdd1243dSDimitry Andric   // Make sure Load with lower Offset is at LI1
717bdd1243dSDimitry Andric   bool Reverse = false;
718bdd1243dSDimitry Andric   if (Offset2.slt(Offset1)) {
719bdd1243dSDimitry Andric     std::swap(LI1, LI2);
720bdd1243dSDimitry Andric     std::swap(ShAmt1, ShAmt2);
721bdd1243dSDimitry Andric     std::swap(Offset1, Offset2);
722bdd1243dSDimitry Andric     std::swap(Load1Ptr, Load2Ptr);
723bdd1243dSDimitry Andric     std::swap(LoadSize1, LoadSize2);
724bdd1243dSDimitry Andric     Reverse = true;
725bdd1243dSDimitry Andric   }
726bdd1243dSDimitry Andric 
727bdd1243dSDimitry Andric   // Big endian swap the shifts
728bdd1243dSDimitry Andric   if (IsBigEndian)
729bdd1243dSDimitry Andric     std::swap(ShAmt1, ShAmt2);
730bdd1243dSDimitry Andric 
731bdd1243dSDimitry Andric   // Find Shifts values.
732bdd1243dSDimitry Andric   uint64_t Shift1 = 0, Shift2 = 0;
73306c3fb27SDimitry Andric   if (ShAmt1)
73406c3fb27SDimitry Andric     Shift1 = ShAmt1->getZExtValue();
73506c3fb27SDimitry Andric   if (ShAmt2)
73606c3fb27SDimitry Andric     Shift2 = ShAmt2->getZExtValue();
737bdd1243dSDimitry Andric 
738bdd1243dSDimitry Andric   // First load is always LI1. This is where we put the new load.
739bdd1243dSDimitry Andric   // Use the merged load size available from LI1 for forward loads.
740bdd1243dSDimitry Andric   if (LOps.FoundRoot) {
741bdd1243dSDimitry Andric     if (!Reverse)
742bdd1243dSDimitry Andric       LoadSize1 = LOps.LoadSize;
743bdd1243dSDimitry Andric     else
744bdd1243dSDimitry Andric       LoadSize2 = LOps.LoadSize;
745bdd1243dSDimitry Andric   }
746bdd1243dSDimitry Andric 
747bdd1243dSDimitry Andric   // Verify if shift amount and load index aligns and verifies that loads
748bdd1243dSDimitry Andric   // are consecutive.
749bdd1243dSDimitry Andric   uint64_t ShiftDiff = IsBigEndian ? LoadSize2 : LoadSize1;
750bdd1243dSDimitry Andric   uint64_t PrevSize =
751bdd1243dSDimitry Andric       DL.getTypeStoreSize(IntegerType::get(LI1->getContext(), LoadSize1));
752bdd1243dSDimitry Andric   if ((Shift2 - Shift1) != ShiftDiff || (Offset2 - Offset1) != PrevSize)
753bdd1243dSDimitry Andric     return false;
754bdd1243dSDimitry Andric 
755bdd1243dSDimitry Andric   // Update LOps
756bdd1243dSDimitry Andric   AAMDNodes AATags1 = LOps.AATags;
757bdd1243dSDimitry Andric   AAMDNodes AATags2 = LI2->getAAMetadata();
758bdd1243dSDimitry Andric   if (LOps.FoundRoot == false) {
759bdd1243dSDimitry Andric     LOps.FoundRoot = true;
760bdd1243dSDimitry Andric     AATags1 = LI1->getAAMetadata();
761bdd1243dSDimitry Andric   }
762bdd1243dSDimitry Andric   LOps.LoadSize = LoadSize1 + LoadSize2;
763bdd1243dSDimitry Andric   LOps.RootInsert = Start;
764bdd1243dSDimitry Andric 
765bdd1243dSDimitry Andric   // Concatenate the AATags of the Merged Loads.
766bdd1243dSDimitry Andric   LOps.AATags = AATags1.concat(AATags2);
767bdd1243dSDimitry Andric 
768bdd1243dSDimitry Andric   LOps.Root = LI1;
769bdd1243dSDimitry Andric   LOps.Shift = ShAmt1;
770bdd1243dSDimitry Andric   LOps.ZextType = X->getType();
771bdd1243dSDimitry Andric   return true;
772bdd1243dSDimitry Andric }
773bdd1243dSDimitry Andric 
774bdd1243dSDimitry Andric // For a given BB instruction, evaluate all loads in the chain that form a
775bdd1243dSDimitry Andric // pattern which suggests that the loads can be combined. The one and only use
776bdd1243dSDimitry Andric // of the loads is to form a wider load.
foldConsecutiveLoads(Instruction & I,const DataLayout & DL,TargetTransformInfo & TTI,AliasAnalysis & AA,const DominatorTree & DT)777bdd1243dSDimitry Andric static bool foldConsecutiveLoads(Instruction &I, const DataLayout &DL,
77806c3fb27SDimitry Andric                                  TargetTransformInfo &TTI, AliasAnalysis &AA,
77906c3fb27SDimitry Andric                                  const DominatorTree &DT) {
780bdd1243dSDimitry Andric   // Only consider load chains of scalar values.
781bdd1243dSDimitry Andric   if (isa<VectorType>(I.getType()))
782bdd1243dSDimitry Andric     return false;
783bdd1243dSDimitry Andric 
784bdd1243dSDimitry Andric   LoadOps LOps;
785bdd1243dSDimitry Andric   if (!foldLoadsRecursive(&I, LOps, DL, AA) || !LOps.FoundRoot)
786bdd1243dSDimitry Andric     return false;
787bdd1243dSDimitry Andric 
788bdd1243dSDimitry Andric   IRBuilder<> Builder(&I);
789bdd1243dSDimitry Andric   LoadInst *NewLoad = nullptr, *LI1 = LOps.Root;
790bdd1243dSDimitry Andric 
791bdd1243dSDimitry Andric   IntegerType *WiderType = IntegerType::get(I.getContext(), LOps.LoadSize);
792bdd1243dSDimitry Andric   // TTI based checks if we want to proceed with wider load
793bdd1243dSDimitry Andric   bool Allowed = TTI.isTypeLegal(WiderType);
794bdd1243dSDimitry Andric   if (!Allowed)
795bdd1243dSDimitry Andric     return false;
796bdd1243dSDimitry Andric 
797bdd1243dSDimitry Andric   unsigned AS = LI1->getPointerAddressSpace();
798bdd1243dSDimitry Andric   unsigned Fast = 0;
799bdd1243dSDimitry Andric   Allowed = TTI.allowsMisalignedMemoryAccesses(I.getContext(), LOps.LoadSize,
800bdd1243dSDimitry Andric                                                AS, LI1->getAlign(), &Fast);
801bdd1243dSDimitry Andric   if (!Allowed || !Fast)
802bdd1243dSDimitry Andric     return false;
803bdd1243dSDimitry Andric 
80406c3fb27SDimitry Andric   // Get the Index and Ptr for the new GEP.
805bdd1243dSDimitry Andric   Value *Load1Ptr = LI1->getPointerOperand();
806bdd1243dSDimitry Andric   Builder.SetInsertPoint(LOps.RootInsert);
80706c3fb27SDimitry Andric   if (!DT.dominates(Load1Ptr, LOps.RootInsert)) {
80806c3fb27SDimitry Andric     APInt Offset1(DL.getIndexTypeSizeInBits(Load1Ptr->getType()), 0);
80906c3fb27SDimitry Andric     Load1Ptr = Load1Ptr->stripAndAccumulateConstantOffsets(
81006c3fb27SDimitry Andric         DL, Offset1, /* AllowNonInbounds */ true);
8117a6dacacSDimitry Andric     Load1Ptr = Builder.CreatePtrAdd(Load1Ptr,
81206c3fb27SDimitry Andric                                     Builder.getInt32(Offset1.getZExtValue()));
81306c3fb27SDimitry Andric   }
81406c3fb27SDimitry Andric   // Generate wider load.
81506c3fb27SDimitry Andric   NewLoad = Builder.CreateAlignedLoad(WiderType, Load1Ptr, LI1->getAlign(),
816bdd1243dSDimitry Andric                                       LI1->isVolatile(), "");
817bdd1243dSDimitry Andric   NewLoad->takeName(LI1);
818bdd1243dSDimitry Andric   // Set the New Load AATags Metadata.
819bdd1243dSDimitry Andric   if (LOps.AATags)
820bdd1243dSDimitry Andric     NewLoad->setAAMetadata(LOps.AATags);
821bdd1243dSDimitry Andric 
822bdd1243dSDimitry Andric   Value *NewOp = NewLoad;
823bdd1243dSDimitry Andric   // Check if zero extend needed.
824bdd1243dSDimitry Andric   if (LOps.ZextType)
825bdd1243dSDimitry Andric     NewOp = Builder.CreateZExt(NewOp, LOps.ZextType);
826bdd1243dSDimitry Andric 
827bdd1243dSDimitry Andric   // Check if shift needed. We need to shift with the amount of load1
828bdd1243dSDimitry Andric   // shift if not zero.
829bdd1243dSDimitry Andric   if (LOps.Shift)
83006c3fb27SDimitry Andric     NewOp = Builder.CreateShl(NewOp, ConstantInt::get(I.getContext(), *LOps.Shift));
831bdd1243dSDimitry Andric   I.replaceAllUsesWith(NewOp);
832bdd1243dSDimitry Andric 
833bdd1243dSDimitry Andric   return true;
834bdd1243dSDimitry Andric }
835bdd1243dSDimitry Andric 
83606c3fb27SDimitry Andric // Calculate GEP Stride and accumulated const ModOffset. Return Stride and
83706c3fb27SDimitry Andric // ModOffset
83806c3fb27SDimitry Andric static std::pair<APInt, APInt>
getStrideAndModOffsetOfGEP(Value * PtrOp,const DataLayout & DL)83906c3fb27SDimitry Andric getStrideAndModOffsetOfGEP(Value *PtrOp, const DataLayout &DL) {
84006c3fb27SDimitry Andric   unsigned BW = DL.getIndexTypeSizeInBits(PtrOp->getType());
84106c3fb27SDimitry Andric   std::optional<APInt> Stride;
84206c3fb27SDimitry Andric   APInt ModOffset(BW, 0);
84306c3fb27SDimitry Andric   // Return a minimum gep stride, greatest common divisor of consective gep
84406c3fb27SDimitry Andric   // index scales(c.f. Bézout's identity).
84506c3fb27SDimitry Andric   while (auto *GEP = dyn_cast<GEPOperator>(PtrOp)) {
84606c3fb27SDimitry Andric     MapVector<Value *, APInt> VarOffsets;
84706c3fb27SDimitry Andric     if (!GEP->collectOffset(DL, BW, VarOffsets, ModOffset))
84806c3fb27SDimitry Andric       break;
84906c3fb27SDimitry Andric 
85006c3fb27SDimitry Andric     for (auto [V, Scale] : VarOffsets) {
85106c3fb27SDimitry Andric       // Only keep a power of two factor for non-inbounds
85206c3fb27SDimitry Andric       if (!GEP->isInBounds())
85306c3fb27SDimitry Andric         Scale = APInt::getOneBitSet(Scale.getBitWidth(), Scale.countr_zero());
85406c3fb27SDimitry Andric 
85506c3fb27SDimitry Andric       if (!Stride)
85606c3fb27SDimitry Andric         Stride = Scale;
85706c3fb27SDimitry Andric       else
85806c3fb27SDimitry Andric         Stride = APIntOps::GreatestCommonDivisor(*Stride, Scale);
85906c3fb27SDimitry Andric     }
86006c3fb27SDimitry Andric 
86106c3fb27SDimitry Andric     PtrOp = GEP->getPointerOperand();
86206c3fb27SDimitry Andric   }
86306c3fb27SDimitry Andric 
86406c3fb27SDimitry Andric   // Check whether pointer arrives back at Global Variable via at least one GEP.
86506c3fb27SDimitry Andric   // Even if it doesn't, we can check by alignment.
86606c3fb27SDimitry Andric   if (!isa<GlobalVariable>(PtrOp) || !Stride)
86706c3fb27SDimitry Andric     return {APInt(BW, 1), APInt(BW, 0)};
86806c3fb27SDimitry Andric 
86906c3fb27SDimitry Andric   // In consideration of signed GEP indices, non-negligible offset become
87006c3fb27SDimitry Andric   // remainder of division by minimum GEP stride.
87106c3fb27SDimitry Andric   ModOffset = ModOffset.srem(*Stride);
87206c3fb27SDimitry Andric   if (ModOffset.isNegative())
87306c3fb27SDimitry Andric     ModOffset += *Stride;
87406c3fb27SDimitry Andric 
87506c3fb27SDimitry Andric   return {*Stride, ModOffset};
87606c3fb27SDimitry Andric }
87706c3fb27SDimitry Andric 
87806c3fb27SDimitry Andric /// If C is a constant patterned array and all valid loaded results for given
87906c3fb27SDimitry Andric /// alignment are same to a constant, return that constant.
foldPatternedLoads(Instruction & I,const DataLayout & DL)88006c3fb27SDimitry Andric static bool foldPatternedLoads(Instruction &I, const DataLayout &DL) {
88106c3fb27SDimitry Andric   auto *LI = dyn_cast<LoadInst>(&I);
88206c3fb27SDimitry Andric   if (!LI || LI->isVolatile())
88306c3fb27SDimitry Andric     return false;
88406c3fb27SDimitry Andric 
88506c3fb27SDimitry Andric   // We can only fold the load if it is from a constant global with definitive
88606c3fb27SDimitry Andric   // initializer. Skip expensive logic if this is not the case.
88706c3fb27SDimitry Andric   auto *PtrOp = LI->getPointerOperand();
88806c3fb27SDimitry Andric   auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(PtrOp));
88906c3fb27SDimitry Andric   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
89006c3fb27SDimitry Andric     return false;
89106c3fb27SDimitry Andric 
89206c3fb27SDimitry Andric   // Bail for large initializers in excess of 4K to avoid too many scans.
89306c3fb27SDimitry Andric   Constant *C = GV->getInitializer();
89406c3fb27SDimitry Andric   uint64_t GVSize = DL.getTypeAllocSize(C->getType());
89506c3fb27SDimitry Andric   if (!GVSize || 4096 < GVSize)
89606c3fb27SDimitry Andric     return false;
89706c3fb27SDimitry Andric 
89806c3fb27SDimitry Andric   Type *LoadTy = LI->getType();
89906c3fb27SDimitry Andric   unsigned BW = DL.getIndexTypeSizeInBits(PtrOp->getType());
90006c3fb27SDimitry Andric   auto [Stride, ConstOffset] = getStrideAndModOffsetOfGEP(PtrOp, DL);
90106c3fb27SDimitry Andric 
90206c3fb27SDimitry Andric   // Any possible offset could be multiple of GEP stride. And any valid
90306c3fb27SDimitry Andric   // offset is multiple of load alignment, so checking only multiples of bigger
90406c3fb27SDimitry Andric   // one is sufficient to say results' equality.
90506c3fb27SDimitry Andric   if (auto LA = LI->getAlign();
90606c3fb27SDimitry Andric       LA <= GV->getAlign().valueOrOne() && Stride.getZExtValue() < LA.value()) {
90706c3fb27SDimitry Andric     ConstOffset = APInt(BW, 0);
90806c3fb27SDimitry Andric     Stride = APInt(BW, LA.value());
90906c3fb27SDimitry Andric   }
91006c3fb27SDimitry Andric 
91106c3fb27SDimitry Andric   Constant *Ca = ConstantFoldLoadFromConst(C, LoadTy, ConstOffset, DL);
91206c3fb27SDimitry Andric   if (!Ca)
91306c3fb27SDimitry Andric     return false;
91406c3fb27SDimitry Andric 
91506c3fb27SDimitry Andric   unsigned E = GVSize - DL.getTypeStoreSize(LoadTy);
91606c3fb27SDimitry Andric   for (; ConstOffset.getZExtValue() <= E; ConstOffset += Stride)
91706c3fb27SDimitry Andric     if (Ca != ConstantFoldLoadFromConst(C, LoadTy, ConstOffset, DL))
91806c3fb27SDimitry Andric       return false;
91906c3fb27SDimitry Andric 
92006c3fb27SDimitry Andric   I.replaceAllUsesWith(Ca);
92106c3fb27SDimitry Andric 
92206c3fb27SDimitry Andric   return true;
92306c3fb27SDimitry Andric }
92406c3fb27SDimitry Andric 
9250b57cec5SDimitry Andric /// This is the entry point for folds that could be implemented in regular
9260b57cec5SDimitry Andric /// InstCombine, but they are separated because they are not expected to
9270b57cec5SDimitry Andric /// occur frequently and/or have more than a constant-length pattern match.
foldUnusualPatterns(Function & F,DominatorTree & DT,TargetTransformInfo & TTI,TargetLibraryInfo & TLI,AliasAnalysis & AA,AssumptionCache & AC)92881ad6265SDimitry Andric static bool foldUnusualPatterns(Function &F, DominatorTree &DT,
929972a253aSDimitry Andric                                 TargetTransformInfo &TTI,
93006c3fb27SDimitry Andric                                 TargetLibraryInfo &TLI, AliasAnalysis &AA,
9318a4dda33SDimitry Andric                                 AssumptionCache &AC) {
9320b57cec5SDimitry Andric   bool MadeChange = false;
9330b57cec5SDimitry Andric   for (BasicBlock &BB : F) {
9340b57cec5SDimitry Andric     // Ignore unreachable basic blocks.
9350b57cec5SDimitry Andric     if (!DT.isReachableFromEntry(&BB))
9360b57cec5SDimitry Andric       continue;
937972a253aSDimitry Andric 
938bdd1243dSDimitry Andric     const DataLayout &DL = F.getParent()->getDataLayout();
939bdd1243dSDimitry Andric 
9400b57cec5SDimitry Andric     // Walk the block backwards for efficiency. We're matching a chain of
9410b57cec5SDimitry Andric     // use->defs, so we're more likely to succeed by starting from the bottom.
9420b57cec5SDimitry Andric     // Also, we want to avoid matching partial patterns.
9430b57cec5SDimitry Andric     // TODO: It would be more efficient if we removed dead instructions
9440b57cec5SDimitry Andric     // iteratively in this loop rather than waiting until the end.
945972a253aSDimitry Andric     for (Instruction &I : make_early_inc_range(llvm::reverse(BB))) {
9460b57cec5SDimitry Andric       MadeChange |= foldAnyOrAllBitsSet(I);
947e8d8bef9SDimitry Andric       MadeChange |= foldGuardedFunnelShift(I, DT);
9488bcb0991SDimitry Andric       MadeChange |= tryToRecognizePopCount(I);
94981ad6265SDimitry Andric       MadeChange |= tryToFPToSat(I, TTI);
950bdd1243dSDimitry Andric       MadeChange |= tryToRecognizeTableBasedCttz(I);
95106c3fb27SDimitry Andric       MadeChange |= foldConsecutiveLoads(I, DL, TTI, AA, DT);
95206c3fb27SDimitry Andric       MadeChange |= foldPatternedLoads(I, DL);
953bdd1243dSDimitry Andric       // NOTE: This function introduces erasing of the instruction `I`, so it
954bdd1243dSDimitry Andric       // needs to be called at the end of this sequence, otherwise we may make
955bdd1243dSDimitry Andric       // bugs.
9568a4dda33SDimitry Andric       MadeChange |= foldSqrt(I, TTI, TLI, AC, DT);
9570b57cec5SDimitry Andric     }
9580b57cec5SDimitry Andric   }
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   // We're done with transforms, so remove dead instructions.
9610b57cec5SDimitry Andric   if (MadeChange)
9620b57cec5SDimitry Andric     for (BasicBlock &BB : F)
9630b57cec5SDimitry Andric       SimplifyInstructionsInBlock(&BB);
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric   return MadeChange;
9660b57cec5SDimitry Andric }
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric /// This is the entry point for all transforms. Pass manager differences are
9690b57cec5SDimitry Andric /// handled in the callers of this function.
runImpl(Function & F,AssumptionCache & AC,TargetTransformInfo & TTI,TargetLibraryInfo & TLI,DominatorTree & DT,AliasAnalysis & AA)97081ad6265SDimitry Andric static bool runImpl(Function &F, AssumptionCache &AC, TargetTransformInfo &TTI,
971bdd1243dSDimitry Andric                     TargetLibraryInfo &TLI, DominatorTree &DT,
9728a4dda33SDimitry Andric                     AliasAnalysis &AA) {
9730b57cec5SDimitry Andric   bool MadeChange = false;
9740b57cec5SDimitry Andric   const DataLayout &DL = F.getParent()->getDataLayout();
975349cc55cSDimitry Andric   TruncInstCombine TIC(AC, TLI, DL, DT);
9760b57cec5SDimitry Andric   MadeChange |= TIC.run(F);
9778a4dda33SDimitry Andric   MadeChange |= foldUnusualPatterns(F, DT, TTI, TLI, AA, AC);
9780b57cec5SDimitry Andric   return MadeChange;
9790b57cec5SDimitry Andric }
9800b57cec5SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)9810b57cec5SDimitry Andric PreservedAnalyses AggressiveInstCombinePass::run(Function &F,
9820b57cec5SDimitry Andric                                                  FunctionAnalysisManager &AM) {
983349cc55cSDimitry Andric   auto &AC = AM.getResult<AssumptionAnalysis>(F);
9840b57cec5SDimitry Andric   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
9850b57cec5SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
98681ad6265SDimitry Andric   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
987bdd1243dSDimitry Andric   auto &AA = AM.getResult<AAManager>(F);
9888a4dda33SDimitry Andric   if (!runImpl(F, AC, TTI, TLI, DT, AA)) {
9890b57cec5SDimitry Andric     // No changes, all analyses are preserved.
9900b57cec5SDimitry Andric     return PreservedAnalyses::all();
9910b57cec5SDimitry Andric   }
9920b57cec5SDimitry Andric   // Mark all the analyses that instcombine updates as preserved.
9930b57cec5SDimitry Andric   PreservedAnalyses PA;
9940b57cec5SDimitry Andric   PA.preserveSet<CFGAnalyses>();
9950b57cec5SDimitry Andric   return PA;
9960b57cec5SDimitry Andric }
997