1f1f57a31SAmjad Aboud //===- AggressiveInstCombine.cpp ------------------------------------------===//
2f1f57a31SAmjad Aboud //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f1f57a31SAmjad Aboud //
7f1f57a31SAmjad Aboud //===----------------------------------------------------------------------===//
8f1f57a31SAmjad Aboud //
9f1f57a31SAmjad Aboud // This file implements the aggressive expression pattern combiner classes.
10f1f57a31SAmjad Aboud // Currently, it handles expression patterns for:
11f1f57a31SAmjad Aboud //  * Truncate instruction
12f1f57a31SAmjad Aboud //
13f1f57a31SAmjad Aboud //===----------------------------------------------------------------------===//
14f1f57a31SAmjad Aboud 
15f1f57a31SAmjad Aboud #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
16f1f57a31SAmjad Aboud #include "AggressiveInstCombineInternal.h"
1734828716SGeorge Burgess IV #include "llvm-c/Initialization.h"
18837f93afSBenjamin Kramer #include "llvm-c/Transforms/AggressiveInstCombine.h"
19e987ee63SRoman Lebedev #include "llvm/ADT/Statistic.h"
20f1f57a31SAmjad Aboud #include "llvm/Analysis/AliasAnalysis.h"
21d1f9b216SAnton Afanasyev #include "llvm/Analysis/AssumptionCache.h"
22f1f57a31SAmjad Aboud #include "llvm/Analysis/BasicAliasAnalysis.h"
23f1f57a31SAmjad Aboud #include "llvm/Analysis/GlobalsModRef.h"
24f1f57a31SAmjad Aboud #include "llvm/Analysis/TargetLibraryInfo.h"
254a5cb957SDavid Green #include "llvm/Analysis/TargetTransformInfo.h"
2688c5b500SSimon Pilgrim #include "llvm/Analysis/ValueTracking.h"
27d895bff5SAmjad Aboud #include "llvm/IR/Dominators.h"
2886fd5be6SSimon Pilgrim #include "llvm/IR/Function.h"
29d2025a2eSSanjay Patel #include "llvm/IR/IRBuilder.h"
30ba47dd16SDavid Blaikie #include "llvm/IR/LegacyPassManager.h"
31d2025a2eSSanjay Patel #include "llvm/IR/PatternMatch.h"
3205da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
33f1f57a31SAmjad Aboud #include "llvm/Pass.h"
34*e3205b87SSanjay Patel #include "llvm/Transforms/Utils/BuildLibCalls.h"
3534828716SGeorge Burgess IV #include "llvm/Transforms/Utils/Local.h"
36e987ee63SRoman Lebedev 
37f1f57a31SAmjad Aboud using namespace llvm;
38d2025a2eSSanjay Patel using namespace PatternMatch;
39f1f57a31SAmjad Aboud 
4059630917Sserge-sans-paille namespace llvm {
4159630917Sserge-sans-paille class DataLayout;
4259630917Sserge-sans-paille }
4359630917Sserge-sans-paille 
44f1f57a31SAmjad Aboud #define DEBUG_TYPE "aggressive-instcombine"
45f1f57a31SAmjad Aboud 
46e987ee63SRoman Lebedev STATISTIC(NumAnyOrAllBitsSet, "Number of any/all-bits-set patterns folded");
47e987ee63SRoman Lebedev STATISTIC(NumGuardedRotates,
48e987ee63SRoman Lebedev           "Number of guarded rotates transformed into funnel shifts");
4988c5b500SSimon Pilgrim STATISTIC(NumGuardedFunnelShifts,
5088c5b500SSimon Pilgrim           "Number of guarded funnel shifts transformed into funnel shifts");
51e987ee63SRoman Lebedev STATISTIC(NumPopCountRecognized, "Number of popcount idioms recognized");
52e987ee63SRoman Lebedev 
53f1f57a31SAmjad Aboud namespace {
54f1f57a31SAmjad Aboud /// Contains expression pattern combiner logic.
55f1f57a31SAmjad Aboud /// This class provides both the logic to combine expression patterns and
56f1f57a31SAmjad Aboud /// combine them. It differs from InstCombiner class in that each pattern
57f1f57a31SAmjad Aboud /// combiner runs only once as opposed to InstCombine's multi-iteration,
58f1f57a31SAmjad Aboud /// which allows pattern combiner to have higher complexity than the O(1)
59f1f57a31SAmjad Aboud /// required by the instruction combiner.
60f1f57a31SAmjad Aboud class AggressiveInstCombinerLegacyPass : public FunctionPass {
61f1f57a31SAmjad Aboud public:
62f1f57a31SAmjad Aboud   static char ID; // Pass identification, replacement for typeid
63f1f57a31SAmjad Aboud 
AggressiveInstCombinerLegacyPass()64f1f57a31SAmjad Aboud   AggressiveInstCombinerLegacyPass() : FunctionPass(ID) {
65f1f57a31SAmjad Aboud     initializeAggressiveInstCombinerLegacyPassPass(
66f1f57a31SAmjad Aboud         *PassRegistry::getPassRegistry());
67f1f57a31SAmjad Aboud   }
68f1f57a31SAmjad Aboud 
69f1f57a31SAmjad Aboud   void getAnalysisUsage(AnalysisUsage &AU) const override;
70f1f57a31SAmjad Aboud 
71f1f57a31SAmjad Aboud   /// Run all expression pattern optimizations on the given /p F function.
72f1f57a31SAmjad Aboud   ///
73f1f57a31SAmjad Aboud   /// \param F function to optimize.
74f1f57a31SAmjad Aboud   /// \returns true if the IR is changed.
75f1f57a31SAmjad Aboud   bool runOnFunction(Function &F) override;
76f1f57a31SAmjad Aboud };
77f1f57a31SAmjad Aboud } // namespace
78f1f57a31SAmjad Aboud 
7988c5b500SSimon Pilgrim /// Match a pattern for a bitwise funnel/rotate operation that partially guards
8088c5b500SSimon Pilgrim /// against undefined behavior by branching around the funnel-shift/rotation
8188c5b500SSimon Pilgrim /// when the shift amount is 0.
foldGuardedFunnelShift(Instruction & I,const DominatorTree & DT)8288c5b500SSimon Pilgrim static bool foldGuardedFunnelShift(Instruction &I, const DominatorTree &DT) {
83200885e6SSanjay Patel   if (I.getOpcode() != Instruction::PHI || I.getNumOperands() != 2)
84200885e6SSanjay Patel     return false;
85200885e6SSanjay Patel 
86200885e6SSanjay Patel   // As with the one-use checks below, this is not strictly necessary, but we
87200885e6SSanjay Patel   // are being cautious to avoid potential perf regressions on targets that
8888c5b500SSimon Pilgrim   // do not actually have a funnel/rotate instruction (where the funnel shift
8988c5b500SSimon Pilgrim   // would be expanded back into math/shift/logic ops).
90200885e6SSanjay Patel   if (!isPowerOf2_32(I.getType()->getScalarSizeInBits()))
91200885e6SSanjay Patel     return false;
92200885e6SSanjay Patel 
9355f15f99SSimon Pilgrim   // Match V to funnel shift left/right and capture the source operands and
9455f15f99SSimon Pilgrim   // shift amount.
9555f15f99SSimon Pilgrim   auto matchFunnelShift = [](Value *V, Value *&ShVal0, Value *&ShVal1,
9655f15f99SSimon Pilgrim                              Value *&ShAmt) {
9755f15f99SSimon Pilgrim     Value *SubAmt;
98200885e6SSanjay Patel     unsigned Width = V->getType()->getScalarSizeInBits();
99200885e6SSanjay Patel 
10055f15f99SSimon Pilgrim     // fshl(ShVal0, ShVal1, ShAmt)
10155f15f99SSimon Pilgrim     //  == (ShVal0 << ShAmt) | (ShVal1 >> (Width -ShAmt))
10255f15f99SSimon Pilgrim     if (match(V, m_OneUse(m_c_Or(
10355f15f99SSimon Pilgrim                      m_Shl(m_Value(ShVal0), m_Value(ShAmt)),
10455f15f99SSimon Pilgrim                      m_LShr(m_Value(ShVal1),
10555f15f99SSimon Pilgrim                             m_Sub(m_SpecificInt(Width), m_Value(SubAmt))))))) {
10655f15f99SSimon Pilgrim       if (ShAmt == SubAmt) // TODO: Use m_Specific
107200885e6SSanjay Patel         return Intrinsic::fshl;
108200885e6SSanjay Patel     }
109200885e6SSanjay Patel 
11055f15f99SSimon Pilgrim     // fshr(ShVal0, ShVal1, ShAmt)
11155f15f99SSimon Pilgrim     //  == (ShVal0 >> ShAmt) | (ShVal1 << (Width - ShAmt))
11255f15f99SSimon Pilgrim     if (match(V,
11355f15f99SSimon Pilgrim               m_OneUse(m_c_Or(m_Shl(m_Value(ShVal0), m_Sub(m_SpecificInt(Width),
11455f15f99SSimon Pilgrim                                                            m_Value(SubAmt))),
11555f15f99SSimon Pilgrim                               m_LShr(m_Value(ShVal1), m_Value(ShAmt)))))) {
11655f15f99SSimon Pilgrim       if (ShAmt == SubAmt) // TODO: Use m_Specific
117200885e6SSanjay Patel         return Intrinsic::fshr;
118200885e6SSanjay Patel     }
119200885e6SSanjay Patel 
120200885e6SSanjay Patel     return Intrinsic::not_intrinsic;
121200885e6SSanjay Patel   };
122200885e6SSanjay Patel 
12388c5b500SSimon Pilgrim   // One phi operand must be a funnel/rotate operation, and the other phi
12488c5b500SSimon Pilgrim   // operand must be the source value of that funnel/rotate operation:
12555f15f99SSimon Pilgrim   // phi [ rotate(RotSrc, ShAmt), FunnelBB ], [ RotSrc, GuardBB ]
12688c5b500SSimon Pilgrim   // phi [ fshl(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal0, GuardBB ]
12788c5b500SSimon Pilgrim   // phi [ fshr(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal1, GuardBB ]
128200885e6SSanjay Patel   PHINode &Phi = cast<PHINode>(I);
12955f15f99SSimon Pilgrim   unsigned FunnelOp = 0, GuardOp = 1;
130200885e6SSanjay Patel   Value *P0 = Phi.getOperand(0), *P1 = Phi.getOperand(1);
13155f15f99SSimon Pilgrim   Value *ShVal0, *ShVal1, *ShAmt;
13255f15f99SSimon Pilgrim   Intrinsic::ID IID = matchFunnelShift(P0, ShVal0, ShVal1, ShAmt);
13388c5b500SSimon Pilgrim   if (IID == Intrinsic::not_intrinsic ||
13488c5b500SSimon Pilgrim       (IID == Intrinsic::fshl && ShVal0 != P1) ||
13588c5b500SSimon Pilgrim       (IID == Intrinsic::fshr && ShVal1 != P1)) {
13655f15f99SSimon Pilgrim     IID = matchFunnelShift(P1, ShVal0, ShVal1, ShAmt);
13788c5b500SSimon Pilgrim     if (IID == Intrinsic::not_intrinsic ||
13888c5b500SSimon Pilgrim         (IID == Intrinsic::fshl && ShVal0 != P0) ||
13988c5b500SSimon Pilgrim         (IID == Intrinsic::fshr && ShVal1 != P0))
140200885e6SSanjay Patel       return false;
141200885e6SSanjay Patel     assert((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
142200885e6SSanjay Patel            "Pattern must match funnel shift left or right");
14355f15f99SSimon Pilgrim     std::swap(FunnelOp, GuardOp);
144200885e6SSanjay Patel   }
145200885e6SSanjay Patel 
146200885e6SSanjay Patel   // The incoming block with our source operand must be the "guard" block.
14788c5b500SSimon Pilgrim   // That must contain a cmp+branch to avoid the funnel/rotate when the shift
14888c5b500SSimon Pilgrim   // amount is equal to 0. The other incoming block is the block with the
14988c5b500SSimon Pilgrim   // funnel/rotate.
15055f15f99SSimon Pilgrim   BasicBlock *GuardBB = Phi.getIncomingBlock(GuardOp);
15155f15f99SSimon Pilgrim   BasicBlock *FunnelBB = Phi.getIncomingBlock(FunnelOp);
152200885e6SSanjay Patel   Instruction *TermI = GuardBB->getTerminator();
15388c5b500SSimon Pilgrim 
15488c5b500SSimon Pilgrim   // Ensure that the shift values dominate each block.
15588c5b500SSimon Pilgrim   if (!DT.dominates(ShVal0, TermI) || !DT.dominates(ShVal1, TermI))
15688c5b500SSimon Pilgrim     return false;
15788c5b500SSimon Pilgrim 
158200885e6SSanjay Patel   ICmpInst::Predicate Pred;
1595c3bc3c9SFlorian Hahn   BasicBlock *PhiBB = Phi.getParent();
16055f15f99SSimon Pilgrim   if (!match(TermI, m_Br(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()),
16155f15f99SSimon Pilgrim                          m_SpecificBB(PhiBB), m_SpecificBB(FunnelBB))))
162200885e6SSanjay Patel     return false;
163200885e6SSanjay Patel 
1645c3bc3c9SFlorian Hahn   if (Pred != CmpInst::ICMP_EQ)
165200885e6SSanjay Patel     return false;
166200885e6SSanjay Patel 
16788c5b500SSimon Pilgrim   IRBuilder<> Builder(PhiBB, PhiBB->getFirstInsertionPt());
16888c5b500SSimon Pilgrim 
16988c5b500SSimon Pilgrim   if (ShVal0 == ShVal1)
17088c5b500SSimon Pilgrim     ++NumGuardedRotates;
17188c5b500SSimon Pilgrim   else
17288c5b500SSimon Pilgrim     ++NumGuardedFunnelShifts;
17388c5b500SSimon Pilgrim 
17488c5b500SSimon Pilgrim   // If this is not a rotate then the select was blocking poison from the
17588c5b500SSimon Pilgrim   // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
17688c5b500SSimon Pilgrim   bool IsFshl = IID == Intrinsic::fshl;
17788c5b500SSimon Pilgrim   if (ShVal0 != ShVal1) {
17888c5b500SSimon Pilgrim     if (IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal1))
17988c5b500SSimon Pilgrim       ShVal1 = Builder.CreateFreeze(ShVal1);
18088c5b500SSimon Pilgrim     else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal0))
18188c5b500SSimon Pilgrim       ShVal0 = Builder.CreateFreeze(ShVal0);
18288c5b500SSimon Pilgrim   }
18388c5b500SSimon Pilgrim 
184200885e6SSanjay Patel   // We matched a variation of this IR pattern:
185200885e6SSanjay Patel   // GuardBB:
18655f15f99SSimon Pilgrim   //   %cmp = icmp eq i32 %ShAmt, 0
18755f15f99SSimon Pilgrim   //   br i1 %cmp, label %PhiBB, label %FunnelBB
18855f15f99SSimon Pilgrim   // FunnelBB:
18955f15f99SSimon Pilgrim   //   %sub = sub i32 32, %ShAmt
19088c5b500SSimon Pilgrim   //   %shr = lshr i32 %ShVal1, %sub
19188c5b500SSimon Pilgrim   //   %shl = shl i32 %ShVal0, %ShAmt
19288c5b500SSimon Pilgrim   //   %fsh = or i32 %shr, %shl
193200885e6SSanjay Patel   //   br label %PhiBB
194200885e6SSanjay Patel   // PhiBB:
19588c5b500SSimon Pilgrim   //   %cond = phi i32 [ %fsh, %FunnelBB ], [ %ShVal0, %GuardBB ]
196200885e6SSanjay Patel   // -->
19788c5b500SSimon Pilgrim   // llvm.fshl.i32(i32 %ShVal0, i32 %ShVal1, i32 %ShAmt)
198200885e6SSanjay Patel   Function *F = Intrinsic::getDeclaration(Phi.getModule(), IID, Phi.getType());
19955f15f99SSimon Pilgrim   Phi.replaceAllUsesWith(Builder.CreateCall(F, {ShVal0, ShVal1, ShAmt}));
200200885e6SSanjay Patel   return true;
201200885e6SSanjay Patel }
202200885e6SSanjay Patel 
203ac3951a7SSanjay Patel /// This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and
204ac3951a7SSanjay Patel /// the bit indexes (Mask) needed by a masked compare. If we're matching a chain
205ac3951a7SSanjay Patel /// of 'and' ops, then we also need to capture the fact that we saw an
206ac3951a7SSanjay Patel /// "and X, 1", so that's an extra return value for that case.
207ac3951a7SSanjay Patel struct MaskOps {
2089ed6800eSKazu Hirata   Value *Root = nullptr;
209ac3951a7SSanjay Patel   APInt Mask;
210ac3951a7SSanjay Patel   bool MatchAndChain;
2119ed6800eSKazu Hirata   bool FoundAnd1 = false;
212ac3951a7SSanjay Patel 
MaskOpsMaskOps213119aa8faSPawel Bylica   MaskOps(unsigned BitWidth, bool MatchAnds)
2149ed6800eSKazu Hirata       : Mask(APInt::getZero(BitWidth)), MatchAndChain(MatchAnds) {}
215ac3951a7SSanjay Patel };
216ac3951a7SSanjay Patel 
217ac3951a7SSanjay Patel /// This is a recursive helper for foldAnyOrAllBitsSet() that walks through a
218ac3951a7SSanjay Patel /// chain of 'and' or 'or' instructions looking for shift ops of a common source
219ac3951a7SSanjay Patel /// value. Examples:
220d2025a2eSSanjay Patel ///   or (or (or X, (X >> 3)), (X >> 5)), (X >> 8)
221ac3951a7SSanjay Patel /// returns { X, 0x129 }
222ac3951a7SSanjay Patel ///   and (and (X >> 1), 1), (X >> 4)
223ac3951a7SSanjay Patel /// returns { X, 0x12 }
matchAndOrChain(Value * V,MaskOps & MOps)224ac3951a7SSanjay Patel static bool matchAndOrChain(Value *V, MaskOps &MOps) {
225d2025a2eSSanjay Patel   Value *Op0, *Op1;
226ac3951a7SSanjay Patel   if (MOps.MatchAndChain) {
227ac3951a7SSanjay Patel     // Recurse through a chain of 'and' operands. This requires an extra check
228ac3951a7SSanjay Patel     // vs. the 'or' matcher: we must find an "and X, 1" instruction somewhere
229ac3951a7SSanjay Patel     // in the chain to know that all of the high bits are cleared.
230ac3951a7SSanjay Patel     if (match(V, m_And(m_Value(Op0), m_One()))) {
231ac3951a7SSanjay Patel       MOps.FoundAnd1 = true;
232ac3951a7SSanjay Patel       return matchAndOrChain(Op0, MOps);
233ac3951a7SSanjay Patel     }
234ac3951a7SSanjay Patel     if (match(V, m_And(m_Value(Op0), m_Value(Op1))))
235ac3951a7SSanjay Patel       return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
236ac3951a7SSanjay Patel   } else {
237ac3951a7SSanjay Patel     // Recurse through a chain of 'or' operands.
238d2025a2eSSanjay Patel     if (match(V, m_Or(m_Value(Op0), m_Value(Op1))))
239ac3951a7SSanjay Patel       return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
240ac3951a7SSanjay Patel   }
241d2025a2eSSanjay Patel 
242d2025a2eSSanjay Patel   // We need a shift-right or a bare value representing a compare of bit 0 of
243d2025a2eSSanjay Patel   // the original source operand.
244d2025a2eSSanjay Patel   Value *Candidate;
245fadd1523SSimon Pilgrim   const APInt *BitIndex = nullptr;
246fadd1523SSimon Pilgrim   if (!match(V, m_LShr(m_Value(Candidate), m_APInt(BitIndex))))
247d2025a2eSSanjay Patel     Candidate = V;
248d2025a2eSSanjay Patel 
249d2025a2eSSanjay Patel   // Initialize result source operand.
250ac3951a7SSanjay Patel   if (!MOps.Root)
251ac3951a7SSanjay Patel     MOps.Root = Candidate;
252d2025a2eSSanjay Patel 
253bf55e6deSSanjay Patel   // The shift constant is out-of-range? This code hasn't been simplified.
254fadd1523SSimon Pilgrim   if (BitIndex && BitIndex->uge(MOps.Mask.getBitWidth()))
255bf55e6deSSanjay Patel     return false;
256bf55e6deSSanjay Patel 
257d2025a2eSSanjay Patel   // Fill in the mask bit derived from the shift constant.
258fadd1523SSimon Pilgrim   MOps.Mask.setBit(BitIndex ? BitIndex->getZExtValue() : 0);
259ac3951a7SSanjay Patel   return MOps.Root == Candidate;
260d2025a2eSSanjay Patel }
261d2025a2eSSanjay Patel 
262ac3951a7SSanjay Patel /// Match patterns that correspond to "any-bits-set" and "all-bits-set".
263ac3951a7SSanjay Patel /// These will include a chain of 'or' or 'and'-shifted bits from a
264ac3951a7SSanjay Patel /// common source value:
265ac3951a7SSanjay Patel /// and (or  (lshr X, C), ...), 1 --> (X & CMask) != 0
266ac3951a7SSanjay Patel /// and (and (lshr X, C), ...), 1 --> (X & CMask) == CMask
267ac3951a7SSanjay Patel /// Note: "any-bits-clear" and "all-bits-clear" are variations of these patterns
268ac3951a7SSanjay Patel /// that differ only with a final 'not' of the result. We expect that final
269ac3951a7SSanjay Patel /// 'not' to be folded with the compare that we create here (invert predicate).
foldAnyOrAllBitsSet(Instruction & I)270ac3951a7SSanjay Patel static bool foldAnyOrAllBitsSet(Instruction &I) {
271ac3951a7SSanjay Patel   // The 'any-bits-set' ('or' chain) pattern is simpler to match because the
272ac3951a7SSanjay Patel   // final "and X, 1" instruction must be the final op in the sequence.
273ac3951a7SSanjay Patel   bool MatchAllBitsSet;
274ac3951a7SSanjay Patel   if (match(&I, m_c_And(m_OneUse(m_And(m_Value(), m_Value())), m_Value())))
275ac3951a7SSanjay Patel     MatchAllBitsSet = true;
276ac3951a7SSanjay Patel   else if (match(&I, m_And(m_OneUse(m_Or(m_Value(), m_Value())), m_One())))
277ac3951a7SSanjay Patel     MatchAllBitsSet = false;
278ac3951a7SSanjay Patel   else
279d2025a2eSSanjay Patel     return false;
280d2025a2eSSanjay Patel 
281ac3951a7SSanjay Patel   MaskOps MOps(I.getType()->getScalarSizeInBits(), MatchAllBitsSet);
282ac3951a7SSanjay Patel   if (MatchAllBitsSet) {
283ac3951a7SSanjay Patel     if (!matchAndOrChain(cast<BinaryOperator>(&I), MOps) || !MOps.FoundAnd1)
284d2025a2eSSanjay Patel       return false;
285ac3951a7SSanjay Patel   } else {
286ac3951a7SSanjay Patel     if (!matchAndOrChain(cast<BinaryOperator>(&I)->getOperand(0), MOps))
287ac3951a7SSanjay Patel       return false;
288ac3951a7SSanjay Patel   }
289d2025a2eSSanjay Patel 
290ac3951a7SSanjay Patel   // The pattern was found. Create a masked compare that replaces all of the
291ac3951a7SSanjay Patel   // shift and logic ops.
292d2025a2eSSanjay Patel   IRBuilder<> Builder(&I);
293ac3951a7SSanjay Patel   Constant *Mask = ConstantInt::get(I.getType(), MOps.Mask);
294ac3951a7SSanjay Patel   Value *And = Builder.CreateAnd(MOps.Root, Mask);
295119aa8faSPawel Bylica   Value *Cmp = MatchAllBitsSet ? Builder.CreateICmpEQ(And, Mask)
296119aa8faSPawel Bylica                                : Builder.CreateIsNotNull(And);
297ac3951a7SSanjay Patel   Value *Zext = Builder.CreateZExt(Cmp, I.getType());
298d2025a2eSSanjay Patel   I.replaceAllUsesWith(Zext);
299e987ee63SRoman Lebedev   ++NumAnyOrAllBitsSet;
300d2025a2eSSanjay Patel   return true;
301d2025a2eSSanjay Patel }
302d2025a2eSSanjay Patel 
303c17c5864SChen Zheng // Try to recognize below function as popcount intrinsic.
304c17c5864SChen Zheng // This is the "best" algorithm from
305c17c5864SChen Zheng // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
306c17c5864SChen Zheng // Also used in TargetLowering::expandCTPOP().
307c17c5864SChen Zheng //
308c17c5864SChen Zheng // int popcount(unsigned int i) {
309c17c5864SChen Zheng //   i = i - ((i >> 1) & 0x55555555);
310c17c5864SChen Zheng //   i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
311c17c5864SChen Zheng //   i = ((i + (i >> 4)) & 0x0F0F0F0F);
312c17c5864SChen Zheng //   return (i * 0x01010101) >> 24;
313c17c5864SChen Zheng // }
tryToRecognizePopCount(Instruction & I)314c17c5864SChen Zheng static bool tryToRecognizePopCount(Instruction &I) {
315c17c5864SChen Zheng   if (I.getOpcode() != Instruction::LShr)
316c17c5864SChen Zheng     return false;
317c17c5864SChen Zheng 
318c17c5864SChen Zheng   Type *Ty = I.getType();
319c17c5864SChen Zheng   if (!Ty->isIntOrIntVectorTy())
320c17c5864SChen Zheng     return false;
321c17c5864SChen Zheng 
322c17c5864SChen Zheng   unsigned Len = Ty->getScalarSizeInBits();
323c17c5864SChen Zheng   // FIXME: fix Len == 8 and other irregular type lengths.
324c17c5864SChen Zheng   if (!(Len <= 128 && Len > 8 && Len % 8 == 0))
325c17c5864SChen Zheng     return false;
326c17c5864SChen Zheng 
327c17c5864SChen Zheng   APInt Mask55 = APInt::getSplat(Len, APInt(8, 0x55));
328c17c5864SChen Zheng   APInt Mask33 = APInt::getSplat(Len, APInt(8, 0x33));
329c17c5864SChen Zheng   APInt Mask0F = APInt::getSplat(Len, APInt(8, 0x0F));
330c17c5864SChen Zheng   APInt Mask01 = APInt::getSplat(Len, APInt(8, 0x01));
331c17c5864SChen Zheng   APInt MaskShift = APInt(Len, Len - 8);
332c17c5864SChen Zheng 
333c17c5864SChen Zheng   Value *Op0 = I.getOperand(0);
334c17c5864SChen Zheng   Value *Op1 = I.getOperand(1);
335c17c5864SChen Zheng   Value *MulOp0;
336c17c5864SChen Zheng   // Matching "(i * 0x01010101...) >> 24".
337c17c5864SChen Zheng   if ((match(Op0, m_Mul(m_Value(MulOp0), m_SpecificInt(Mask01)))) &&
338c17c5864SChen Zheng        match(Op1, m_SpecificInt(MaskShift))) {
339c17c5864SChen Zheng     Value *ShiftOp0;
340c17c5864SChen Zheng     // Matching "((i + (i >> 4)) & 0x0F0F0F0F...)".
341c17c5864SChen Zheng     if (match(MulOp0, m_And(m_c_Add(m_LShr(m_Value(ShiftOp0), m_SpecificInt(4)),
342c17c5864SChen Zheng                                     m_Deferred(ShiftOp0)),
343c17c5864SChen Zheng                             m_SpecificInt(Mask0F)))) {
344c17c5864SChen Zheng       Value *AndOp0;
345c17c5864SChen Zheng       // Matching "(i & 0x33333333...) + ((i >> 2) & 0x33333333...)".
346c17c5864SChen Zheng       if (match(ShiftOp0,
347c17c5864SChen Zheng                 m_c_Add(m_And(m_Value(AndOp0), m_SpecificInt(Mask33)),
348c17c5864SChen Zheng                         m_And(m_LShr(m_Deferred(AndOp0), m_SpecificInt(2)),
349c17c5864SChen Zheng                               m_SpecificInt(Mask33))))) {
350c17c5864SChen Zheng         Value *Root, *SubOp1;
351c17c5864SChen Zheng         // Matching "i - ((i >> 1) & 0x55555555...)".
352c17c5864SChen Zheng         if (match(AndOp0, m_Sub(m_Value(Root), m_Value(SubOp1))) &&
353c17c5864SChen Zheng             match(SubOp1, m_And(m_LShr(m_Specific(Root), m_SpecificInt(1)),
354c17c5864SChen Zheng                                 m_SpecificInt(Mask55)))) {
355c17c5864SChen Zheng           LLVM_DEBUG(dbgs() << "Recognized popcount intrinsic\n");
356c17c5864SChen Zheng           IRBuilder<> Builder(&I);
357c17c5864SChen Zheng           Function *Func = Intrinsic::getDeclaration(
358c17c5864SChen Zheng               I.getModule(), Intrinsic::ctpop, I.getType());
359c17c5864SChen Zheng           I.replaceAllUsesWith(Builder.CreateCall(Func, {Root}));
360e987ee63SRoman Lebedev           ++NumPopCountRecognized;
361c17c5864SChen Zheng           return true;
362c17c5864SChen Zheng         }
363c17c5864SChen Zheng       }
364c17c5864SChen Zheng     }
365c17c5864SChen Zheng   }
366c17c5864SChen Zheng 
367c17c5864SChen Zheng   return false;
368c17c5864SChen Zheng }
369c17c5864SChen Zheng 
3704a5cb957SDavid Green /// Fold smin(smax(fptosi(x), C1), C2) to llvm.fptosi.sat(x), providing C1 and
3714a5cb957SDavid Green /// C2 saturate the value of the fp conversion. The transform is not reversable
3724a5cb957SDavid Green /// as the fptosi.sat is more defined than the input - all values produce a
3734a5cb957SDavid Green /// valid value for the fptosi.sat, where as some produce poison for original
3744a5cb957SDavid Green /// that were out of range of the integer conversion. The reversed pattern may
3754a5cb957SDavid Green /// use fmax and fmin instead. As we cannot directly reverse the transform, and
3764a5cb957SDavid Green /// it is not always profitable, we make it conditional on the cost being
3774a5cb957SDavid Green /// reported as lower by TTI.
tryToFPToSat(Instruction & I,TargetTransformInfo & TTI)3784a5cb957SDavid Green static bool tryToFPToSat(Instruction &I, TargetTransformInfo &TTI) {
3794a5cb957SDavid Green   // Look for min(max(fptosi, converting to fptosi_sat.
3804a5cb957SDavid Green   Value *In;
3814a5cb957SDavid Green   const APInt *MinC, *MaxC;
3824a5cb957SDavid Green   if (!match(&I, m_SMax(m_OneUse(m_SMin(m_OneUse(m_FPToSI(m_Value(In))),
3834a5cb957SDavid Green                                         m_APInt(MinC))),
3844a5cb957SDavid Green                         m_APInt(MaxC))) &&
3854a5cb957SDavid Green       !match(&I, m_SMin(m_OneUse(m_SMax(m_OneUse(m_FPToSI(m_Value(In))),
3864a5cb957SDavid Green                                         m_APInt(MaxC))),
3874a5cb957SDavid Green                         m_APInt(MinC))))
3884a5cb957SDavid Green     return false;
3894a5cb957SDavid Green 
3904a5cb957SDavid Green   // Check that the constants clamp a saturate.
3914a5cb957SDavid Green   if (!(*MinC + 1).isPowerOf2() || -*MaxC != *MinC + 1)
3924a5cb957SDavid Green     return false;
3934a5cb957SDavid Green 
3944a5cb957SDavid Green   Type *IntTy = I.getType();
3954a5cb957SDavid Green   Type *FpTy = In->getType();
3964a5cb957SDavid Green   Type *SatTy =
3974a5cb957SDavid Green       IntegerType::get(IntTy->getContext(), (*MinC + 1).exactLogBase2() + 1);
3984a5cb957SDavid Green   if (auto *VecTy = dyn_cast<VectorType>(IntTy))
3994a5cb957SDavid Green     SatTy = VectorType::get(SatTy, VecTy->getElementCount());
4004a5cb957SDavid Green 
4014a5cb957SDavid Green   // Get the cost of the intrinsic, and check that against the cost of
4024a5cb957SDavid Green   // fptosi+smin+smax
4034a5cb957SDavid Green   InstructionCost SatCost = TTI.getIntrinsicInstrCost(
4044a5cb957SDavid Green       IntrinsicCostAttributes(Intrinsic::fptosi_sat, SatTy, {In}, {FpTy}),
4054a5cb957SDavid Green       TTI::TCK_RecipThroughput);
4064a5cb957SDavid Green   SatCost += TTI.getCastInstrCost(Instruction::SExt, SatTy, IntTy,
4074a5cb957SDavid Green                                   TTI::CastContextHint::None,
4084a5cb957SDavid Green                                   TTI::TCK_RecipThroughput);
4094a5cb957SDavid Green 
4104a5cb957SDavid Green   InstructionCost MinMaxCost = TTI.getCastInstrCost(
4114a5cb957SDavid Green       Instruction::FPToSI, IntTy, FpTy, TTI::CastContextHint::None,
4124a5cb957SDavid Green       TTI::TCK_RecipThroughput);
4134a5cb957SDavid Green   MinMaxCost += TTI.getIntrinsicInstrCost(
4144a5cb957SDavid Green       IntrinsicCostAttributes(Intrinsic::smin, IntTy, {IntTy}),
4154a5cb957SDavid Green       TTI::TCK_RecipThroughput);
4164a5cb957SDavid Green   MinMaxCost += TTI.getIntrinsicInstrCost(
4174a5cb957SDavid Green       IntrinsicCostAttributes(Intrinsic::smax, IntTy, {IntTy}),
4184a5cb957SDavid Green       TTI::TCK_RecipThroughput);
4194a5cb957SDavid Green 
4204a5cb957SDavid Green   if (SatCost >= MinMaxCost)
4214a5cb957SDavid Green     return false;
4224a5cb957SDavid Green 
4234a5cb957SDavid Green   IRBuilder<> Builder(&I);
4244a5cb957SDavid Green   Function *Fn = Intrinsic::getDeclaration(I.getModule(), Intrinsic::fptosi_sat,
4254a5cb957SDavid Green                                            {SatTy, FpTy});
4264a5cb957SDavid Green   Value *Sat = Builder.CreateCall(Fn, In);
4274a5cb957SDavid Green   I.replaceAllUsesWith(Builder.CreateSExt(Sat, IntTy));
4284a5cb957SDavid Green   return true;
4294a5cb957SDavid Green }
4304a5cb957SDavid Green 
431*e3205b87SSanjay Patel /// Try to replace a mathlib call to sqrt with the LLVM intrinsic. This avoids
432*e3205b87SSanjay Patel /// pessimistic codegen that has to account for setting errno and can enable
433*e3205b87SSanjay Patel /// vectorization.
434*e3205b87SSanjay Patel static bool
foldSqrt(Instruction & I,TargetTransformInfo & TTI,TargetLibraryInfo & TLI)435*e3205b87SSanjay Patel foldSqrt(Instruction &I, TargetTransformInfo &TTI, TargetLibraryInfo &TLI) {
436*e3205b87SSanjay Patel   // Match a call to sqrt mathlib function.
437*e3205b87SSanjay Patel   auto *Call = dyn_cast<CallInst>(&I);
438*e3205b87SSanjay Patel   if (!Call)
439*e3205b87SSanjay Patel     return false;
440*e3205b87SSanjay Patel 
441*e3205b87SSanjay Patel   Module *M = Call->getModule();
442*e3205b87SSanjay Patel   LibFunc Func;
443*e3205b87SSanjay Patel   if (!TLI.getLibFunc(*Call, Func) || !isLibFuncEmittable(M, &TLI, Func))
444*e3205b87SSanjay Patel     return false;
445*e3205b87SSanjay Patel 
446*e3205b87SSanjay Patel   if (Func != LibFunc_sqrt && Func != LibFunc_sqrtf && Func != LibFunc_sqrtl)
447*e3205b87SSanjay Patel     return false;
448*e3205b87SSanjay Patel 
449*e3205b87SSanjay Patel   // If (1) this is a sqrt libcall, (2) we can assume that NAN is not created,
450*e3205b87SSanjay Patel   // and (3) we would not end up lowering to a libcall anyway (which could
451*e3205b87SSanjay Patel   // change the value of errno), then:
452*e3205b87SSanjay Patel   // (1) the operand arg must not be less than -0.0.
453*e3205b87SSanjay Patel   // (2) errno won't be set.
454*e3205b87SSanjay Patel   // (3) it is safe to convert this to an intrinsic call.
455*e3205b87SSanjay Patel   // TODO: Check if the arg is known non-negative.
456*e3205b87SSanjay Patel   Type *Ty = Call->getType();
457*e3205b87SSanjay Patel   if (TTI.haveFastSqrt(Ty) && Call->hasNoNaNs()) {
458*e3205b87SSanjay Patel     IRBuilder<> Builder(&I);
459*e3205b87SSanjay Patel     IRBuilderBase::FastMathFlagGuard Guard(Builder);
460*e3205b87SSanjay Patel     Builder.setFastMathFlags(Call->getFastMathFlags());
461*e3205b87SSanjay Patel 
462*e3205b87SSanjay Patel     Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, Ty);
463*e3205b87SSanjay Patel     Value *NewSqrt = Builder.CreateCall(Sqrt, Call->getArgOperand(0), "sqrt");
464*e3205b87SSanjay Patel     I.replaceAllUsesWith(NewSqrt);
465*e3205b87SSanjay Patel 
466*e3205b87SSanjay Patel     // Explicitly erase the old call because a call with side effects is not
467*e3205b87SSanjay Patel     // trivially dead.
468*e3205b87SSanjay Patel     I.eraseFromParent();
469*e3205b87SSanjay Patel     return true;
470*e3205b87SSanjay Patel   }
471*e3205b87SSanjay Patel 
472*e3205b87SSanjay Patel   return false;
473*e3205b87SSanjay Patel }
474*e3205b87SSanjay Patel 
475d2025a2eSSanjay Patel /// This is the entry point for folds that could be implemented in regular
476d2025a2eSSanjay Patel /// InstCombine, but they are separated because they are not expected to
477d2025a2eSSanjay Patel /// occur frequently and/or have more than a constant-length pattern match.
foldUnusualPatterns(Function & F,DominatorTree & DT,TargetTransformInfo & TTI,TargetLibraryInfo & TLI)4784a5cb957SDavid Green static bool foldUnusualPatterns(Function &F, DominatorTree &DT,
479*e3205b87SSanjay Patel                                 TargetTransformInfo &TTI,
480*e3205b87SSanjay Patel                                 TargetLibraryInfo &TLI) {
481d2025a2eSSanjay Patel   bool MadeChange = false;
482d2025a2eSSanjay Patel   for (BasicBlock &BB : F) {
483d2025a2eSSanjay Patel     // Ignore unreachable basic blocks.
484d2025a2eSSanjay Patel     if (!DT.isReachableFromEntry(&BB))
485d2025a2eSSanjay Patel       continue;
486*e3205b87SSanjay Patel 
487ac3951a7SSanjay Patel     // Walk the block backwards for efficiency. We're matching a chain of
488ac3951a7SSanjay Patel     // use->defs, so we're more likely to succeed by starting from the bottom.
489ac3951a7SSanjay Patel     // Also, we want to avoid matching partial patterns.
490ac3951a7SSanjay Patel     // TODO: It would be more efficient if we removed dead instructions
491ac3951a7SSanjay Patel     // iteratively in this loop rather than waiting until the end.
492*e3205b87SSanjay Patel     for (Instruction &I : make_early_inc_range(llvm::reverse(BB))) {
493ac3951a7SSanjay Patel       MadeChange |= foldAnyOrAllBitsSet(I);
49488c5b500SSimon Pilgrim       MadeChange |= foldGuardedFunnelShift(I, DT);
495c17c5864SChen Zheng       MadeChange |= tryToRecognizePopCount(I);
4964a5cb957SDavid Green       MadeChange |= tryToFPToSat(I, TTI);
497*e3205b87SSanjay Patel       MadeChange |= foldSqrt(I, TTI, TLI);
498200885e6SSanjay Patel     }
499d2025a2eSSanjay Patel   }
500d2025a2eSSanjay Patel 
501d2025a2eSSanjay Patel   // We're done with transforms, so remove dead instructions.
502d2025a2eSSanjay Patel   if (MadeChange)
503d2025a2eSSanjay Patel     for (BasicBlock &BB : F)
504d2025a2eSSanjay Patel       SimplifyInstructionsInBlock(&BB);
505d2025a2eSSanjay Patel 
506d2025a2eSSanjay Patel   return MadeChange;
507d2025a2eSSanjay Patel }
508d2025a2eSSanjay Patel 
509d2025a2eSSanjay Patel /// This is the entry point for all transforms. Pass manager differences are
510d2025a2eSSanjay Patel /// handled in the callers of this function.
runImpl(Function & F,AssumptionCache & AC,TargetTransformInfo & TTI,TargetLibraryInfo & TLI,DominatorTree & DT)5114a5cb957SDavid Green static bool runImpl(Function &F, AssumptionCache &AC, TargetTransformInfo &TTI,
5124a5cb957SDavid Green                     TargetLibraryInfo &TLI, DominatorTree &DT) {
513d2025a2eSSanjay Patel   bool MadeChange = false;
514d2025a2eSSanjay Patel   const DataLayout &DL = F.getParent()->getDataLayout();
515d1f9b216SAnton Afanasyev   TruncInstCombine TIC(AC, TLI, DL, DT);
516d2025a2eSSanjay Patel   MadeChange |= TIC.run(F);
517*e3205b87SSanjay Patel   MadeChange |= foldUnusualPatterns(F, DT, TTI, TLI);
518d2025a2eSSanjay Patel   return MadeChange;
519d2025a2eSSanjay Patel }
520d2025a2eSSanjay Patel 
getAnalysisUsage(AnalysisUsage & AU) const521f1f57a31SAmjad Aboud void AggressiveInstCombinerLegacyPass::getAnalysisUsage(
522f1f57a31SAmjad Aboud     AnalysisUsage &AU) const {
523f1f57a31SAmjad Aboud   AU.setPreservesCFG();
524d1f9b216SAnton Afanasyev   AU.addRequired<AssumptionCacheTracker>();
525d895bff5SAmjad Aboud   AU.addRequired<DominatorTreeWrapperPass>();
526f1f57a31SAmjad Aboud   AU.addRequired<TargetLibraryInfoWrapperPass>();
5274a5cb957SDavid Green   AU.addRequired<TargetTransformInfoWrapperPass>();
528f1f57a31SAmjad Aboud   AU.addPreserved<AAResultsWrapperPass>();
529f1f57a31SAmjad Aboud   AU.addPreserved<BasicAAWrapperPass>();
530d895bff5SAmjad Aboud   AU.addPreserved<DominatorTreeWrapperPass>();
531f1f57a31SAmjad Aboud   AU.addPreserved<GlobalsAAWrapperPass>();
532f1f57a31SAmjad Aboud }
533f1f57a31SAmjad Aboud 
runOnFunction(Function & F)534f1f57a31SAmjad Aboud bool AggressiveInstCombinerLegacyPass::runOnFunction(Function &F) {
535d1f9b216SAnton Afanasyev   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
5369c27b59cSTeresa Johnson   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
537d2025a2eSSanjay Patel   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5384a5cb957SDavid Green   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
5394a5cb957SDavid Green   return runImpl(F, AC, TTI, TLI, DT);
540f1f57a31SAmjad Aboud }
541f1f57a31SAmjad Aboud 
run(Function & F,FunctionAnalysisManager & AM)542f1f57a31SAmjad Aboud PreservedAnalyses AggressiveInstCombinePass::run(Function &F,
543f1f57a31SAmjad Aboud                                                  FunctionAnalysisManager &AM) {
544d1f9b216SAnton Afanasyev   auto &AC = AM.getResult<AssumptionAnalysis>(F);
545f1f57a31SAmjad Aboud   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
546d2025a2eSSanjay Patel   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
5474a5cb957SDavid Green   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
5484a5cb957SDavid Green   if (!runImpl(F, AC, TTI, TLI, DT)) {
549f1f57a31SAmjad Aboud     // No changes, all analyses are preserved.
550f1f57a31SAmjad Aboud     return PreservedAnalyses::all();
551d2025a2eSSanjay Patel   }
552f1f57a31SAmjad Aboud   // Mark all the analyses that instcombine updates as preserved.
553f1f57a31SAmjad Aboud   PreservedAnalyses PA;
554f1f57a31SAmjad Aboud   PA.preserveSet<CFGAnalyses>();
555f1f57a31SAmjad Aboud   return PA;
556f1f57a31SAmjad Aboud }
557f1f57a31SAmjad Aboud 
558f1f57a31SAmjad Aboud char AggressiveInstCombinerLegacyPass::ID = 0;
559f1f57a31SAmjad Aboud INITIALIZE_PASS_BEGIN(AggressiveInstCombinerLegacyPass,
560f1f57a31SAmjad Aboud                       "aggressive-instcombine",
561f1f57a31SAmjad Aboud                       "Combine pattern based expressions", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)562d1f9b216SAnton Afanasyev INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
563d895bff5SAmjad Aboud INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
564f1f57a31SAmjad Aboud INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
5654a5cb957SDavid Green INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
566f1f57a31SAmjad Aboud INITIALIZE_PASS_END(AggressiveInstCombinerLegacyPass, "aggressive-instcombine",
567f1f57a31SAmjad Aboud                     "Combine pattern based expressions", false, false)
568f1f57a31SAmjad Aboud 
569d4eb2073SCraig Topper // Initialization Routines
570d4eb2073SCraig Topper void llvm::initializeAggressiveInstCombine(PassRegistry &Registry) {
571d4eb2073SCraig Topper   initializeAggressiveInstCombinerLegacyPassPass(Registry);
572d4eb2073SCraig Topper }
573d4eb2073SCraig Topper 
LLVMInitializeAggressiveInstCombiner(LLVMPassRegistryRef R)5741bcb258bSCraig Topper void LLVMInitializeAggressiveInstCombiner(LLVMPassRegistryRef R) {
5751bcb258bSCraig Topper   initializeAggressiveInstCombinerLegacyPassPass(*unwrap(R));
5761bcb258bSCraig Topper }
5771bcb258bSCraig Topper 
createAggressiveInstCombinerPass()578f1f57a31SAmjad Aboud FunctionPass *llvm::createAggressiveInstCombinerPass() {
579f1f57a31SAmjad Aboud   return new AggressiveInstCombinerLegacyPass();
580f1f57a31SAmjad Aboud }
581ba47dd16SDavid Blaikie 
LLVMAddAggressiveInstCombinerPass(LLVMPassManagerRef PM)582ba47dd16SDavid Blaikie void LLVMAddAggressiveInstCombinerPass(LLVMPassManagerRef PM) {
583ba47dd16SDavid Blaikie   unwrap(PM)->add(createAggressiveInstCombinerPass());
584ba47dd16SDavid Blaikie }
585