xref: /freebsd/contrib/llvm-project/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
10b57cec5SDimitry Andric //===- HexagonLoopIdiomRecognition.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 #include "llvm/ADT/APInt.h"
100b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
110b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
120b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
130b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
140b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
150b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
160b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
170b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
190b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/LoopPass.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
260b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
270b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
280b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
290b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
300b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
310b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
320b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
330b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
340b57cec5SDimitry Andric #include "llvm/IR/Function.h"
350b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
360b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
370b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
380b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
390b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
400b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
41480093f4SDimitry Andric #include "llvm/IR/IntrinsicsHexagon.h"
420b57cec5SDimitry Andric #include "llvm/IR/Module.h"
430b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
440b57cec5SDimitry Andric #include "llvm/IR/Type.h"
450b57cec5SDimitry Andric #include "llvm/IR/User.h"
460b57cec5SDimitry Andric #include "llvm/IR/Value.h"
47480093f4SDimitry Andric #include "llvm/InitializePasses.h"
480b57cec5SDimitry Andric #include "llvm/Pass.h"
490b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
500b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
510b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
520b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
530b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
540b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h"
550b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
560b57cec5SDimitry Andric #include "llvm/Transforms/Scalar.h"
570b57cec5SDimitry Andric #include "llvm/Transforms/Utils.h"
58480093f4SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
59*5ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
600b57cec5SDimitry Andric #include <algorithm>
610b57cec5SDimitry Andric #include <array>
620b57cec5SDimitry Andric #include <cassert>
630b57cec5SDimitry Andric #include <cstdint>
640b57cec5SDimitry Andric #include <cstdlib>
650b57cec5SDimitry Andric #include <deque>
660b57cec5SDimitry Andric #include <functional>
670b57cec5SDimitry Andric #include <iterator>
680b57cec5SDimitry Andric #include <map>
690b57cec5SDimitry Andric #include <set>
700b57cec5SDimitry Andric #include <utility>
710b57cec5SDimitry Andric #include <vector>
720b57cec5SDimitry Andric 
73480093f4SDimitry Andric #define DEBUG_TYPE "hexagon-lir"
74480093f4SDimitry Andric 
750b57cec5SDimitry Andric using namespace llvm;
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric static cl::opt<bool> DisableMemcpyIdiom("disable-memcpy-idiom",
780b57cec5SDimitry Andric   cl::Hidden, cl::init(false),
790b57cec5SDimitry Andric   cl::desc("Disable generation of memcpy in loop idiom recognition"));
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric static cl::opt<bool> DisableMemmoveIdiom("disable-memmove-idiom",
820b57cec5SDimitry Andric   cl::Hidden, cl::init(false),
830b57cec5SDimitry Andric   cl::desc("Disable generation of memmove in loop idiom recognition"));
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric static cl::opt<unsigned> RuntimeMemSizeThreshold("runtime-mem-idiom-threshold",
860b57cec5SDimitry Andric   cl::Hidden, cl::init(0), cl::desc("Threshold (in bytes) for the runtime "
870b57cec5SDimitry Andric   "check guarding the memmove."));
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric static cl::opt<unsigned> CompileTimeMemSizeThreshold(
900b57cec5SDimitry Andric   "compile-time-mem-idiom-threshold", cl::Hidden, cl::init(64),
910b57cec5SDimitry Andric   cl::desc("Threshold (in bytes) to perform the transformation, if the "
920b57cec5SDimitry Andric     "runtime loop count (mem transfer size) is known at compile-time."));
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric static cl::opt<bool> OnlyNonNestedMemmove("only-nonnested-memmove-idiom",
950b57cec5SDimitry Andric   cl::Hidden, cl::init(true),
960b57cec5SDimitry Andric   cl::desc("Only enable generating memmove in non-nested loops"));
970b57cec5SDimitry Andric 
988bcb0991SDimitry Andric static cl::opt<bool> HexagonVolatileMemcpy(
998bcb0991SDimitry Andric     "disable-hexagon-volatile-memcpy", cl::Hidden, cl::init(false),
1000b57cec5SDimitry Andric     cl::desc("Enable Hexagon-specific memcpy for volatile destination."));
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric static cl::opt<unsigned> SimplifyLimit("hlir-simplify-limit", cl::init(10000),
1030b57cec5SDimitry Andric   cl::Hidden, cl::desc("Maximum number of simplification steps in HLIR"));
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric static const char *HexagonVolatileMemcpyName
1060b57cec5SDimitry Andric   = "hexagon_memcpy_forward_vp4cp4n2";
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric namespace llvm {
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric   void initializeHexagonLoopIdiomRecognizePass(PassRegistry&);
1120b57cec5SDimitry Andric   Pass *createHexagonLoopIdiomPass();
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric } // end namespace llvm
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric namespace {
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   class HexagonLoopIdiomRecognize : public LoopPass {
1190b57cec5SDimitry Andric   public:
1200b57cec5SDimitry Andric     static char ID;
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric     explicit HexagonLoopIdiomRecognize() : LoopPass(ID) {
1230b57cec5SDimitry Andric       initializeHexagonLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
1240b57cec5SDimitry Andric     }
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric     StringRef getPassName() const override {
1270b57cec5SDimitry Andric       return "Recognize Hexagon-specific loop idioms";
1280b57cec5SDimitry Andric     }
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric    void getAnalysisUsage(AnalysisUsage &AU) const override {
1310b57cec5SDimitry Andric       AU.addRequired<LoopInfoWrapperPass>();
1320b57cec5SDimitry Andric       AU.addRequiredID(LoopSimplifyID);
1330b57cec5SDimitry Andric       AU.addRequiredID(LCSSAID);
1340b57cec5SDimitry Andric       AU.addRequired<AAResultsWrapperPass>();
1350b57cec5SDimitry Andric       AU.addPreserved<AAResultsWrapperPass>();
1360b57cec5SDimitry Andric       AU.addRequired<ScalarEvolutionWrapperPass>();
1370b57cec5SDimitry Andric       AU.addRequired<DominatorTreeWrapperPass>();
1380b57cec5SDimitry Andric       AU.addRequired<TargetLibraryInfoWrapperPass>();
1390b57cec5SDimitry Andric       AU.addPreserved<TargetLibraryInfoWrapperPass>();
1400b57cec5SDimitry Andric     }
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric   private:
1450b57cec5SDimitry Andric     int getSCEVStride(const SCEVAddRecExpr *StoreEv);
1460b57cec5SDimitry Andric     bool isLegalStore(Loop *CurLoop, StoreInst *SI);
1470b57cec5SDimitry Andric     void collectStores(Loop *CurLoop, BasicBlock *BB,
1480b57cec5SDimitry Andric         SmallVectorImpl<StoreInst*> &Stores);
1490b57cec5SDimitry Andric     bool processCopyingStore(Loop *CurLoop, StoreInst *SI, const SCEV *BECount);
1500b57cec5SDimitry Andric     bool coverLoop(Loop *L, SmallVectorImpl<Instruction*> &Insts) const;
1510b57cec5SDimitry Andric     bool runOnLoopBlock(Loop *CurLoop, BasicBlock *BB, const SCEV *BECount,
1520b57cec5SDimitry Andric         SmallVectorImpl<BasicBlock*> &ExitBlocks);
1530b57cec5SDimitry Andric     bool runOnCountableLoop(Loop *L);
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric     AliasAnalysis *AA;
1560b57cec5SDimitry Andric     const DataLayout *DL;
1570b57cec5SDimitry Andric     DominatorTree *DT;
1580b57cec5SDimitry Andric     LoopInfo *LF;
1590b57cec5SDimitry Andric     const TargetLibraryInfo *TLI;
1600b57cec5SDimitry Andric     ScalarEvolution *SE;
1610b57cec5SDimitry Andric     bool HasMemcpy, HasMemmove;
1620b57cec5SDimitry Andric   };
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   struct Simplifier {
1650b57cec5SDimitry Andric     struct Rule {
1660b57cec5SDimitry Andric       using FuncType = std::function<Value* (Instruction*, LLVMContext&)>;
1670b57cec5SDimitry Andric       Rule(StringRef N, FuncType F) : Name(N), Fn(F) {}
1680b57cec5SDimitry Andric       StringRef Name;   // For debugging.
1690b57cec5SDimitry Andric       FuncType Fn;
1700b57cec5SDimitry Andric     };
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric     void addRule(StringRef N, const Rule::FuncType &F) {
1730b57cec5SDimitry Andric       Rules.push_back(Rule(N, F));
1740b57cec5SDimitry Andric     }
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric   private:
1770b57cec5SDimitry Andric     struct WorkListType {
1780b57cec5SDimitry Andric       WorkListType() = default;
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric       void push_back(Value* V) {
1810b57cec5SDimitry Andric         // Do not push back duplicates.
1820b57cec5SDimitry Andric         if (!S.count(V)) { Q.push_back(V); S.insert(V); }
1830b57cec5SDimitry Andric       }
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric       Value *pop_front_val() {
1860b57cec5SDimitry Andric         Value *V = Q.front(); Q.pop_front(); S.erase(V);
1870b57cec5SDimitry Andric         return V;
1880b57cec5SDimitry Andric       }
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric       bool empty() const { return Q.empty(); }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric     private:
1930b57cec5SDimitry Andric       std::deque<Value*> Q;
1940b57cec5SDimitry Andric       std::set<Value*> S;
1950b57cec5SDimitry Andric     };
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric     using ValueSetType = std::set<Value *>;
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric     std::vector<Rule> Rules;
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric   public:
2020b57cec5SDimitry Andric     struct Context {
2030b57cec5SDimitry Andric       using ValueMapType = DenseMap<Value *, Value *>;
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric       Value *Root;
2060b57cec5SDimitry Andric       ValueSetType Used;    // The set of all cloned values used by Root.
2070b57cec5SDimitry Andric       ValueSetType Clones;  // The set of all cloned values.
2080b57cec5SDimitry Andric       LLVMContext &Ctx;
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric       Context(Instruction *Exp)
2110b57cec5SDimitry Andric         : Ctx(Exp->getParent()->getParent()->getContext()) {
2120b57cec5SDimitry Andric         initialize(Exp);
2130b57cec5SDimitry Andric       }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric       ~Context() { cleanup(); }
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric       void print(raw_ostream &OS, const Value *V) const;
2180b57cec5SDimitry Andric       Value *materialize(BasicBlock *B, BasicBlock::iterator At);
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric     private:
2210b57cec5SDimitry Andric       friend struct Simplifier;
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric       void initialize(Instruction *Exp);
2240b57cec5SDimitry Andric       void cleanup();
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric       template <typename FuncT> void traverse(Value *V, FuncT F);
2270b57cec5SDimitry Andric       void record(Value *V);
2280b57cec5SDimitry Andric       void use(Value *V);
2290b57cec5SDimitry Andric       void unuse(Value *V);
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric       bool equal(const Instruction *I, const Instruction *J) const;
2320b57cec5SDimitry Andric       Value *find(Value *Tree, Value *Sub) const;
2330b57cec5SDimitry Andric       Value *subst(Value *Tree, Value *OldV, Value *NewV);
2340b57cec5SDimitry Andric       void replace(Value *OldV, Value *NewV);
2350b57cec5SDimitry Andric       void link(Instruction *I, BasicBlock *B, BasicBlock::iterator At);
2360b57cec5SDimitry Andric     };
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric     Value *simplify(Context &C);
2390b57cec5SDimitry Andric   };
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric   struct PE {
2420b57cec5SDimitry Andric     PE(const Simplifier::Context &c, Value *v = nullptr) : C(c), V(v) {}
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric     const Simplifier::Context &C;
2450b57cec5SDimitry Andric     const Value *V;
2460b57cec5SDimitry Andric   };
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric   LLVM_ATTRIBUTE_USED
2490b57cec5SDimitry Andric   raw_ostream &operator<<(raw_ostream &OS, const PE &P) {
2500b57cec5SDimitry Andric     P.C.print(OS, P.V ? P.V : P.C.Root);
2510b57cec5SDimitry Andric     return OS;
2520b57cec5SDimitry Andric   }
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric } // end anonymous namespace
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric char HexagonLoopIdiomRecognize::ID = 0;
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(HexagonLoopIdiomRecognize, "hexagon-loop-idiom",
2590b57cec5SDimitry Andric     "Recognize Hexagon-specific loop idioms", false, false)
2600b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
2610b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2620b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
2630b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
2640b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2650b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2660b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2670b57cec5SDimitry Andric INITIALIZE_PASS_END(HexagonLoopIdiomRecognize, "hexagon-loop-idiom",
2680b57cec5SDimitry Andric     "Recognize Hexagon-specific loop idioms", false, false)
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric template <typename FuncT>
2710b57cec5SDimitry Andric void Simplifier::Context::traverse(Value *V, FuncT F) {
2720b57cec5SDimitry Andric   WorkListType Q;
2730b57cec5SDimitry Andric   Q.push_back(V);
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   while (!Q.empty()) {
2760b57cec5SDimitry Andric     Instruction *U = dyn_cast<Instruction>(Q.pop_front_val());
2770b57cec5SDimitry Andric     if (!U || U->getParent())
2780b57cec5SDimitry Andric       continue;
2790b57cec5SDimitry Andric     if (!F(U))
2800b57cec5SDimitry Andric       continue;
2810b57cec5SDimitry Andric     for (Value *Op : U->operands())
2820b57cec5SDimitry Andric       Q.push_back(Op);
2830b57cec5SDimitry Andric   }
2840b57cec5SDimitry Andric }
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric void Simplifier::Context::print(raw_ostream &OS, const Value *V) const {
2870b57cec5SDimitry Andric   const auto *U = dyn_cast<const Instruction>(V);
2880b57cec5SDimitry Andric   if (!U) {
2890b57cec5SDimitry Andric     OS << V << '(' << *V << ')';
2900b57cec5SDimitry Andric     return;
2910b57cec5SDimitry Andric   }
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric   if (U->getParent()) {
2940b57cec5SDimitry Andric     OS << U << '(';
2950b57cec5SDimitry Andric     U->printAsOperand(OS, true);
2960b57cec5SDimitry Andric     OS << ')';
2970b57cec5SDimitry Andric     return;
2980b57cec5SDimitry Andric   }
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric   unsigned N = U->getNumOperands();
3010b57cec5SDimitry Andric   if (N != 0)
3020b57cec5SDimitry Andric     OS << U << '(';
3030b57cec5SDimitry Andric   OS << U->getOpcodeName();
3040b57cec5SDimitry Andric   for (const Value *Op : U->operands()) {
3050b57cec5SDimitry Andric     OS << ' ';
3060b57cec5SDimitry Andric     print(OS, Op);
3070b57cec5SDimitry Andric   }
3080b57cec5SDimitry Andric   if (N != 0)
3090b57cec5SDimitry Andric     OS << ')';
3100b57cec5SDimitry Andric }
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric void Simplifier::Context::initialize(Instruction *Exp) {
3130b57cec5SDimitry Andric   // Perform a deep clone of the expression, set Root to the root
3140b57cec5SDimitry Andric   // of the clone, and build a map from the cloned values to the
3150b57cec5SDimitry Andric   // original ones.
3160b57cec5SDimitry Andric   ValueMapType M;
3170b57cec5SDimitry Andric   BasicBlock *Block = Exp->getParent();
3180b57cec5SDimitry Andric   WorkListType Q;
3190b57cec5SDimitry Andric   Q.push_back(Exp);
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   while (!Q.empty()) {
3220b57cec5SDimitry Andric     Value *V = Q.pop_front_val();
3230b57cec5SDimitry Andric     if (M.find(V) != M.end())
3240b57cec5SDimitry Andric       continue;
3250b57cec5SDimitry Andric     if (Instruction *U = dyn_cast<Instruction>(V)) {
3260b57cec5SDimitry Andric       if (isa<PHINode>(U) || U->getParent() != Block)
3270b57cec5SDimitry Andric         continue;
3280b57cec5SDimitry Andric       for (Value *Op : U->operands())
3290b57cec5SDimitry Andric         Q.push_back(Op);
3300b57cec5SDimitry Andric       M.insert({U, U->clone()});
3310b57cec5SDimitry Andric     }
3320b57cec5SDimitry Andric   }
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric   for (std::pair<Value*,Value*> P : M) {
3350b57cec5SDimitry Andric     Instruction *U = cast<Instruction>(P.second);
3360b57cec5SDimitry Andric     for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) {
3370b57cec5SDimitry Andric       auto F = M.find(U->getOperand(i));
3380b57cec5SDimitry Andric       if (F != M.end())
3390b57cec5SDimitry Andric         U->setOperand(i, F->second);
3400b57cec5SDimitry Andric     }
3410b57cec5SDimitry Andric   }
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric   auto R = M.find(Exp);
3440b57cec5SDimitry Andric   assert(R != M.end());
3450b57cec5SDimitry Andric   Root = R->second;
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   record(Root);
3480b57cec5SDimitry Andric   use(Root);
3490b57cec5SDimitry Andric }
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric void Simplifier::Context::record(Value *V) {
3520b57cec5SDimitry Andric   auto Record = [this](Instruction *U) -> bool {
3530b57cec5SDimitry Andric     Clones.insert(U);
3540b57cec5SDimitry Andric     return true;
3550b57cec5SDimitry Andric   };
3560b57cec5SDimitry Andric   traverse(V, Record);
3570b57cec5SDimitry Andric }
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric void Simplifier::Context::use(Value *V) {
3600b57cec5SDimitry Andric   auto Use = [this](Instruction *U) -> bool {
3610b57cec5SDimitry Andric     Used.insert(U);
3620b57cec5SDimitry Andric     return true;
3630b57cec5SDimitry Andric   };
3640b57cec5SDimitry Andric   traverse(V, Use);
3650b57cec5SDimitry Andric }
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric void Simplifier::Context::unuse(Value *V) {
3680b57cec5SDimitry Andric   if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != nullptr)
3690b57cec5SDimitry Andric     return;
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   auto Unuse = [this](Instruction *U) -> bool {
3720b57cec5SDimitry Andric     if (!U->use_empty())
3730b57cec5SDimitry Andric       return false;
3740b57cec5SDimitry Andric     Used.erase(U);
3750b57cec5SDimitry Andric     return true;
3760b57cec5SDimitry Andric   };
3770b57cec5SDimitry Andric   traverse(V, Unuse);
3780b57cec5SDimitry Andric }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric Value *Simplifier::Context::subst(Value *Tree, Value *OldV, Value *NewV) {
3810b57cec5SDimitry Andric   if (Tree == OldV)
3820b57cec5SDimitry Andric     return NewV;
3830b57cec5SDimitry Andric   if (OldV == NewV)
3840b57cec5SDimitry Andric     return Tree;
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric   WorkListType Q;
3870b57cec5SDimitry Andric   Q.push_back(Tree);
3880b57cec5SDimitry Andric   while (!Q.empty()) {
3890b57cec5SDimitry Andric     Instruction *U = dyn_cast<Instruction>(Q.pop_front_val());
3900b57cec5SDimitry Andric     // If U is not an instruction, or it's not a clone, skip it.
3910b57cec5SDimitry Andric     if (!U || U->getParent())
3920b57cec5SDimitry Andric       continue;
3930b57cec5SDimitry Andric     for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) {
3940b57cec5SDimitry Andric       Value *Op = U->getOperand(i);
3950b57cec5SDimitry Andric       if (Op == OldV) {
3960b57cec5SDimitry Andric         U->setOperand(i, NewV);
3970b57cec5SDimitry Andric         unuse(OldV);
3980b57cec5SDimitry Andric       } else {
3990b57cec5SDimitry Andric         Q.push_back(Op);
4000b57cec5SDimitry Andric       }
4010b57cec5SDimitry Andric     }
4020b57cec5SDimitry Andric   }
4030b57cec5SDimitry Andric   return Tree;
4040b57cec5SDimitry Andric }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric void Simplifier::Context::replace(Value *OldV, Value *NewV) {
4070b57cec5SDimitry Andric   if (Root == OldV) {
4080b57cec5SDimitry Andric     Root = NewV;
4090b57cec5SDimitry Andric     use(Root);
4100b57cec5SDimitry Andric     return;
4110b57cec5SDimitry Andric   }
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   // NewV may be a complex tree that has just been created by one of the
4140b57cec5SDimitry Andric   // transformation rules. We need to make sure that it is commoned with
4150b57cec5SDimitry Andric   // the existing Root to the maximum extent possible.
4160b57cec5SDimitry Andric   // Identify all subtrees of NewV (including NewV itself) that have
4170b57cec5SDimitry Andric   // equivalent counterparts in Root, and replace those subtrees with
4180b57cec5SDimitry Andric   // these counterparts.
4190b57cec5SDimitry Andric   WorkListType Q;
4200b57cec5SDimitry Andric   Q.push_back(NewV);
4210b57cec5SDimitry Andric   while (!Q.empty()) {
4220b57cec5SDimitry Andric     Value *V = Q.pop_front_val();
4230b57cec5SDimitry Andric     Instruction *U = dyn_cast<Instruction>(V);
4240b57cec5SDimitry Andric     if (!U || U->getParent())
4250b57cec5SDimitry Andric       continue;
4260b57cec5SDimitry Andric     if (Value *DupV = find(Root, V)) {
4270b57cec5SDimitry Andric       if (DupV != V)
4280b57cec5SDimitry Andric         NewV = subst(NewV, V, DupV);
4290b57cec5SDimitry Andric     } else {
4300b57cec5SDimitry Andric       for (Value *Op : U->operands())
4310b57cec5SDimitry Andric         Q.push_back(Op);
4320b57cec5SDimitry Andric     }
4330b57cec5SDimitry Andric   }
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric   // Now, simply replace OldV with NewV in Root.
4360b57cec5SDimitry Andric   Root = subst(Root, OldV, NewV);
4370b57cec5SDimitry Andric   use(Root);
4380b57cec5SDimitry Andric }
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric void Simplifier::Context::cleanup() {
4410b57cec5SDimitry Andric   for (Value *V : Clones) {
4420b57cec5SDimitry Andric     Instruction *U = cast<Instruction>(V);
4430b57cec5SDimitry Andric     if (!U->getParent())
4440b57cec5SDimitry Andric       U->dropAllReferences();
4450b57cec5SDimitry Andric   }
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric   for (Value *V : Clones) {
4480b57cec5SDimitry Andric     Instruction *U = cast<Instruction>(V);
4490b57cec5SDimitry Andric     if (!U->getParent())
4500b57cec5SDimitry Andric       U->deleteValue();
4510b57cec5SDimitry Andric   }
4520b57cec5SDimitry Andric }
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric bool Simplifier::Context::equal(const Instruction *I,
4550b57cec5SDimitry Andric                                 const Instruction *J) const {
4560b57cec5SDimitry Andric   if (I == J)
4570b57cec5SDimitry Andric     return true;
4580b57cec5SDimitry Andric   if (!I->isSameOperationAs(J))
4590b57cec5SDimitry Andric     return false;
4600b57cec5SDimitry Andric   if (isa<PHINode>(I))
4610b57cec5SDimitry Andric     return I->isIdenticalTo(J);
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric   for (unsigned i = 0, n = I->getNumOperands(); i != n; ++i) {
4640b57cec5SDimitry Andric     Value *OpI = I->getOperand(i), *OpJ = J->getOperand(i);
4650b57cec5SDimitry Andric     if (OpI == OpJ)
4660b57cec5SDimitry Andric       continue;
4670b57cec5SDimitry Andric     auto *InI = dyn_cast<const Instruction>(OpI);
4680b57cec5SDimitry Andric     auto *InJ = dyn_cast<const Instruction>(OpJ);
4690b57cec5SDimitry Andric     if (InI && InJ) {
4700b57cec5SDimitry Andric       if (!equal(InI, InJ))
4710b57cec5SDimitry Andric         return false;
4720b57cec5SDimitry Andric     } else if (InI != InJ || !InI)
4730b57cec5SDimitry Andric       return false;
4740b57cec5SDimitry Andric   }
4750b57cec5SDimitry Andric   return true;
4760b57cec5SDimitry Andric }
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric Value *Simplifier::Context::find(Value *Tree, Value *Sub) const {
4790b57cec5SDimitry Andric   Instruction *SubI = dyn_cast<Instruction>(Sub);
4800b57cec5SDimitry Andric   WorkListType Q;
4810b57cec5SDimitry Andric   Q.push_back(Tree);
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric   while (!Q.empty()) {
4840b57cec5SDimitry Andric     Value *V = Q.pop_front_val();
4850b57cec5SDimitry Andric     if (V == Sub)
4860b57cec5SDimitry Andric       return V;
4870b57cec5SDimitry Andric     Instruction *U = dyn_cast<Instruction>(V);
4880b57cec5SDimitry Andric     if (!U || U->getParent())
4890b57cec5SDimitry Andric       continue;
4900b57cec5SDimitry Andric     if (SubI && equal(SubI, U))
4910b57cec5SDimitry Andric       return U;
4920b57cec5SDimitry Andric     assert(!isa<PHINode>(U));
4930b57cec5SDimitry Andric     for (Value *Op : U->operands())
4940b57cec5SDimitry Andric       Q.push_back(Op);
4950b57cec5SDimitry Andric   }
4960b57cec5SDimitry Andric   return nullptr;
4970b57cec5SDimitry Andric }
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric void Simplifier::Context::link(Instruction *I, BasicBlock *B,
5000b57cec5SDimitry Andric       BasicBlock::iterator At) {
5010b57cec5SDimitry Andric   if (I->getParent())
5020b57cec5SDimitry Andric     return;
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric   for (Value *Op : I->operands()) {
5050b57cec5SDimitry Andric     if (Instruction *OpI = dyn_cast<Instruction>(Op))
5060b57cec5SDimitry Andric       link(OpI, B, At);
5070b57cec5SDimitry Andric   }
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric   B->getInstList().insert(At, I);
5100b57cec5SDimitry Andric }
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric Value *Simplifier::Context::materialize(BasicBlock *B,
5130b57cec5SDimitry Andric       BasicBlock::iterator At) {
5140b57cec5SDimitry Andric   if (Instruction *RootI = dyn_cast<Instruction>(Root))
5150b57cec5SDimitry Andric     link(RootI, B, At);
5160b57cec5SDimitry Andric   return Root;
5170b57cec5SDimitry Andric }
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric Value *Simplifier::simplify(Context &C) {
5200b57cec5SDimitry Andric   WorkListType Q;
5210b57cec5SDimitry Andric   Q.push_back(C.Root);
5220b57cec5SDimitry Andric   unsigned Count = 0;
5230b57cec5SDimitry Andric   const unsigned Limit = SimplifyLimit;
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric   while (!Q.empty()) {
5260b57cec5SDimitry Andric     if (Count++ >= Limit)
5270b57cec5SDimitry Andric       break;
5280b57cec5SDimitry Andric     Instruction *U = dyn_cast<Instruction>(Q.pop_front_val());
5290b57cec5SDimitry Andric     if (!U || U->getParent() || !C.Used.count(U))
5300b57cec5SDimitry Andric       continue;
5310b57cec5SDimitry Andric     bool Changed = false;
5320b57cec5SDimitry Andric     for (Rule &R : Rules) {
5330b57cec5SDimitry Andric       Value *W = R.Fn(U, C.Ctx);
5340b57cec5SDimitry Andric       if (!W)
5350b57cec5SDimitry Andric         continue;
5360b57cec5SDimitry Andric       Changed = true;
5370b57cec5SDimitry Andric       C.record(W);
5380b57cec5SDimitry Andric       C.replace(U, W);
5390b57cec5SDimitry Andric       Q.push_back(C.Root);
5400b57cec5SDimitry Andric       break;
5410b57cec5SDimitry Andric     }
5420b57cec5SDimitry Andric     if (!Changed) {
5430b57cec5SDimitry Andric       for (Value *Op : U->operands())
5440b57cec5SDimitry Andric         Q.push_back(Op);
5450b57cec5SDimitry Andric     }
5460b57cec5SDimitry Andric   }
5470b57cec5SDimitry Andric   return Count < Limit ? C.Root : nullptr;
5480b57cec5SDimitry Andric }
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5510b57cec5SDimitry Andric //
5520b57cec5SDimitry Andric //          Implementation of PolynomialMultiplyRecognize
5530b57cec5SDimitry Andric //
5540b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric namespace {
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   class PolynomialMultiplyRecognize {
5590b57cec5SDimitry Andric   public:
5600b57cec5SDimitry Andric     explicit PolynomialMultiplyRecognize(Loop *loop, const DataLayout &dl,
5610b57cec5SDimitry Andric         const DominatorTree &dt, const TargetLibraryInfo &tli,
5620b57cec5SDimitry Andric         ScalarEvolution &se)
5630b57cec5SDimitry Andric       : CurLoop(loop), DL(dl), DT(dt), TLI(tli), SE(se) {}
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric     bool recognize();
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric   private:
5680b57cec5SDimitry Andric     using ValueSeq = SetVector<Value *>;
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric     IntegerType *getPmpyType() const {
5710b57cec5SDimitry Andric       LLVMContext &Ctx = CurLoop->getHeader()->getParent()->getContext();
5720b57cec5SDimitry Andric       return IntegerType::get(Ctx, 32);
5730b57cec5SDimitry Andric     }
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric     bool isPromotableTo(Value *V, IntegerType *Ty);
5760b57cec5SDimitry Andric     void promoteTo(Instruction *In, IntegerType *DestTy, BasicBlock *LoopB);
5770b57cec5SDimitry Andric     bool promoteTypes(BasicBlock *LoopB, BasicBlock *ExitB);
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric     Value *getCountIV(BasicBlock *BB);
5800b57cec5SDimitry Andric     bool findCycle(Value *Out, Value *In, ValueSeq &Cycle);
5810b57cec5SDimitry Andric     void classifyCycle(Instruction *DivI, ValueSeq &Cycle, ValueSeq &Early,
5820b57cec5SDimitry Andric           ValueSeq &Late);
5830b57cec5SDimitry Andric     bool classifyInst(Instruction *UseI, ValueSeq &Early, ValueSeq &Late);
5840b57cec5SDimitry Andric     bool commutesWithShift(Instruction *I);
5850b57cec5SDimitry Andric     bool highBitsAreZero(Value *V, unsigned IterCount);
5860b57cec5SDimitry Andric     bool keepsHighBitsZero(Value *V, unsigned IterCount);
5870b57cec5SDimitry Andric     bool isOperandShifted(Instruction *I, Value *Op);
5880b57cec5SDimitry Andric     bool convertShiftsToLeft(BasicBlock *LoopB, BasicBlock *ExitB,
5890b57cec5SDimitry Andric           unsigned IterCount);
5900b57cec5SDimitry Andric     void cleanupLoopBody(BasicBlock *LoopB);
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric     struct ParsedValues {
5930b57cec5SDimitry Andric       ParsedValues() = default;
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric       Value *M = nullptr;
5960b57cec5SDimitry Andric       Value *P = nullptr;
5970b57cec5SDimitry Andric       Value *Q = nullptr;
5980b57cec5SDimitry Andric       Value *R = nullptr;
5990b57cec5SDimitry Andric       Value *X = nullptr;
6000b57cec5SDimitry Andric       Instruction *Res = nullptr;
6010b57cec5SDimitry Andric       unsigned IterCount = 0;
6020b57cec5SDimitry Andric       bool Left = false;
6030b57cec5SDimitry Andric       bool Inv = false;
6040b57cec5SDimitry Andric     };
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric     bool matchLeftShift(SelectInst *SelI, Value *CIV, ParsedValues &PV);
6070b57cec5SDimitry Andric     bool matchRightShift(SelectInst *SelI, ParsedValues &PV);
6080b57cec5SDimitry Andric     bool scanSelect(SelectInst *SI, BasicBlock *LoopB, BasicBlock *PrehB,
6090b57cec5SDimitry Andric           Value *CIV, ParsedValues &PV, bool PreScan);
6100b57cec5SDimitry Andric     unsigned getInverseMxN(unsigned QP);
6110b57cec5SDimitry Andric     Value *generate(BasicBlock::iterator At, ParsedValues &PV);
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric     void setupPreSimplifier(Simplifier &S);
6140b57cec5SDimitry Andric     void setupPostSimplifier(Simplifier &S);
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric     Loop *CurLoop;
6170b57cec5SDimitry Andric     const DataLayout &DL;
6180b57cec5SDimitry Andric     const DominatorTree &DT;
6190b57cec5SDimitry Andric     const TargetLibraryInfo &TLI;
6200b57cec5SDimitry Andric     ScalarEvolution &SE;
6210b57cec5SDimitry Andric   };
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric } // end anonymous namespace
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric Value *PolynomialMultiplyRecognize::getCountIV(BasicBlock *BB) {
6260b57cec5SDimitry Andric   pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
6270b57cec5SDimitry Andric   if (std::distance(PI, PE) != 2)
6280b57cec5SDimitry Andric     return nullptr;
6290b57cec5SDimitry Andric   BasicBlock *PB = (*PI == BB) ? *std::next(PI) : *PI;
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric   for (auto I = BB->begin(), E = BB->end(); I != E && isa<PHINode>(I); ++I) {
6320b57cec5SDimitry Andric     auto *PN = cast<PHINode>(I);
6330b57cec5SDimitry Andric     Value *InitV = PN->getIncomingValueForBlock(PB);
6340b57cec5SDimitry Andric     if (!isa<ConstantInt>(InitV) || !cast<ConstantInt>(InitV)->isZero())
6350b57cec5SDimitry Andric       continue;
6360b57cec5SDimitry Andric     Value *IterV = PN->getIncomingValueForBlock(BB);
6370b57cec5SDimitry Andric     auto *BO = dyn_cast<BinaryOperator>(IterV);
6388bcb0991SDimitry Andric     if (!BO)
6398bcb0991SDimitry Andric       continue;
6400b57cec5SDimitry Andric     if (BO->getOpcode() != Instruction::Add)
6410b57cec5SDimitry Andric       continue;
6420b57cec5SDimitry Andric     Value *IncV = nullptr;
6430b57cec5SDimitry Andric     if (BO->getOperand(0) == PN)
6440b57cec5SDimitry Andric       IncV = BO->getOperand(1);
6450b57cec5SDimitry Andric     else if (BO->getOperand(1) == PN)
6460b57cec5SDimitry Andric       IncV = BO->getOperand(0);
6470b57cec5SDimitry Andric     if (IncV == nullptr)
6480b57cec5SDimitry Andric       continue;
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric     if (auto *T = dyn_cast<ConstantInt>(IncV))
6510b57cec5SDimitry Andric       if (T->getZExtValue() == 1)
6520b57cec5SDimitry Andric         return PN;
6530b57cec5SDimitry Andric   }
6540b57cec5SDimitry Andric   return nullptr;
6550b57cec5SDimitry Andric }
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric static void replaceAllUsesOfWithIn(Value *I, Value *J, BasicBlock *BB) {
6580b57cec5SDimitry Andric   for (auto UI = I->user_begin(), UE = I->user_end(); UI != UE;) {
6590b57cec5SDimitry Andric     Use &TheUse = UI.getUse();
6600b57cec5SDimitry Andric     ++UI;
6610b57cec5SDimitry Andric     if (auto *II = dyn_cast<Instruction>(TheUse.getUser()))
6620b57cec5SDimitry Andric       if (BB == II->getParent())
6630b57cec5SDimitry Andric         II->replaceUsesOfWith(I, J);
6640b57cec5SDimitry Andric   }
6650b57cec5SDimitry Andric }
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::matchLeftShift(SelectInst *SelI,
6680b57cec5SDimitry Andric       Value *CIV, ParsedValues &PV) {
6690b57cec5SDimitry Andric   // Match the following:
6700b57cec5SDimitry Andric   //   select (X & (1 << i)) != 0 ? R ^ (Q << i) : R
6710b57cec5SDimitry Andric   //   select (X & (1 << i)) == 0 ? R : R ^ (Q << i)
6720b57cec5SDimitry Andric   // The condition may also check for equality with the masked value, i.e
6730b57cec5SDimitry Andric   //   select (X & (1 << i)) == (1 << i) ? R ^ (Q << i) : R
6740b57cec5SDimitry Andric   //   select (X & (1 << i)) != (1 << i) ? R : R ^ (Q << i);
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric   Value *CondV = SelI->getCondition();
6770b57cec5SDimitry Andric   Value *TrueV = SelI->getTrueValue();
6780b57cec5SDimitry Andric   Value *FalseV = SelI->getFalseValue();
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric   using namespace PatternMatch;
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric   CmpInst::Predicate P;
6830b57cec5SDimitry Andric   Value *A = nullptr, *B = nullptr, *C = nullptr;
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric   if (!match(CondV, m_ICmp(P, m_And(m_Value(A), m_Value(B)), m_Value(C))) &&
6860b57cec5SDimitry Andric       !match(CondV, m_ICmp(P, m_Value(C), m_And(m_Value(A), m_Value(B)))))
6870b57cec5SDimitry Andric     return false;
6880b57cec5SDimitry Andric   if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE)
6890b57cec5SDimitry Andric     return false;
6900b57cec5SDimitry Andric   // Matched: select (A & B) == C ? ... : ...
6910b57cec5SDimitry Andric   //          select (A & B) != C ? ... : ...
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric   Value *X = nullptr, *Sh1 = nullptr;
6940b57cec5SDimitry Andric   // Check (A & B) for (X & (1 << i)):
6950b57cec5SDimitry Andric   if (match(A, m_Shl(m_One(), m_Specific(CIV)))) {
6960b57cec5SDimitry Andric     Sh1 = A;
6970b57cec5SDimitry Andric     X = B;
6980b57cec5SDimitry Andric   } else if (match(B, m_Shl(m_One(), m_Specific(CIV)))) {
6990b57cec5SDimitry Andric     Sh1 = B;
7000b57cec5SDimitry Andric     X = A;
7010b57cec5SDimitry Andric   } else {
7020b57cec5SDimitry Andric     // TODO: Could also check for an induction variable containing single
7030b57cec5SDimitry Andric     // bit shifted left by 1 in each iteration.
7040b57cec5SDimitry Andric     return false;
7050b57cec5SDimitry Andric   }
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric   bool TrueIfZero;
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric   // Check C against the possible values for comparison: 0 and (1 << i):
7100b57cec5SDimitry Andric   if (match(C, m_Zero()))
7110b57cec5SDimitry Andric     TrueIfZero = (P == CmpInst::ICMP_EQ);
7120b57cec5SDimitry Andric   else if (C == Sh1)
7130b57cec5SDimitry Andric     TrueIfZero = (P == CmpInst::ICMP_NE);
7140b57cec5SDimitry Andric   else
7150b57cec5SDimitry Andric     return false;
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric   // So far, matched:
7180b57cec5SDimitry Andric   //   select (X & (1 << i)) ? ... : ...
7190b57cec5SDimitry Andric   // including variations of the check against zero/non-zero value.
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   Value *ShouldSameV = nullptr, *ShouldXoredV = nullptr;
7220b57cec5SDimitry Andric   if (TrueIfZero) {
7230b57cec5SDimitry Andric     ShouldSameV = TrueV;
7240b57cec5SDimitry Andric     ShouldXoredV = FalseV;
7250b57cec5SDimitry Andric   } else {
7260b57cec5SDimitry Andric     ShouldSameV = FalseV;
7270b57cec5SDimitry Andric     ShouldXoredV = TrueV;
7280b57cec5SDimitry Andric   }
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   Value *Q = nullptr, *R = nullptr, *Y = nullptr, *Z = nullptr;
7310b57cec5SDimitry Andric   Value *T = nullptr;
7320b57cec5SDimitry Andric   if (match(ShouldXoredV, m_Xor(m_Value(Y), m_Value(Z)))) {
7330b57cec5SDimitry Andric     // Matched: select +++ ? ... : Y ^ Z
7340b57cec5SDimitry Andric     //          select +++ ? Y ^ Z : ...
7350b57cec5SDimitry Andric     // where +++ denotes previously checked matches.
7360b57cec5SDimitry Andric     if (ShouldSameV == Y)
7370b57cec5SDimitry Andric       T = Z;
7380b57cec5SDimitry Andric     else if (ShouldSameV == Z)
7390b57cec5SDimitry Andric       T = Y;
7400b57cec5SDimitry Andric     else
7410b57cec5SDimitry Andric       return false;
7420b57cec5SDimitry Andric     R = ShouldSameV;
7430b57cec5SDimitry Andric     // Matched: select +++ ? R : R ^ T
7440b57cec5SDimitry Andric     //          select +++ ? R ^ T : R
7450b57cec5SDimitry Andric     // depending on TrueIfZero.
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric   } else if (match(ShouldSameV, m_Zero())) {
7480b57cec5SDimitry Andric     // Matched: select +++ ? 0 : ...
7490b57cec5SDimitry Andric     //          select +++ ? ... : 0
7500b57cec5SDimitry Andric     if (!SelI->hasOneUse())
7510b57cec5SDimitry Andric       return false;
7520b57cec5SDimitry Andric     T = ShouldXoredV;
7530b57cec5SDimitry Andric     // Matched: select +++ ? 0 : T
7540b57cec5SDimitry Andric     //          select +++ ? T : 0
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric     Value *U = *SelI->user_begin();
7570b57cec5SDimitry Andric     if (!match(U, m_Xor(m_Specific(SelI), m_Value(R))) &&
7580b57cec5SDimitry Andric         !match(U, m_Xor(m_Value(R), m_Specific(SelI))))
7590b57cec5SDimitry Andric       return false;
7600b57cec5SDimitry Andric     // Matched: xor (select +++ ? 0 : T), R
7610b57cec5SDimitry Andric     //          xor (select +++ ? T : 0), R
7620b57cec5SDimitry Andric   } else
7630b57cec5SDimitry Andric     return false;
7640b57cec5SDimitry Andric 
7650b57cec5SDimitry Andric   // The xor input value T is isolated into its own match so that it could
7660b57cec5SDimitry Andric   // be checked against an induction variable containing a shifted bit
7670b57cec5SDimitry Andric   // (todo).
7680b57cec5SDimitry Andric   // For now, check against (Q << i).
7690b57cec5SDimitry Andric   if (!match(T, m_Shl(m_Value(Q), m_Specific(CIV))) &&
7700b57cec5SDimitry Andric       !match(T, m_Shl(m_ZExt(m_Value(Q)), m_ZExt(m_Specific(CIV)))))
7710b57cec5SDimitry Andric     return false;
7720b57cec5SDimitry Andric   // Matched: select +++ ? R : R ^ (Q << i)
7730b57cec5SDimitry Andric   //          select +++ ? R ^ (Q << i) : R
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   PV.X = X;
7760b57cec5SDimitry Andric   PV.Q = Q;
7770b57cec5SDimitry Andric   PV.R = R;
7780b57cec5SDimitry Andric   PV.Left = true;
7790b57cec5SDimitry Andric   return true;
7800b57cec5SDimitry Andric }
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::matchRightShift(SelectInst *SelI,
7830b57cec5SDimitry Andric       ParsedValues &PV) {
7840b57cec5SDimitry Andric   // Match the following:
7850b57cec5SDimitry Andric   //   select (X & 1) != 0 ? (R >> 1) ^ Q : (R >> 1)
7860b57cec5SDimitry Andric   //   select (X & 1) == 0 ? (R >> 1) : (R >> 1) ^ Q
7870b57cec5SDimitry Andric   // The condition may also check for equality with the masked value, i.e
7880b57cec5SDimitry Andric   //   select (X & 1) == 1 ? (R >> 1) ^ Q : (R >> 1)
7890b57cec5SDimitry Andric   //   select (X & 1) != 1 ? (R >> 1) : (R >> 1) ^ Q
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric   Value *CondV = SelI->getCondition();
7920b57cec5SDimitry Andric   Value *TrueV = SelI->getTrueValue();
7930b57cec5SDimitry Andric   Value *FalseV = SelI->getFalseValue();
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric   using namespace PatternMatch;
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   Value *C = nullptr;
7980b57cec5SDimitry Andric   CmpInst::Predicate P;
7990b57cec5SDimitry Andric   bool TrueIfZero;
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric   if (match(CondV, m_ICmp(P, m_Value(C), m_Zero())) ||
8020b57cec5SDimitry Andric       match(CondV, m_ICmp(P, m_Zero(), m_Value(C)))) {
8030b57cec5SDimitry Andric     if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE)
8040b57cec5SDimitry Andric       return false;
8050b57cec5SDimitry Andric     // Matched: select C == 0 ? ... : ...
8060b57cec5SDimitry Andric     //          select C != 0 ? ... : ...
8070b57cec5SDimitry Andric     TrueIfZero = (P == CmpInst::ICMP_EQ);
8080b57cec5SDimitry Andric   } else if (match(CondV, m_ICmp(P, m_Value(C), m_One())) ||
8090b57cec5SDimitry Andric              match(CondV, m_ICmp(P, m_One(), m_Value(C)))) {
8100b57cec5SDimitry Andric     if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE)
8110b57cec5SDimitry Andric       return false;
8120b57cec5SDimitry Andric     // Matched: select C == 1 ? ... : ...
8130b57cec5SDimitry Andric     //          select C != 1 ? ... : ...
8140b57cec5SDimitry Andric     TrueIfZero = (P == CmpInst::ICMP_NE);
8150b57cec5SDimitry Andric   } else
8160b57cec5SDimitry Andric     return false;
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   Value *X = nullptr;
8190b57cec5SDimitry Andric   if (!match(C, m_And(m_Value(X), m_One())) &&
8200b57cec5SDimitry Andric       !match(C, m_And(m_One(), m_Value(X))))
8210b57cec5SDimitry Andric     return false;
8220b57cec5SDimitry Andric   // Matched: select (X & 1) == +++ ? ... : ...
8230b57cec5SDimitry Andric   //          select (X & 1) != +++ ? ... : ...
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric   Value *R = nullptr, *Q = nullptr;
8260b57cec5SDimitry Andric   if (TrueIfZero) {
8270b57cec5SDimitry Andric     // The select's condition is true if the tested bit is 0.
8280b57cec5SDimitry Andric     // TrueV must be the shift, FalseV must be the xor.
8290b57cec5SDimitry Andric     if (!match(TrueV, m_LShr(m_Value(R), m_One())))
8300b57cec5SDimitry Andric       return false;
8310b57cec5SDimitry Andric     // Matched: select +++ ? (R >> 1) : ...
8320b57cec5SDimitry Andric     if (!match(FalseV, m_Xor(m_Specific(TrueV), m_Value(Q))) &&
8330b57cec5SDimitry Andric         !match(FalseV, m_Xor(m_Value(Q), m_Specific(TrueV))))
8340b57cec5SDimitry Andric       return false;
8350b57cec5SDimitry Andric     // Matched: select +++ ? (R >> 1) : (R >> 1) ^ Q
8360b57cec5SDimitry Andric     // with commuting ^.
8370b57cec5SDimitry Andric   } else {
8380b57cec5SDimitry Andric     // The select's condition is true if the tested bit is 1.
8390b57cec5SDimitry Andric     // TrueV must be the xor, FalseV must be the shift.
8400b57cec5SDimitry Andric     if (!match(FalseV, m_LShr(m_Value(R), m_One())))
8410b57cec5SDimitry Andric       return false;
8420b57cec5SDimitry Andric     // Matched: select +++ ? ... : (R >> 1)
8430b57cec5SDimitry Andric     if (!match(TrueV, m_Xor(m_Specific(FalseV), m_Value(Q))) &&
8440b57cec5SDimitry Andric         !match(TrueV, m_Xor(m_Value(Q), m_Specific(FalseV))))
8450b57cec5SDimitry Andric       return false;
8460b57cec5SDimitry Andric     // Matched: select +++ ? (R >> 1) ^ Q : (R >> 1)
8470b57cec5SDimitry Andric     // with commuting ^.
8480b57cec5SDimitry Andric   }
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric   PV.X = X;
8510b57cec5SDimitry Andric   PV.Q = Q;
8520b57cec5SDimitry Andric   PV.R = R;
8530b57cec5SDimitry Andric   PV.Left = false;
8540b57cec5SDimitry Andric   return true;
8550b57cec5SDimitry Andric }
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::scanSelect(SelectInst *SelI,
8580b57cec5SDimitry Andric       BasicBlock *LoopB, BasicBlock *PrehB, Value *CIV, ParsedValues &PV,
8590b57cec5SDimitry Andric       bool PreScan) {
8600b57cec5SDimitry Andric   using namespace PatternMatch;
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric   // The basic pattern for R = P.Q is:
8630b57cec5SDimitry Andric   // for i = 0..31
8640b57cec5SDimitry Andric   //   R = phi (0, R')
8650b57cec5SDimitry Andric   //   if (P & (1 << i))        ; test-bit(P, i)
8660b57cec5SDimitry Andric   //     R' = R ^ (Q << i)
8670b57cec5SDimitry Andric   //
8680b57cec5SDimitry Andric   // Similarly, the basic pattern for R = (P/Q).Q - P
8690b57cec5SDimitry Andric   // for i = 0..31
8700b57cec5SDimitry Andric   //   R = phi(P, R')
8710b57cec5SDimitry Andric   //   if (R & (1 << i))
8720b57cec5SDimitry Andric   //     R' = R ^ (Q << i)
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric   // There exist idioms, where instead of Q being shifted left, P is shifted
8750b57cec5SDimitry Andric   // right. This produces a result that is shifted right by 32 bits (the
8760b57cec5SDimitry Andric   // non-shifted result is 64-bit).
8770b57cec5SDimitry Andric   //
8780b57cec5SDimitry Andric   // For R = P.Q, this would be:
8790b57cec5SDimitry Andric   // for i = 0..31
8800b57cec5SDimitry Andric   //   R = phi (0, R')
8810b57cec5SDimitry Andric   //   if ((P >> i) & 1)
8820b57cec5SDimitry Andric   //     R' = (R >> 1) ^ Q      ; R is cycled through the loop, so it must
8830b57cec5SDimitry Andric   //   else                     ; be shifted by 1, not i.
8840b57cec5SDimitry Andric   //     R' = R >> 1
8850b57cec5SDimitry Andric   //
8860b57cec5SDimitry Andric   // And for the inverse:
8870b57cec5SDimitry Andric   // for i = 0..31
8880b57cec5SDimitry Andric   //   R = phi (P, R')
8890b57cec5SDimitry Andric   //   if (R & 1)
8900b57cec5SDimitry Andric   //     R' = (R >> 1) ^ Q
8910b57cec5SDimitry Andric   //   else
8920b57cec5SDimitry Andric   //     R' = R >> 1
8930b57cec5SDimitry Andric 
8940b57cec5SDimitry Andric   // The left-shifting idioms share the same pattern:
8950b57cec5SDimitry Andric   //   select (X & (1 << i)) ? R ^ (Q << i) : R
8960b57cec5SDimitry Andric   // Similarly for right-shifting idioms:
8970b57cec5SDimitry Andric   //   select (X & 1) ? (R >> 1) ^ Q
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric   if (matchLeftShift(SelI, CIV, PV)) {
9000b57cec5SDimitry Andric     // If this is a pre-scan, getting this far is sufficient.
9010b57cec5SDimitry Andric     if (PreScan)
9020b57cec5SDimitry Andric       return true;
9030b57cec5SDimitry Andric 
9040b57cec5SDimitry Andric     // Need to make sure that the SelI goes back into R.
9050b57cec5SDimitry Andric     auto *RPhi = dyn_cast<PHINode>(PV.R);
9060b57cec5SDimitry Andric     if (!RPhi)
9070b57cec5SDimitry Andric       return false;
9080b57cec5SDimitry Andric     if (SelI != RPhi->getIncomingValueForBlock(LoopB))
9090b57cec5SDimitry Andric       return false;
9100b57cec5SDimitry Andric     PV.Res = SelI;
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric     // If X is loop invariant, it must be the input polynomial, and the
9130b57cec5SDimitry Andric     // idiom is the basic polynomial multiply.
9140b57cec5SDimitry Andric     if (CurLoop->isLoopInvariant(PV.X)) {
9150b57cec5SDimitry Andric       PV.P = PV.X;
9160b57cec5SDimitry Andric       PV.Inv = false;
9170b57cec5SDimitry Andric     } else {
9180b57cec5SDimitry Andric       // X is not loop invariant. If X == R, this is the inverse pmpy.
9190b57cec5SDimitry Andric       // Otherwise, check for an xor with an invariant value. If the
9200b57cec5SDimitry Andric       // variable argument to the xor is R, then this is still a valid
9210b57cec5SDimitry Andric       // inverse pmpy.
9220b57cec5SDimitry Andric       PV.Inv = true;
9230b57cec5SDimitry Andric       if (PV.X != PV.R) {
9240b57cec5SDimitry Andric         Value *Var = nullptr, *Inv = nullptr, *X1 = nullptr, *X2 = nullptr;
9250b57cec5SDimitry Andric         if (!match(PV.X, m_Xor(m_Value(X1), m_Value(X2))))
9260b57cec5SDimitry Andric           return false;
9270b57cec5SDimitry Andric         auto *I1 = dyn_cast<Instruction>(X1);
9280b57cec5SDimitry Andric         auto *I2 = dyn_cast<Instruction>(X2);
9290b57cec5SDimitry Andric         if (!I1 || I1->getParent() != LoopB) {
9300b57cec5SDimitry Andric           Var = X2;
9310b57cec5SDimitry Andric           Inv = X1;
9320b57cec5SDimitry Andric         } else if (!I2 || I2->getParent() != LoopB) {
9330b57cec5SDimitry Andric           Var = X1;
9340b57cec5SDimitry Andric           Inv = X2;
9350b57cec5SDimitry Andric         } else
9360b57cec5SDimitry Andric           return false;
9370b57cec5SDimitry Andric         if (Var != PV.R)
9380b57cec5SDimitry Andric           return false;
9390b57cec5SDimitry Andric         PV.M = Inv;
9400b57cec5SDimitry Andric       }
9410b57cec5SDimitry Andric       // The input polynomial P still needs to be determined. It will be
9420b57cec5SDimitry Andric       // the entry value of R.
9430b57cec5SDimitry Andric       Value *EntryP = RPhi->getIncomingValueForBlock(PrehB);
9440b57cec5SDimitry Andric       PV.P = EntryP;
9450b57cec5SDimitry Andric     }
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric     return true;
9480b57cec5SDimitry Andric   }
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   if (matchRightShift(SelI, PV)) {
9510b57cec5SDimitry Andric     // If this is an inverse pattern, the Q polynomial must be known at
9520b57cec5SDimitry Andric     // compile time.
9530b57cec5SDimitry Andric     if (PV.Inv && !isa<ConstantInt>(PV.Q))
9540b57cec5SDimitry Andric       return false;
9550b57cec5SDimitry Andric     if (PreScan)
9560b57cec5SDimitry Andric       return true;
9570b57cec5SDimitry Andric     // There is no exact matching of right-shift pmpy.
9580b57cec5SDimitry Andric     return false;
9590b57cec5SDimitry Andric   }
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric   return false;
9620b57cec5SDimitry Andric }
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::isPromotableTo(Value *Val,
9650b57cec5SDimitry Andric       IntegerType *DestTy) {
9660b57cec5SDimitry Andric   IntegerType *T = dyn_cast<IntegerType>(Val->getType());
9670b57cec5SDimitry Andric   if (!T || T->getBitWidth() > DestTy->getBitWidth())
9680b57cec5SDimitry Andric     return false;
9690b57cec5SDimitry Andric   if (T->getBitWidth() == DestTy->getBitWidth())
9700b57cec5SDimitry Andric     return true;
9710b57cec5SDimitry Andric   // Non-instructions are promotable. The reason why an instruction may not
9720b57cec5SDimitry Andric   // be promotable is that it may produce a different result if its operands
9730b57cec5SDimitry Andric   // and the result are promoted, for example, it may produce more non-zero
9740b57cec5SDimitry Andric   // bits. While it would still be possible to represent the proper result
9750b57cec5SDimitry Andric   // in a wider type, it may require adding additional instructions (which
9760b57cec5SDimitry Andric   // we don't want to do).
9770b57cec5SDimitry Andric   Instruction *In = dyn_cast<Instruction>(Val);
9780b57cec5SDimitry Andric   if (!In)
9790b57cec5SDimitry Andric     return true;
9800b57cec5SDimitry Andric   // The bitwidth of the source type is smaller than the destination.
9810b57cec5SDimitry Andric   // Check if the individual operation can be promoted.
9820b57cec5SDimitry Andric   switch (In->getOpcode()) {
9830b57cec5SDimitry Andric     case Instruction::PHI:
9840b57cec5SDimitry Andric     case Instruction::ZExt:
9850b57cec5SDimitry Andric     case Instruction::And:
9860b57cec5SDimitry Andric     case Instruction::Or:
9870b57cec5SDimitry Andric     case Instruction::Xor:
9880b57cec5SDimitry Andric     case Instruction::LShr: // Shift right is ok.
9890b57cec5SDimitry Andric     case Instruction::Select:
9900b57cec5SDimitry Andric     case Instruction::Trunc:
9910b57cec5SDimitry Andric       return true;
9920b57cec5SDimitry Andric     case Instruction::ICmp:
9930b57cec5SDimitry Andric       if (CmpInst *CI = cast<CmpInst>(In))
9940b57cec5SDimitry Andric         return CI->isEquality() || CI->isUnsigned();
9950b57cec5SDimitry Andric       llvm_unreachable("Cast failed unexpectedly");
9960b57cec5SDimitry Andric     case Instruction::Add:
9970b57cec5SDimitry Andric       return In->hasNoSignedWrap() && In->hasNoUnsignedWrap();
9980b57cec5SDimitry Andric   }
9990b57cec5SDimitry Andric   return false;
10000b57cec5SDimitry Andric }
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric void PolynomialMultiplyRecognize::promoteTo(Instruction *In,
10030b57cec5SDimitry Andric       IntegerType *DestTy, BasicBlock *LoopB) {
10040b57cec5SDimitry Andric   Type *OrigTy = In->getType();
10050b57cec5SDimitry Andric   assert(!OrigTy->isVoidTy() && "Invalid instruction to promote");
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric   // Leave boolean values alone.
10080b57cec5SDimitry Andric   if (!In->getType()->isIntegerTy(1))
10090b57cec5SDimitry Andric     In->mutateType(DestTy);
10100b57cec5SDimitry Andric   unsigned DestBW = DestTy->getBitWidth();
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric   // Handle PHIs.
10130b57cec5SDimitry Andric   if (PHINode *P = dyn_cast<PHINode>(In)) {
10140b57cec5SDimitry Andric     unsigned N = P->getNumIncomingValues();
10150b57cec5SDimitry Andric     for (unsigned i = 0; i != N; ++i) {
10160b57cec5SDimitry Andric       BasicBlock *InB = P->getIncomingBlock(i);
10170b57cec5SDimitry Andric       if (InB == LoopB)
10180b57cec5SDimitry Andric         continue;
10190b57cec5SDimitry Andric       Value *InV = P->getIncomingValue(i);
10200b57cec5SDimitry Andric       IntegerType *Ty = cast<IntegerType>(InV->getType());
10210b57cec5SDimitry Andric       // Do not promote values in PHI nodes of type i1.
10220b57cec5SDimitry Andric       if (Ty != P->getType()) {
10230b57cec5SDimitry Andric         // If the value type does not match the PHI type, the PHI type
10240b57cec5SDimitry Andric         // must have been promoted.
10250b57cec5SDimitry Andric         assert(Ty->getBitWidth() < DestBW);
10260b57cec5SDimitry Andric         InV = IRBuilder<>(InB->getTerminator()).CreateZExt(InV, DestTy);
10270b57cec5SDimitry Andric         P->setIncomingValue(i, InV);
10280b57cec5SDimitry Andric       }
10290b57cec5SDimitry Andric     }
10300b57cec5SDimitry Andric   } else if (ZExtInst *Z = dyn_cast<ZExtInst>(In)) {
10310b57cec5SDimitry Andric     Value *Op = Z->getOperand(0);
10320b57cec5SDimitry Andric     if (Op->getType() == Z->getType())
10330b57cec5SDimitry Andric       Z->replaceAllUsesWith(Op);
10340b57cec5SDimitry Andric     Z->eraseFromParent();
10350b57cec5SDimitry Andric     return;
10360b57cec5SDimitry Andric   }
10370b57cec5SDimitry Andric   if (TruncInst *T = dyn_cast<TruncInst>(In)) {
10380b57cec5SDimitry Andric     IntegerType *TruncTy = cast<IntegerType>(OrigTy);
10390b57cec5SDimitry Andric     Value *Mask = ConstantInt::get(DestTy, (1u << TruncTy->getBitWidth()) - 1);
10400b57cec5SDimitry Andric     Value *And = IRBuilder<>(In).CreateAnd(T->getOperand(0), Mask);
10410b57cec5SDimitry Andric     T->replaceAllUsesWith(And);
10420b57cec5SDimitry Andric     T->eraseFromParent();
10430b57cec5SDimitry Andric     return;
10440b57cec5SDimitry Andric   }
10450b57cec5SDimitry Andric 
10460b57cec5SDimitry Andric   // Promote immediates.
10470b57cec5SDimitry Andric   for (unsigned i = 0, n = In->getNumOperands(); i != n; ++i) {
10480b57cec5SDimitry Andric     if (ConstantInt *CI = dyn_cast<ConstantInt>(In->getOperand(i)))
10490b57cec5SDimitry Andric       if (CI->getType()->getBitWidth() < DestBW)
10500b57cec5SDimitry Andric         In->setOperand(i, ConstantInt::get(DestTy, CI->getZExtValue()));
10510b57cec5SDimitry Andric   }
10520b57cec5SDimitry Andric }
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::promoteTypes(BasicBlock *LoopB,
10550b57cec5SDimitry Andric       BasicBlock *ExitB) {
10560b57cec5SDimitry Andric   assert(LoopB);
10570b57cec5SDimitry Andric   // Skip loops where the exit block has more than one predecessor. The values
10580b57cec5SDimitry Andric   // coming from the loop block will be promoted to another type, and so the
10590b57cec5SDimitry Andric   // values coming into the exit block from other predecessors would also have
10600b57cec5SDimitry Andric   // to be promoted.
10610b57cec5SDimitry Andric   if (!ExitB || (ExitB->getSinglePredecessor() != LoopB))
10620b57cec5SDimitry Andric     return false;
10630b57cec5SDimitry Andric   IntegerType *DestTy = getPmpyType();
10640b57cec5SDimitry Andric   // Check if the exit values have types that are no wider than the type
10650b57cec5SDimitry Andric   // that we want to promote to.
10660b57cec5SDimitry Andric   unsigned DestBW = DestTy->getBitWidth();
10670b57cec5SDimitry Andric   for (PHINode &P : ExitB->phis()) {
10680b57cec5SDimitry Andric     if (P.getNumIncomingValues() != 1)
10690b57cec5SDimitry Andric       return false;
10700b57cec5SDimitry Andric     assert(P.getIncomingBlock(0) == LoopB);
10710b57cec5SDimitry Andric     IntegerType *T = dyn_cast<IntegerType>(P.getType());
10720b57cec5SDimitry Andric     if (!T || T->getBitWidth() > DestBW)
10730b57cec5SDimitry Andric       return false;
10740b57cec5SDimitry Andric   }
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric   // Check all instructions in the loop.
10770b57cec5SDimitry Andric   for (Instruction &In : *LoopB)
10780b57cec5SDimitry Andric     if (!In.isTerminator() && !isPromotableTo(&In, DestTy))
10790b57cec5SDimitry Andric       return false;
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric   // Perform the promotion.
10820b57cec5SDimitry Andric   std::vector<Instruction*> LoopIns;
10830b57cec5SDimitry Andric   std::transform(LoopB->begin(), LoopB->end(), std::back_inserter(LoopIns),
10840b57cec5SDimitry Andric                  [](Instruction &In) { return &In; });
10850b57cec5SDimitry Andric   for (Instruction *In : LoopIns)
10860b57cec5SDimitry Andric     if (!In->isTerminator())
10870b57cec5SDimitry Andric       promoteTo(In, DestTy, LoopB);
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric   // Fix up the PHI nodes in the exit block.
10900b57cec5SDimitry Andric   Instruction *EndI = ExitB->getFirstNonPHI();
10910b57cec5SDimitry Andric   BasicBlock::iterator End = EndI ? EndI->getIterator() : ExitB->end();
10920b57cec5SDimitry Andric   for (auto I = ExitB->begin(); I != End; ++I) {
10930b57cec5SDimitry Andric     PHINode *P = dyn_cast<PHINode>(I);
10940b57cec5SDimitry Andric     if (!P)
10950b57cec5SDimitry Andric       break;
10960b57cec5SDimitry Andric     Type *Ty0 = P->getIncomingValue(0)->getType();
10970b57cec5SDimitry Andric     Type *PTy = P->getType();
10980b57cec5SDimitry Andric     if (PTy != Ty0) {
10990b57cec5SDimitry Andric       assert(Ty0 == DestTy);
11000b57cec5SDimitry Andric       // In order to create the trunc, P must have the promoted type.
11010b57cec5SDimitry Andric       P->mutateType(Ty0);
11020b57cec5SDimitry Andric       Value *T = IRBuilder<>(ExitB, End).CreateTrunc(P, PTy);
11030b57cec5SDimitry Andric       // In order for the RAUW to work, the types of P and T must match.
11040b57cec5SDimitry Andric       P->mutateType(PTy);
11050b57cec5SDimitry Andric       P->replaceAllUsesWith(T);
11060b57cec5SDimitry Andric       // Final update of the P's type.
11070b57cec5SDimitry Andric       P->mutateType(Ty0);
11080b57cec5SDimitry Andric       cast<Instruction>(T)->setOperand(0, P);
11090b57cec5SDimitry Andric     }
11100b57cec5SDimitry Andric   }
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric   return true;
11130b57cec5SDimitry Andric }
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::findCycle(Value *Out, Value *In,
11160b57cec5SDimitry Andric       ValueSeq &Cycle) {
11170b57cec5SDimitry Andric   // Out = ..., In, ...
11180b57cec5SDimitry Andric   if (Out == In)
11190b57cec5SDimitry Andric     return true;
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric   auto *BB = cast<Instruction>(Out)->getParent();
11220b57cec5SDimitry Andric   bool HadPhi = false;
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric   for (auto U : Out->users()) {
11250b57cec5SDimitry Andric     auto *I = dyn_cast<Instruction>(&*U);
11260b57cec5SDimitry Andric     if (I == nullptr || I->getParent() != BB)
11270b57cec5SDimitry Andric       continue;
11280b57cec5SDimitry Andric     // Make sure that there are no multi-iteration cycles, e.g.
11290b57cec5SDimitry Andric     //   p1 = phi(p2)
11300b57cec5SDimitry Andric     //   p2 = phi(p1)
11310b57cec5SDimitry Andric     // The cycle p1->p2->p1 would span two loop iterations.
11320b57cec5SDimitry Andric     // Check that there is only one phi in the cycle.
11330b57cec5SDimitry Andric     bool IsPhi = isa<PHINode>(I);
11340b57cec5SDimitry Andric     if (IsPhi && HadPhi)
11350b57cec5SDimitry Andric       return false;
11360b57cec5SDimitry Andric     HadPhi |= IsPhi;
11370b57cec5SDimitry Andric     if (Cycle.count(I))
11380b57cec5SDimitry Andric       return false;
11390b57cec5SDimitry Andric     Cycle.insert(I);
11400b57cec5SDimitry Andric     if (findCycle(I, In, Cycle))
11410b57cec5SDimitry Andric       break;
11420b57cec5SDimitry Andric     Cycle.remove(I);
11430b57cec5SDimitry Andric   }
11440b57cec5SDimitry Andric   return !Cycle.empty();
11450b57cec5SDimitry Andric }
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric void PolynomialMultiplyRecognize::classifyCycle(Instruction *DivI,
11480b57cec5SDimitry Andric       ValueSeq &Cycle, ValueSeq &Early, ValueSeq &Late) {
11490b57cec5SDimitry Andric   // All the values in the cycle that are between the phi node and the
11500b57cec5SDimitry Andric   // divider instruction will be classified as "early", all other values
11510b57cec5SDimitry Andric   // will be "late".
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric   bool IsE = true;
11540b57cec5SDimitry Andric   unsigned I, N = Cycle.size();
11550b57cec5SDimitry Andric   for (I = 0; I < N; ++I) {
11560b57cec5SDimitry Andric     Value *V = Cycle[I];
11570b57cec5SDimitry Andric     if (DivI == V)
11580b57cec5SDimitry Andric       IsE = false;
11590b57cec5SDimitry Andric     else if (!isa<PHINode>(V))
11600b57cec5SDimitry Andric       continue;
11610b57cec5SDimitry Andric     // Stop if found either.
11620b57cec5SDimitry Andric     break;
11630b57cec5SDimitry Andric   }
11640b57cec5SDimitry Andric   // "I" is the index of either DivI or the phi node, whichever was first.
11650b57cec5SDimitry Andric   // "E" is "false" or "true" respectively.
11660b57cec5SDimitry Andric   ValueSeq &First = !IsE ? Early : Late;
11670b57cec5SDimitry Andric   for (unsigned J = 0; J < I; ++J)
11680b57cec5SDimitry Andric     First.insert(Cycle[J]);
11690b57cec5SDimitry Andric 
11700b57cec5SDimitry Andric   ValueSeq &Second = IsE ? Early : Late;
11710b57cec5SDimitry Andric   Second.insert(Cycle[I]);
11720b57cec5SDimitry Andric   for (++I; I < N; ++I) {
11730b57cec5SDimitry Andric     Value *V = Cycle[I];
11740b57cec5SDimitry Andric     if (DivI == V || isa<PHINode>(V))
11750b57cec5SDimitry Andric       break;
11760b57cec5SDimitry Andric     Second.insert(V);
11770b57cec5SDimitry Andric   }
11780b57cec5SDimitry Andric 
11790b57cec5SDimitry Andric   for (; I < N; ++I)
11800b57cec5SDimitry Andric     First.insert(Cycle[I]);
11810b57cec5SDimitry Andric }
11820b57cec5SDimitry Andric 
11830b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::classifyInst(Instruction *UseI,
11840b57cec5SDimitry Andric       ValueSeq &Early, ValueSeq &Late) {
11850b57cec5SDimitry Andric   // Select is an exception, since the condition value does not have to be
11860b57cec5SDimitry Andric   // classified in the same way as the true/false values. The true/false
11870b57cec5SDimitry Andric   // values do have to be both early or both late.
11880b57cec5SDimitry Andric   if (UseI->getOpcode() == Instruction::Select) {
11890b57cec5SDimitry Andric     Value *TV = UseI->getOperand(1), *FV = UseI->getOperand(2);
11900b57cec5SDimitry Andric     if (Early.count(TV) || Early.count(FV)) {
11910b57cec5SDimitry Andric       if (Late.count(TV) || Late.count(FV))
11920b57cec5SDimitry Andric         return false;
11930b57cec5SDimitry Andric       Early.insert(UseI);
11940b57cec5SDimitry Andric     } else if (Late.count(TV) || Late.count(FV)) {
11950b57cec5SDimitry Andric       if (Early.count(TV) || Early.count(FV))
11960b57cec5SDimitry Andric         return false;
11970b57cec5SDimitry Andric       Late.insert(UseI);
11980b57cec5SDimitry Andric     }
11990b57cec5SDimitry Andric     return true;
12000b57cec5SDimitry Andric   }
12010b57cec5SDimitry Andric 
12020b57cec5SDimitry Andric   // Not sure what would be the example of this, but the code below relies
12030b57cec5SDimitry Andric   // on having at least one operand.
12040b57cec5SDimitry Andric   if (UseI->getNumOperands() == 0)
12050b57cec5SDimitry Andric     return true;
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric   bool AE = true, AL = true;
12080b57cec5SDimitry Andric   for (auto &I : UseI->operands()) {
12090b57cec5SDimitry Andric     if (Early.count(&*I))
12100b57cec5SDimitry Andric       AL = false;
12110b57cec5SDimitry Andric     else if (Late.count(&*I))
12120b57cec5SDimitry Andric       AE = false;
12130b57cec5SDimitry Andric   }
12140b57cec5SDimitry Andric   // If the operands appear "all early" and "all late" at the same time,
12150b57cec5SDimitry Andric   // then it means that none of them are actually classified as either.
12160b57cec5SDimitry Andric   // This is harmless.
12170b57cec5SDimitry Andric   if (AE && AL)
12180b57cec5SDimitry Andric     return true;
12190b57cec5SDimitry Andric   // Conversely, if they are neither "all early" nor "all late", then
12200b57cec5SDimitry Andric   // we have a mixture of early and late operands that is not a known
12210b57cec5SDimitry Andric   // exception.
12220b57cec5SDimitry Andric   if (!AE && !AL)
12230b57cec5SDimitry Andric     return false;
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric   // Check that we have covered the two special cases.
12260b57cec5SDimitry Andric   assert(AE != AL);
12270b57cec5SDimitry Andric 
12280b57cec5SDimitry Andric   if (AE)
12290b57cec5SDimitry Andric     Early.insert(UseI);
12300b57cec5SDimitry Andric   else
12310b57cec5SDimitry Andric     Late.insert(UseI);
12320b57cec5SDimitry Andric   return true;
12330b57cec5SDimitry Andric }
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::commutesWithShift(Instruction *I) {
12360b57cec5SDimitry Andric   switch (I->getOpcode()) {
12370b57cec5SDimitry Andric     case Instruction::And:
12380b57cec5SDimitry Andric     case Instruction::Or:
12390b57cec5SDimitry Andric     case Instruction::Xor:
12400b57cec5SDimitry Andric     case Instruction::LShr:
12410b57cec5SDimitry Andric     case Instruction::Shl:
12420b57cec5SDimitry Andric     case Instruction::Select:
12430b57cec5SDimitry Andric     case Instruction::ICmp:
12440b57cec5SDimitry Andric     case Instruction::PHI:
12450b57cec5SDimitry Andric       break;
12460b57cec5SDimitry Andric     default:
12470b57cec5SDimitry Andric       return false;
12480b57cec5SDimitry Andric   }
12490b57cec5SDimitry Andric   return true;
12500b57cec5SDimitry Andric }
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::highBitsAreZero(Value *V,
12530b57cec5SDimitry Andric       unsigned IterCount) {
12540b57cec5SDimitry Andric   auto *T = dyn_cast<IntegerType>(V->getType());
12550b57cec5SDimitry Andric   if (!T)
12560b57cec5SDimitry Andric     return false;
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric   KnownBits Known(T->getBitWidth());
12590b57cec5SDimitry Andric   computeKnownBits(V, Known, DL);
12600b57cec5SDimitry Andric   return Known.countMinLeadingZeros() >= IterCount;
12610b57cec5SDimitry Andric }
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::keepsHighBitsZero(Value *V,
12640b57cec5SDimitry Andric       unsigned IterCount) {
12650b57cec5SDimitry Andric   // Assume that all inputs to the value have the high bits zero.
12660b57cec5SDimitry Andric   // Check if the value itself preserves the zeros in the high bits.
12670b57cec5SDimitry Andric   if (auto *C = dyn_cast<ConstantInt>(V))
12680b57cec5SDimitry Andric     return C->getValue().countLeadingZeros() >= IterCount;
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric   if (auto *I = dyn_cast<Instruction>(V)) {
12710b57cec5SDimitry Andric     switch (I->getOpcode()) {
12720b57cec5SDimitry Andric       case Instruction::And:
12730b57cec5SDimitry Andric       case Instruction::Or:
12740b57cec5SDimitry Andric       case Instruction::Xor:
12750b57cec5SDimitry Andric       case Instruction::LShr:
12760b57cec5SDimitry Andric       case Instruction::Select:
12770b57cec5SDimitry Andric       case Instruction::ICmp:
12780b57cec5SDimitry Andric       case Instruction::PHI:
12790b57cec5SDimitry Andric       case Instruction::ZExt:
12800b57cec5SDimitry Andric         return true;
12810b57cec5SDimitry Andric     }
12820b57cec5SDimitry Andric   }
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric   return false;
12850b57cec5SDimitry Andric }
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::isOperandShifted(Instruction *I, Value *Op) {
12880b57cec5SDimitry Andric   unsigned Opc = I->getOpcode();
12890b57cec5SDimitry Andric   if (Opc == Instruction::Shl || Opc == Instruction::LShr)
12900b57cec5SDimitry Andric     return Op != I->getOperand(1);
12910b57cec5SDimitry Andric   return true;
12920b57cec5SDimitry Andric }
12930b57cec5SDimitry Andric 
12940b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::convertShiftsToLeft(BasicBlock *LoopB,
12950b57cec5SDimitry Andric       BasicBlock *ExitB, unsigned IterCount) {
12960b57cec5SDimitry Andric   Value *CIV = getCountIV(LoopB);
12970b57cec5SDimitry Andric   if (CIV == nullptr)
12980b57cec5SDimitry Andric     return false;
12990b57cec5SDimitry Andric   auto *CIVTy = dyn_cast<IntegerType>(CIV->getType());
13000b57cec5SDimitry Andric   if (CIVTy == nullptr)
13010b57cec5SDimitry Andric     return false;
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric   ValueSeq RShifts;
13040b57cec5SDimitry Andric   ValueSeq Early, Late, Cycled;
13050b57cec5SDimitry Andric 
13060b57cec5SDimitry Andric   // Find all value cycles that contain logical right shifts by 1.
13070b57cec5SDimitry Andric   for (Instruction &I : *LoopB) {
13080b57cec5SDimitry Andric     using namespace PatternMatch;
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric     Value *V = nullptr;
13110b57cec5SDimitry Andric     if (!match(&I, m_LShr(m_Value(V), m_One())))
13120b57cec5SDimitry Andric       continue;
13130b57cec5SDimitry Andric     ValueSeq C;
13140b57cec5SDimitry Andric     if (!findCycle(&I, V, C))
13150b57cec5SDimitry Andric       continue;
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric     // Found a cycle.
13180b57cec5SDimitry Andric     C.insert(&I);
13190b57cec5SDimitry Andric     classifyCycle(&I, C, Early, Late);
13200b57cec5SDimitry Andric     Cycled.insert(C.begin(), C.end());
13210b57cec5SDimitry Andric     RShifts.insert(&I);
13220b57cec5SDimitry Andric   }
13230b57cec5SDimitry Andric 
13240b57cec5SDimitry Andric   // Find the set of all values affected by the shift cycles, i.e. all
13250b57cec5SDimitry Andric   // cycled values, and (recursively) all their users.
13260b57cec5SDimitry Andric   ValueSeq Users(Cycled.begin(), Cycled.end());
13270b57cec5SDimitry Andric   for (unsigned i = 0; i < Users.size(); ++i) {
13280b57cec5SDimitry Andric     Value *V = Users[i];
13290b57cec5SDimitry Andric     if (!isa<IntegerType>(V->getType()))
13300b57cec5SDimitry Andric       return false;
13310b57cec5SDimitry Andric     auto *R = cast<Instruction>(V);
13320b57cec5SDimitry Andric     // If the instruction does not commute with shifts, the loop cannot
13330b57cec5SDimitry Andric     // be unshifted.
13340b57cec5SDimitry Andric     if (!commutesWithShift(R))
13350b57cec5SDimitry Andric       return false;
13360b57cec5SDimitry Andric     for (auto I = R->user_begin(), E = R->user_end(); I != E; ++I) {
13370b57cec5SDimitry Andric       auto *T = cast<Instruction>(*I);
13380b57cec5SDimitry Andric       // Skip users from outside of the loop. They will be handled later.
13390b57cec5SDimitry Andric       // Also, skip the right-shifts and phi nodes, since they mix early
13400b57cec5SDimitry Andric       // and late values.
13410b57cec5SDimitry Andric       if (T->getParent() != LoopB || RShifts.count(T) || isa<PHINode>(T))
13420b57cec5SDimitry Andric         continue;
13430b57cec5SDimitry Andric 
13440b57cec5SDimitry Andric       Users.insert(T);
13450b57cec5SDimitry Andric       if (!classifyInst(T, Early, Late))
13460b57cec5SDimitry Andric         return false;
13470b57cec5SDimitry Andric     }
13480b57cec5SDimitry Andric   }
13490b57cec5SDimitry Andric 
13500b57cec5SDimitry Andric   if (Users.empty())
13510b57cec5SDimitry Andric     return false;
13520b57cec5SDimitry Andric 
13530b57cec5SDimitry Andric   // Verify that high bits remain zero.
13540b57cec5SDimitry Andric   ValueSeq Internal(Users.begin(), Users.end());
13550b57cec5SDimitry Andric   ValueSeq Inputs;
13560b57cec5SDimitry Andric   for (unsigned i = 0; i < Internal.size(); ++i) {
13570b57cec5SDimitry Andric     auto *R = dyn_cast<Instruction>(Internal[i]);
13580b57cec5SDimitry Andric     if (!R)
13590b57cec5SDimitry Andric       continue;
13600b57cec5SDimitry Andric     for (Value *Op : R->operands()) {
13610b57cec5SDimitry Andric       auto *T = dyn_cast<Instruction>(Op);
13620b57cec5SDimitry Andric       if (T && T->getParent() != LoopB)
13630b57cec5SDimitry Andric         Inputs.insert(Op);
13640b57cec5SDimitry Andric       else
13650b57cec5SDimitry Andric         Internal.insert(Op);
13660b57cec5SDimitry Andric     }
13670b57cec5SDimitry Andric   }
13680b57cec5SDimitry Andric   for (Value *V : Inputs)
13690b57cec5SDimitry Andric     if (!highBitsAreZero(V, IterCount))
13700b57cec5SDimitry Andric       return false;
13710b57cec5SDimitry Andric   for (Value *V : Internal)
13720b57cec5SDimitry Andric     if (!keepsHighBitsZero(V, IterCount))
13730b57cec5SDimitry Andric       return false;
13740b57cec5SDimitry Andric 
13750b57cec5SDimitry Andric   // Finally, the work can be done. Unshift each user.
13760b57cec5SDimitry Andric   IRBuilder<> IRB(LoopB);
13770b57cec5SDimitry Andric   std::map<Value*,Value*> ShiftMap;
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric   using CastMapType = std::map<std::pair<Value *, Type *>, Value *>;
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric   CastMapType CastMap;
13820b57cec5SDimitry Andric 
13830b57cec5SDimitry Andric   auto upcast = [] (CastMapType &CM, IRBuilder<> &IRB, Value *V,
13840b57cec5SDimitry Andric         IntegerType *Ty) -> Value* {
13850b57cec5SDimitry Andric     auto H = CM.find(std::make_pair(V, Ty));
13860b57cec5SDimitry Andric     if (H != CM.end())
13870b57cec5SDimitry Andric       return H->second;
13880b57cec5SDimitry Andric     Value *CV = IRB.CreateIntCast(V, Ty, false);
13890b57cec5SDimitry Andric     CM.insert(std::make_pair(std::make_pair(V, Ty), CV));
13900b57cec5SDimitry Andric     return CV;
13910b57cec5SDimitry Andric   };
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric   for (auto I = LoopB->begin(), E = LoopB->end(); I != E; ++I) {
13940b57cec5SDimitry Andric     using namespace PatternMatch;
13950b57cec5SDimitry Andric 
13960b57cec5SDimitry Andric     if (isa<PHINode>(I) || !Users.count(&*I))
13970b57cec5SDimitry Andric       continue;
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric     // Match lshr x, 1.
14000b57cec5SDimitry Andric     Value *V = nullptr;
14010b57cec5SDimitry Andric     if (match(&*I, m_LShr(m_Value(V), m_One()))) {
14020b57cec5SDimitry Andric       replaceAllUsesOfWithIn(&*I, V, LoopB);
14030b57cec5SDimitry Andric       continue;
14040b57cec5SDimitry Andric     }
14050b57cec5SDimitry Andric     // For each non-cycled operand, replace it with the corresponding
14060b57cec5SDimitry Andric     // value shifted left.
14070b57cec5SDimitry Andric     for (auto &J : I->operands()) {
14080b57cec5SDimitry Andric       Value *Op = J.get();
14090b57cec5SDimitry Andric       if (!isOperandShifted(&*I, Op))
14100b57cec5SDimitry Andric         continue;
14110b57cec5SDimitry Andric       if (Users.count(Op))
14120b57cec5SDimitry Andric         continue;
14130b57cec5SDimitry Andric       // Skip shifting zeros.
14140b57cec5SDimitry Andric       if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
14150b57cec5SDimitry Andric         continue;
14160b57cec5SDimitry Andric       // Check if we have already generated a shift for this value.
14170b57cec5SDimitry Andric       auto F = ShiftMap.find(Op);
14180b57cec5SDimitry Andric       Value *W = (F != ShiftMap.end()) ? F->second : nullptr;
14190b57cec5SDimitry Andric       if (W == nullptr) {
14200b57cec5SDimitry Andric         IRB.SetInsertPoint(&*I);
14210b57cec5SDimitry Andric         // First, the shift amount will be CIV or CIV+1, depending on
14220b57cec5SDimitry Andric         // whether the value is early or late. Instead of creating CIV+1,
14230b57cec5SDimitry Andric         // do a single shift of the value.
14240b57cec5SDimitry Andric         Value *ShAmt = CIV, *ShVal = Op;
14250b57cec5SDimitry Andric         auto *VTy = cast<IntegerType>(ShVal->getType());
14260b57cec5SDimitry Andric         auto *ATy = cast<IntegerType>(ShAmt->getType());
14270b57cec5SDimitry Andric         if (Late.count(&*I))
14280b57cec5SDimitry Andric           ShVal = IRB.CreateShl(Op, ConstantInt::get(VTy, 1));
14290b57cec5SDimitry Andric         // Second, the types of the shifted value and the shift amount
14300b57cec5SDimitry Andric         // must match.
14310b57cec5SDimitry Andric         if (VTy != ATy) {
14320b57cec5SDimitry Andric           if (VTy->getBitWidth() < ATy->getBitWidth())
14330b57cec5SDimitry Andric             ShVal = upcast(CastMap, IRB, ShVal, ATy);
14340b57cec5SDimitry Andric           else
14350b57cec5SDimitry Andric             ShAmt = upcast(CastMap, IRB, ShAmt, VTy);
14360b57cec5SDimitry Andric         }
14370b57cec5SDimitry Andric         // Ready to generate the shift and memoize it.
14380b57cec5SDimitry Andric         W = IRB.CreateShl(ShVal, ShAmt);
14390b57cec5SDimitry Andric         ShiftMap.insert(std::make_pair(Op, W));
14400b57cec5SDimitry Andric       }
14410b57cec5SDimitry Andric       I->replaceUsesOfWith(Op, W);
14420b57cec5SDimitry Andric     }
14430b57cec5SDimitry Andric   }
14440b57cec5SDimitry Andric 
14450b57cec5SDimitry Andric   // Update the users outside of the loop to account for having left
14460b57cec5SDimitry Andric   // shifts. They would normally be shifted right in the loop, so shift
14470b57cec5SDimitry Andric   // them right after the loop exit.
14480b57cec5SDimitry Andric   // Take advantage of the loop-closed SSA form, which has all the post-
14490b57cec5SDimitry Andric   // loop values in phi nodes.
14500b57cec5SDimitry Andric   IRB.SetInsertPoint(ExitB, ExitB->getFirstInsertionPt());
14510b57cec5SDimitry Andric   for (auto P = ExitB->begin(), Q = ExitB->end(); P != Q; ++P) {
14520b57cec5SDimitry Andric     if (!isa<PHINode>(P))
14530b57cec5SDimitry Andric       break;
14540b57cec5SDimitry Andric     auto *PN = cast<PHINode>(P);
14550b57cec5SDimitry Andric     Value *U = PN->getIncomingValueForBlock(LoopB);
14560b57cec5SDimitry Andric     if (!Users.count(U))
14570b57cec5SDimitry Andric       continue;
14580b57cec5SDimitry Andric     Value *S = IRB.CreateLShr(PN, ConstantInt::get(PN->getType(), IterCount));
14590b57cec5SDimitry Andric     PN->replaceAllUsesWith(S);
14600b57cec5SDimitry Andric     // The above RAUW will create
14610b57cec5SDimitry Andric     //   S = lshr S, IterCount
14620b57cec5SDimitry Andric     // so we need to fix it back into
14630b57cec5SDimitry Andric     //   S = lshr PN, IterCount
14640b57cec5SDimitry Andric     cast<User>(S)->replaceUsesOfWith(S, PN);
14650b57cec5SDimitry Andric   }
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric   return true;
14680b57cec5SDimitry Andric }
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric void PolynomialMultiplyRecognize::cleanupLoopBody(BasicBlock *LoopB) {
14710b57cec5SDimitry Andric   for (auto &I : *LoopB)
14720b57cec5SDimitry Andric     if (Value *SV = SimplifyInstruction(&I, {DL, &TLI, &DT}))
14730b57cec5SDimitry Andric       I.replaceAllUsesWith(SV);
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric   for (auto I = LoopB->begin(), N = I; I != LoopB->end(); I = N) {
14760b57cec5SDimitry Andric     N = std::next(I);
14770b57cec5SDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(&*I, &TLI);
14780b57cec5SDimitry Andric   }
14790b57cec5SDimitry Andric }
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric unsigned PolynomialMultiplyRecognize::getInverseMxN(unsigned QP) {
14820b57cec5SDimitry Andric   // Arrays of coefficients of Q and the inverse, C.
14830b57cec5SDimitry Andric   // Q[i] = coefficient at x^i.
14840b57cec5SDimitry Andric   std::array<char,32> Q, C;
14850b57cec5SDimitry Andric 
14860b57cec5SDimitry Andric   for (unsigned i = 0; i < 32; ++i) {
14870b57cec5SDimitry Andric     Q[i] = QP & 1;
14880b57cec5SDimitry Andric     QP >>= 1;
14890b57cec5SDimitry Andric   }
14900b57cec5SDimitry Andric   assert(Q[0] == 1);
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric   // Find C, such that
14930b57cec5SDimitry Andric   // (Q[n]*x^n + ... + Q[1]*x + Q[0]) * (C[n]*x^n + ... + C[1]*x + C[0]) = 1
14940b57cec5SDimitry Andric   //
14950b57cec5SDimitry Andric   // For it to have a solution, Q[0] must be 1. Since this is Z2[x], the
14960b57cec5SDimitry Andric   // operations * and + are & and ^ respectively.
14970b57cec5SDimitry Andric   //
14980b57cec5SDimitry Andric   // Find C[i] recursively, by comparing i-th coefficient in the product
14990b57cec5SDimitry Andric   // with 0 (or 1 for i=0).
15000b57cec5SDimitry Andric   //
15010b57cec5SDimitry Andric   // C[0] = 1, since C[0] = Q[0], and Q[0] = 1.
15020b57cec5SDimitry Andric   C[0] = 1;
15030b57cec5SDimitry Andric   for (unsigned i = 1; i < 32; ++i) {
15040b57cec5SDimitry Andric     // Solve for C[i] in:
15050b57cec5SDimitry Andric     //   C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] ^ C[i]Q[0] = 0
15060b57cec5SDimitry Andric     // This is equivalent to
15070b57cec5SDimitry Andric     //   C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] ^ C[i] = 0
15080b57cec5SDimitry Andric     // which is
15090b57cec5SDimitry Andric     //   C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] = C[i]
15100b57cec5SDimitry Andric     unsigned T = 0;
15110b57cec5SDimitry Andric     for (unsigned j = 0; j < i; ++j)
15120b57cec5SDimitry Andric       T = T ^ (C[j] & Q[i-j]);
15130b57cec5SDimitry Andric     C[i] = T;
15140b57cec5SDimitry Andric   }
15150b57cec5SDimitry Andric 
15160b57cec5SDimitry Andric   unsigned QV = 0;
15170b57cec5SDimitry Andric   for (unsigned i = 0; i < 32; ++i)
15180b57cec5SDimitry Andric     if (C[i])
15190b57cec5SDimitry Andric       QV |= (1 << i);
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric   return QV;
15220b57cec5SDimitry Andric }
15230b57cec5SDimitry Andric 
15240b57cec5SDimitry Andric Value *PolynomialMultiplyRecognize::generate(BasicBlock::iterator At,
15250b57cec5SDimitry Andric       ParsedValues &PV) {
15260b57cec5SDimitry Andric   IRBuilder<> B(&*At);
15270b57cec5SDimitry Andric   Module *M = At->getParent()->getParent()->getParent();
15280b57cec5SDimitry Andric   Function *PMF = Intrinsic::getDeclaration(M, Intrinsic::hexagon_M4_pmpyw);
15290b57cec5SDimitry Andric 
15300b57cec5SDimitry Andric   Value *P = PV.P, *Q = PV.Q, *P0 = P;
15310b57cec5SDimitry Andric   unsigned IC = PV.IterCount;
15320b57cec5SDimitry Andric 
15330b57cec5SDimitry Andric   if (PV.M != nullptr)
15340b57cec5SDimitry Andric     P0 = P = B.CreateXor(P, PV.M);
15350b57cec5SDimitry Andric 
15360b57cec5SDimitry Andric   // Create a bit mask to clear the high bits beyond IterCount.
15370b57cec5SDimitry Andric   auto *BMI = ConstantInt::get(P->getType(), APInt::getLowBitsSet(32, IC));
15380b57cec5SDimitry Andric 
15390b57cec5SDimitry Andric   if (PV.IterCount != 32)
15400b57cec5SDimitry Andric     P = B.CreateAnd(P, BMI);
15410b57cec5SDimitry Andric 
15420b57cec5SDimitry Andric   if (PV.Inv) {
15430b57cec5SDimitry Andric     auto *QI = dyn_cast<ConstantInt>(PV.Q);
15440b57cec5SDimitry Andric     assert(QI && QI->getBitWidth() <= 32);
15450b57cec5SDimitry Andric 
15460b57cec5SDimitry Andric     // Again, clearing bits beyond IterCount.
15470b57cec5SDimitry Andric     unsigned M = (1 << PV.IterCount) - 1;
15480b57cec5SDimitry Andric     unsigned Tmp = (QI->getZExtValue() | 1) & M;
15490b57cec5SDimitry Andric     unsigned QV = getInverseMxN(Tmp) & M;
15500b57cec5SDimitry Andric     auto *QVI = ConstantInt::get(QI->getType(), QV);
15510b57cec5SDimitry Andric     P = B.CreateCall(PMF, {P, QVI});
15520b57cec5SDimitry Andric     P = B.CreateTrunc(P, QI->getType());
15530b57cec5SDimitry Andric     if (IC != 32)
15540b57cec5SDimitry Andric       P = B.CreateAnd(P, BMI);
15550b57cec5SDimitry Andric   }
15560b57cec5SDimitry Andric 
15570b57cec5SDimitry Andric   Value *R = B.CreateCall(PMF, {P, Q});
15580b57cec5SDimitry Andric 
15590b57cec5SDimitry Andric   if (PV.M != nullptr)
15600b57cec5SDimitry Andric     R = B.CreateXor(R, B.CreateIntCast(P0, R->getType(), false));
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric   return R;
15630b57cec5SDimitry Andric }
15640b57cec5SDimitry Andric 
15650b57cec5SDimitry Andric static bool hasZeroSignBit(const Value *V) {
15660b57cec5SDimitry Andric   if (const auto *CI = dyn_cast<const ConstantInt>(V))
15670b57cec5SDimitry Andric     return (CI->getType()->getSignBit() & CI->getSExtValue()) == 0;
15680b57cec5SDimitry Andric   const Instruction *I = dyn_cast<const Instruction>(V);
15690b57cec5SDimitry Andric   if (!I)
15700b57cec5SDimitry Andric     return false;
15710b57cec5SDimitry Andric   switch (I->getOpcode()) {
15720b57cec5SDimitry Andric     case Instruction::LShr:
15730b57cec5SDimitry Andric       if (const auto SI = dyn_cast<const ConstantInt>(I->getOperand(1)))
15740b57cec5SDimitry Andric         return SI->getZExtValue() > 0;
15750b57cec5SDimitry Andric       return false;
15760b57cec5SDimitry Andric     case Instruction::Or:
15770b57cec5SDimitry Andric     case Instruction::Xor:
15780b57cec5SDimitry Andric       return hasZeroSignBit(I->getOperand(0)) &&
15790b57cec5SDimitry Andric              hasZeroSignBit(I->getOperand(1));
15800b57cec5SDimitry Andric     case Instruction::And:
15810b57cec5SDimitry Andric       return hasZeroSignBit(I->getOperand(0)) ||
15820b57cec5SDimitry Andric              hasZeroSignBit(I->getOperand(1));
15830b57cec5SDimitry Andric   }
15840b57cec5SDimitry Andric   return false;
15850b57cec5SDimitry Andric }
15860b57cec5SDimitry Andric 
15870b57cec5SDimitry Andric void PolynomialMultiplyRecognize::setupPreSimplifier(Simplifier &S) {
15880b57cec5SDimitry Andric   S.addRule("sink-zext",
15890b57cec5SDimitry Andric     // Sink zext past bitwise operations.
15900b57cec5SDimitry Andric     [](Instruction *I, LLVMContext &Ctx) -> Value* {
15910b57cec5SDimitry Andric       if (I->getOpcode() != Instruction::ZExt)
15920b57cec5SDimitry Andric         return nullptr;
15930b57cec5SDimitry Andric       Instruction *T = dyn_cast<Instruction>(I->getOperand(0));
15940b57cec5SDimitry Andric       if (!T)
15950b57cec5SDimitry Andric         return nullptr;
15960b57cec5SDimitry Andric       switch (T->getOpcode()) {
15970b57cec5SDimitry Andric         case Instruction::And:
15980b57cec5SDimitry Andric         case Instruction::Or:
15990b57cec5SDimitry Andric         case Instruction::Xor:
16000b57cec5SDimitry Andric           break;
16010b57cec5SDimitry Andric         default:
16020b57cec5SDimitry Andric           return nullptr;
16030b57cec5SDimitry Andric       }
16040b57cec5SDimitry Andric       IRBuilder<> B(Ctx);
16050b57cec5SDimitry Andric       return B.CreateBinOp(cast<BinaryOperator>(T)->getOpcode(),
16060b57cec5SDimitry Andric                            B.CreateZExt(T->getOperand(0), I->getType()),
16070b57cec5SDimitry Andric                            B.CreateZExt(T->getOperand(1), I->getType()));
16080b57cec5SDimitry Andric     });
16090b57cec5SDimitry Andric   S.addRule("xor/and -> and/xor",
16100b57cec5SDimitry Andric     // (xor (and x a) (and y a)) -> (and (xor x y) a)
16110b57cec5SDimitry Andric     [](Instruction *I, LLVMContext &Ctx) -> Value* {
16120b57cec5SDimitry Andric       if (I->getOpcode() != Instruction::Xor)
16130b57cec5SDimitry Andric         return nullptr;
16140b57cec5SDimitry Andric       Instruction *And0 = dyn_cast<Instruction>(I->getOperand(0));
16150b57cec5SDimitry Andric       Instruction *And1 = dyn_cast<Instruction>(I->getOperand(1));
16160b57cec5SDimitry Andric       if (!And0 || !And1)
16170b57cec5SDimitry Andric         return nullptr;
16180b57cec5SDimitry Andric       if (And0->getOpcode() != Instruction::And ||
16190b57cec5SDimitry Andric           And1->getOpcode() != Instruction::And)
16200b57cec5SDimitry Andric         return nullptr;
16210b57cec5SDimitry Andric       if (And0->getOperand(1) != And1->getOperand(1))
16220b57cec5SDimitry Andric         return nullptr;
16230b57cec5SDimitry Andric       IRBuilder<> B(Ctx);
16240b57cec5SDimitry Andric       return B.CreateAnd(B.CreateXor(And0->getOperand(0), And1->getOperand(0)),
16250b57cec5SDimitry Andric                          And0->getOperand(1));
16260b57cec5SDimitry Andric     });
16270b57cec5SDimitry Andric   S.addRule("sink binop into select",
16280b57cec5SDimitry Andric     // (Op (select c x y) z) -> (select c (Op x z) (Op y z))
16290b57cec5SDimitry Andric     // (Op x (select c y z)) -> (select c (Op x y) (Op x z))
16300b57cec5SDimitry Andric     [](Instruction *I, LLVMContext &Ctx) -> Value* {
16310b57cec5SDimitry Andric       BinaryOperator *BO = dyn_cast<BinaryOperator>(I);
16320b57cec5SDimitry Andric       if (!BO)
16330b57cec5SDimitry Andric         return nullptr;
16340b57cec5SDimitry Andric       Instruction::BinaryOps Op = BO->getOpcode();
16350b57cec5SDimitry Andric       if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(0))) {
16360b57cec5SDimitry Andric         IRBuilder<> B(Ctx);
16370b57cec5SDimitry Andric         Value *X = Sel->getTrueValue(), *Y = Sel->getFalseValue();
16380b57cec5SDimitry Andric         Value *Z = BO->getOperand(1);
16390b57cec5SDimitry Andric         return B.CreateSelect(Sel->getCondition(),
16400b57cec5SDimitry Andric                               B.CreateBinOp(Op, X, Z),
16410b57cec5SDimitry Andric                               B.CreateBinOp(Op, Y, Z));
16420b57cec5SDimitry Andric       }
16430b57cec5SDimitry Andric       if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(1))) {
16440b57cec5SDimitry Andric         IRBuilder<> B(Ctx);
16450b57cec5SDimitry Andric         Value *X = BO->getOperand(0);
16460b57cec5SDimitry Andric         Value *Y = Sel->getTrueValue(), *Z = Sel->getFalseValue();
16470b57cec5SDimitry Andric         return B.CreateSelect(Sel->getCondition(),
16480b57cec5SDimitry Andric                               B.CreateBinOp(Op, X, Y),
16490b57cec5SDimitry Andric                               B.CreateBinOp(Op, X, Z));
16500b57cec5SDimitry Andric       }
16510b57cec5SDimitry Andric       return nullptr;
16520b57cec5SDimitry Andric     });
16530b57cec5SDimitry Andric   S.addRule("fold select-select",
16540b57cec5SDimitry Andric     // (select c (select c x y) z) -> (select c x z)
16550b57cec5SDimitry Andric     // (select c x (select c y z)) -> (select c x z)
16560b57cec5SDimitry Andric     [](Instruction *I, LLVMContext &Ctx) -> Value* {
16570b57cec5SDimitry Andric       SelectInst *Sel = dyn_cast<SelectInst>(I);
16580b57cec5SDimitry Andric       if (!Sel)
16590b57cec5SDimitry Andric         return nullptr;
16600b57cec5SDimitry Andric       IRBuilder<> B(Ctx);
16610b57cec5SDimitry Andric       Value *C = Sel->getCondition();
16620b57cec5SDimitry Andric       if (SelectInst *Sel0 = dyn_cast<SelectInst>(Sel->getTrueValue())) {
16630b57cec5SDimitry Andric         if (Sel0->getCondition() == C)
16640b57cec5SDimitry Andric           return B.CreateSelect(C, Sel0->getTrueValue(), Sel->getFalseValue());
16650b57cec5SDimitry Andric       }
16660b57cec5SDimitry Andric       if (SelectInst *Sel1 = dyn_cast<SelectInst>(Sel->getFalseValue())) {
16670b57cec5SDimitry Andric         if (Sel1->getCondition() == C)
16680b57cec5SDimitry Andric           return B.CreateSelect(C, Sel->getTrueValue(), Sel1->getFalseValue());
16690b57cec5SDimitry Andric       }
16700b57cec5SDimitry Andric       return nullptr;
16710b57cec5SDimitry Andric     });
16720b57cec5SDimitry Andric   S.addRule("or-signbit -> xor-signbit",
16730b57cec5SDimitry Andric     // (or (lshr x 1) 0x800.0) -> (xor (lshr x 1) 0x800.0)
16740b57cec5SDimitry Andric     [](Instruction *I, LLVMContext &Ctx) -> Value* {
16750b57cec5SDimitry Andric       if (I->getOpcode() != Instruction::Or)
16760b57cec5SDimitry Andric         return nullptr;
16770b57cec5SDimitry Andric       ConstantInt *Msb = dyn_cast<ConstantInt>(I->getOperand(1));
16780b57cec5SDimitry Andric       if (!Msb || Msb->getZExtValue() != Msb->getType()->getSignBit())
16790b57cec5SDimitry Andric         return nullptr;
16800b57cec5SDimitry Andric       if (!hasZeroSignBit(I->getOperand(0)))
16810b57cec5SDimitry Andric         return nullptr;
16820b57cec5SDimitry Andric       return IRBuilder<>(Ctx).CreateXor(I->getOperand(0), Msb);
16830b57cec5SDimitry Andric     });
16840b57cec5SDimitry Andric   S.addRule("sink lshr into binop",
16850b57cec5SDimitry Andric     // (lshr (BitOp x y) c) -> (BitOp (lshr x c) (lshr y c))
16860b57cec5SDimitry Andric     [](Instruction *I, LLVMContext &Ctx) -> Value* {
16870b57cec5SDimitry Andric       if (I->getOpcode() != Instruction::LShr)
16880b57cec5SDimitry Andric         return nullptr;
16890b57cec5SDimitry Andric       BinaryOperator *BitOp = dyn_cast<BinaryOperator>(I->getOperand(0));
16900b57cec5SDimitry Andric       if (!BitOp)
16910b57cec5SDimitry Andric         return nullptr;
16920b57cec5SDimitry Andric       switch (BitOp->getOpcode()) {
16930b57cec5SDimitry Andric         case Instruction::And:
16940b57cec5SDimitry Andric         case Instruction::Or:
16950b57cec5SDimitry Andric         case Instruction::Xor:
16960b57cec5SDimitry Andric           break;
16970b57cec5SDimitry Andric         default:
16980b57cec5SDimitry Andric           return nullptr;
16990b57cec5SDimitry Andric       }
17000b57cec5SDimitry Andric       IRBuilder<> B(Ctx);
17010b57cec5SDimitry Andric       Value *S = I->getOperand(1);
17020b57cec5SDimitry Andric       return B.CreateBinOp(BitOp->getOpcode(),
17030b57cec5SDimitry Andric                 B.CreateLShr(BitOp->getOperand(0), S),
17040b57cec5SDimitry Andric                 B.CreateLShr(BitOp->getOperand(1), S));
17050b57cec5SDimitry Andric     });
17060b57cec5SDimitry Andric   S.addRule("expose bitop-const",
17070b57cec5SDimitry Andric     // (BitOp1 (BitOp2 x a) b) -> (BitOp2 x (BitOp1 a b))
17080b57cec5SDimitry Andric     [](Instruction *I, LLVMContext &Ctx) -> Value* {
17090b57cec5SDimitry Andric       auto IsBitOp = [](unsigned Op) -> bool {
17100b57cec5SDimitry Andric         switch (Op) {
17110b57cec5SDimitry Andric           case Instruction::And:
17120b57cec5SDimitry Andric           case Instruction::Or:
17130b57cec5SDimitry Andric           case Instruction::Xor:
17140b57cec5SDimitry Andric             return true;
17150b57cec5SDimitry Andric         }
17160b57cec5SDimitry Andric         return false;
17170b57cec5SDimitry Andric       };
17180b57cec5SDimitry Andric       BinaryOperator *BitOp1 = dyn_cast<BinaryOperator>(I);
17190b57cec5SDimitry Andric       if (!BitOp1 || !IsBitOp(BitOp1->getOpcode()))
17200b57cec5SDimitry Andric         return nullptr;
17210b57cec5SDimitry Andric       BinaryOperator *BitOp2 = dyn_cast<BinaryOperator>(BitOp1->getOperand(0));
17220b57cec5SDimitry Andric       if (!BitOp2 || !IsBitOp(BitOp2->getOpcode()))
17230b57cec5SDimitry Andric         return nullptr;
17240b57cec5SDimitry Andric       ConstantInt *CA = dyn_cast<ConstantInt>(BitOp2->getOperand(1));
17250b57cec5SDimitry Andric       ConstantInt *CB = dyn_cast<ConstantInt>(BitOp1->getOperand(1));
17260b57cec5SDimitry Andric       if (!CA || !CB)
17270b57cec5SDimitry Andric         return nullptr;
17280b57cec5SDimitry Andric       IRBuilder<> B(Ctx);
17290b57cec5SDimitry Andric       Value *X = BitOp2->getOperand(0);
17300b57cec5SDimitry Andric       return B.CreateBinOp(BitOp2->getOpcode(), X,
17310b57cec5SDimitry Andric                 B.CreateBinOp(BitOp1->getOpcode(), CA, CB));
17320b57cec5SDimitry Andric     });
17330b57cec5SDimitry Andric }
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric void PolynomialMultiplyRecognize::setupPostSimplifier(Simplifier &S) {
17360b57cec5SDimitry Andric   S.addRule("(and (xor (and x a) y) b) -> (and (xor x y) b), if b == b&a",
17370b57cec5SDimitry Andric     [](Instruction *I, LLVMContext &Ctx) -> Value* {
17380b57cec5SDimitry Andric       if (I->getOpcode() != Instruction::And)
17390b57cec5SDimitry Andric         return nullptr;
17400b57cec5SDimitry Andric       Instruction *Xor = dyn_cast<Instruction>(I->getOperand(0));
17410b57cec5SDimitry Andric       ConstantInt *C0 = dyn_cast<ConstantInt>(I->getOperand(1));
17420b57cec5SDimitry Andric       if (!Xor || !C0)
17430b57cec5SDimitry Andric         return nullptr;
17440b57cec5SDimitry Andric       if (Xor->getOpcode() != Instruction::Xor)
17450b57cec5SDimitry Andric         return nullptr;
17460b57cec5SDimitry Andric       Instruction *And0 = dyn_cast<Instruction>(Xor->getOperand(0));
17470b57cec5SDimitry Andric       Instruction *And1 = dyn_cast<Instruction>(Xor->getOperand(1));
17480b57cec5SDimitry Andric       // Pick the first non-null and.
17490b57cec5SDimitry Andric       if (!And0 || And0->getOpcode() != Instruction::And)
17500b57cec5SDimitry Andric         std::swap(And0, And1);
17510b57cec5SDimitry Andric       ConstantInt *C1 = dyn_cast<ConstantInt>(And0->getOperand(1));
17520b57cec5SDimitry Andric       if (!C1)
17530b57cec5SDimitry Andric         return nullptr;
17540b57cec5SDimitry Andric       uint32_t V0 = C0->getZExtValue();
17550b57cec5SDimitry Andric       uint32_t V1 = C1->getZExtValue();
17560b57cec5SDimitry Andric       if (V0 != (V0 & V1))
17570b57cec5SDimitry Andric         return nullptr;
17580b57cec5SDimitry Andric       IRBuilder<> B(Ctx);
17590b57cec5SDimitry Andric       return B.CreateAnd(B.CreateXor(And0->getOperand(0), And1), C0);
17600b57cec5SDimitry Andric     });
17610b57cec5SDimitry Andric }
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::recognize() {
17640b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Starting PolynomialMultiplyRecognize on loop\n"
17650b57cec5SDimitry Andric                     << *CurLoop << '\n');
17660b57cec5SDimitry Andric   // Restrictions:
17670b57cec5SDimitry Andric   // - The loop must consist of a single block.
17680b57cec5SDimitry Andric   // - The iteration count must be known at compile-time.
17690b57cec5SDimitry Andric   // - The loop must have an induction variable starting from 0, and
17700b57cec5SDimitry Andric   //   incremented in each iteration of the loop.
17710b57cec5SDimitry Andric   BasicBlock *LoopB = CurLoop->getHeader();
17720b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Loop header:\n" << *LoopB);
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric   if (LoopB != CurLoop->getLoopLatch())
17750b57cec5SDimitry Andric     return false;
17760b57cec5SDimitry Andric   BasicBlock *ExitB = CurLoop->getExitBlock();
17770b57cec5SDimitry Andric   if (ExitB == nullptr)
17780b57cec5SDimitry Andric     return false;
17790b57cec5SDimitry Andric   BasicBlock *EntryB = CurLoop->getLoopPreheader();
17800b57cec5SDimitry Andric   if (EntryB == nullptr)
17810b57cec5SDimitry Andric     return false;
17820b57cec5SDimitry Andric 
17830b57cec5SDimitry Andric   unsigned IterCount = 0;
17840b57cec5SDimitry Andric   const SCEV *CT = SE.getBackedgeTakenCount(CurLoop);
17850b57cec5SDimitry Andric   if (isa<SCEVCouldNotCompute>(CT))
17860b57cec5SDimitry Andric     return false;
17870b57cec5SDimitry Andric   if (auto *CV = dyn_cast<SCEVConstant>(CT))
17880b57cec5SDimitry Andric     IterCount = CV->getValue()->getZExtValue() + 1;
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric   Value *CIV = getCountIV(LoopB);
17910b57cec5SDimitry Andric   ParsedValues PV;
17920b57cec5SDimitry Andric   Simplifier PreSimp;
17930b57cec5SDimitry Andric   PV.IterCount = IterCount;
17940b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Loop IV: " << *CIV << "\nIterCount: " << IterCount
17950b57cec5SDimitry Andric                     << '\n');
17960b57cec5SDimitry Andric 
17970b57cec5SDimitry Andric   setupPreSimplifier(PreSimp);
17980b57cec5SDimitry Andric 
17990b57cec5SDimitry Andric   // Perform a preliminary scan of select instructions to see if any of them
18000b57cec5SDimitry Andric   // looks like a generator of the polynomial multiply steps. Assume that a
18010b57cec5SDimitry Andric   // loop can only contain a single transformable operation, so stop the
18020b57cec5SDimitry Andric   // traversal after the first reasonable candidate was found.
18030b57cec5SDimitry Andric   // XXX: Currently this approach can modify the loop before being 100% sure
18040b57cec5SDimitry Andric   // that the transformation can be carried out.
18050b57cec5SDimitry Andric   bool FoundPreScan = false;
18060b57cec5SDimitry Andric   auto FeedsPHI = [LoopB](const Value *V) -> bool {
18070b57cec5SDimitry Andric     for (const Value *U : V->users()) {
18080b57cec5SDimitry Andric       if (const auto *P = dyn_cast<const PHINode>(U))
18090b57cec5SDimitry Andric         if (P->getParent() == LoopB)
18100b57cec5SDimitry Andric           return true;
18110b57cec5SDimitry Andric     }
18120b57cec5SDimitry Andric     return false;
18130b57cec5SDimitry Andric   };
18140b57cec5SDimitry Andric   for (Instruction &In : *LoopB) {
18150b57cec5SDimitry Andric     SelectInst *SI = dyn_cast<SelectInst>(&In);
18160b57cec5SDimitry Andric     if (!SI || !FeedsPHI(SI))
18170b57cec5SDimitry Andric       continue;
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric     Simplifier::Context C(SI);
18200b57cec5SDimitry Andric     Value *T = PreSimp.simplify(C);
18210b57cec5SDimitry Andric     SelectInst *SelI = (T && isa<SelectInst>(T)) ? cast<SelectInst>(T) : SI;
18220b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "scanSelect(pre-scan): " << PE(C, SelI) << '\n');
18230b57cec5SDimitry Andric     if (scanSelect(SelI, LoopB, EntryB, CIV, PV, true)) {
18240b57cec5SDimitry Andric       FoundPreScan = true;
18250b57cec5SDimitry Andric       if (SelI != SI) {
18260b57cec5SDimitry Andric         Value *NewSel = C.materialize(LoopB, SI->getIterator());
18270b57cec5SDimitry Andric         SI->replaceAllUsesWith(NewSel);
18280b57cec5SDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(SI, &TLI);
18290b57cec5SDimitry Andric       }
18300b57cec5SDimitry Andric       break;
18310b57cec5SDimitry Andric     }
18320b57cec5SDimitry Andric   }
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric   if (!FoundPreScan) {
18350b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Have not found candidates for pmpy\n");
18360b57cec5SDimitry Andric     return false;
18370b57cec5SDimitry Andric   }
18380b57cec5SDimitry Andric 
18390b57cec5SDimitry Andric   if (!PV.Left) {
18400b57cec5SDimitry Andric     // The right shift version actually only returns the higher bits of
18410b57cec5SDimitry Andric     // the result (each iteration discards the LSB). If we want to convert it
18420b57cec5SDimitry Andric     // to a left-shifting loop, the working data type must be at least as
18430b57cec5SDimitry Andric     // wide as the target's pmpy instruction.
18440b57cec5SDimitry Andric     if (!promoteTypes(LoopB, ExitB))
18450b57cec5SDimitry Andric       return false;
18460b57cec5SDimitry Andric     // Run post-promotion simplifications.
18470b57cec5SDimitry Andric     Simplifier PostSimp;
18480b57cec5SDimitry Andric     setupPostSimplifier(PostSimp);
18490b57cec5SDimitry Andric     for (Instruction &In : *LoopB) {
18500b57cec5SDimitry Andric       SelectInst *SI = dyn_cast<SelectInst>(&In);
18510b57cec5SDimitry Andric       if (!SI || !FeedsPHI(SI))
18520b57cec5SDimitry Andric         continue;
18530b57cec5SDimitry Andric       Simplifier::Context C(SI);
18540b57cec5SDimitry Andric       Value *T = PostSimp.simplify(C);
18550b57cec5SDimitry Andric       SelectInst *SelI = dyn_cast_or_null<SelectInst>(T);
18560b57cec5SDimitry Andric       if (SelI != SI) {
18570b57cec5SDimitry Andric         Value *NewSel = C.materialize(LoopB, SI->getIterator());
18580b57cec5SDimitry Andric         SI->replaceAllUsesWith(NewSel);
18590b57cec5SDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(SI, &TLI);
18600b57cec5SDimitry Andric       }
18610b57cec5SDimitry Andric       break;
18620b57cec5SDimitry Andric     }
18630b57cec5SDimitry Andric 
18640b57cec5SDimitry Andric     if (!convertShiftsToLeft(LoopB, ExitB, IterCount))
18650b57cec5SDimitry Andric       return false;
18660b57cec5SDimitry Andric     cleanupLoopBody(LoopB);
18670b57cec5SDimitry Andric   }
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric   // Scan the loop again, find the generating select instruction.
18700b57cec5SDimitry Andric   bool FoundScan = false;
18710b57cec5SDimitry Andric   for (Instruction &In : *LoopB) {
18720b57cec5SDimitry Andric     SelectInst *SelI = dyn_cast<SelectInst>(&In);
18730b57cec5SDimitry Andric     if (!SelI)
18740b57cec5SDimitry Andric       continue;
18750b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "scanSelect: " << *SelI << '\n');
18760b57cec5SDimitry Andric     FoundScan = scanSelect(SelI, LoopB, EntryB, CIV, PV, false);
18770b57cec5SDimitry Andric     if (FoundScan)
18780b57cec5SDimitry Andric       break;
18790b57cec5SDimitry Andric   }
18800b57cec5SDimitry Andric   assert(FoundScan);
18810b57cec5SDimitry Andric 
18820b57cec5SDimitry Andric   LLVM_DEBUG({
18830b57cec5SDimitry Andric     StringRef PP = (PV.M ? "(P+M)" : "P");
18840b57cec5SDimitry Andric     if (!PV.Inv)
18850b57cec5SDimitry Andric       dbgs() << "Found pmpy idiom: R = " << PP << ".Q\n";
18860b57cec5SDimitry Andric     else
18870b57cec5SDimitry Andric       dbgs() << "Found inverse pmpy idiom: R = (" << PP << "/Q).Q) + "
18880b57cec5SDimitry Andric              << PP << "\n";
18890b57cec5SDimitry Andric     dbgs() << "  Res:" << *PV.Res << "\n  P:" << *PV.P << "\n";
18900b57cec5SDimitry Andric     if (PV.M)
18910b57cec5SDimitry Andric       dbgs() << "  M:" << *PV.M << "\n";
18920b57cec5SDimitry Andric     dbgs() << "  Q:" << *PV.Q << "\n";
18930b57cec5SDimitry Andric     dbgs() << "  Iteration count:" << PV.IterCount << "\n";
18940b57cec5SDimitry Andric   });
18950b57cec5SDimitry Andric 
18960b57cec5SDimitry Andric   BasicBlock::iterator At(EntryB->getTerminator());
18970b57cec5SDimitry Andric   Value *PM = generate(At, PV);
18980b57cec5SDimitry Andric   if (PM == nullptr)
18990b57cec5SDimitry Andric     return false;
19000b57cec5SDimitry Andric 
19010b57cec5SDimitry Andric   if (PM->getType() != PV.Res->getType())
19020b57cec5SDimitry Andric     PM = IRBuilder<>(&*At).CreateIntCast(PM, PV.Res->getType(), false);
19030b57cec5SDimitry Andric 
19040b57cec5SDimitry Andric   PV.Res->replaceAllUsesWith(PM);
19050b57cec5SDimitry Andric   PV.Res->eraseFromParent();
19060b57cec5SDimitry Andric   return true;
19070b57cec5SDimitry Andric }
19080b57cec5SDimitry Andric 
19090b57cec5SDimitry Andric int HexagonLoopIdiomRecognize::getSCEVStride(const SCEVAddRecExpr *S) {
19100b57cec5SDimitry Andric   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
19110b57cec5SDimitry Andric     return SC->getAPInt().getSExtValue();
19120b57cec5SDimitry Andric   return 0;
19130b57cec5SDimitry Andric }
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric bool HexagonLoopIdiomRecognize::isLegalStore(Loop *CurLoop, StoreInst *SI) {
19160b57cec5SDimitry Andric   // Allow volatile stores if HexagonVolatileMemcpy is enabled.
19170b57cec5SDimitry Andric   if (!(SI->isVolatile() && HexagonVolatileMemcpy) && !SI->isSimple())
19180b57cec5SDimitry Andric     return false;
19190b57cec5SDimitry Andric 
19200b57cec5SDimitry Andric   Value *StoredVal = SI->getValueOperand();
19210b57cec5SDimitry Andric   Value *StorePtr = SI->getPointerOperand();
19220b57cec5SDimitry Andric 
19230b57cec5SDimitry Andric   // Reject stores that are so large that they overflow an unsigned.
19240b57cec5SDimitry Andric   uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
19250b57cec5SDimitry Andric   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
19260b57cec5SDimitry Andric     return false;
19270b57cec5SDimitry Andric 
19280b57cec5SDimitry Andric   // See if the pointer expression is an AddRec like {base,+,1} on the current
19290b57cec5SDimitry Andric   // loop, which indicates a strided store.  If we have something else, it's a
19300b57cec5SDimitry Andric   // random store we can't handle.
19310b57cec5SDimitry Andric   auto *StoreEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
19320b57cec5SDimitry Andric   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
19330b57cec5SDimitry Andric     return false;
19340b57cec5SDimitry Andric 
19350b57cec5SDimitry Andric   // Check to see if the stride matches the size of the store.  If so, then we
19360b57cec5SDimitry Andric   // know that every byte is touched in the loop.
19370b57cec5SDimitry Andric   int Stride = getSCEVStride(StoreEv);
19380b57cec5SDimitry Andric   if (Stride == 0)
19390b57cec5SDimitry Andric     return false;
19400b57cec5SDimitry Andric   unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
19410b57cec5SDimitry Andric   if (StoreSize != unsigned(std::abs(Stride)))
19420b57cec5SDimitry Andric     return false;
19430b57cec5SDimitry Andric 
19440b57cec5SDimitry Andric   // The store must be feeding a non-volatile load.
19450b57cec5SDimitry Andric   LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
19460b57cec5SDimitry Andric   if (!LI || !LI->isSimple())
19470b57cec5SDimitry Andric     return false;
19480b57cec5SDimitry Andric 
19490b57cec5SDimitry Andric   // See if the pointer expression is an AddRec like {base,+,1} on the current
19500b57cec5SDimitry Andric   // loop, which indicates a strided load.  If we have something else, it's a
19510b57cec5SDimitry Andric   // random load we can't handle.
19520b57cec5SDimitry Andric   Value *LoadPtr = LI->getPointerOperand();
19530b57cec5SDimitry Andric   auto *LoadEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));
19540b57cec5SDimitry Andric   if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
19550b57cec5SDimitry Andric     return false;
19560b57cec5SDimitry Andric 
19570b57cec5SDimitry Andric   // The store and load must share the same stride.
19580b57cec5SDimitry Andric   if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
19590b57cec5SDimitry Andric     return false;
19600b57cec5SDimitry Andric 
19610b57cec5SDimitry Andric   // Success.  This store can be converted into a memcpy.
19620b57cec5SDimitry Andric   return true;
19630b57cec5SDimitry Andric }
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric /// mayLoopAccessLocation - Return true if the specified loop might access the
19660b57cec5SDimitry Andric /// specified pointer location, which is a loop-strided access.  The 'Access'
19670b57cec5SDimitry Andric /// argument specifies what the verboten forms of access are (read or write).
19680b57cec5SDimitry Andric static bool
19690b57cec5SDimitry Andric mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
19700b57cec5SDimitry Andric                       const SCEV *BECount, unsigned StoreSize,
19710b57cec5SDimitry Andric                       AliasAnalysis &AA,
19720b57cec5SDimitry Andric                       SmallPtrSetImpl<Instruction *> &Ignored) {
19730b57cec5SDimitry Andric   // Get the location that may be stored across the loop.  Since the access
19740b57cec5SDimitry Andric   // is strided positively through memory, we say that the modified location
19750b57cec5SDimitry Andric   // starts at the pointer and has infinite size.
19760b57cec5SDimitry Andric   LocationSize AccessSize = LocationSize::unknown();
19770b57cec5SDimitry Andric 
19780b57cec5SDimitry Andric   // If the loop iterates a fixed number of times, we can refine the access
19790b57cec5SDimitry Andric   // size to be exactly the size of the memset, which is (BECount+1)*StoreSize
19800b57cec5SDimitry Andric   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
19810b57cec5SDimitry Andric     AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) *
19820b57cec5SDimitry Andric                                        StoreSize);
19830b57cec5SDimitry Andric 
19840b57cec5SDimitry Andric   // TODO: For this to be really effective, we have to dive into the pointer
19850b57cec5SDimitry Andric   // operand in the store.  Store to &A[i] of 100 will always return may alias
19860b57cec5SDimitry Andric   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
19870b57cec5SDimitry Andric   // which will then no-alias a store to &A[100].
19880b57cec5SDimitry Andric   MemoryLocation StoreLoc(Ptr, AccessSize);
19890b57cec5SDimitry Andric 
19900b57cec5SDimitry Andric   for (auto *B : L->blocks())
19910b57cec5SDimitry Andric     for (auto &I : *B)
19920b57cec5SDimitry Andric       if (Ignored.count(&I) == 0 &&
19930b57cec5SDimitry Andric           isModOrRefSet(
19940b57cec5SDimitry Andric               intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access)))
19950b57cec5SDimitry Andric         return true;
19960b57cec5SDimitry Andric 
19970b57cec5SDimitry Andric   return false;
19980b57cec5SDimitry Andric }
19990b57cec5SDimitry Andric 
20000b57cec5SDimitry Andric void HexagonLoopIdiomRecognize::collectStores(Loop *CurLoop, BasicBlock *BB,
20010b57cec5SDimitry Andric       SmallVectorImpl<StoreInst*> &Stores) {
20020b57cec5SDimitry Andric   Stores.clear();
20030b57cec5SDimitry Andric   for (Instruction &I : *BB)
20040b57cec5SDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(&I))
20050b57cec5SDimitry Andric       if (isLegalStore(CurLoop, SI))
20060b57cec5SDimitry Andric         Stores.push_back(SI);
20070b57cec5SDimitry Andric }
20080b57cec5SDimitry Andric 
20090b57cec5SDimitry Andric bool HexagonLoopIdiomRecognize::processCopyingStore(Loop *CurLoop,
20100b57cec5SDimitry Andric       StoreInst *SI, const SCEV *BECount) {
20110b57cec5SDimitry Andric   assert((SI->isSimple() || (SI->isVolatile() && HexagonVolatileMemcpy)) &&
20120b57cec5SDimitry Andric          "Expected only non-volatile stores, or Hexagon-specific memcpy"
20130b57cec5SDimitry Andric          "to volatile destination.");
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric   Value *StorePtr = SI->getPointerOperand();
20160b57cec5SDimitry Andric   auto *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
20170b57cec5SDimitry Andric   unsigned Stride = getSCEVStride(StoreEv);
20180b57cec5SDimitry Andric   unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
20190b57cec5SDimitry Andric   if (Stride != StoreSize)
20200b57cec5SDimitry Andric     return false;
20210b57cec5SDimitry Andric 
20220b57cec5SDimitry Andric   // See if the pointer expression is an AddRec like {base,+,1} on the current
20230b57cec5SDimitry Andric   // loop, which indicates a strided load.  If we have something else, it's a
20240b57cec5SDimitry Andric   // random load we can't handle.
20258bcb0991SDimitry Andric   auto *LI = cast<LoadInst>(SI->getValueOperand());
20260b57cec5SDimitry Andric   auto *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
20270b57cec5SDimitry Andric 
20280b57cec5SDimitry Andric   // The trip count of the loop and the base pointer of the addrec SCEV is
20290b57cec5SDimitry Andric   // guaranteed to be loop invariant, which means that it should dominate the
20300b57cec5SDimitry Andric   // header.  This allows us to insert code for it in the preheader.
20310b57cec5SDimitry Andric   BasicBlock *Preheader = CurLoop->getLoopPreheader();
20320b57cec5SDimitry Andric   Instruction *ExpPt = Preheader->getTerminator();
20330b57cec5SDimitry Andric   IRBuilder<> Builder(ExpPt);
20340b57cec5SDimitry Andric   SCEVExpander Expander(*SE, *DL, "hexagon-loop-idiom");
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric   Type *IntPtrTy = Builder.getIntPtrTy(*DL, SI->getPointerAddressSpace());
20370b57cec5SDimitry Andric 
20380b57cec5SDimitry Andric   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
20390b57cec5SDimitry Andric   // this into a memcpy/memmove in the loop preheader now if we want.  However,
20400b57cec5SDimitry Andric   // this would be unsafe to do if there is anything else in the loop that may
20410b57cec5SDimitry Andric   // read or write the memory region we're storing to.  For memcpy, this
20420b57cec5SDimitry Andric   // includes the load that feeds the stores.  Check for an alias by generating
20430b57cec5SDimitry Andric   // the base address and checking everything.
20440b57cec5SDimitry Andric   Value *StoreBasePtr = Expander.expandCodeFor(StoreEv->getStart(),
20450b57cec5SDimitry Andric       Builder.getInt8PtrTy(SI->getPointerAddressSpace()), ExpPt);
20460b57cec5SDimitry Andric   Value *LoadBasePtr = nullptr;
20470b57cec5SDimitry Andric 
20480b57cec5SDimitry Andric   bool Overlap = false;
20490b57cec5SDimitry Andric   bool DestVolatile = SI->isVolatile();
20500b57cec5SDimitry Andric   Type *BECountTy = BECount->getType();
20510b57cec5SDimitry Andric 
20520b57cec5SDimitry Andric   if (DestVolatile) {
20530b57cec5SDimitry Andric     // The trip count must fit in i32, since it is the type of the "num_words"
20540b57cec5SDimitry Andric     // argument to hexagon_memcpy_forward_vp4cp4n2.
20550b57cec5SDimitry Andric     if (StoreSize != 4 || DL->getTypeSizeInBits(BECountTy) > 32) {
20560b57cec5SDimitry Andric CleanupAndExit:
20570b57cec5SDimitry Andric       // If we generated new code for the base pointer, clean up.
20580b57cec5SDimitry Andric       Expander.clear();
20590b57cec5SDimitry Andric       if (StoreBasePtr && (LoadBasePtr != StoreBasePtr)) {
20600b57cec5SDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
20610b57cec5SDimitry Andric         StoreBasePtr = nullptr;
20620b57cec5SDimitry Andric       }
20630b57cec5SDimitry Andric       if (LoadBasePtr) {
20640b57cec5SDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
20650b57cec5SDimitry Andric         LoadBasePtr = nullptr;
20660b57cec5SDimitry Andric       }
20670b57cec5SDimitry Andric       return false;
20680b57cec5SDimitry Andric     }
20690b57cec5SDimitry Andric   }
20700b57cec5SDimitry Andric 
20710b57cec5SDimitry Andric   SmallPtrSet<Instruction*, 2> Ignore1;
20720b57cec5SDimitry Andric   Ignore1.insert(SI);
20730b57cec5SDimitry Andric   if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
20740b57cec5SDimitry Andric                             StoreSize, *AA, Ignore1)) {
20750b57cec5SDimitry Andric     // Check if the load is the offending instruction.
20760b57cec5SDimitry Andric     Ignore1.insert(LI);
20770b57cec5SDimitry Andric     if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop,
20780b57cec5SDimitry Andric                               BECount, StoreSize, *AA, Ignore1)) {
20790b57cec5SDimitry Andric       // Still bad. Nothing we can do.
20800b57cec5SDimitry Andric       goto CleanupAndExit;
20810b57cec5SDimitry Andric     }
20820b57cec5SDimitry Andric     // It worked with the load ignored.
20830b57cec5SDimitry Andric     Overlap = true;
20840b57cec5SDimitry Andric   }
20850b57cec5SDimitry Andric 
20860b57cec5SDimitry Andric   if (!Overlap) {
20870b57cec5SDimitry Andric     if (DisableMemcpyIdiom || !HasMemcpy)
20880b57cec5SDimitry Andric       goto CleanupAndExit;
20890b57cec5SDimitry Andric   } else {
20900b57cec5SDimitry Andric     // Don't generate memmove if this function will be inlined. This is
20910b57cec5SDimitry Andric     // because the caller will undergo this transformation after inlining.
20920b57cec5SDimitry Andric     Function *Func = CurLoop->getHeader()->getParent();
20930b57cec5SDimitry Andric     if (Func->hasFnAttribute(Attribute::AlwaysInline))
20940b57cec5SDimitry Andric       goto CleanupAndExit;
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric     // In case of a memmove, the call to memmove will be executed instead
20970b57cec5SDimitry Andric     // of the loop, so we need to make sure that there is nothing else in
20980b57cec5SDimitry Andric     // the loop than the load, store and instructions that these two depend
20990b57cec5SDimitry Andric     // on.
21000b57cec5SDimitry Andric     SmallVector<Instruction*,2> Insts;
21010b57cec5SDimitry Andric     Insts.push_back(SI);
21020b57cec5SDimitry Andric     Insts.push_back(LI);
21030b57cec5SDimitry Andric     if (!coverLoop(CurLoop, Insts))
21040b57cec5SDimitry Andric       goto CleanupAndExit;
21050b57cec5SDimitry Andric 
21060b57cec5SDimitry Andric     if (DisableMemmoveIdiom || !HasMemmove)
21070b57cec5SDimitry Andric       goto CleanupAndExit;
21080b57cec5SDimitry Andric     bool IsNested = CurLoop->getParentLoop() != nullptr;
21090b57cec5SDimitry Andric     if (IsNested && OnlyNonNestedMemmove)
21100b57cec5SDimitry Andric       goto CleanupAndExit;
21110b57cec5SDimitry Andric   }
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric   // For a memcpy, we have to make sure that the input array is not being
21140b57cec5SDimitry Andric   // mutated by the loop.
21150b57cec5SDimitry Andric   LoadBasePtr = Expander.expandCodeFor(LoadEv->getStart(),
21160b57cec5SDimitry Andric       Builder.getInt8PtrTy(LI->getPointerAddressSpace()), ExpPt);
21170b57cec5SDimitry Andric 
21180b57cec5SDimitry Andric   SmallPtrSet<Instruction*, 2> Ignore2;
21190b57cec5SDimitry Andric   Ignore2.insert(SI);
21200b57cec5SDimitry Andric   if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
21210b57cec5SDimitry Andric                             StoreSize, *AA, Ignore2))
21220b57cec5SDimitry Andric     goto CleanupAndExit;
21230b57cec5SDimitry Andric 
21240b57cec5SDimitry Andric   // Check the stride.
21250b57cec5SDimitry Andric   bool StridePos = getSCEVStride(LoadEv) >= 0;
21260b57cec5SDimitry Andric 
21270b57cec5SDimitry Andric   // Currently, the volatile memcpy only emulates traversing memory forward.
21280b57cec5SDimitry Andric   if (!StridePos && DestVolatile)
21290b57cec5SDimitry Andric     goto CleanupAndExit;
21300b57cec5SDimitry Andric 
21310b57cec5SDimitry Andric   bool RuntimeCheck = (Overlap || DestVolatile);
21320b57cec5SDimitry Andric 
21330b57cec5SDimitry Andric   BasicBlock *ExitB;
21340b57cec5SDimitry Andric   if (RuntimeCheck) {
21350b57cec5SDimitry Andric     // The runtime check needs a single exit block.
21360b57cec5SDimitry Andric     SmallVector<BasicBlock*, 8> ExitBlocks;
21370b57cec5SDimitry Andric     CurLoop->getUniqueExitBlocks(ExitBlocks);
21380b57cec5SDimitry Andric     if (ExitBlocks.size() != 1)
21390b57cec5SDimitry Andric       goto CleanupAndExit;
21400b57cec5SDimitry Andric     ExitB = ExitBlocks[0];
21410b57cec5SDimitry Andric   }
21420b57cec5SDimitry Andric 
21430b57cec5SDimitry Andric   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
21440b57cec5SDimitry Andric   // pointer size if it isn't already.
21450b57cec5SDimitry Andric   LLVMContext &Ctx = SI->getContext();
21460b57cec5SDimitry Andric   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
21470b57cec5SDimitry Andric   DebugLoc DLoc = SI->getDebugLoc();
21480b57cec5SDimitry Andric 
21490b57cec5SDimitry Andric   const SCEV *NumBytesS =
21500b57cec5SDimitry Andric       SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
21510b57cec5SDimitry Andric   if (StoreSize != 1)
21520b57cec5SDimitry Andric     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
21530b57cec5SDimitry Andric                                SCEV::FlagNUW);
21540b57cec5SDimitry Andric   Value *NumBytes = Expander.expandCodeFor(NumBytesS, IntPtrTy, ExpPt);
21550b57cec5SDimitry Andric   if (Instruction *In = dyn_cast<Instruction>(NumBytes))
21560b57cec5SDimitry Andric     if (Value *Simp = SimplifyInstruction(In, {*DL, TLI, DT}))
21570b57cec5SDimitry Andric       NumBytes = Simp;
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric   CallInst *NewCall;
21600b57cec5SDimitry Andric 
21610b57cec5SDimitry Andric   if (RuntimeCheck) {
21620b57cec5SDimitry Andric     unsigned Threshold = RuntimeMemSizeThreshold;
21630b57cec5SDimitry Andric     if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) {
21640b57cec5SDimitry Andric       uint64_t C = CI->getZExtValue();
21650b57cec5SDimitry Andric       if (Threshold != 0 && C < Threshold)
21660b57cec5SDimitry Andric         goto CleanupAndExit;
21670b57cec5SDimitry Andric       if (C < CompileTimeMemSizeThreshold)
21680b57cec5SDimitry Andric         goto CleanupAndExit;
21690b57cec5SDimitry Andric     }
21700b57cec5SDimitry Andric 
21710b57cec5SDimitry Andric     BasicBlock *Header = CurLoop->getHeader();
21720b57cec5SDimitry Andric     Function *Func = Header->getParent();
21730b57cec5SDimitry Andric     Loop *ParentL = LF->getLoopFor(Preheader);
21740b57cec5SDimitry Andric     StringRef HeaderName = Header->getName();
21750b57cec5SDimitry Andric 
21760b57cec5SDimitry Andric     // Create a new (empty) preheader, and update the PHI nodes in the
21770b57cec5SDimitry Andric     // header to use the new preheader.
21780b57cec5SDimitry Andric     BasicBlock *NewPreheader = BasicBlock::Create(Ctx, HeaderName+".rtli.ph",
21790b57cec5SDimitry Andric                                                   Func, Header);
21800b57cec5SDimitry Andric     if (ParentL)
21810b57cec5SDimitry Andric       ParentL->addBasicBlockToLoop(NewPreheader, *LF);
21820b57cec5SDimitry Andric     IRBuilder<>(NewPreheader).CreateBr(Header);
21830b57cec5SDimitry Andric     for (auto &In : *Header) {
21840b57cec5SDimitry Andric       PHINode *PN = dyn_cast<PHINode>(&In);
21850b57cec5SDimitry Andric       if (!PN)
21860b57cec5SDimitry Andric         break;
21870b57cec5SDimitry Andric       int bx = PN->getBasicBlockIndex(Preheader);
21880b57cec5SDimitry Andric       if (bx >= 0)
21890b57cec5SDimitry Andric         PN->setIncomingBlock(bx, NewPreheader);
21900b57cec5SDimitry Andric     }
21910b57cec5SDimitry Andric     DT->addNewBlock(NewPreheader, Preheader);
21920b57cec5SDimitry Andric     DT->changeImmediateDominator(Header, NewPreheader);
21930b57cec5SDimitry Andric 
21940b57cec5SDimitry Andric     // Check for safe conditions to execute memmove.
21950b57cec5SDimitry Andric     // If stride is positive, copying things from higher to lower addresses
21960b57cec5SDimitry Andric     // is equivalent to memmove.  For negative stride, it's the other way
21970b57cec5SDimitry Andric     // around.  Copying forward in memory with positive stride may not be
21980b57cec5SDimitry Andric     // same as memmove since we may be copying values that we just stored
21990b57cec5SDimitry Andric     // in some previous iteration.
22000b57cec5SDimitry Andric     Value *LA = Builder.CreatePtrToInt(LoadBasePtr, IntPtrTy);
22010b57cec5SDimitry Andric     Value *SA = Builder.CreatePtrToInt(StoreBasePtr, IntPtrTy);
22020b57cec5SDimitry Andric     Value *LowA = StridePos ? SA : LA;
22030b57cec5SDimitry Andric     Value *HighA = StridePos ? LA : SA;
22040b57cec5SDimitry Andric     Value *CmpA = Builder.CreateICmpULT(LowA, HighA);
22050b57cec5SDimitry Andric     Value *Cond = CmpA;
22060b57cec5SDimitry Andric 
22070b57cec5SDimitry Andric     // Check for distance between pointers. Since the case LowA < HighA
22080b57cec5SDimitry Andric     // is checked for above, assume LowA >= HighA.
22090b57cec5SDimitry Andric     Value *Dist = Builder.CreateSub(LowA, HighA);
22100b57cec5SDimitry Andric     Value *CmpD = Builder.CreateICmpSLE(NumBytes, Dist);
22110b57cec5SDimitry Andric     Value *CmpEither = Builder.CreateOr(Cond, CmpD);
22120b57cec5SDimitry Andric     Cond = CmpEither;
22130b57cec5SDimitry Andric 
22140b57cec5SDimitry Andric     if (Threshold != 0) {
22150b57cec5SDimitry Andric       Type *Ty = NumBytes->getType();
22160b57cec5SDimitry Andric       Value *Thr = ConstantInt::get(Ty, Threshold);
22170b57cec5SDimitry Andric       Value *CmpB = Builder.CreateICmpULT(Thr, NumBytes);
22180b57cec5SDimitry Andric       Value *CmpBoth = Builder.CreateAnd(Cond, CmpB);
22190b57cec5SDimitry Andric       Cond = CmpBoth;
22200b57cec5SDimitry Andric     }
22210b57cec5SDimitry Andric     BasicBlock *MemmoveB = BasicBlock::Create(Ctx, Header->getName()+".rtli",
22220b57cec5SDimitry Andric                                               Func, NewPreheader);
22230b57cec5SDimitry Andric     if (ParentL)
22240b57cec5SDimitry Andric       ParentL->addBasicBlockToLoop(MemmoveB, *LF);
22250b57cec5SDimitry Andric     Instruction *OldT = Preheader->getTerminator();
22260b57cec5SDimitry Andric     Builder.CreateCondBr(Cond, MemmoveB, NewPreheader);
22270b57cec5SDimitry Andric     OldT->eraseFromParent();
22280b57cec5SDimitry Andric     Preheader->setName(Preheader->getName()+".old");
22290b57cec5SDimitry Andric     DT->addNewBlock(MemmoveB, Preheader);
22300b57cec5SDimitry Andric     // Find the new immediate dominator of the exit block.
22310b57cec5SDimitry Andric     BasicBlock *ExitD = Preheader;
22320b57cec5SDimitry Andric     for (auto PI = pred_begin(ExitB), PE = pred_end(ExitB); PI != PE; ++PI) {
22330b57cec5SDimitry Andric       BasicBlock *PB = *PI;
22340b57cec5SDimitry Andric       ExitD = DT->findNearestCommonDominator(ExitD, PB);
22350b57cec5SDimitry Andric       if (!ExitD)
22360b57cec5SDimitry Andric         break;
22370b57cec5SDimitry Andric     }
22380b57cec5SDimitry Andric     // If the prior immediate dominator of ExitB was dominated by the
22390b57cec5SDimitry Andric     // old preheader, then the old preheader becomes the new immediate
22400b57cec5SDimitry Andric     // dominator.  Otherwise don't change anything (because the newly
22410b57cec5SDimitry Andric     // added blocks are dominated by the old preheader).
22420b57cec5SDimitry Andric     if (ExitD && DT->dominates(Preheader, ExitD)) {
22430b57cec5SDimitry Andric       DomTreeNode *BN = DT->getNode(ExitB);
22440b57cec5SDimitry Andric       DomTreeNode *DN = DT->getNode(ExitD);
22450b57cec5SDimitry Andric       BN->setIDom(DN);
22460b57cec5SDimitry Andric     }
22470b57cec5SDimitry Andric 
22480b57cec5SDimitry Andric     // Add a call to memmove to the conditional block.
22490b57cec5SDimitry Andric     IRBuilder<> CondBuilder(MemmoveB);
22500b57cec5SDimitry Andric     CondBuilder.CreateBr(ExitB);
22510b57cec5SDimitry Andric     CondBuilder.SetInsertPoint(MemmoveB->getTerminator());
22520b57cec5SDimitry Andric 
22530b57cec5SDimitry Andric     if (DestVolatile) {
22540b57cec5SDimitry Andric       Type *Int32Ty = Type::getInt32Ty(Ctx);
22550b57cec5SDimitry Andric       Type *Int32PtrTy = Type::getInt32PtrTy(Ctx);
22560b57cec5SDimitry Andric       Type *VoidTy = Type::getVoidTy(Ctx);
22570b57cec5SDimitry Andric       Module *M = Func->getParent();
22580b57cec5SDimitry Andric       FunctionCallee Fn = M->getOrInsertFunction(
22590b57cec5SDimitry Andric           HexagonVolatileMemcpyName, VoidTy, Int32PtrTy, Int32PtrTy, Int32Ty);
22600b57cec5SDimitry Andric 
22610b57cec5SDimitry Andric       const SCEV *OneS = SE->getConstant(Int32Ty, 1);
22620b57cec5SDimitry Andric       const SCEV *BECount32 = SE->getTruncateOrZeroExtend(BECount, Int32Ty);
22630b57cec5SDimitry Andric       const SCEV *NumWordsS = SE->getAddExpr(BECount32, OneS, SCEV::FlagNUW);
22640b57cec5SDimitry Andric       Value *NumWords = Expander.expandCodeFor(NumWordsS, Int32Ty,
22650b57cec5SDimitry Andric                                                MemmoveB->getTerminator());
22660b57cec5SDimitry Andric       if (Instruction *In = dyn_cast<Instruction>(NumWords))
22670b57cec5SDimitry Andric         if (Value *Simp = SimplifyInstruction(In, {*DL, TLI, DT}))
22680b57cec5SDimitry Andric           NumWords = Simp;
22690b57cec5SDimitry Andric 
22700b57cec5SDimitry Andric       Value *Op0 = (StoreBasePtr->getType() == Int32PtrTy)
22710b57cec5SDimitry Andric                       ? StoreBasePtr
22720b57cec5SDimitry Andric                       : CondBuilder.CreateBitCast(StoreBasePtr, Int32PtrTy);
22730b57cec5SDimitry Andric       Value *Op1 = (LoadBasePtr->getType() == Int32PtrTy)
22740b57cec5SDimitry Andric                       ? LoadBasePtr
22750b57cec5SDimitry Andric                       : CondBuilder.CreateBitCast(LoadBasePtr, Int32PtrTy);
22760b57cec5SDimitry Andric       NewCall = CondBuilder.CreateCall(Fn, {Op0, Op1, NumWords});
22770b57cec5SDimitry Andric     } else {
2278480093f4SDimitry Andric       NewCall = CondBuilder.CreateMemMove(
2279480093f4SDimitry Andric           StoreBasePtr, SI->getAlign(), LoadBasePtr, LI->getAlign(), NumBytes);
22800b57cec5SDimitry Andric     }
22810b57cec5SDimitry Andric   } else {
2282480093f4SDimitry Andric     NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->getAlign(), LoadBasePtr,
2283480093f4SDimitry Andric                                    LI->getAlign(), NumBytes);
22840b57cec5SDimitry Andric     // Okay, the memcpy has been formed.  Zap the original store and
22850b57cec5SDimitry Andric     // anything that feeds into it.
22860b57cec5SDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(SI, TLI);
22870b57cec5SDimitry Andric   }
22880b57cec5SDimitry Andric 
22890b57cec5SDimitry Andric   NewCall->setDebugLoc(DLoc);
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Formed " << (Overlap ? "memmove: " : "memcpy: ")
22920b57cec5SDimitry Andric                     << *NewCall << "\n"
22930b57cec5SDimitry Andric                     << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
22940b57cec5SDimitry Andric                     << "    from store ptr=" << *StoreEv << " at: " << *SI
22950b57cec5SDimitry Andric                     << "\n");
22960b57cec5SDimitry Andric 
22970b57cec5SDimitry Andric   return true;
22980b57cec5SDimitry Andric }
22990b57cec5SDimitry Andric 
23000b57cec5SDimitry Andric // Check if the instructions in Insts, together with their dependencies
23010b57cec5SDimitry Andric // cover the loop in the sense that the loop could be safely eliminated once
23020b57cec5SDimitry Andric // the instructions in Insts are removed.
23030b57cec5SDimitry Andric bool HexagonLoopIdiomRecognize::coverLoop(Loop *L,
23040b57cec5SDimitry Andric       SmallVectorImpl<Instruction*> &Insts) const {
23050b57cec5SDimitry Andric   SmallSet<BasicBlock*,8> LoopBlocks;
23060b57cec5SDimitry Andric   for (auto *B : L->blocks())
23070b57cec5SDimitry Andric     LoopBlocks.insert(B);
23080b57cec5SDimitry Andric 
23090b57cec5SDimitry Andric   SetVector<Instruction*> Worklist(Insts.begin(), Insts.end());
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric   // Collect all instructions from the loop that the instructions in Insts
23120b57cec5SDimitry Andric   // depend on (plus their dependencies, etc.).  These instructions will
23130b57cec5SDimitry Andric   // constitute the expression trees that feed those in Insts, but the trees
23140b57cec5SDimitry Andric   // will be limited only to instructions contained in the loop.
23150b57cec5SDimitry Andric   for (unsigned i = 0; i < Worklist.size(); ++i) {
23160b57cec5SDimitry Andric     Instruction *In = Worklist[i];
23170b57cec5SDimitry Andric     for (auto I = In->op_begin(), E = In->op_end(); I != E; ++I) {
23180b57cec5SDimitry Andric       Instruction *OpI = dyn_cast<Instruction>(I);
23190b57cec5SDimitry Andric       if (!OpI)
23200b57cec5SDimitry Andric         continue;
23210b57cec5SDimitry Andric       BasicBlock *PB = OpI->getParent();
23220b57cec5SDimitry Andric       if (!LoopBlocks.count(PB))
23230b57cec5SDimitry Andric         continue;
23240b57cec5SDimitry Andric       Worklist.insert(OpI);
23250b57cec5SDimitry Andric     }
23260b57cec5SDimitry Andric   }
23270b57cec5SDimitry Andric 
23280b57cec5SDimitry Andric   // Scan all instructions in the loop, if any of them have a user outside
23290b57cec5SDimitry Andric   // of the loop, or outside of the expressions collected above, then either
23300b57cec5SDimitry Andric   // the loop has a side-effect visible outside of it, or there are
23310b57cec5SDimitry Andric   // instructions in it that are not involved in the original set Insts.
23320b57cec5SDimitry Andric   for (auto *B : L->blocks()) {
23330b57cec5SDimitry Andric     for (auto &In : *B) {
23340b57cec5SDimitry Andric       if (isa<BranchInst>(In) || isa<DbgInfoIntrinsic>(In))
23350b57cec5SDimitry Andric         continue;
23360b57cec5SDimitry Andric       if (!Worklist.count(&In) && In.mayHaveSideEffects())
23370b57cec5SDimitry Andric         return false;
2338480093f4SDimitry Andric       for (auto K : In.users()) {
23390b57cec5SDimitry Andric         Instruction *UseI = dyn_cast<Instruction>(K);
23400b57cec5SDimitry Andric         if (!UseI)
23410b57cec5SDimitry Andric           continue;
23420b57cec5SDimitry Andric         BasicBlock *UseB = UseI->getParent();
23430b57cec5SDimitry Andric         if (LF->getLoopFor(UseB) != L)
23440b57cec5SDimitry Andric           return false;
23450b57cec5SDimitry Andric       }
23460b57cec5SDimitry Andric     }
23470b57cec5SDimitry Andric   }
23480b57cec5SDimitry Andric 
23490b57cec5SDimitry Andric   return true;
23500b57cec5SDimitry Andric }
23510b57cec5SDimitry Andric 
23520b57cec5SDimitry Andric /// runOnLoopBlock - Process the specified block, which lives in a counted loop
23530b57cec5SDimitry Andric /// with the specified backedge count.  This block is known to be in the current
23540b57cec5SDimitry Andric /// loop and not in any subloops.
23550b57cec5SDimitry Andric bool HexagonLoopIdiomRecognize::runOnLoopBlock(Loop *CurLoop, BasicBlock *BB,
23560b57cec5SDimitry Andric       const SCEV *BECount, SmallVectorImpl<BasicBlock*> &ExitBlocks) {
23570b57cec5SDimitry Andric   // We can only promote stores in this block if they are unconditionally
23580b57cec5SDimitry Andric   // executed in the loop.  For a block to be unconditionally executed, it has
23590b57cec5SDimitry Andric   // to dominate all the exit blocks of the loop.  Verify this now.
23600b57cec5SDimitry Andric   auto DominatedByBB = [this,BB] (BasicBlock *EB) -> bool {
23610b57cec5SDimitry Andric     return DT->dominates(BB, EB);
23620b57cec5SDimitry Andric   };
23630b57cec5SDimitry Andric   if (!all_of(ExitBlocks, DominatedByBB))
23640b57cec5SDimitry Andric     return false;
23650b57cec5SDimitry Andric 
23660b57cec5SDimitry Andric   bool MadeChange = false;
23670b57cec5SDimitry Andric   // Look for store instructions, which may be optimized to memset/memcpy.
23680b57cec5SDimitry Andric   SmallVector<StoreInst*,8> Stores;
23690b57cec5SDimitry Andric   collectStores(CurLoop, BB, Stores);
23700b57cec5SDimitry Andric 
23710b57cec5SDimitry Andric   // Optimize the store into a memcpy, if it feeds an similarly strided load.
23720b57cec5SDimitry Andric   for (auto &SI : Stores)
23730b57cec5SDimitry Andric     MadeChange |= processCopyingStore(CurLoop, SI, BECount);
23740b57cec5SDimitry Andric 
23750b57cec5SDimitry Andric   return MadeChange;
23760b57cec5SDimitry Andric }
23770b57cec5SDimitry Andric 
23780b57cec5SDimitry Andric bool HexagonLoopIdiomRecognize::runOnCountableLoop(Loop *L) {
23790b57cec5SDimitry Andric   PolynomialMultiplyRecognize PMR(L, *DL, *DT, *TLI, *SE);
23800b57cec5SDimitry Andric   if (PMR.recognize())
23810b57cec5SDimitry Andric     return true;
23820b57cec5SDimitry Andric 
23830b57cec5SDimitry Andric   if (!HasMemcpy && !HasMemmove)
23840b57cec5SDimitry Andric     return false;
23850b57cec5SDimitry Andric 
23860b57cec5SDimitry Andric   const SCEV *BECount = SE->getBackedgeTakenCount(L);
23870b57cec5SDimitry Andric   assert(!isa<SCEVCouldNotCompute>(BECount) &&
23880b57cec5SDimitry Andric          "runOnCountableLoop() called on a loop without a predictable"
23890b57cec5SDimitry Andric          "backedge-taken count");
23900b57cec5SDimitry Andric 
23910b57cec5SDimitry Andric   SmallVector<BasicBlock *, 8> ExitBlocks;
23920b57cec5SDimitry Andric   L->getUniqueExitBlocks(ExitBlocks);
23930b57cec5SDimitry Andric 
23940b57cec5SDimitry Andric   bool Changed = false;
23950b57cec5SDimitry Andric 
23960b57cec5SDimitry Andric   // Scan all the blocks in the loop that are not in subloops.
23970b57cec5SDimitry Andric   for (auto *BB : L->getBlocks()) {
23980b57cec5SDimitry Andric     // Ignore blocks in subloops.
23990b57cec5SDimitry Andric     if (LF->getLoopFor(BB) != L)
24000b57cec5SDimitry Andric       continue;
24010b57cec5SDimitry Andric     Changed |= runOnLoopBlock(L, BB, BECount, ExitBlocks);
24020b57cec5SDimitry Andric   }
24030b57cec5SDimitry Andric 
24040b57cec5SDimitry Andric   return Changed;
24050b57cec5SDimitry Andric }
24060b57cec5SDimitry Andric 
24070b57cec5SDimitry Andric bool HexagonLoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
24080b57cec5SDimitry Andric   const Module &M = *L->getHeader()->getParent()->getParent();
24090b57cec5SDimitry Andric   if (Triple(M.getTargetTriple()).getArch() != Triple::hexagon)
24100b57cec5SDimitry Andric     return false;
24110b57cec5SDimitry Andric 
24120b57cec5SDimitry Andric   if (skipLoop(L))
24130b57cec5SDimitry Andric     return false;
24140b57cec5SDimitry Andric 
24150b57cec5SDimitry Andric   // If the loop could not be converted to canonical form, it must have an
24160b57cec5SDimitry Andric   // indirectbr in it, just give up.
24170b57cec5SDimitry Andric   if (!L->getLoopPreheader())
24180b57cec5SDimitry Andric     return false;
24190b57cec5SDimitry Andric 
24200b57cec5SDimitry Andric   // Disable loop idiom recognition if the function's name is a common idiom.
24210b57cec5SDimitry Andric   StringRef Name = L->getHeader()->getParent()->getName();
24220b57cec5SDimitry Andric   if (Name == "memset" || Name == "memcpy" || Name == "memmove")
24230b57cec5SDimitry Andric     return false;
24240b57cec5SDimitry Andric 
24250b57cec5SDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
24260b57cec5SDimitry Andric   DL = &L->getHeader()->getModule()->getDataLayout();
24270b57cec5SDimitry Andric   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
24280b57cec5SDimitry Andric   LF = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
24298bcb0991SDimitry Andric   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
24308bcb0991SDimitry Andric       *L->getHeader()->getParent());
24310b57cec5SDimitry Andric   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
24320b57cec5SDimitry Andric 
24330b57cec5SDimitry Andric   HasMemcpy = TLI->has(LibFunc_memcpy);
24340b57cec5SDimitry Andric   HasMemmove = TLI->has(LibFunc_memmove);
24350b57cec5SDimitry Andric 
24360b57cec5SDimitry Andric   if (SE->hasLoopInvariantBackedgeTakenCount(L))
24370b57cec5SDimitry Andric     return runOnCountableLoop(L);
24380b57cec5SDimitry Andric   return false;
24390b57cec5SDimitry Andric }
24400b57cec5SDimitry Andric 
24410b57cec5SDimitry Andric Pass *llvm::createHexagonLoopIdiomPass() {
24420b57cec5SDimitry Andric   return new HexagonLoopIdiomRecognize();
24430b57cec5SDimitry Andric }
2444