xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Utils/ScalarEvolutionExpander.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
15ffd83dbSDimitry Andric //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
25ffd83dbSDimitry Andric //
35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65ffd83dbSDimitry Andric //
75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
85ffd83dbSDimitry Andric //
95ffd83dbSDimitry Andric // This file contains the implementation of the scalar evolution expander,
105ffd83dbSDimitry Andric // which is used to generate the code corresponding to a given scalar evolution
115ffd83dbSDimitry Andric // expression.
125ffd83dbSDimitry Andric //
135ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
145ffd83dbSDimitry Andric 
155ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
165ffd83dbSDimitry Andric #include "llvm/ADT/STLExtras.h"
175ffd83dbSDimitry Andric #include "llvm/ADT/SmallSet.h"
185ffd83dbSDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
195ffd83dbSDimitry Andric #include "llvm/Analysis/LoopInfo.h"
205ffd83dbSDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
215ffd83dbSDimitry Andric #include "llvm/IR/DataLayout.h"
225ffd83dbSDimitry Andric #include "llvm/IR/Dominators.h"
235ffd83dbSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
245ffd83dbSDimitry Andric #include "llvm/IR/LLVMContext.h"
255ffd83dbSDimitry Andric #include "llvm/IR/Module.h"
265ffd83dbSDimitry Andric #include "llvm/IR/PatternMatch.h"
275ffd83dbSDimitry Andric #include "llvm/Support/CommandLine.h"
285ffd83dbSDimitry Andric #include "llvm/Support/Debug.h"
295ffd83dbSDimitry Andric #include "llvm/Support/raw_ostream.h"
30*e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
315ffd83dbSDimitry Andric 
325ffd83dbSDimitry Andric using namespace llvm;
335ffd83dbSDimitry Andric 
345ffd83dbSDimitry Andric cl::opt<unsigned> llvm::SCEVCheapExpansionBudget(
355ffd83dbSDimitry Andric     "scev-cheap-expansion-budget", cl::Hidden, cl::init(4),
365ffd83dbSDimitry Andric     cl::desc("When performing SCEV expansion only if it is cheap to do, this "
375ffd83dbSDimitry Andric              "controls the budget that is considered cheap (default = 4)"));
385ffd83dbSDimitry Andric 
395ffd83dbSDimitry Andric using namespace PatternMatch;
405ffd83dbSDimitry Andric 
415ffd83dbSDimitry Andric /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
42*e8d8bef9SDimitry Andric /// reusing an existing cast if a suitable one (= dominating IP) exists, or
435ffd83dbSDimitry Andric /// creating a new one.
445ffd83dbSDimitry Andric Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
455ffd83dbSDimitry Andric                                        Instruction::CastOps Op,
465ffd83dbSDimitry Andric                                        BasicBlock::iterator IP) {
475ffd83dbSDimitry Andric   // This function must be called with the builder having a valid insertion
485ffd83dbSDimitry Andric   // point. It doesn't need to be the actual IP where the uses of the returned
495ffd83dbSDimitry Andric   // cast will be added, but it must dominate such IP.
505ffd83dbSDimitry Andric   // We use this precondition to produce a cast that will dominate all its
515ffd83dbSDimitry Andric   // uses. In particular, this is crucial for the case where the builder's
525ffd83dbSDimitry Andric   // insertion point *is* the point where we were asked to put the cast.
535ffd83dbSDimitry Andric   // Since we don't know the builder's insertion point is actually
545ffd83dbSDimitry Andric   // where the uses will be added (only that it dominates it), we are
555ffd83dbSDimitry Andric   // not allowed to move it.
565ffd83dbSDimitry Andric   BasicBlock::iterator BIP = Builder.GetInsertPoint();
575ffd83dbSDimitry Andric 
585ffd83dbSDimitry Andric   Instruction *Ret = nullptr;
595ffd83dbSDimitry Andric 
605ffd83dbSDimitry Andric   // Check to see if there is already a cast!
61*e8d8bef9SDimitry Andric   for (User *U : V->users()) {
62*e8d8bef9SDimitry Andric     if (U->getType() != Ty)
63*e8d8bef9SDimitry Andric       continue;
64*e8d8bef9SDimitry Andric     CastInst *CI = dyn_cast<CastInst>(U);
65*e8d8bef9SDimitry Andric     if (!CI || CI->getOpcode() != Op)
66*e8d8bef9SDimitry Andric       continue;
67*e8d8bef9SDimitry Andric 
68*e8d8bef9SDimitry Andric     // Found a suitable cast that is at IP or comes before IP. Use it. Note that
69*e8d8bef9SDimitry Andric     // the cast must also properly dominate the Builder's insertion point.
70*e8d8bef9SDimitry Andric     if (IP->getParent() == CI->getParent() && &*BIP != CI &&
71*e8d8bef9SDimitry Andric         (&*IP == CI || CI->comesBefore(&*IP))) {
725ffd83dbSDimitry Andric       Ret = CI;
735ffd83dbSDimitry Andric       break;
745ffd83dbSDimitry Andric     }
75*e8d8bef9SDimitry Andric   }
765ffd83dbSDimitry Andric 
775ffd83dbSDimitry Andric   // Create a new cast.
78*e8d8bef9SDimitry Andric   if (!Ret) {
795ffd83dbSDimitry Andric     Ret = CastInst::Create(Op, V, Ty, V->getName(), &*IP);
80*e8d8bef9SDimitry Andric     rememberInstruction(Ret);
81*e8d8bef9SDimitry Andric   }
825ffd83dbSDimitry Andric 
835ffd83dbSDimitry Andric   // We assert at the end of the function since IP might point to an
845ffd83dbSDimitry Andric   // instruction with different dominance properties than a cast
855ffd83dbSDimitry Andric   // (an invoke for example) and not dominate BIP (but the cast does).
865ffd83dbSDimitry Andric   assert(SE.DT.dominates(Ret, &*BIP));
875ffd83dbSDimitry Andric 
885ffd83dbSDimitry Andric   return Ret;
895ffd83dbSDimitry Andric }
905ffd83dbSDimitry Andric 
91*e8d8bef9SDimitry Andric BasicBlock::iterator
92*e8d8bef9SDimitry Andric SCEVExpander::findInsertPointAfter(Instruction *I, Instruction *MustDominate) {
935ffd83dbSDimitry Andric   BasicBlock::iterator IP = ++I->getIterator();
945ffd83dbSDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(I))
955ffd83dbSDimitry Andric     IP = II->getNormalDest()->begin();
965ffd83dbSDimitry Andric 
975ffd83dbSDimitry Andric   while (isa<PHINode>(IP))
985ffd83dbSDimitry Andric     ++IP;
995ffd83dbSDimitry Andric 
1005ffd83dbSDimitry Andric   if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
1015ffd83dbSDimitry Andric     ++IP;
1025ffd83dbSDimitry Andric   } else if (isa<CatchSwitchInst>(IP)) {
103*e8d8bef9SDimitry Andric     IP = MustDominate->getParent()->getFirstInsertionPt();
1045ffd83dbSDimitry Andric   } else {
1055ffd83dbSDimitry Andric     assert(!IP->isEHPad() && "unexpected eh pad!");
1065ffd83dbSDimitry Andric   }
1075ffd83dbSDimitry Andric 
108*e8d8bef9SDimitry Andric   // Adjust insert point to be after instructions inserted by the expander, so
109*e8d8bef9SDimitry Andric   // we can re-use already inserted instructions. Avoid skipping past the
110*e8d8bef9SDimitry Andric   // original \p MustDominate, in case it is an inserted instruction.
111*e8d8bef9SDimitry Andric   while (isInsertedInstruction(&*IP) && &*IP != MustDominate)
112*e8d8bef9SDimitry Andric     ++IP;
113*e8d8bef9SDimitry Andric 
1145ffd83dbSDimitry Andric   return IP;
1155ffd83dbSDimitry Andric }
1165ffd83dbSDimitry Andric 
1175ffd83dbSDimitry Andric /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
1185ffd83dbSDimitry Andric /// which must be possible with a noop cast, doing what we can to share
1195ffd83dbSDimitry Andric /// the casts.
1205ffd83dbSDimitry Andric Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
1215ffd83dbSDimitry Andric   Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
1225ffd83dbSDimitry Andric   assert((Op == Instruction::BitCast ||
1235ffd83dbSDimitry Andric           Op == Instruction::PtrToInt ||
1245ffd83dbSDimitry Andric           Op == Instruction::IntToPtr) &&
1255ffd83dbSDimitry Andric          "InsertNoopCastOfTo cannot perform non-noop casts!");
1265ffd83dbSDimitry Andric   assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
1275ffd83dbSDimitry Andric          "InsertNoopCastOfTo cannot change sizes!");
1285ffd83dbSDimitry Andric 
129*e8d8bef9SDimitry Andric   // inttoptr only works for integral pointers. For non-integral pointers, we
130*e8d8bef9SDimitry Andric   // can create a GEP on i8* null  with the integral value as index. Note that
131*e8d8bef9SDimitry Andric   // it is safe to use GEP of null instead of inttoptr here, because only
132*e8d8bef9SDimitry Andric   // expressions already based on a GEP of null should be converted to pointers
133*e8d8bef9SDimitry Andric   // during expansion.
134*e8d8bef9SDimitry Andric   if (Op == Instruction::IntToPtr) {
135*e8d8bef9SDimitry Andric     auto *PtrTy = cast<PointerType>(Ty);
136*e8d8bef9SDimitry Andric     if (DL.isNonIntegralPointerType(PtrTy)) {
137*e8d8bef9SDimitry Andric       auto *Int8PtrTy = Builder.getInt8PtrTy(PtrTy->getAddressSpace());
138*e8d8bef9SDimitry Andric       assert(DL.getTypeAllocSize(Int8PtrTy->getElementType()) == 1 &&
139*e8d8bef9SDimitry Andric              "alloc size of i8 must by 1 byte for the GEP to be correct");
140*e8d8bef9SDimitry Andric       auto *GEP = Builder.CreateGEP(
141*e8d8bef9SDimitry Andric           Builder.getInt8Ty(), Constant::getNullValue(Int8PtrTy), V, "uglygep");
142*e8d8bef9SDimitry Andric       return Builder.CreateBitCast(GEP, Ty);
143*e8d8bef9SDimitry Andric     }
144*e8d8bef9SDimitry Andric   }
1455ffd83dbSDimitry Andric   // Short-circuit unnecessary bitcasts.
1465ffd83dbSDimitry Andric   if (Op == Instruction::BitCast) {
1475ffd83dbSDimitry Andric     if (V->getType() == Ty)
1485ffd83dbSDimitry Andric       return V;
1495ffd83dbSDimitry Andric     if (CastInst *CI = dyn_cast<CastInst>(V)) {
1505ffd83dbSDimitry Andric       if (CI->getOperand(0)->getType() == Ty)
1515ffd83dbSDimitry Andric         return CI->getOperand(0);
1525ffd83dbSDimitry Andric     }
1535ffd83dbSDimitry Andric   }
1545ffd83dbSDimitry Andric   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
1555ffd83dbSDimitry Andric   if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
1565ffd83dbSDimitry Andric       SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
1575ffd83dbSDimitry Andric     if (CastInst *CI = dyn_cast<CastInst>(V))
1585ffd83dbSDimitry Andric       if ((CI->getOpcode() == Instruction::PtrToInt ||
1595ffd83dbSDimitry Andric            CI->getOpcode() == Instruction::IntToPtr) &&
1605ffd83dbSDimitry Andric           SE.getTypeSizeInBits(CI->getType()) ==
1615ffd83dbSDimitry Andric           SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
1625ffd83dbSDimitry Andric         return CI->getOperand(0);
1635ffd83dbSDimitry Andric     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1645ffd83dbSDimitry Andric       if ((CE->getOpcode() == Instruction::PtrToInt ||
1655ffd83dbSDimitry Andric            CE->getOpcode() == Instruction::IntToPtr) &&
1665ffd83dbSDimitry Andric           SE.getTypeSizeInBits(CE->getType()) ==
1675ffd83dbSDimitry Andric           SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
1685ffd83dbSDimitry Andric         return CE->getOperand(0);
1695ffd83dbSDimitry Andric   }
1705ffd83dbSDimitry Andric 
1715ffd83dbSDimitry Andric   // Fold a cast of a constant.
1725ffd83dbSDimitry Andric   if (Constant *C = dyn_cast<Constant>(V))
1735ffd83dbSDimitry Andric     return ConstantExpr::getCast(Op, C, Ty);
1745ffd83dbSDimitry Andric 
1755ffd83dbSDimitry Andric   // Cast the argument at the beginning of the entry block, after
1765ffd83dbSDimitry Andric   // any bitcasts of other arguments.
1775ffd83dbSDimitry Andric   if (Argument *A = dyn_cast<Argument>(V)) {
1785ffd83dbSDimitry Andric     BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
1795ffd83dbSDimitry Andric     while ((isa<BitCastInst>(IP) &&
1805ffd83dbSDimitry Andric             isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
1815ffd83dbSDimitry Andric             cast<BitCastInst>(IP)->getOperand(0) != A) ||
1825ffd83dbSDimitry Andric            isa<DbgInfoIntrinsic>(IP))
1835ffd83dbSDimitry Andric       ++IP;
1845ffd83dbSDimitry Andric     return ReuseOrCreateCast(A, Ty, Op, IP);
1855ffd83dbSDimitry Andric   }
1865ffd83dbSDimitry Andric 
1875ffd83dbSDimitry Andric   // Cast the instruction immediately after the instruction.
1885ffd83dbSDimitry Andric   Instruction *I = cast<Instruction>(V);
189*e8d8bef9SDimitry Andric   BasicBlock::iterator IP = findInsertPointAfter(I, &*Builder.GetInsertPoint());
1905ffd83dbSDimitry Andric   return ReuseOrCreateCast(I, Ty, Op, IP);
1915ffd83dbSDimitry Andric }
1925ffd83dbSDimitry Andric 
1935ffd83dbSDimitry Andric /// InsertBinop - Insert the specified binary operator, doing a small amount
1945ffd83dbSDimitry Andric /// of work to avoid inserting an obviously redundant operation, and hoisting
1955ffd83dbSDimitry Andric /// to an outer loop when the opportunity is there and it is safe.
1965ffd83dbSDimitry Andric Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
1975ffd83dbSDimitry Andric                                  Value *LHS, Value *RHS,
1985ffd83dbSDimitry Andric                                  SCEV::NoWrapFlags Flags, bool IsSafeToHoist) {
1995ffd83dbSDimitry Andric   // Fold a binop with constant operands.
2005ffd83dbSDimitry Andric   if (Constant *CLHS = dyn_cast<Constant>(LHS))
2015ffd83dbSDimitry Andric     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2025ffd83dbSDimitry Andric       return ConstantExpr::get(Opcode, CLHS, CRHS);
2035ffd83dbSDimitry Andric 
2045ffd83dbSDimitry Andric   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
2055ffd83dbSDimitry Andric   unsigned ScanLimit = 6;
2065ffd83dbSDimitry Andric   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
2075ffd83dbSDimitry Andric   // Scanning starts from the last instruction before the insertion point.
2085ffd83dbSDimitry Andric   BasicBlock::iterator IP = Builder.GetInsertPoint();
2095ffd83dbSDimitry Andric   if (IP != BlockBegin) {
2105ffd83dbSDimitry Andric     --IP;
2115ffd83dbSDimitry Andric     for (; ScanLimit; --IP, --ScanLimit) {
2125ffd83dbSDimitry Andric       // Don't count dbg.value against the ScanLimit, to avoid perturbing the
2135ffd83dbSDimitry Andric       // generated code.
2145ffd83dbSDimitry Andric       if (isa<DbgInfoIntrinsic>(IP))
2155ffd83dbSDimitry Andric         ScanLimit++;
2165ffd83dbSDimitry Andric 
2175ffd83dbSDimitry Andric       auto canGenerateIncompatiblePoison = [&Flags](Instruction *I) {
2185ffd83dbSDimitry Andric         // Ensure that no-wrap flags match.
2195ffd83dbSDimitry Andric         if (isa<OverflowingBinaryOperator>(I)) {
2205ffd83dbSDimitry Andric           if (I->hasNoSignedWrap() != (Flags & SCEV::FlagNSW))
2215ffd83dbSDimitry Andric             return true;
2225ffd83dbSDimitry Andric           if (I->hasNoUnsignedWrap() != (Flags & SCEV::FlagNUW))
2235ffd83dbSDimitry Andric             return true;
2245ffd83dbSDimitry Andric         }
2255ffd83dbSDimitry Andric         // Conservatively, do not use any instruction which has any of exact
2265ffd83dbSDimitry Andric         // flags installed.
2275ffd83dbSDimitry Andric         if (isa<PossiblyExactOperator>(I) && I->isExact())
2285ffd83dbSDimitry Andric           return true;
2295ffd83dbSDimitry Andric         return false;
2305ffd83dbSDimitry Andric       };
2315ffd83dbSDimitry Andric       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
2325ffd83dbSDimitry Andric           IP->getOperand(1) == RHS && !canGenerateIncompatiblePoison(&*IP))
2335ffd83dbSDimitry Andric         return &*IP;
2345ffd83dbSDimitry Andric       if (IP == BlockBegin) break;
2355ffd83dbSDimitry Andric     }
2365ffd83dbSDimitry Andric   }
2375ffd83dbSDimitry Andric 
2385ffd83dbSDimitry Andric   // Save the original insertion point so we can restore it when we're done.
2395ffd83dbSDimitry Andric   DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
2405ffd83dbSDimitry Andric   SCEVInsertPointGuard Guard(Builder, this);
2415ffd83dbSDimitry Andric 
2425ffd83dbSDimitry Andric   if (IsSafeToHoist) {
2435ffd83dbSDimitry Andric     // Move the insertion point out of as many loops as we can.
2445ffd83dbSDimitry Andric     while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
2455ffd83dbSDimitry Andric       if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
2465ffd83dbSDimitry Andric       BasicBlock *Preheader = L->getLoopPreheader();
2475ffd83dbSDimitry Andric       if (!Preheader) break;
2485ffd83dbSDimitry Andric 
2495ffd83dbSDimitry Andric       // Ok, move up a level.
2505ffd83dbSDimitry Andric       Builder.SetInsertPoint(Preheader->getTerminator());
2515ffd83dbSDimitry Andric     }
2525ffd83dbSDimitry Andric   }
2535ffd83dbSDimitry Andric 
2545ffd83dbSDimitry Andric   // If we haven't found this binop, insert it.
2555ffd83dbSDimitry Andric   Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
2565ffd83dbSDimitry Andric   BO->setDebugLoc(Loc);
2575ffd83dbSDimitry Andric   if (Flags & SCEV::FlagNUW)
2585ffd83dbSDimitry Andric     BO->setHasNoUnsignedWrap();
2595ffd83dbSDimitry Andric   if (Flags & SCEV::FlagNSW)
2605ffd83dbSDimitry Andric     BO->setHasNoSignedWrap();
2615ffd83dbSDimitry Andric 
2625ffd83dbSDimitry Andric   return BO;
2635ffd83dbSDimitry Andric }
2645ffd83dbSDimitry Andric 
2655ffd83dbSDimitry Andric /// FactorOutConstant - Test if S is divisible by Factor, using signed
2665ffd83dbSDimitry Andric /// division. If so, update S with Factor divided out and return true.
2675ffd83dbSDimitry Andric /// S need not be evenly divisible if a reasonable remainder can be
2685ffd83dbSDimitry Andric /// computed.
2695ffd83dbSDimitry Andric static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
2705ffd83dbSDimitry Andric                               const SCEV *Factor, ScalarEvolution &SE,
2715ffd83dbSDimitry Andric                               const DataLayout &DL) {
2725ffd83dbSDimitry Andric   // Everything is divisible by one.
2735ffd83dbSDimitry Andric   if (Factor->isOne())
2745ffd83dbSDimitry Andric     return true;
2755ffd83dbSDimitry Andric 
2765ffd83dbSDimitry Andric   // x/x == 1.
2775ffd83dbSDimitry Andric   if (S == Factor) {
2785ffd83dbSDimitry Andric     S = SE.getConstant(S->getType(), 1);
2795ffd83dbSDimitry Andric     return true;
2805ffd83dbSDimitry Andric   }
2815ffd83dbSDimitry Andric 
2825ffd83dbSDimitry Andric   // For a Constant, check for a multiple of the given factor.
2835ffd83dbSDimitry Andric   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2845ffd83dbSDimitry Andric     // 0/x == 0.
2855ffd83dbSDimitry Andric     if (C->isZero())
2865ffd83dbSDimitry Andric       return true;
2875ffd83dbSDimitry Andric     // Check for divisibility.
2885ffd83dbSDimitry Andric     if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
2895ffd83dbSDimitry Andric       ConstantInt *CI =
2905ffd83dbSDimitry Andric           ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt()));
2915ffd83dbSDimitry Andric       // If the quotient is zero and the remainder is non-zero, reject
2925ffd83dbSDimitry Andric       // the value at this scale. It will be considered for subsequent
2935ffd83dbSDimitry Andric       // smaller scales.
2945ffd83dbSDimitry Andric       if (!CI->isZero()) {
2955ffd83dbSDimitry Andric         const SCEV *Div = SE.getConstant(CI);
2965ffd83dbSDimitry Andric         S = Div;
2975ffd83dbSDimitry Andric         Remainder = SE.getAddExpr(
2985ffd83dbSDimitry Andric             Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt())));
2995ffd83dbSDimitry Andric         return true;
3005ffd83dbSDimitry Andric       }
3015ffd83dbSDimitry Andric     }
3025ffd83dbSDimitry Andric   }
3035ffd83dbSDimitry Andric 
3045ffd83dbSDimitry Andric   // In a Mul, check if there is a constant operand which is a multiple
3055ffd83dbSDimitry Andric   // of the given factor.
3065ffd83dbSDimitry Andric   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
3075ffd83dbSDimitry Andric     // Size is known, check if there is a constant operand which is a multiple
3085ffd83dbSDimitry Andric     // of the given factor. If so, we can factor it.
3095ffd83dbSDimitry Andric     if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor))
3105ffd83dbSDimitry Andric       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
3115ffd83dbSDimitry Andric         if (!C->getAPInt().srem(FC->getAPInt())) {
312*e8d8bef9SDimitry Andric           SmallVector<const SCEV *, 4> NewMulOps(M->operands());
3135ffd83dbSDimitry Andric           NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt()));
3145ffd83dbSDimitry Andric           S = SE.getMulExpr(NewMulOps);
3155ffd83dbSDimitry Andric           return true;
3165ffd83dbSDimitry Andric         }
3175ffd83dbSDimitry Andric   }
3185ffd83dbSDimitry Andric 
3195ffd83dbSDimitry Andric   // In an AddRec, check if both start and step are divisible.
3205ffd83dbSDimitry Andric   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
3215ffd83dbSDimitry Andric     const SCEV *Step = A->getStepRecurrence(SE);
3225ffd83dbSDimitry Andric     const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
3235ffd83dbSDimitry Andric     if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
3245ffd83dbSDimitry Andric       return false;
3255ffd83dbSDimitry Andric     if (!StepRem->isZero())
3265ffd83dbSDimitry Andric       return false;
3275ffd83dbSDimitry Andric     const SCEV *Start = A->getStart();
3285ffd83dbSDimitry Andric     if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
3295ffd83dbSDimitry Andric       return false;
3305ffd83dbSDimitry Andric     S = SE.getAddRecExpr(Start, Step, A->getLoop(),
3315ffd83dbSDimitry Andric                          A->getNoWrapFlags(SCEV::FlagNW));
3325ffd83dbSDimitry Andric     return true;
3335ffd83dbSDimitry Andric   }
3345ffd83dbSDimitry Andric 
3355ffd83dbSDimitry Andric   return false;
3365ffd83dbSDimitry Andric }
3375ffd83dbSDimitry Andric 
3385ffd83dbSDimitry Andric /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
3395ffd83dbSDimitry Andric /// is the number of SCEVAddRecExprs present, which are kept at the end of
3405ffd83dbSDimitry Andric /// the list.
3415ffd83dbSDimitry Andric ///
3425ffd83dbSDimitry Andric static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
3435ffd83dbSDimitry Andric                                 Type *Ty,
3445ffd83dbSDimitry Andric                                 ScalarEvolution &SE) {
3455ffd83dbSDimitry Andric   unsigned NumAddRecs = 0;
3465ffd83dbSDimitry Andric   for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
3475ffd83dbSDimitry Andric     ++NumAddRecs;
3485ffd83dbSDimitry Andric   // Group Ops into non-addrecs and addrecs.
3495ffd83dbSDimitry Andric   SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
3505ffd83dbSDimitry Andric   SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
3515ffd83dbSDimitry Andric   // Let ScalarEvolution sort and simplify the non-addrecs list.
3525ffd83dbSDimitry Andric   const SCEV *Sum = NoAddRecs.empty() ?
3535ffd83dbSDimitry Andric                     SE.getConstant(Ty, 0) :
3545ffd83dbSDimitry Andric                     SE.getAddExpr(NoAddRecs);
3555ffd83dbSDimitry Andric   // If it returned an add, use the operands. Otherwise it simplified
3565ffd83dbSDimitry Andric   // the sum into a single value, so just use that.
3575ffd83dbSDimitry Andric   Ops.clear();
3585ffd83dbSDimitry Andric   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
3595ffd83dbSDimitry Andric     Ops.append(Add->op_begin(), Add->op_end());
3605ffd83dbSDimitry Andric   else if (!Sum->isZero())
3615ffd83dbSDimitry Andric     Ops.push_back(Sum);
3625ffd83dbSDimitry Andric   // Then append the addrecs.
3635ffd83dbSDimitry Andric   Ops.append(AddRecs.begin(), AddRecs.end());
3645ffd83dbSDimitry Andric }
3655ffd83dbSDimitry Andric 
3665ffd83dbSDimitry Andric /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
3675ffd83dbSDimitry Andric /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
3685ffd83dbSDimitry Andric /// This helps expose more opportunities for folding parts of the expressions
3695ffd83dbSDimitry Andric /// into GEP indices.
3705ffd83dbSDimitry Andric ///
3715ffd83dbSDimitry Andric static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
3725ffd83dbSDimitry Andric                          Type *Ty,
3735ffd83dbSDimitry Andric                          ScalarEvolution &SE) {
3745ffd83dbSDimitry Andric   // Find the addrecs.
3755ffd83dbSDimitry Andric   SmallVector<const SCEV *, 8> AddRecs;
3765ffd83dbSDimitry Andric   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3775ffd83dbSDimitry Andric     while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
3785ffd83dbSDimitry Andric       const SCEV *Start = A->getStart();
3795ffd83dbSDimitry Andric       if (Start->isZero()) break;
3805ffd83dbSDimitry Andric       const SCEV *Zero = SE.getConstant(Ty, 0);
3815ffd83dbSDimitry Andric       AddRecs.push_back(SE.getAddRecExpr(Zero,
3825ffd83dbSDimitry Andric                                          A->getStepRecurrence(SE),
3835ffd83dbSDimitry Andric                                          A->getLoop(),
3845ffd83dbSDimitry Andric                                          A->getNoWrapFlags(SCEV::FlagNW)));
3855ffd83dbSDimitry Andric       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
3865ffd83dbSDimitry Andric         Ops[i] = Zero;
3875ffd83dbSDimitry Andric         Ops.append(Add->op_begin(), Add->op_end());
3885ffd83dbSDimitry Andric         e += Add->getNumOperands();
3895ffd83dbSDimitry Andric       } else {
3905ffd83dbSDimitry Andric         Ops[i] = Start;
3915ffd83dbSDimitry Andric       }
3925ffd83dbSDimitry Andric     }
3935ffd83dbSDimitry Andric   if (!AddRecs.empty()) {
3945ffd83dbSDimitry Andric     // Add the addrecs onto the end of the list.
3955ffd83dbSDimitry Andric     Ops.append(AddRecs.begin(), AddRecs.end());
3965ffd83dbSDimitry Andric     // Resort the operand list, moving any constants to the front.
3975ffd83dbSDimitry Andric     SimplifyAddOperands(Ops, Ty, SE);
3985ffd83dbSDimitry Andric   }
3995ffd83dbSDimitry Andric }
4005ffd83dbSDimitry Andric 
4015ffd83dbSDimitry Andric /// expandAddToGEP - Expand an addition expression with a pointer type into
4025ffd83dbSDimitry Andric /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
4035ffd83dbSDimitry Andric /// BasicAliasAnalysis and other passes analyze the result. See the rules
4045ffd83dbSDimitry Andric /// for getelementptr vs. inttoptr in
4055ffd83dbSDimitry Andric /// http://llvm.org/docs/LangRef.html#pointeraliasing
4065ffd83dbSDimitry Andric /// for details.
4075ffd83dbSDimitry Andric ///
4085ffd83dbSDimitry Andric /// Design note: The correctness of using getelementptr here depends on
4095ffd83dbSDimitry Andric /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
4105ffd83dbSDimitry Andric /// they may introduce pointer arithmetic which may not be safely converted
4115ffd83dbSDimitry Andric /// into getelementptr.
4125ffd83dbSDimitry Andric ///
4135ffd83dbSDimitry Andric /// Design note: It might seem desirable for this function to be more
4145ffd83dbSDimitry Andric /// loop-aware. If some of the indices are loop-invariant while others
4155ffd83dbSDimitry Andric /// aren't, it might seem desirable to emit multiple GEPs, keeping the
4165ffd83dbSDimitry Andric /// loop-invariant portions of the overall computation outside the loop.
4175ffd83dbSDimitry Andric /// However, there are a few reasons this is not done here. Hoisting simple
4185ffd83dbSDimitry Andric /// arithmetic is a low-level optimization that often isn't very
4195ffd83dbSDimitry Andric /// important until late in the optimization process. In fact, passes
4205ffd83dbSDimitry Andric /// like InstructionCombining will combine GEPs, even if it means
4215ffd83dbSDimitry Andric /// pushing loop-invariant computation down into loops, so even if the
4225ffd83dbSDimitry Andric /// GEPs were split here, the work would quickly be undone. The
4235ffd83dbSDimitry Andric /// LoopStrengthReduction pass, which is usually run quite late (and
4245ffd83dbSDimitry Andric /// after the last InstructionCombining pass), takes care of hoisting
4255ffd83dbSDimitry Andric /// loop-invariant portions of expressions, after considering what
4265ffd83dbSDimitry Andric /// can be folded using target addressing modes.
4275ffd83dbSDimitry Andric ///
4285ffd83dbSDimitry Andric Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
4295ffd83dbSDimitry Andric                                     const SCEV *const *op_end,
4305ffd83dbSDimitry Andric                                     PointerType *PTy,
4315ffd83dbSDimitry Andric                                     Type *Ty,
4325ffd83dbSDimitry Andric                                     Value *V) {
4335ffd83dbSDimitry Andric   Type *OriginalElTy = PTy->getElementType();
4345ffd83dbSDimitry Andric   Type *ElTy = OriginalElTy;
4355ffd83dbSDimitry Andric   SmallVector<Value *, 4> GepIndices;
4365ffd83dbSDimitry Andric   SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
4375ffd83dbSDimitry Andric   bool AnyNonZeroIndices = false;
4385ffd83dbSDimitry Andric 
4395ffd83dbSDimitry Andric   // Split AddRecs up into parts as either of the parts may be usable
4405ffd83dbSDimitry Andric   // without the other.
4415ffd83dbSDimitry Andric   SplitAddRecs(Ops, Ty, SE);
4425ffd83dbSDimitry Andric 
4435ffd83dbSDimitry Andric   Type *IntIdxTy = DL.getIndexType(PTy);
4445ffd83dbSDimitry Andric 
4455ffd83dbSDimitry Andric   // Descend down the pointer's type and attempt to convert the other
4465ffd83dbSDimitry Andric   // operands into GEP indices, at each level. The first index in a GEP
4475ffd83dbSDimitry Andric   // indexes into the array implied by the pointer operand; the rest of
4485ffd83dbSDimitry Andric   // the indices index into the element or field type selected by the
4495ffd83dbSDimitry Andric   // preceding index.
4505ffd83dbSDimitry Andric   for (;;) {
4515ffd83dbSDimitry Andric     // If the scale size is not 0, attempt to factor out a scale for
4525ffd83dbSDimitry Andric     // array indexing.
4535ffd83dbSDimitry Andric     SmallVector<const SCEV *, 8> ScaledOps;
4545ffd83dbSDimitry Andric     if (ElTy->isSized()) {
4555ffd83dbSDimitry Andric       const SCEV *ElSize = SE.getSizeOfExpr(IntIdxTy, ElTy);
4565ffd83dbSDimitry Andric       if (!ElSize->isZero()) {
4575ffd83dbSDimitry Andric         SmallVector<const SCEV *, 8> NewOps;
4585ffd83dbSDimitry Andric         for (const SCEV *Op : Ops) {
4595ffd83dbSDimitry Andric           const SCEV *Remainder = SE.getConstant(Ty, 0);
4605ffd83dbSDimitry Andric           if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
4615ffd83dbSDimitry Andric             // Op now has ElSize factored out.
4625ffd83dbSDimitry Andric             ScaledOps.push_back(Op);
4635ffd83dbSDimitry Andric             if (!Remainder->isZero())
4645ffd83dbSDimitry Andric               NewOps.push_back(Remainder);
4655ffd83dbSDimitry Andric             AnyNonZeroIndices = true;
4665ffd83dbSDimitry Andric           } else {
4675ffd83dbSDimitry Andric             // The operand was not divisible, so add it to the list of operands
4685ffd83dbSDimitry Andric             // we'll scan next iteration.
4695ffd83dbSDimitry Andric             NewOps.push_back(Op);
4705ffd83dbSDimitry Andric           }
4715ffd83dbSDimitry Andric         }
4725ffd83dbSDimitry Andric         // If we made any changes, update Ops.
4735ffd83dbSDimitry Andric         if (!ScaledOps.empty()) {
4745ffd83dbSDimitry Andric           Ops = NewOps;
4755ffd83dbSDimitry Andric           SimplifyAddOperands(Ops, Ty, SE);
4765ffd83dbSDimitry Andric         }
4775ffd83dbSDimitry Andric       }
4785ffd83dbSDimitry Andric     }
4795ffd83dbSDimitry Andric 
4805ffd83dbSDimitry Andric     // Record the scaled array index for this level of the type. If
4815ffd83dbSDimitry Andric     // we didn't find any operands that could be factored, tentatively
4825ffd83dbSDimitry Andric     // assume that element zero was selected (since the zero offset
4835ffd83dbSDimitry Andric     // would obviously be folded away).
484*e8d8bef9SDimitry Andric     Value *Scaled =
485*e8d8bef9SDimitry Andric         ScaledOps.empty()
486*e8d8bef9SDimitry Andric             ? Constant::getNullValue(Ty)
487*e8d8bef9SDimitry Andric             : expandCodeForImpl(SE.getAddExpr(ScaledOps), Ty, false);
4885ffd83dbSDimitry Andric     GepIndices.push_back(Scaled);
4895ffd83dbSDimitry Andric 
4905ffd83dbSDimitry Andric     // Collect struct field index operands.
4915ffd83dbSDimitry Andric     while (StructType *STy = dyn_cast<StructType>(ElTy)) {
4925ffd83dbSDimitry Andric       bool FoundFieldNo = false;
4935ffd83dbSDimitry Andric       // An empty struct has no fields.
4945ffd83dbSDimitry Andric       if (STy->getNumElements() == 0) break;
4955ffd83dbSDimitry Andric       // Field offsets are known. See if a constant offset falls within any of
4965ffd83dbSDimitry Andric       // the struct fields.
4975ffd83dbSDimitry Andric       if (Ops.empty())
4985ffd83dbSDimitry Andric         break;
4995ffd83dbSDimitry Andric       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
5005ffd83dbSDimitry Andric         if (SE.getTypeSizeInBits(C->getType()) <= 64) {
5015ffd83dbSDimitry Andric           const StructLayout &SL = *DL.getStructLayout(STy);
5025ffd83dbSDimitry Andric           uint64_t FullOffset = C->getValue()->getZExtValue();
5035ffd83dbSDimitry Andric           if (FullOffset < SL.getSizeInBytes()) {
5045ffd83dbSDimitry Andric             unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
5055ffd83dbSDimitry Andric             GepIndices.push_back(
5065ffd83dbSDimitry Andric                 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
5075ffd83dbSDimitry Andric             ElTy = STy->getTypeAtIndex(ElIdx);
5085ffd83dbSDimitry Andric             Ops[0] =
5095ffd83dbSDimitry Andric                 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
5105ffd83dbSDimitry Andric             AnyNonZeroIndices = true;
5115ffd83dbSDimitry Andric             FoundFieldNo = true;
5125ffd83dbSDimitry Andric           }
5135ffd83dbSDimitry Andric         }
5145ffd83dbSDimitry Andric       // If no struct field offsets were found, tentatively assume that
5155ffd83dbSDimitry Andric       // field zero was selected (since the zero offset would obviously
5165ffd83dbSDimitry Andric       // be folded away).
5175ffd83dbSDimitry Andric       if (!FoundFieldNo) {
5185ffd83dbSDimitry Andric         ElTy = STy->getTypeAtIndex(0u);
5195ffd83dbSDimitry Andric         GepIndices.push_back(
5205ffd83dbSDimitry Andric           Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
5215ffd83dbSDimitry Andric       }
5225ffd83dbSDimitry Andric     }
5235ffd83dbSDimitry Andric 
5245ffd83dbSDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
5255ffd83dbSDimitry Andric       ElTy = ATy->getElementType();
5265ffd83dbSDimitry Andric     else
5275ffd83dbSDimitry Andric       // FIXME: Handle VectorType.
5285ffd83dbSDimitry Andric       // E.g., If ElTy is scalable vector, then ElSize is not a compile-time
5295ffd83dbSDimitry Andric       // constant, therefore can not be factored out. The generated IR is less
5305ffd83dbSDimitry Andric       // ideal with base 'V' cast to i8* and do ugly getelementptr over that.
5315ffd83dbSDimitry Andric       break;
5325ffd83dbSDimitry Andric   }
5335ffd83dbSDimitry Andric 
5345ffd83dbSDimitry Andric   // If none of the operands were convertible to proper GEP indices, cast
5355ffd83dbSDimitry Andric   // the base to i8* and do an ugly getelementptr with that. It's still
5365ffd83dbSDimitry Andric   // better than ptrtoint+arithmetic+inttoptr at least.
5375ffd83dbSDimitry Andric   if (!AnyNonZeroIndices) {
5385ffd83dbSDimitry Andric     // Cast the base to i8*.
5395ffd83dbSDimitry Andric     V = InsertNoopCastOfTo(V,
5405ffd83dbSDimitry Andric        Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
5415ffd83dbSDimitry Andric 
5425ffd83dbSDimitry Andric     assert(!isa<Instruction>(V) ||
5435ffd83dbSDimitry Andric            SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
5445ffd83dbSDimitry Andric 
5455ffd83dbSDimitry Andric     // Expand the operands for a plain byte offset.
546*e8d8bef9SDimitry Andric     Value *Idx = expandCodeForImpl(SE.getAddExpr(Ops), Ty, false);
5475ffd83dbSDimitry Andric 
5485ffd83dbSDimitry Andric     // Fold a GEP with constant operands.
5495ffd83dbSDimitry Andric     if (Constant *CLHS = dyn_cast<Constant>(V))
5505ffd83dbSDimitry Andric       if (Constant *CRHS = dyn_cast<Constant>(Idx))
5515ffd83dbSDimitry Andric         return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
5525ffd83dbSDimitry Andric                                               CLHS, CRHS);
5535ffd83dbSDimitry Andric 
5545ffd83dbSDimitry Andric     // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
5555ffd83dbSDimitry Andric     unsigned ScanLimit = 6;
5565ffd83dbSDimitry Andric     BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
5575ffd83dbSDimitry Andric     // Scanning starts from the last instruction before the insertion point.
5585ffd83dbSDimitry Andric     BasicBlock::iterator IP = Builder.GetInsertPoint();
5595ffd83dbSDimitry Andric     if (IP != BlockBegin) {
5605ffd83dbSDimitry Andric       --IP;
5615ffd83dbSDimitry Andric       for (; ScanLimit; --IP, --ScanLimit) {
5625ffd83dbSDimitry Andric         // Don't count dbg.value against the ScanLimit, to avoid perturbing the
5635ffd83dbSDimitry Andric         // generated code.
5645ffd83dbSDimitry Andric         if (isa<DbgInfoIntrinsic>(IP))
5655ffd83dbSDimitry Andric           ScanLimit++;
5665ffd83dbSDimitry Andric         if (IP->getOpcode() == Instruction::GetElementPtr &&
5675ffd83dbSDimitry Andric             IP->getOperand(0) == V && IP->getOperand(1) == Idx)
5685ffd83dbSDimitry Andric           return &*IP;
5695ffd83dbSDimitry Andric         if (IP == BlockBegin) break;
5705ffd83dbSDimitry Andric       }
5715ffd83dbSDimitry Andric     }
5725ffd83dbSDimitry Andric 
5735ffd83dbSDimitry Andric     // Save the original insertion point so we can restore it when we're done.
5745ffd83dbSDimitry Andric     SCEVInsertPointGuard Guard(Builder, this);
5755ffd83dbSDimitry Andric 
5765ffd83dbSDimitry Andric     // Move the insertion point out of as many loops as we can.
5775ffd83dbSDimitry Andric     while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
5785ffd83dbSDimitry Andric       if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
5795ffd83dbSDimitry Andric       BasicBlock *Preheader = L->getLoopPreheader();
5805ffd83dbSDimitry Andric       if (!Preheader) break;
5815ffd83dbSDimitry Andric 
5825ffd83dbSDimitry Andric       // Ok, move up a level.
5835ffd83dbSDimitry Andric       Builder.SetInsertPoint(Preheader->getTerminator());
5845ffd83dbSDimitry Andric     }
5855ffd83dbSDimitry Andric 
5865ffd83dbSDimitry Andric     // Emit a GEP.
587*e8d8bef9SDimitry Andric     return Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
5885ffd83dbSDimitry Andric   }
5895ffd83dbSDimitry Andric 
5905ffd83dbSDimitry Andric   {
5915ffd83dbSDimitry Andric     SCEVInsertPointGuard Guard(Builder, this);
5925ffd83dbSDimitry Andric 
5935ffd83dbSDimitry Andric     // Move the insertion point out of as many loops as we can.
5945ffd83dbSDimitry Andric     while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
5955ffd83dbSDimitry Andric       if (!L->isLoopInvariant(V)) break;
5965ffd83dbSDimitry Andric 
5975ffd83dbSDimitry Andric       bool AnyIndexNotLoopInvariant = any_of(
5985ffd83dbSDimitry Andric           GepIndices, [L](Value *Op) { return !L->isLoopInvariant(Op); });
5995ffd83dbSDimitry Andric 
6005ffd83dbSDimitry Andric       if (AnyIndexNotLoopInvariant)
6015ffd83dbSDimitry Andric         break;
6025ffd83dbSDimitry Andric 
6035ffd83dbSDimitry Andric       BasicBlock *Preheader = L->getLoopPreheader();
6045ffd83dbSDimitry Andric       if (!Preheader) break;
6055ffd83dbSDimitry Andric 
6065ffd83dbSDimitry Andric       // Ok, move up a level.
6075ffd83dbSDimitry Andric       Builder.SetInsertPoint(Preheader->getTerminator());
6085ffd83dbSDimitry Andric     }
6095ffd83dbSDimitry Andric 
6105ffd83dbSDimitry Andric     // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
6115ffd83dbSDimitry Andric     // because ScalarEvolution may have changed the address arithmetic to
6125ffd83dbSDimitry Andric     // compute a value which is beyond the end of the allocated object.
6135ffd83dbSDimitry Andric     Value *Casted = V;
6145ffd83dbSDimitry Andric     if (V->getType() != PTy)
6155ffd83dbSDimitry Andric       Casted = InsertNoopCastOfTo(Casted, PTy);
6165ffd83dbSDimitry Andric     Value *GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices, "scevgep");
6175ffd83dbSDimitry Andric     Ops.push_back(SE.getUnknown(GEP));
6185ffd83dbSDimitry Andric   }
6195ffd83dbSDimitry Andric 
6205ffd83dbSDimitry Andric   return expand(SE.getAddExpr(Ops));
6215ffd83dbSDimitry Andric }
6225ffd83dbSDimitry Andric 
6235ffd83dbSDimitry Andric Value *SCEVExpander::expandAddToGEP(const SCEV *Op, PointerType *PTy, Type *Ty,
6245ffd83dbSDimitry Andric                                     Value *V) {
6255ffd83dbSDimitry Andric   const SCEV *const Ops[1] = {Op};
6265ffd83dbSDimitry Andric   return expandAddToGEP(Ops, Ops + 1, PTy, Ty, V);
6275ffd83dbSDimitry Andric }
6285ffd83dbSDimitry Andric 
6295ffd83dbSDimitry Andric /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
6305ffd83dbSDimitry Andric /// SCEV expansion. If they are nested, this is the most nested. If they are
6315ffd83dbSDimitry Andric /// neighboring, pick the later.
6325ffd83dbSDimitry Andric static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
6335ffd83dbSDimitry Andric                                         DominatorTree &DT) {
6345ffd83dbSDimitry Andric   if (!A) return B;
6355ffd83dbSDimitry Andric   if (!B) return A;
6365ffd83dbSDimitry Andric   if (A->contains(B)) return B;
6375ffd83dbSDimitry Andric   if (B->contains(A)) return A;
6385ffd83dbSDimitry Andric   if (DT.dominates(A->getHeader(), B->getHeader())) return B;
6395ffd83dbSDimitry Andric   if (DT.dominates(B->getHeader(), A->getHeader())) return A;
6405ffd83dbSDimitry Andric   return A; // Arbitrarily break the tie.
6415ffd83dbSDimitry Andric }
6425ffd83dbSDimitry Andric 
6435ffd83dbSDimitry Andric /// getRelevantLoop - Get the most relevant loop associated with the given
6445ffd83dbSDimitry Andric /// expression, according to PickMostRelevantLoop.
6455ffd83dbSDimitry Andric const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
6465ffd83dbSDimitry Andric   // Test whether we've already computed the most relevant loop for this SCEV.
6475ffd83dbSDimitry Andric   auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
6485ffd83dbSDimitry Andric   if (!Pair.second)
6495ffd83dbSDimitry Andric     return Pair.first->second;
6505ffd83dbSDimitry Andric 
6515ffd83dbSDimitry Andric   if (isa<SCEVConstant>(S))
6525ffd83dbSDimitry Andric     // A constant has no relevant loops.
6535ffd83dbSDimitry Andric     return nullptr;
6545ffd83dbSDimitry Andric   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6555ffd83dbSDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
6565ffd83dbSDimitry Andric       return Pair.first->second = SE.LI.getLoopFor(I->getParent());
6575ffd83dbSDimitry Andric     // A non-instruction has no relevant loops.
6585ffd83dbSDimitry Andric     return nullptr;
6595ffd83dbSDimitry Andric   }
6605ffd83dbSDimitry Andric   if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
6615ffd83dbSDimitry Andric     const Loop *L = nullptr;
6625ffd83dbSDimitry Andric     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
6635ffd83dbSDimitry Andric       L = AR->getLoop();
6645ffd83dbSDimitry Andric     for (const SCEV *Op : N->operands())
6655ffd83dbSDimitry Andric       L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
6665ffd83dbSDimitry Andric     return RelevantLoops[N] = L;
6675ffd83dbSDimitry Andric   }
6685ffd83dbSDimitry Andric   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
6695ffd83dbSDimitry Andric     const Loop *Result = getRelevantLoop(C->getOperand());
6705ffd83dbSDimitry Andric     return RelevantLoops[C] = Result;
6715ffd83dbSDimitry Andric   }
6725ffd83dbSDimitry Andric   if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
6735ffd83dbSDimitry Andric     const Loop *Result = PickMostRelevantLoop(
6745ffd83dbSDimitry Andric         getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
6755ffd83dbSDimitry Andric     return RelevantLoops[D] = Result;
6765ffd83dbSDimitry Andric   }
6775ffd83dbSDimitry Andric   llvm_unreachable("Unexpected SCEV type!");
6785ffd83dbSDimitry Andric }
6795ffd83dbSDimitry Andric 
6805ffd83dbSDimitry Andric namespace {
6815ffd83dbSDimitry Andric 
6825ffd83dbSDimitry Andric /// LoopCompare - Compare loops by PickMostRelevantLoop.
6835ffd83dbSDimitry Andric class LoopCompare {
6845ffd83dbSDimitry Andric   DominatorTree &DT;
6855ffd83dbSDimitry Andric public:
6865ffd83dbSDimitry Andric   explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
6875ffd83dbSDimitry Andric 
6885ffd83dbSDimitry Andric   bool operator()(std::pair<const Loop *, const SCEV *> LHS,
6895ffd83dbSDimitry Andric                   std::pair<const Loop *, const SCEV *> RHS) const {
6905ffd83dbSDimitry Andric     // Keep pointer operands sorted at the end.
6915ffd83dbSDimitry Andric     if (LHS.second->getType()->isPointerTy() !=
6925ffd83dbSDimitry Andric         RHS.second->getType()->isPointerTy())
6935ffd83dbSDimitry Andric       return LHS.second->getType()->isPointerTy();
6945ffd83dbSDimitry Andric 
6955ffd83dbSDimitry Andric     // Compare loops with PickMostRelevantLoop.
6965ffd83dbSDimitry Andric     if (LHS.first != RHS.first)
6975ffd83dbSDimitry Andric       return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
6985ffd83dbSDimitry Andric 
6995ffd83dbSDimitry Andric     // If one operand is a non-constant negative and the other is not,
7005ffd83dbSDimitry Andric     // put the non-constant negative on the right so that a sub can
7015ffd83dbSDimitry Andric     // be used instead of a negate and add.
7025ffd83dbSDimitry Andric     if (LHS.second->isNonConstantNegative()) {
7035ffd83dbSDimitry Andric       if (!RHS.second->isNonConstantNegative())
7045ffd83dbSDimitry Andric         return false;
7055ffd83dbSDimitry Andric     } else if (RHS.second->isNonConstantNegative())
7065ffd83dbSDimitry Andric       return true;
7075ffd83dbSDimitry Andric 
7085ffd83dbSDimitry Andric     // Otherwise they are equivalent according to this comparison.
7095ffd83dbSDimitry Andric     return false;
7105ffd83dbSDimitry Andric   }
7115ffd83dbSDimitry Andric };
7125ffd83dbSDimitry Andric 
7135ffd83dbSDimitry Andric }
7145ffd83dbSDimitry Andric 
7155ffd83dbSDimitry Andric Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
7165ffd83dbSDimitry Andric   Type *Ty = SE.getEffectiveSCEVType(S->getType());
7175ffd83dbSDimitry Andric 
7185ffd83dbSDimitry Andric   // Collect all the add operands in a loop, along with their associated loops.
7195ffd83dbSDimitry Andric   // Iterate in reverse so that constants are emitted last, all else equal, and
7205ffd83dbSDimitry Andric   // so that pointer operands are inserted first, which the code below relies on
7215ffd83dbSDimitry Andric   // to form more involved GEPs.
7225ffd83dbSDimitry Andric   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
7235ffd83dbSDimitry Andric   for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
7245ffd83dbSDimitry Andric        E(S->op_begin()); I != E; ++I)
7255ffd83dbSDimitry Andric     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
7265ffd83dbSDimitry Andric 
7275ffd83dbSDimitry Andric   // Sort by loop. Use a stable sort so that constants follow non-constants and
7285ffd83dbSDimitry Andric   // pointer operands precede non-pointer operands.
7295ffd83dbSDimitry Andric   llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
7305ffd83dbSDimitry Andric 
7315ffd83dbSDimitry Andric   // Emit instructions to add all the operands. Hoist as much as possible
7325ffd83dbSDimitry Andric   // out of loops, and form meaningful getelementptrs where possible.
7335ffd83dbSDimitry Andric   Value *Sum = nullptr;
7345ffd83dbSDimitry Andric   for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
7355ffd83dbSDimitry Andric     const Loop *CurLoop = I->first;
7365ffd83dbSDimitry Andric     const SCEV *Op = I->second;
7375ffd83dbSDimitry Andric     if (!Sum) {
7385ffd83dbSDimitry Andric       // This is the first operand. Just expand it.
7395ffd83dbSDimitry Andric       Sum = expand(Op);
7405ffd83dbSDimitry Andric       ++I;
7415ffd83dbSDimitry Andric     } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
7425ffd83dbSDimitry Andric       // The running sum expression is a pointer. Try to form a getelementptr
7435ffd83dbSDimitry Andric       // at this level with that as the base.
7445ffd83dbSDimitry Andric       SmallVector<const SCEV *, 4> NewOps;
7455ffd83dbSDimitry Andric       for (; I != E && I->first == CurLoop; ++I) {
7465ffd83dbSDimitry Andric         // If the operand is SCEVUnknown and not instructions, peek through
7475ffd83dbSDimitry Andric         // it, to enable more of it to be folded into the GEP.
7485ffd83dbSDimitry Andric         const SCEV *X = I->second;
7495ffd83dbSDimitry Andric         if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
7505ffd83dbSDimitry Andric           if (!isa<Instruction>(U->getValue()))
7515ffd83dbSDimitry Andric             X = SE.getSCEV(U->getValue());
7525ffd83dbSDimitry Andric         NewOps.push_back(X);
7535ffd83dbSDimitry Andric       }
7545ffd83dbSDimitry Andric       Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
7555ffd83dbSDimitry Andric     } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
7565ffd83dbSDimitry Andric       // The running sum is an integer, and there's a pointer at this level.
7575ffd83dbSDimitry Andric       // Try to form a getelementptr. If the running sum is instructions,
7585ffd83dbSDimitry Andric       // use a SCEVUnknown to avoid re-analyzing them.
7595ffd83dbSDimitry Andric       SmallVector<const SCEV *, 4> NewOps;
7605ffd83dbSDimitry Andric       NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
7615ffd83dbSDimitry Andric                                                SE.getSCEV(Sum));
7625ffd83dbSDimitry Andric       for (++I; I != E && I->first == CurLoop; ++I)
7635ffd83dbSDimitry Andric         NewOps.push_back(I->second);
7645ffd83dbSDimitry Andric       Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
7655ffd83dbSDimitry Andric     } else if (Op->isNonConstantNegative()) {
7665ffd83dbSDimitry Andric       // Instead of doing a negate and add, just do a subtract.
767*e8d8bef9SDimitry Andric       Value *W = expandCodeForImpl(SE.getNegativeSCEV(Op), Ty, false);
7685ffd83dbSDimitry Andric       Sum = InsertNoopCastOfTo(Sum, Ty);
7695ffd83dbSDimitry Andric       Sum = InsertBinop(Instruction::Sub, Sum, W, SCEV::FlagAnyWrap,
7705ffd83dbSDimitry Andric                         /*IsSafeToHoist*/ true);
7715ffd83dbSDimitry Andric       ++I;
7725ffd83dbSDimitry Andric     } else {
7735ffd83dbSDimitry Andric       // A simple add.
774*e8d8bef9SDimitry Andric       Value *W = expandCodeForImpl(Op, Ty, false);
7755ffd83dbSDimitry Andric       Sum = InsertNoopCastOfTo(Sum, Ty);
7765ffd83dbSDimitry Andric       // Canonicalize a constant to the RHS.
7775ffd83dbSDimitry Andric       if (isa<Constant>(Sum)) std::swap(Sum, W);
7785ffd83dbSDimitry Andric       Sum = InsertBinop(Instruction::Add, Sum, W, S->getNoWrapFlags(),
7795ffd83dbSDimitry Andric                         /*IsSafeToHoist*/ true);
7805ffd83dbSDimitry Andric       ++I;
7815ffd83dbSDimitry Andric     }
7825ffd83dbSDimitry Andric   }
7835ffd83dbSDimitry Andric 
7845ffd83dbSDimitry Andric   return Sum;
7855ffd83dbSDimitry Andric }
7865ffd83dbSDimitry Andric 
7875ffd83dbSDimitry Andric Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
7885ffd83dbSDimitry Andric   Type *Ty = SE.getEffectiveSCEVType(S->getType());
7895ffd83dbSDimitry Andric 
7905ffd83dbSDimitry Andric   // Collect all the mul operands in a loop, along with their associated loops.
7915ffd83dbSDimitry Andric   // Iterate in reverse so that constants are emitted last, all else equal.
7925ffd83dbSDimitry Andric   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
7935ffd83dbSDimitry Andric   for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
7945ffd83dbSDimitry Andric        E(S->op_begin()); I != E; ++I)
7955ffd83dbSDimitry Andric     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
7965ffd83dbSDimitry Andric 
7975ffd83dbSDimitry Andric   // Sort by loop. Use a stable sort so that constants follow non-constants.
7985ffd83dbSDimitry Andric   llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
7995ffd83dbSDimitry Andric 
8005ffd83dbSDimitry Andric   // Emit instructions to mul all the operands. Hoist as much as possible
8015ffd83dbSDimitry Andric   // out of loops.
8025ffd83dbSDimitry Andric   Value *Prod = nullptr;
8035ffd83dbSDimitry Andric   auto I = OpsAndLoops.begin();
8045ffd83dbSDimitry Andric 
8055ffd83dbSDimitry Andric   // Expand the calculation of X pow N in the following manner:
8065ffd83dbSDimitry Andric   // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then:
8075ffd83dbSDimitry Andric   // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK).
8085ffd83dbSDimitry Andric   const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops, &Ty]() {
8095ffd83dbSDimitry Andric     auto E = I;
8105ffd83dbSDimitry Andric     // Calculate how many times the same operand from the same loop is included
8115ffd83dbSDimitry Andric     // into this power.
8125ffd83dbSDimitry Andric     uint64_t Exponent = 0;
8135ffd83dbSDimitry Andric     const uint64_t MaxExponent = UINT64_MAX >> 1;
8145ffd83dbSDimitry Andric     // No one sane will ever try to calculate such huge exponents, but if we
8155ffd83dbSDimitry Andric     // need this, we stop on UINT64_MAX / 2 because we need to exit the loop
8165ffd83dbSDimitry Andric     // below when the power of 2 exceeds our Exponent, and we want it to be
8175ffd83dbSDimitry Andric     // 1u << 31 at most to not deal with unsigned overflow.
8185ffd83dbSDimitry Andric     while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) {
8195ffd83dbSDimitry Andric       ++Exponent;
8205ffd83dbSDimitry Andric       ++E;
8215ffd83dbSDimitry Andric     }
8225ffd83dbSDimitry Andric     assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?");
8235ffd83dbSDimitry Andric 
8245ffd83dbSDimitry Andric     // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them
8255ffd83dbSDimitry Andric     // that are needed into the result.
826*e8d8bef9SDimitry Andric     Value *P = expandCodeForImpl(I->second, Ty, false);
8275ffd83dbSDimitry Andric     Value *Result = nullptr;
8285ffd83dbSDimitry Andric     if (Exponent & 1)
8295ffd83dbSDimitry Andric       Result = P;
8305ffd83dbSDimitry Andric     for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
8315ffd83dbSDimitry Andric       P = InsertBinop(Instruction::Mul, P, P, SCEV::FlagAnyWrap,
8325ffd83dbSDimitry Andric                       /*IsSafeToHoist*/ true);
8335ffd83dbSDimitry Andric       if (Exponent & BinExp)
8345ffd83dbSDimitry Andric         Result = Result ? InsertBinop(Instruction::Mul, Result, P,
8355ffd83dbSDimitry Andric                                       SCEV::FlagAnyWrap,
8365ffd83dbSDimitry Andric                                       /*IsSafeToHoist*/ true)
8375ffd83dbSDimitry Andric                         : P;
8385ffd83dbSDimitry Andric     }
8395ffd83dbSDimitry Andric 
8405ffd83dbSDimitry Andric     I = E;
8415ffd83dbSDimitry Andric     assert(Result && "Nothing was expanded?");
8425ffd83dbSDimitry Andric     return Result;
8435ffd83dbSDimitry Andric   };
8445ffd83dbSDimitry Andric 
8455ffd83dbSDimitry Andric   while (I != OpsAndLoops.end()) {
8465ffd83dbSDimitry Andric     if (!Prod) {
8475ffd83dbSDimitry Andric       // This is the first operand. Just expand it.
8485ffd83dbSDimitry Andric       Prod = ExpandOpBinPowN();
8495ffd83dbSDimitry Andric     } else if (I->second->isAllOnesValue()) {
8505ffd83dbSDimitry Andric       // Instead of doing a multiply by negative one, just do a negate.
8515ffd83dbSDimitry Andric       Prod = InsertNoopCastOfTo(Prod, Ty);
8525ffd83dbSDimitry Andric       Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod,
8535ffd83dbSDimitry Andric                          SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
8545ffd83dbSDimitry Andric       ++I;
8555ffd83dbSDimitry Andric     } else {
8565ffd83dbSDimitry Andric       // A simple mul.
8575ffd83dbSDimitry Andric       Value *W = ExpandOpBinPowN();
8585ffd83dbSDimitry Andric       Prod = InsertNoopCastOfTo(Prod, Ty);
8595ffd83dbSDimitry Andric       // Canonicalize a constant to the RHS.
8605ffd83dbSDimitry Andric       if (isa<Constant>(Prod)) std::swap(Prod, W);
8615ffd83dbSDimitry Andric       const APInt *RHS;
8625ffd83dbSDimitry Andric       if (match(W, m_Power2(RHS))) {
8635ffd83dbSDimitry Andric         // Canonicalize Prod*(1<<C) to Prod<<C.
8645ffd83dbSDimitry Andric         assert(!Ty->isVectorTy() && "vector types are not SCEVable");
8655ffd83dbSDimitry Andric         auto NWFlags = S->getNoWrapFlags();
8665ffd83dbSDimitry Andric         // clear nsw flag if shl will produce poison value.
8675ffd83dbSDimitry Andric         if (RHS->logBase2() == RHS->getBitWidth() - 1)
8685ffd83dbSDimitry Andric           NWFlags = ScalarEvolution::clearFlags(NWFlags, SCEV::FlagNSW);
8695ffd83dbSDimitry Andric         Prod = InsertBinop(Instruction::Shl, Prod,
8705ffd83dbSDimitry Andric                            ConstantInt::get(Ty, RHS->logBase2()), NWFlags,
8715ffd83dbSDimitry Andric                            /*IsSafeToHoist*/ true);
8725ffd83dbSDimitry Andric       } else {
8735ffd83dbSDimitry Andric         Prod = InsertBinop(Instruction::Mul, Prod, W, S->getNoWrapFlags(),
8745ffd83dbSDimitry Andric                            /*IsSafeToHoist*/ true);
8755ffd83dbSDimitry Andric       }
8765ffd83dbSDimitry Andric     }
8775ffd83dbSDimitry Andric   }
8785ffd83dbSDimitry Andric 
8795ffd83dbSDimitry Andric   return Prod;
8805ffd83dbSDimitry Andric }
8815ffd83dbSDimitry Andric 
8825ffd83dbSDimitry Andric Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
8835ffd83dbSDimitry Andric   Type *Ty = SE.getEffectiveSCEVType(S->getType());
8845ffd83dbSDimitry Andric 
885*e8d8bef9SDimitry Andric   Value *LHS = expandCodeForImpl(S->getLHS(), Ty, false);
8865ffd83dbSDimitry Andric   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
8875ffd83dbSDimitry Andric     const APInt &RHS = SC->getAPInt();
8885ffd83dbSDimitry Andric     if (RHS.isPowerOf2())
8895ffd83dbSDimitry Andric       return InsertBinop(Instruction::LShr, LHS,
8905ffd83dbSDimitry Andric                          ConstantInt::get(Ty, RHS.logBase2()),
8915ffd83dbSDimitry Andric                          SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
8925ffd83dbSDimitry Andric   }
8935ffd83dbSDimitry Andric 
894*e8d8bef9SDimitry Andric   Value *RHS = expandCodeForImpl(S->getRHS(), Ty, false);
8955ffd83dbSDimitry Andric   return InsertBinop(Instruction::UDiv, LHS, RHS, SCEV::FlagAnyWrap,
8965ffd83dbSDimitry Andric                      /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS()));
8975ffd83dbSDimitry Andric }
8985ffd83dbSDimitry Andric 
8995ffd83dbSDimitry Andric /// Move parts of Base into Rest to leave Base with the minimal
9005ffd83dbSDimitry Andric /// expression that provides a pointer operand suitable for a
9015ffd83dbSDimitry Andric /// GEP expansion.
9025ffd83dbSDimitry Andric static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
9035ffd83dbSDimitry Andric                               ScalarEvolution &SE) {
9045ffd83dbSDimitry Andric   while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
9055ffd83dbSDimitry Andric     Base = A->getStart();
9065ffd83dbSDimitry Andric     Rest = SE.getAddExpr(Rest,
9075ffd83dbSDimitry Andric                          SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
9085ffd83dbSDimitry Andric                                           A->getStepRecurrence(SE),
9095ffd83dbSDimitry Andric                                           A->getLoop(),
9105ffd83dbSDimitry Andric                                           A->getNoWrapFlags(SCEV::FlagNW)));
9115ffd83dbSDimitry Andric   }
9125ffd83dbSDimitry Andric   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
9135ffd83dbSDimitry Andric     Base = A->getOperand(A->getNumOperands()-1);
914*e8d8bef9SDimitry Andric     SmallVector<const SCEV *, 8> NewAddOps(A->operands());
9155ffd83dbSDimitry Andric     NewAddOps.back() = Rest;
9165ffd83dbSDimitry Andric     Rest = SE.getAddExpr(NewAddOps);
9175ffd83dbSDimitry Andric     ExposePointerBase(Base, Rest, SE);
9185ffd83dbSDimitry Andric   }
9195ffd83dbSDimitry Andric }
9205ffd83dbSDimitry Andric 
9215ffd83dbSDimitry Andric /// Determine if this is a well-behaved chain of instructions leading back to
9225ffd83dbSDimitry Andric /// the PHI. If so, it may be reused by expanded expressions.
9235ffd83dbSDimitry Andric bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
9245ffd83dbSDimitry Andric                                          const Loop *L) {
9255ffd83dbSDimitry Andric   if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
9265ffd83dbSDimitry Andric       (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
9275ffd83dbSDimitry Andric     return false;
9285ffd83dbSDimitry Andric   // If any of the operands don't dominate the insert position, bail.
9295ffd83dbSDimitry Andric   // Addrec operands are always loop-invariant, so this can only happen
9305ffd83dbSDimitry Andric   // if there are instructions which haven't been hoisted.
9315ffd83dbSDimitry Andric   if (L == IVIncInsertLoop) {
9325ffd83dbSDimitry Andric     for (User::op_iterator OI = IncV->op_begin()+1,
9335ffd83dbSDimitry Andric            OE = IncV->op_end(); OI != OE; ++OI)
9345ffd83dbSDimitry Andric       if (Instruction *OInst = dyn_cast<Instruction>(OI))
9355ffd83dbSDimitry Andric         if (!SE.DT.dominates(OInst, IVIncInsertPos))
9365ffd83dbSDimitry Andric           return false;
9375ffd83dbSDimitry Andric   }
9385ffd83dbSDimitry Andric   // Advance to the next instruction.
9395ffd83dbSDimitry Andric   IncV = dyn_cast<Instruction>(IncV->getOperand(0));
9405ffd83dbSDimitry Andric   if (!IncV)
9415ffd83dbSDimitry Andric     return false;
9425ffd83dbSDimitry Andric 
9435ffd83dbSDimitry Andric   if (IncV->mayHaveSideEffects())
9445ffd83dbSDimitry Andric     return false;
9455ffd83dbSDimitry Andric 
9465ffd83dbSDimitry Andric   if (IncV == PN)
9475ffd83dbSDimitry Andric     return true;
9485ffd83dbSDimitry Andric 
9495ffd83dbSDimitry Andric   return isNormalAddRecExprPHI(PN, IncV, L);
9505ffd83dbSDimitry Andric }
9515ffd83dbSDimitry Andric 
9525ffd83dbSDimitry Andric /// getIVIncOperand returns an induction variable increment's induction
9535ffd83dbSDimitry Andric /// variable operand.
9545ffd83dbSDimitry Andric ///
9555ffd83dbSDimitry Andric /// If allowScale is set, any type of GEP is allowed as long as the nonIV
9565ffd83dbSDimitry Andric /// operands dominate InsertPos.
9575ffd83dbSDimitry Andric ///
9585ffd83dbSDimitry Andric /// If allowScale is not set, ensure that a GEP increment conforms to one of the
9595ffd83dbSDimitry Andric /// simple patterns generated by getAddRecExprPHILiterally and
9605ffd83dbSDimitry Andric /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
9615ffd83dbSDimitry Andric Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
9625ffd83dbSDimitry Andric                                            Instruction *InsertPos,
9635ffd83dbSDimitry Andric                                            bool allowScale) {
9645ffd83dbSDimitry Andric   if (IncV == InsertPos)
9655ffd83dbSDimitry Andric     return nullptr;
9665ffd83dbSDimitry Andric 
9675ffd83dbSDimitry Andric   switch (IncV->getOpcode()) {
9685ffd83dbSDimitry Andric   default:
9695ffd83dbSDimitry Andric     return nullptr;
9705ffd83dbSDimitry Andric   // Check for a simple Add/Sub or GEP of a loop invariant step.
9715ffd83dbSDimitry Andric   case Instruction::Add:
9725ffd83dbSDimitry Andric   case Instruction::Sub: {
9735ffd83dbSDimitry Andric     Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
9745ffd83dbSDimitry Andric     if (!OInst || SE.DT.dominates(OInst, InsertPos))
9755ffd83dbSDimitry Andric       return dyn_cast<Instruction>(IncV->getOperand(0));
9765ffd83dbSDimitry Andric     return nullptr;
9775ffd83dbSDimitry Andric   }
9785ffd83dbSDimitry Andric   case Instruction::BitCast:
9795ffd83dbSDimitry Andric     return dyn_cast<Instruction>(IncV->getOperand(0));
9805ffd83dbSDimitry Andric   case Instruction::GetElementPtr:
9815ffd83dbSDimitry Andric     for (auto I = IncV->op_begin() + 1, E = IncV->op_end(); I != E; ++I) {
9825ffd83dbSDimitry Andric       if (isa<Constant>(*I))
9835ffd83dbSDimitry Andric         continue;
9845ffd83dbSDimitry Andric       if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
9855ffd83dbSDimitry Andric         if (!SE.DT.dominates(OInst, InsertPos))
9865ffd83dbSDimitry Andric           return nullptr;
9875ffd83dbSDimitry Andric       }
9885ffd83dbSDimitry Andric       if (allowScale) {
9895ffd83dbSDimitry Andric         // allow any kind of GEP as long as it can be hoisted.
9905ffd83dbSDimitry Andric         continue;
9915ffd83dbSDimitry Andric       }
9925ffd83dbSDimitry Andric       // This must be a pointer addition of constants (pretty), which is already
9935ffd83dbSDimitry Andric       // handled, or some number of address-size elements (ugly). Ugly geps
9945ffd83dbSDimitry Andric       // have 2 operands. i1* is used by the expander to represent an
9955ffd83dbSDimitry Andric       // address-size element.
9965ffd83dbSDimitry Andric       if (IncV->getNumOperands() != 2)
9975ffd83dbSDimitry Andric         return nullptr;
9985ffd83dbSDimitry Andric       unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
9995ffd83dbSDimitry Andric       if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
10005ffd83dbSDimitry Andric           && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
10015ffd83dbSDimitry Andric         return nullptr;
10025ffd83dbSDimitry Andric       break;
10035ffd83dbSDimitry Andric     }
10045ffd83dbSDimitry Andric     return dyn_cast<Instruction>(IncV->getOperand(0));
10055ffd83dbSDimitry Andric   }
10065ffd83dbSDimitry Andric }
10075ffd83dbSDimitry Andric 
10085ffd83dbSDimitry Andric /// If the insert point of the current builder or any of the builders on the
10095ffd83dbSDimitry Andric /// stack of saved builders has 'I' as its insert point, update it to point to
10105ffd83dbSDimitry Andric /// the instruction after 'I'.  This is intended to be used when the instruction
10115ffd83dbSDimitry Andric /// 'I' is being moved.  If this fixup is not done and 'I' is moved to a
10125ffd83dbSDimitry Andric /// different block, the inconsistent insert point (with a mismatched
10135ffd83dbSDimitry Andric /// Instruction and Block) can lead to an instruction being inserted in a block
10145ffd83dbSDimitry Andric /// other than its parent.
10155ffd83dbSDimitry Andric void SCEVExpander::fixupInsertPoints(Instruction *I) {
10165ffd83dbSDimitry Andric   BasicBlock::iterator It(*I);
10175ffd83dbSDimitry Andric   BasicBlock::iterator NewInsertPt = std::next(It);
10185ffd83dbSDimitry Andric   if (Builder.GetInsertPoint() == It)
10195ffd83dbSDimitry Andric     Builder.SetInsertPoint(&*NewInsertPt);
10205ffd83dbSDimitry Andric   for (auto *InsertPtGuard : InsertPointGuards)
10215ffd83dbSDimitry Andric     if (InsertPtGuard->GetInsertPoint() == It)
10225ffd83dbSDimitry Andric       InsertPtGuard->SetInsertPoint(NewInsertPt);
10235ffd83dbSDimitry Andric }
10245ffd83dbSDimitry Andric 
10255ffd83dbSDimitry Andric /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
10265ffd83dbSDimitry Andric /// it available to other uses in this loop. Recursively hoist any operands,
10275ffd83dbSDimitry Andric /// until we reach a value that dominates InsertPos.
10285ffd83dbSDimitry Andric bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
10295ffd83dbSDimitry Andric   if (SE.DT.dominates(IncV, InsertPos))
10305ffd83dbSDimitry Andric       return true;
10315ffd83dbSDimitry Andric 
10325ffd83dbSDimitry Andric   // InsertPos must itself dominate IncV so that IncV's new position satisfies
10335ffd83dbSDimitry Andric   // its existing users.
10345ffd83dbSDimitry Andric   if (isa<PHINode>(InsertPos) ||
10355ffd83dbSDimitry Andric       !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
10365ffd83dbSDimitry Andric     return false;
10375ffd83dbSDimitry Andric 
10385ffd83dbSDimitry Andric   if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
10395ffd83dbSDimitry Andric     return false;
10405ffd83dbSDimitry Andric 
10415ffd83dbSDimitry Andric   // Check that the chain of IV operands leading back to Phi can be hoisted.
10425ffd83dbSDimitry Andric   SmallVector<Instruction*, 4> IVIncs;
10435ffd83dbSDimitry Andric   for(;;) {
10445ffd83dbSDimitry Andric     Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
10455ffd83dbSDimitry Andric     if (!Oper)
10465ffd83dbSDimitry Andric       return false;
10475ffd83dbSDimitry Andric     // IncV is safe to hoist.
10485ffd83dbSDimitry Andric     IVIncs.push_back(IncV);
10495ffd83dbSDimitry Andric     IncV = Oper;
10505ffd83dbSDimitry Andric     if (SE.DT.dominates(IncV, InsertPos))
10515ffd83dbSDimitry Andric       break;
10525ffd83dbSDimitry Andric   }
10535ffd83dbSDimitry Andric   for (auto I = IVIncs.rbegin(), E = IVIncs.rend(); I != E; ++I) {
10545ffd83dbSDimitry Andric     fixupInsertPoints(*I);
10555ffd83dbSDimitry Andric     (*I)->moveBefore(InsertPos);
10565ffd83dbSDimitry Andric   }
10575ffd83dbSDimitry Andric   return true;
10585ffd83dbSDimitry Andric }
10595ffd83dbSDimitry Andric 
10605ffd83dbSDimitry Andric /// Determine if this cyclic phi is in a form that would have been generated by
10615ffd83dbSDimitry Andric /// LSR. We don't care if the phi was actually expanded in this pass, as long
10625ffd83dbSDimitry Andric /// as it is in a low-cost form, for example, no implied multiplication. This
10635ffd83dbSDimitry Andric /// should match any patterns generated by getAddRecExprPHILiterally and
10645ffd83dbSDimitry Andric /// expandAddtoGEP.
10655ffd83dbSDimitry Andric bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
10665ffd83dbSDimitry Andric                                            const Loop *L) {
10675ffd83dbSDimitry Andric   for(Instruction *IVOper = IncV;
10685ffd83dbSDimitry Andric       (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
10695ffd83dbSDimitry Andric                                 /*allowScale=*/false));) {
10705ffd83dbSDimitry Andric     if (IVOper == PN)
10715ffd83dbSDimitry Andric       return true;
10725ffd83dbSDimitry Andric   }
10735ffd83dbSDimitry Andric   return false;
10745ffd83dbSDimitry Andric }
10755ffd83dbSDimitry Andric 
10765ffd83dbSDimitry Andric /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
10775ffd83dbSDimitry Andric /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
10785ffd83dbSDimitry Andric /// need to materialize IV increments elsewhere to handle difficult situations.
10795ffd83dbSDimitry Andric Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
10805ffd83dbSDimitry Andric                                  Type *ExpandTy, Type *IntTy,
10815ffd83dbSDimitry Andric                                  bool useSubtract) {
10825ffd83dbSDimitry Andric   Value *IncV;
10835ffd83dbSDimitry Andric   // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
10845ffd83dbSDimitry Andric   if (ExpandTy->isPointerTy()) {
10855ffd83dbSDimitry Andric     PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
10865ffd83dbSDimitry Andric     // If the step isn't constant, don't use an implicitly scaled GEP, because
10875ffd83dbSDimitry Andric     // that would require a multiply inside the loop.
10885ffd83dbSDimitry Andric     if (!isa<ConstantInt>(StepV))
10895ffd83dbSDimitry Andric       GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
10905ffd83dbSDimitry Andric                                   GEPPtrTy->getAddressSpace());
10915ffd83dbSDimitry Andric     IncV = expandAddToGEP(SE.getSCEV(StepV), GEPPtrTy, IntTy, PN);
1092*e8d8bef9SDimitry Andric     if (IncV->getType() != PN->getType())
10935ffd83dbSDimitry Andric       IncV = Builder.CreateBitCast(IncV, PN->getType());
10945ffd83dbSDimitry Andric   } else {
10955ffd83dbSDimitry Andric     IncV = useSubtract ?
10965ffd83dbSDimitry Andric       Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
10975ffd83dbSDimitry Andric       Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
10985ffd83dbSDimitry Andric   }
10995ffd83dbSDimitry Andric   return IncV;
11005ffd83dbSDimitry Andric }
11015ffd83dbSDimitry Andric 
11025ffd83dbSDimitry Andric /// Hoist the addrec instruction chain rooted in the loop phi above the
11035ffd83dbSDimitry Andric /// position. This routine assumes that this is possible (has been checked).
11045ffd83dbSDimitry Andric void SCEVExpander::hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
11055ffd83dbSDimitry Andric                                   Instruction *Pos, PHINode *LoopPhi) {
11065ffd83dbSDimitry Andric   do {
11075ffd83dbSDimitry Andric     if (DT->dominates(InstToHoist, Pos))
11085ffd83dbSDimitry Andric       break;
11095ffd83dbSDimitry Andric     // Make sure the increment is where we want it. But don't move it
11105ffd83dbSDimitry Andric     // down past a potential existing post-inc user.
11115ffd83dbSDimitry Andric     fixupInsertPoints(InstToHoist);
11125ffd83dbSDimitry Andric     InstToHoist->moveBefore(Pos);
11135ffd83dbSDimitry Andric     Pos = InstToHoist;
11145ffd83dbSDimitry Andric     InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
11155ffd83dbSDimitry Andric   } while (InstToHoist != LoopPhi);
11165ffd83dbSDimitry Andric }
11175ffd83dbSDimitry Andric 
11185ffd83dbSDimitry Andric /// Check whether we can cheaply express the requested SCEV in terms of
11195ffd83dbSDimitry Andric /// the available PHI SCEV by truncation and/or inversion of the step.
11205ffd83dbSDimitry Andric static bool canBeCheaplyTransformed(ScalarEvolution &SE,
11215ffd83dbSDimitry Andric                                     const SCEVAddRecExpr *Phi,
11225ffd83dbSDimitry Andric                                     const SCEVAddRecExpr *Requested,
11235ffd83dbSDimitry Andric                                     bool &InvertStep) {
11245ffd83dbSDimitry Andric   Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
11255ffd83dbSDimitry Andric   Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
11265ffd83dbSDimitry Andric 
11275ffd83dbSDimitry Andric   if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
11285ffd83dbSDimitry Andric     return false;
11295ffd83dbSDimitry Andric 
11305ffd83dbSDimitry Andric   // Try truncate it if necessary.
11315ffd83dbSDimitry Andric   Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
11325ffd83dbSDimitry Andric   if (!Phi)
11335ffd83dbSDimitry Andric     return false;
11345ffd83dbSDimitry Andric 
11355ffd83dbSDimitry Andric   // Check whether truncation will help.
11365ffd83dbSDimitry Andric   if (Phi == Requested) {
11375ffd83dbSDimitry Andric     InvertStep = false;
11385ffd83dbSDimitry Andric     return true;
11395ffd83dbSDimitry Andric   }
11405ffd83dbSDimitry Andric 
11415ffd83dbSDimitry Andric   // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
11425ffd83dbSDimitry Andric   if (SE.getAddExpr(Requested->getStart(),
11435ffd83dbSDimitry Andric                     SE.getNegativeSCEV(Requested)) == Phi) {
11445ffd83dbSDimitry Andric     InvertStep = true;
11455ffd83dbSDimitry Andric     return true;
11465ffd83dbSDimitry Andric   }
11475ffd83dbSDimitry Andric 
11485ffd83dbSDimitry Andric   return false;
11495ffd83dbSDimitry Andric }
11505ffd83dbSDimitry Andric 
11515ffd83dbSDimitry Andric static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
11525ffd83dbSDimitry Andric   if (!isa<IntegerType>(AR->getType()))
11535ffd83dbSDimitry Andric     return false;
11545ffd83dbSDimitry Andric 
11555ffd83dbSDimitry Andric   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
11565ffd83dbSDimitry Andric   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
11575ffd83dbSDimitry Andric   const SCEV *Step = AR->getStepRecurrence(SE);
11585ffd83dbSDimitry Andric   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
11595ffd83dbSDimitry Andric                                             SE.getSignExtendExpr(AR, WideTy));
11605ffd83dbSDimitry Andric   const SCEV *ExtendAfterOp =
11615ffd83dbSDimitry Andric     SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
11625ffd83dbSDimitry Andric   return ExtendAfterOp == OpAfterExtend;
11635ffd83dbSDimitry Andric }
11645ffd83dbSDimitry Andric 
11655ffd83dbSDimitry Andric static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
11665ffd83dbSDimitry Andric   if (!isa<IntegerType>(AR->getType()))
11675ffd83dbSDimitry Andric     return false;
11685ffd83dbSDimitry Andric 
11695ffd83dbSDimitry Andric   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
11705ffd83dbSDimitry Andric   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
11715ffd83dbSDimitry Andric   const SCEV *Step = AR->getStepRecurrence(SE);
11725ffd83dbSDimitry Andric   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
11735ffd83dbSDimitry Andric                                             SE.getZeroExtendExpr(AR, WideTy));
11745ffd83dbSDimitry Andric   const SCEV *ExtendAfterOp =
11755ffd83dbSDimitry Andric     SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
11765ffd83dbSDimitry Andric   return ExtendAfterOp == OpAfterExtend;
11775ffd83dbSDimitry Andric }
11785ffd83dbSDimitry Andric 
11795ffd83dbSDimitry Andric /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
11805ffd83dbSDimitry Andric /// the base addrec, which is the addrec without any non-loop-dominating
11815ffd83dbSDimitry Andric /// values, and return the PHI.
11825ffd83dbSDimitry Andric PHINode *
11835ffd83dbSDimitry Andric SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
11845ffd83dbSDimitry Andric                                         const Loop *L,
11855ffd83dbSDimitry Andric                                         Type *ExpandTy,
11865ffd83dbSDimitry Andric                                         Type *IntTy,
11875ffd83dbSDimitry Andric                                         Type *&TruncTy,
11885ffd83dbSDimitry Andric                                         bool &InvertStep) {
11895ffd83dbSDimitry Andric   assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
11905ffd83dbSDimitry Andric 
11915ffd83dbSDimitry Andric   // Reuse a previously-inserted PHI, if present.
11925ffd83dbSDimitry Andric   BasicBlock *LatchBlock = L->getLoopLatch();
11935ffd83dbSDimitry Andric   if (LatchBlock) {
11945ffd83dbSDimitry Andric     PHINode *AddRecPhiMatch = nullptr;
11955ffd83dbSDimitry Andric     Instruction *IncV = nullptr;
11965ffd83dbSDimitry Andric     TruncTy = nullptr;
11975ffd83dbSDimitry Andric     InvertStep = false;
11985ffd83dbSDimitry Andric 
11995ffd83dbSDimitry Andric     // Only try partially matching scevs that need truncation and/or
12005ffd83dbSDimitry Andric     // step-inversion if we know this loop is outside the current loop.
12015ffd83dbSDimitry Andric     bool TryNonMatchingSCEV =
12025ffd83dbSDimitry Andric         IVIncInsertLoop &&
12035ffd83dbSDimitry Andric         SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
12045ffd83dbSDimitry Andric 
12055ffd83dbSDimitry Andric     for (PHINode &PN : L->getHeader()->phis()) {
12065ffd83dbSDimitry Andric       if (!SE.isSCEVable(PN.getType()))
12075ffd83dbSDimitry Andric         continue;
12085ffd83dbSDimitry Andric 
1209*e8d8bef9SDimitry Andric       // We should not look for a incomplete PHI. Getting SCEV for a incomplete
1210*e8d8bef9SDimitry Andric       // PHI has no meaning at all.
1211*e8d8bef9SDimitry Andric       if (!PN.isComplete()) {
1212*e8d8bef9SDimitry Andric         DEBUG_WITH_TYPE(
1213*e8d8bef9SDimitry Andric             DebugType, dbgs() << "One incomplete PHI is found: " << PN << "\n");
1214*e8d8bef9SDimitry Andric         continue;
1215*e8d8bef9SDimitry Andric       }
1216*e8d8bef9SDimitry Andric 
12175ffd83dbSDimitry Andric       const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
12185ffd83dbSDimitry Andric       if (!PhiSCEV)
12195ffd83dbSDimitry Andric         continue;
12205ffd83dbSDimitry Andric 
12215ffd83dbSDimitry Andric       bool IsMatchingSCEV = PhiSCEV == Normalized;
12225ffd83dbSDimitry Andric       // We only handle truncation and inversion of phi recurrences for the
12235ffd83dbSDimitry Andric       // expanded expression if the expanded expression's loop dominates the
12245ffd83dbSDimitry Andric       // loop we insert to. Check now, so we can bail out early.
12255ffd83dbSDimitry Andric       if (!IsMatchingSCEV && !TryNonMatchingSCEV)
12265ffd83dbSDimitry Andric           continue;
12275ffd83dbSDimitry Andric 
12285ffd83dbSDimitry Andric       // TODO: this possibly can be reworked to avoid this cast at all.
12295ffd83dbSDimitry Andric       Instruction *TempIncV =
12305ffd83dbSDimitry Andric           dyn_cast<Instruction>(PN.getIncomingValueForBlock(LatchBlock));
12315ffd83dbSDimitry Andric       if (!TempIncV)
12325ffd83dbSDimitry Andric         continue;
12335ffd83dbSDimitry Andric 
12345ffd83dbSDimitry Andric       // Check whether we can reuse this PHI node.
12355ffd83dbSDimitry Andric       if (LSRMode) {
12365ffd83dbSDimitry Andric         if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
12375ffd83dbSDimitry Andric           continue;
12385ffd83dbSDimitry Andric         if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
12395ffd83dbSDimitry Andric           continue;
12405ffd83dbSDimitry Andric       } else {
12415ffd83dbSDimitry Andric         if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
12425ffd83dbSDimitry Andric           continue;
12435ffd83dbSDimitry Andric       }
12445ffd83dbSDimitry Andric 
12455ffd83dbSDimitry Andric       // Stop if we have found an exact match SCEV.
12465ffd83dbSDimitry Andric       if (IsMatchingSCEV) {
12475ffd83dbSDimitry Andric         IncV = TempIncV;
12485ffd83dbSDimitry Andric         TruncTy = nullptr;
12495ffd83dbSDimitry Andric         InvertStep = false;
12505ffd83dbSDimitry Andric         AddRecPhiMatch = &PN;
12515ffd83dbSDimitry Andric         break;
12525ffd83dbSDimitry Andric       }
12535ffd83dbSDimitry Andric 
12545ffd83dbSDimitry Andric       // Try whether the phi can be translated into the requested form
12555ffd83dbSDimitry Andric       // (truncated and/or offset by a constant).
12565ffd83dbSDimitry Andric       if ((!TruncTy || InvertStep) &&
12575ffd83dbSDimitry Andric           canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
12585ffd83dbSDimitry Andric         // Record the phi node. But don't stop we might find an exact match
12595ffd83dbSDimitry Andric         // later.
12605ffd83dbSDimitry Andric         AddRecPhiMatch = &PN;
12615ffd83dbSDimitry Andric         IncV = TempIncV;
12625ffd83dbSDimitry Andric         TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
12635ffd83dbSDimitry Andric       }
12645ffd83dbSDimitry Andric     }
12655ffd83dbSDimitry Andric 
12665ffd83dbSDimitry Andric     if (AddRecPhiMatch) {
12675ffd83dbSDimitry Andric       // Potentially, move the increment. We have made sure in
12685ffd83dbSDimitry Andric       // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
12695ffd83dbSDimitry Andric       if (L == IVIncInsertLoop)
12705ffd83dbSDimitry Andric         hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
12715ffd83dbSDimitry Andric 
12725ffd83dbSDimitry Andric       // Ok, the add recurrence looks usable.
12735ffd83dbSDimitry Andric       // Remember this PHI, even in post-inc mode.
12745ffd83dbSDimitry Andric       InsertedValues.insert(AddRecPhiMatch);
12755ffd83dbSDimitry Andric       // Remember the increment.
12765ffd83dbSDimitry Andric       rememberInstruction(IncV);
1277*e8d8bef9SDimitry Andric       // Those values were not actually inserted but re-used.
1278*e8d8bef9SDimitry Andric       ReusedValues.insert(AddRecPhiMatch);
1279*e8d8bef9SDimitry Andric       ReusedValues.insert(IncV);
12805ffd83dbSDimitry Andric       return AddRecPhiMatch;
12815ffd83dbSDimitry Andric     }
12825ffd83dbSDimitry Andric   }
12835ffd83dbSDimitry Andric 
12845ffd83dbSDimitry Andric   // Save the original insertion point so we can restore it when we're done.
12855ffd83dbSDimitry Andric   SCEVInsertPointGuard Guard(Builder, this);
12865ffd83dbSDimitry Andric 
12875ffd83dbSDimitry Andric   // Another AddRec may need to be recursively expanded below. For example, if
12885ffd83dbSDimitry Andric   // this AddRec is quadratic, the StepV may itself be an AddRec in this
12895ffd83dbSDimitry Andric   // loop. Remove this loop from the PostIncLoops set before expanding such
12905ffd83dbSDimitry Andric   // AddRecs. Otherwise, we cannot find a valid position for the step
12915ffd83dbSDimitry Andric   // (i.e. StepV can never dominate its loop header).  Ideally, we could do
12925ffd83dbSDimitry Andric   // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
12935ffd83dbSDimitry Andric   // so it's not worth implementing SmallPtrSet::swap.
12945ffd83dbSDimitry Andric   PostIncLoopSet SavedPostIncLoops = PostIncLoops;
12955ffd83dbSDimitry Andric   PostIncLoops.clear();
12965ffd83dbSDimitry Andric 
12975ffd83dbSDimitry Andric   // Expand code for the start value into the loop preheader.
12985ffd83dbSDimitry Andric   assert(L->getLoopPreheader() &&
12995ffd83dbSDimitry Andric          "Can't expand add recurrences without a loop preheader!");
1300*e8d8bef9SDimitry Andric   Value *StartV =
1301*e8d8bef9SDimitry Andric       expandCodeForImpl(Normalized->getStart(), ExpandTy,
1302*e8d8bef9SDimitry Andric                         L->getLoopPreheader()->getTerminator(), false);
13035ffd83dbSDimitry Andric 
13045ffd83dbSDimitry Andric   // StartV must have been be inserted into L's preheader to dominate the new
13055ffd83dbSDimitry Andric   // phi.
13065ffd83dbSDimitry Andric   assert(!isa<Instruction>(StartV) ||
13075ffd83dbSDimitry Andric          SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
13085ffd83dbSDimitry Andric                                  L->getHeader()));
13095ffd83dbSDimitry Andric 
13105ffd83dbSDimitry Andric   // Expand code for the step value. Do this before creating the PHI so that PHI
13115ffd83dbSDimitry Andric   // reuse code doesn't see an incomplete PHI.
13125ffd83dbSDimitry Andric   const SCEV *Step = Normalized->getStepRecurrence(SE);
13135ffd83dbSDimitry Andric   // If the stride is negative, insert a sub instead of an add for the increment
13145ffd83dbSDimitry Andric   // (unless it's a constant, because subtracts of constants are canonicalized
13155ffd83dbSDimitry Andric   // to adds).
13165ffd83dbSDimitry Andric   bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
13175ffd83dbSDimitry Andric   if (useSubtract)
13185ffd83dbSDimitry Andric     Step = SE.getNegativeSCEV(Step);
13195ffd83dbSDimitry Andric   // Expand the step somewhere that dominates the loop header.
1320*e8d8bef9SDimitry Andric   Value *StepV = expandCodeForImpl(
1321*e8d8bef9SDimitry Andric       Step, IntTy, &*L->getHeader()->getFirstInsertionPt(), false);
13225ffd83dbSDimitry Andric 
13235ffd83dbSDimitry Andric   // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
13245ffd83dbSDimitry Andric   // we actually do emit an addition.  It does not apply if we emit a
13255ffd83dbSDimitry Andric   // subtraction.
13265ffd83dbSDimitry Andric   bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
13275ffd83dbSDimitry Andric   bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
13285ffd83dbSDimitry Andric 
13295ffd83dbSDimitry Andric   // Create the PHI.
13305ffd83dbSDimitry Andric   BasicBlock *Header = L->getHeader();
13315ffd83dbSDimitry Andric   Builder.SetInsertPoint(Header, Header->begin());
13325ffd83dbSDimitry Andric   pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
13335ffd83dbSDimitry Andric   PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
13345ffd83dbSDimitry Andric                                   Twine(IVName) + ".iv");
13355ffd83dbSDimitry Andric 
13365ffd83dbSDimitry Andric   // Create the step instructions and populate the PHI.
13375ffd83dbSDimitry Andric   for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
13385ffd83dbSDimitry Andric     BasicBlock *Pred = *HPI;
13395ffd83dbSDimitry Andric 
13405ffd83dbSDimitry Andric     // Add a start value.
13415ffd83dbSDimitry Andric     if (!L->contains(Pred)) {
13425ffd83dbSDimitry Andric       PN->addIncoming(StartV, Pred);
13435ffd83dbSDimitry Andric       continue;
13445ffd83dbSDimitry Andric     }
13455ffd83dbSDimitry Andric 
13465ffd83dbSDimitry Andric     // Create a step value and add it to the PHI.
13475ffd83dbSDimitry Andric     // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
13485ffd83dbSDimitry Andric     // instructions at IVIncInsertPos.
13495ffd83dbSDimitry Andric     Instruction *InsertPos = L == IVIncInsertLoop ?
13505ffd83dbSDimitry Andric       IVIncInsertPos : Pred->getTerminator();
13515ffd83dbSDimitry Andric     Builder.SetInsertPoint(InsertPos);
13525ffd83dbSDimitry Andric     Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
13535ffd83dbSDimitry Andric 
13545ffd83dbSDimitry Andric     if (isa<OverflowingBinaryOperator>(IncV)) {
13555ffd83dbSDimitry Andric       if (IncrementIsNUW)
13565ffd83dbSDimitry Andric         cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
13575ffd83dbSDimitry Andric       if (IncrementIsNSW)
13585ffd83dbSDimitry Andric         cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
13595ffd83dbSDimitry Andric     }
13605ffd83dbSDimitry Andric     PN->addIncoming(IncV, Pred);
13615ffd83dbSDimitry Andric   }
13625ffd83dbSDimitry Andric 
13635ffd83dbSDimitry Andric   // After expanding subexpressions, restore the PostIncLoops set so the caller
13645ffd83dbSDimitry Andric   // can ensure that IVIncrement dominates the current uses.
13655ffd83dbSDimitry Andric   PostIncLoops = SavedPostIncLoops;
13665ffd83dbSDimitry Andric 
13675ffd83dbSDimitry Andric   // Remember this PHI, even in post-inc mode.
13685ffd83dbSDimitry Andric   InsertedValues.insert(PN);
13695ffd83dbSDimitry Andric 
13705ffd83dbSDimitry Andric   return PN;
13715ffd83dbSDimitry Andric }
13725ffd83dbSDimitry Andric 
13735ffd83dbSDimitry Andric Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
13745ffd83dbSDimitry Andric   Type *STy = S->getType();
13755ffd83dbSDimitry Andric   Type *IntTy = SE.getEffectiveSCEVType(STy);
13765ffd83dbSDimitry Andric   const Loop *L = S->getLoop();
13775ffd83dbSDimitry Andric 
13785ffd83dbSDimitry Andric   // Determine a normalized form of this expression, which is the expression
13795ffd83dbSDimitry Andric   // before any post-inc adjustment is made.
13805ffd83dbSDimitry Andric   const SCEVAddRecExpr *Normalized = S;
13815ffd83dbSDimitry Andric   if (PostIncLoops.count(L)) {
13825ffd83dbSDimitry Andric     PostIncLoopSet Loops;
13835ffd83dbSDimitry Andric     Loops.insert(L);
13845ffd83dbSDimitry Andric     Normalized = cast<SCEVAddRecExpr>(normalizeForPostIncUse(S, Loops, SE));
13855ffd83dbSDimitry Andric   }
13865ffd83dbSDimitry Andric 
13875ffd83dbSDimitry Andric   // Strip off any non-loop-dominating component from the addrec start.
13885ffd83dbSDimitry Andric   const SCEV *Start = Normalized->getStart();
13895ffd83dbSDimitry Andric   const SCEV *PostLoopOffset = nullptr;
13905ffd83dbSDimitry Andric   if (!SE.properlyDominates(Start, L->getHeader())) {
13915ffd83dbSDimitry Andric     PostLoopOffset = Start;
13925ffd83dbSDimitry Andric     Start = SE.getConstant(Normalized->getType(), 0);
13935ffd83dbSDimitry Andric     Normalized = cast<SCEVAddRecExpr>(
13945ffd83dbSDimitry Andric       SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
13955ffd83dbSDimitry Andric                        Normalized->getLoop(),
13965ffd83dbSDimitry Andric                        Normalized->getNoWrapFlags(SCEV::FlagNW)));
13975ffd83dbSDimitry Andric   }
13985ffd83dbSDimitry Andric 
13995ffd83dbSDimitry Andric   // Strip off any non-loop-dominating component from the addrec step.
14005ffd83dbSDimitry Andric   const SCEV *Step = Normalized->getStepRecurrence(SE);
14015ffd83dbSDimitry Andric   const SCEV *PostLoopScale = nullptr;
14025ffd83dbSDimitry Andric   if (!SE.dominates(Step, L->getHeader())) {
14035ffd83dbSDimitry Andric     PostLoopScale = Step;
14045ffd83dbSDimitry Andric     Step = SE.getConstant(Normalized->getType(), 1);
14055ffd83dbSDimitry Andric     if (!Start->isZero()) {
14065ffd83dbSDimitry Andric         // The normalization below assumes that Start is constant zero, so if
14075ffd83dbSDimitry Andric         // it isn't re-associate Start to PostLoopOffset.
14085ffd83dbSDimitry Andric         assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?");
14095ffd83dbSDimitry Andric         PostLoopOffset = Start;
14105ffd83dbSDimitry Andric         Start = SE.getConstant(Normalized->getType(), 0);
14115ffd83dbSDimitry Andric     }
14125ffd83dbSDimitry Andric     Normalized =
14135ffd83dbSDimitry Andric       cast<SCEVAddRecExpr>(SE.getAddRecExpr(
14145ffd83dbSDimitry Andric                              Start, Step, Normalized->getLoop(),
14155ffd83dbSDimitry Andric                              Normalized->getNoWrapFlags(SCEV::FlagNW)));
14165ffd83dbSDimitry Andric   }
14175ffd83dbSDimitry Andric 
14185ffd83dbSDimitry Andric   // Expand the core addrec. If we need post-loop scaling, force it to
14195ffd83dbSDimitry Andric   // expand to an integer type to avoid the need for additional casting.
14205ffd83dbSDimitry Andric   Type *ExpandTy = PostLoopScale ? IntTy : STy;
14215ffd83dbSDimitry Andric   // We can't use a pointer type for the addrec if the pointer type is
14225ffd83dbSDimitry Andric   // non-integral.
14235ffd83dbSDimitry Andric   Type *AddRecPHIExpandTy =
14245ffd83dbSDimitry Andric       DL.isNonIntegralPointerType(STy) ? Normalized->getType() : ExpandTy;
14255ffd83dbSDimitry Andric 
14265ffd83dbSDimitry Andric   // In some cases, we decide to reuse an existing phi node but need to truncate
14275ffd83dbSDimitry Andric   // it and/or invert the step.
14285ffd83dbSDimitry Andric   Type *TruncTy = nullptr;
14295ffd83dbSDimitry Andric   bool InvertStep = false;
14305ffd83dbSDimitry Andric   PHINode *PN = getAddRecExprPHILiterally(Normalized, L, AddRecPHIExpandTy,
14315ffd83dbSDimitry Andric                                           IntTy, TruncTy, InvertStep);
14325ffd83dbSDimitry Andric 
14335ffd83dbSDimitry Andric   // Accommodate post-inc mode, if necessary.
14345ffd83dbSDimitry Andric   Value *Result;
14355ffd83dbSDimitry Andric   if (!PostIncLoops.count(L))
14365ffd83dbSDimitry Andric     Result = PN;
14375ffd83dbSDimitry Andric   else {
14385ffd83dbSDimitry Andric     // In PostInc mode, use the post-incremented value.
14395ffd83dbSDimitry Andric     BasicBlock *LatchBlock = L->getLoopLatch();
14405ffd83dbSDimitry Andric     assert(LatchBlock && "PostInc mode requires a unique loop latch!");
14415ffd83dbSDimitry Andric     Result = PN->getIncomingValueForBlock(LatchBlock);
14425ffd83dbSDimitry Andric 
1443*e8d8bef9SDimitry Andric     // We might be introducing a new use of the post-inc IV that is not poison
1444*e8d8bef9SDimitry Andric     // safe, in which case we should drop poison generating flags. Only keep
1445*e8d8bef9SDimitry Andric     // those flags for which SCEV has proven that they always hold.
1446*e8d8bef9SDimitry Andric     if (isa<OverflowingBinaryOperator>(Result)) {
1447*e8d8bef9SDimitry Andric       auto *I = cast<Instruction>(Result);
1448*e8d8bef9SDimitry Andric       if (!S->hasNoUnsignedWrap())
1449*e8d8bef9SDimitry Andric         I->setHasNoUnsignedWrap(false);
1450*e8d8bef9SDimitry Andric       if (!S->hasNoSignedWrap())
1451*e8d8bef9SDimitry Andric         I->setHasNoSignedWrap(false);
1452*e8d8bef9SDimitry Andric     }
1453*e8d8bef9SDimitry Andric 
14545ffd83dbSDimitry Andric     // For an expansion to use the postinc form, the client must call
14555ffd83dbSDimitry Andric     // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
14565ffd83dbSDimitry Andric     // or dominated by IVIncInsertPos.
14575ffd83dbSDimitry Andric     if (isa<Instruction>(Result) &&
14585ffd83dbSDimitry Andric         !SE.DT.dominates(cast<Instruction>(Result),
14595ffd83dbSDimitry Andric                          &*Builder.GetInsertPoint())) {
14605ffd83dbSDimitry Andric       // The induction variable's postinc expansion does not dominate this use.
14615ffd83dbSDimitry Andric       // IVUsers tries to prevent this case, so it is rare. However, it can
14625ffd83dbSDimitry Andric       // happen when an IVUser outside the loop is not dominated by the latch
14635ffd83dbSDimitry Andric       // block. Adjusting IVIncInsertPos before expansion begins cannot handle
14645ffd83dbSDimitry Andric       // all cases. Consider a phi outside whose operand is replaced during
14655ffd83dbSDimitry Andric       // expansion with the value of the postinc user. Without fundamentally
14665ffd83dbSDimitry Andric       // changing the way postinc users are tracked, the only remedy is
14675ffd83dbSDimitry Andric       // inserting an extra IV increment. StepV might fold into PostLoopOffset,
14685ffd83dbSDimitry Andric       // but hopefully expandCodeFor handles that.
14695ffd83dbSDimitry Andric       bool useSubtract =
14705ffd83dbSDimitry Andric         !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
14715ffd83dbSDimitry Andric       if (useSubtract)
14725ffd83dbSDimitry Andric         Step = SE.getNegativeSCEV(Step);
14735ffd83dbSDimitry Andric       Value *StepV;
14745ffd83dbSDimitry Andric       {
14755ffd83dbSDimitry Andric         // Expand the step somewhere that dominates the loop header.
14765ffd83dbSDimitry Andric         SCEVInsertPointGuard Guard(Builder, this);
1477*e8d8bef9SDimitry Andric         StepV = expandCodeForImpl(
1478*e8d8bef9SDimitry Andric             Step, IntTy, &*L->getHeader()->getFirstInsertionPt(), false);
14795ffd83dbSDimitry Andric       }
14805ffd83dbSDimitry Andric       Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
14815ffd83dbSDimitry Andric     }
14825ffd83dbSDimitry Andric   }
14835ffd83dbSDimitry Andric 
14845ffd83dbSDimitry Andric   // We have decided to reuse an induction variable of a dominating loop. Apply
14855ffd83dbSDimitry Andric   // truncation and/or inversion of the step.
14865ffd83dbSDimitry Andric   if (TruncTy) {
14875ffd83dbSDimitry Andric     Type *ResTy = Result->getType();
14885ffd83dbSDimitry Andric     // Normalize the result type.
14895ffd83dbSDimitry Andric     if (ResTy != SE.getEffectiveSCEVType(ResTy))
14905ffd83dbSDimitry Andric       Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
14915ffd83dbSDimitry Andric     // Truncate the result.
1492*e8d8bef9SDimitry Andric     if (TruncTy != Result->getType())
14935ffd83dbSDimitry Andric       Result = Builder.CreateTrunc(Result, TruncTy);
1494*e8d8bef9SDimitry Andric 
14955ffd83dbSDimitry Andric     // Invert the result.
1496*e8d8bef9SDimitry Andric     if (InvertStep)
1497*e8d8bef9SDimitry Andric       Result = Builder.CreateSub(
1498*e8d8bef9SDimitry Andric           expandCodeForImpl(Normalized->getStart(), TruncTy, false), Result);
14995ffd83dbSDimitry Andric   }
15005ffd83dbSDimitry Andric 
15015ffd83dbSDimitry Andric   // Re-apply any non-loop-dominating scale.
15025ffd83dbSDimitry Andric   if (PostLoopScale) {
15035ffd83dbSDimitry Andric     assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
15045ffd83dbSDimitry Andric     Result = InsertNoopCastOfTo(Result, IntTy);
15055ffd83dbSDimitry Andric     Result = Builder.CreateMul(Result,
1506*e8d8bef9SDimitry Andric                                expandCodeForImpl(PostLoopScale, IntTy, false));
15075ffd83dbSDimitry Andric   }
15085ffd83dbSDimitry Andric 
15095ffd83dbSDimitry Andric   // Re-apply any non-loop-dominating offset.
15105ffd83dbSDimitry Andric   if (PostLoopOffset) {
15115ffd83dbSDimitry Andric     if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
15125ffd83dbSDimitry Andric       if (Result->getType()->isIntegerTy()) {
1513*e8d8bef9SDimitry Andric         Value *Base = expandCodeForImpl(PostLoopOffset, ExpandTy, false);
15145ffd83dbSDimitry Andric         Result = expandAddToGEP(SE.getUnknown(Result), PTy, IntTy, Base);
15155ffd83dbSDimitry Andric       } else {
15165ffd83dbSDimitry Andric         Result = expandAddToGEP(PostLoopOffset, PTy, IntTy, Result);
15175ffd83dbSDimitry Andric       }
15185ffd83dbSDimitry Andric     } else {
15195ffd83dbSDimitry Andric       Result = InsertNoopCastOfTo(Result, IntTy);
1520*e8d8bef9SDimitry Andric       Result = Builder.CreateAdd(
1521*e8d8bef9SDimitry Andric           Result, expandCodeForImpl(PostLoopOffset, IntTy, false));
15225ffd83dbSDimitry Andric     }
15235ffd83dbSDimitry Andric   }
15245ffd83dbSDimitry Andric 
15255ffd83dbSDimitry Andric   return Result;
15265ffd83dbSDimitry Andric }
15275ffd83dbSDimitry Andric 
15285ffd83dbSDimitry Andric Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
15295ffd83dbSDimitry Andric   // In canonical mode we compute the addrec as an expression of a canonical IV
15305ffd83dbSDimitry Andric   // using evaluateAtIteration and expand the resulting SCEV expression. This
15315ffd83dbSDimitry Andric   // way we avoid introducing new IVs to carry on the comutation of the addrec
15325ffd83dbSDimitry Andric   // throughout the loop.
15335ffd83dbSDimitry Andric   //
15345ffd83dbSDimitry Andric   // For nested addrecs evaluateAtIteration might need a canonical IV of a
15355ffd83dbSDimitry Andric   // type wider than the addrec itself. Emitting a canonical IV of the
15365ffd83dbSDimitry Andric   // proper type might produce non-legal types, for example expanding an i64
15375ffd83dbSDimitry Andric   // {0,+,2,+,1} addrec would need an i65 canonical IV. To avoid this just fall
15385ffd83dbSDimitry Andric   // back to non-canonical mode for nested addrecs.
15395ffd83dbSDimitry Andric   if (!CanonicalMode || (S->getNumOperands() > 2))
15405ffd83dbSDimitry Andric     return expandAddRecExprLiterally(S);
15415ffd83dbSDimitry Andric 
15425ffd83dbSDimitry Andric   Type *Ty = SE.getEffectiveSCEVType(S->getType());
15435ffd83dbSDimitry Andric   const Loop *L = S->getLoop();
15445ffd83dbSDimitry Andric 
15455ffd83dbSDimitry Andric   // First check for an existing canonical IV in a suitable type.
15465ffd83dbSDimitry Andric   PHINode *CanonicalIV = nullptr;
15475ffd83dbSDimitry Andric   if (PHINode *PN = L->getCanonicalInductionVariable())
15485ffd83dbSDimitry Andric     if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
15495ffd83dbSDimitry Andric       CanonicalIV = PN;
15505ffd83dbSDimitry Andric 
15515ffd83dbSDimitry Andric   // Rewrite an AddRec in terms of the canonical induction variable, if
15525ffd83dbSDimitry Andric   // its type is more narrow.
15535ffd83dbSDimitry Andric   if (CanonicalIV &&
15545ffd83dbSDimitry Andric       SE.getTypeSizeInBits(CanonicalIV->getType()) >
15555ffd83dbSDimitry Andric       SE.getTypeSizeInBits(Ty)) {
15565ffd83dbSDimitry Andric     SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
15575ffd83dbSDimitry Andric     for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
15585ffd83dbSDimitry Andric       NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
15595ffd83dbSDimitry Andric     Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
15605ffd83dbSDimitry Andric                                        S->getNoWrapFlags(SCEV::FlagNW)));
15615ffd83dbSDimitry Andric     BasicBlock::iterator NewInsertPt =
1562*e8d8bef9SDimitry Andric         findInsertPointAfter(cast<Instruction>(V), &*Builder.GetInsertPoint());
1563*e8d8bef9SDimitry Andric     V = expandCodeForImpl(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
1564*e8d8bef9SDimitry Andric                           &*NewInsertPt, false);
15655ffd83dbSDimitry Andric     return V;
15665ffd83dbSDimitry Andric   }
15675ffd83dbSDimitry Andric 
15685ffd83dbSDimitry Andric   // {X,+,F} --> X + {0,+,F}
15695ffd83dbSDimitry Andric   if (!S->getStart()->isZero()) {
1570*e8d8bef9SDimitry Andric     SmallVector<const SCEV *, 4> NewOps(S->operands());
15715ffd83dbSDimitry Andric     NewOps[0] = SE.getConstant(Ty, 0);
15725ffd83dbSDimitry Andric     const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
15735ffd83dbSDimitry Andric                                         S->getNoWrapFlags(SCEV::FlagNW));
15745ffd83dbSDimitry Andric 
15755ffd83dbSDimitry Andric     // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
15765ffd83dbSDimitry Andric     // comments on expandAddToGEP for details.
15775ffd83dbSDimitry Andric     const SCEV *Base = S->getStart();
15785ffd83dbSDimitry Andric     // Dig into the expression to find the pointer base for a GEP.
15795ffd83dbSDimitry Andric     const SCEV *ExposedRest = Rest;
15805ffd83dbSDimitry Andric     ExposePointerBase(Base, ExposedRest, SE);
15815ffd83dbSDimitry Andric     // If we found a pointer, expand the AddRec with a GEP.
15825ffd83dbSDimitry Andric     if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
15835ffd83dbSDimitry Andric       // Make sure the Base isn't something exotic, such as a multiplied
15845ffd83dbSDimitry Andric       // or divided pointer value. In those cases, the result type isn't
15855ffd83dbSDimitry Andric       // actually a pointer type.
15865ffd83dbSDimitry Andric       if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
15875ffd83dbSDimitry Andric         Value *StartV = expand(Base);
15885ffd83dbSDimitry Andric         assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
15895ffd83dbSDimitry Andric         return expandAddToGEP(ExposedRest, PTy, Ty, StartV);
15905ffd83dbSDimitry Andric       }
15915ffd83dbSDimitry Andric     }
15925ffd83dbSDimitry Andric 
15935ffd83dbSDimitry Andric     // Just do a normal add. Pre-expand the operands to suppress folding.
15945ffd83dbSDimitry Andric     //
15955ffd83dbSDimitry Andric     // The LHS and RHS values are factored out of the expand call to make the
15965ffd83dbSDimitry Andric     // output independent of the argument evaluation order.
15975ffd83dbSDimitry Andric     const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
15985ffd83dbSDimitry Andric     const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
15995ffd83dbSDimitry Andric     return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
16005ffd83dbSDimitry Andric   }
16015ffd83dbSDimitry Andric 
16025ffd83dbSDimitry Andric   // If we don't yet have a canonical IV, create one.
16035ffd83dbSDimitry Andric   if (!CanonicalIV) {
16045ffd83dbSDimitry Andric     // Create and insert the PHI node for the induction variable in the
16055ffd83dbSDimitry Andric     // specified loop.
16065ffd83dbSDimitry Andric     BasicBlock *Header = L->getHeader();
16075ffd83dbSDimitry Andric     pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
16085ffd83dbSDimitry Andric     CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
16095ffd83dbSDimitry Andric                                   &Header->front());
16105ffd83dbSDimitry Andric     rememberInstruction(CanonicalIV);
16115ffd83dbSDimitry Andric 
16125ffd83dbSDimitry Andric     SmallSet<BasicBlock *, 4> PredSeen;
16135ffd83dbSDimitry Andric     Constant *One = ConstantInt::get(Ty, 1);
16145ffd83dbSDimitry Andric     for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
16155ffd83dbSDimitry Andric       BasicBlock *HP = *HPI;
16165ffd83dbSDimitry Andric       if (!PredSeen.insert(HP).second) {
16175ffd83dbSDimitry Andric         // There must be an incoming value for each predecessor, even the
16185ffd83dbSDimitry Andric         // duplicates!
16195ffd83dbSDimitry Andric         CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
16205ffd83dbSDimitry Andric         continue;
16215ffd83dbSDimitry Andric       }
16225ffd83dbSDimitry Andric 
16235ffd83dbSDimitry Andric       if (L->contains(HP)) {
16245ffd83dbSDimitry Andric         // Insert a unit add instruction right before the terminator
16255ffd83dbSDimitry Andric         // corresponding to the back-edge.
16265ffd83dbSDimitry Andric         Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
16275ffd83dbSDimitry Andric                                                      "indvar.next",
16285ffd83dbSDimitry Andric                                                      HP->getTerminator());
16295ffd83dbSDimitry Andric         Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
16305ffd83dbSDimitry Andric         rememberInstruction(Add);
16315ffd83dbSDimitry Andric         CanonicalIV->addIncoming(Add, HP);
16325ffd83dbSDimitry Andric       } else {
16335ffd83dbSDimitry Andric         CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
16345ffd83dbSDimitry Andric       }
16355ffd83dbSDimitry Andric     }
16365ffd83dbSDimitry Andric   }
16375ffd83dbSDimitry Andric 
16385ffd83dbSDimitry Andric   // {0,+,1} --> Insert a canonical induction variable into the loop!
16395ffd83dbSDimitry Andric   if (S->isAffine() && S->getOperand(1)->isOne()) {
16405ffd83dbSDimitry Andric     assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
16415ffd83dbSDimitry Andric            "IVs with types different from the canonical IV should "
16425ffd83dbSDimitry Andric            "already have been handled!");
16435ffd83dbSDimitry Andric     return CanonicalIV;
16445ffd83dbSDimitry Andric   }
16455ffd83dbSDimitry Andric 
16465ffd83dbSDimitry Andric   // {0,+,F} --> {0,+,1} * F
16475ffd83dbSDimitry Andric 
16485ffd83dbSDimitry Andric   // If this is a simple linear addrec, emit it now as a special case.
16495ffd83dbSDimitry Andric   if (S->isAffine())    // {0,+,F} --> i*F
16505ffd83dbSDimitry Andric     return
16515ffd83dbSDimitry Andric       expand(SE.getTruncateOrNoop(
16525ffd83dbSDimitry Andric         SE.getMulExpr(SE.getUnknown(CanonicalIV),
16535ffd83dbSDimitry Andric                       SE.getNoopOrAnyExtend(S->getOperand(1),
16545ffd83dbSDimitry Andric                                             CanonicalIV->getType())),
16555ffd83dbSDimitry Andric         Ty));
16565ffd83dbSDimitry Andric 
16575ffd83dbSDimitry Andric   // If this is a chain of recurrences, turn it into a closed form, using the
16585ffd83dbSDimitry Andric   // folders, then expandCodeFor the closed form.  This allows the folders to
16595ffd83dbSDimitry Andric   // simplify the expression without having to build a bunch of special code
16605ffd83dbSDimitry Andric   // into this folder.
16615ffd83dbSDimitry Andric   const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
16625ffd83dbSDimitry Andric 
16635ffd83dbSDimitry Andric   // Promote S up to the canonical IV type, if the cast is foldable.
16645ffd83dbSDimitry Andric   const SCEV *NewS = S;
16655ffd83dbSDimitry Andric   const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
16665ffd83dbSDimitry Andric   if (isa<SCEVAddRecExpr>(Ext))
16675ffd83dbSDimitry Andric     NewS = Ext;
16685ffd83dbSDimitry Andric 
16695ffd83dbSDimitry Andric   const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
16705ffd83dbSDimitry Andric   //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
16715ffd83dbSDimitry Andric 
16725ffd83dbSDimitry Andric   // Truncate the result down to the original type, if needed.
16735ffd83dbSDimitry Andric   const SCEV *T = SE.getTruncateOrNoop(V, Ty);
16745ffd83dbSDimitry Andric   return expand(T);
16755ffd83dbSDimitry Andric }
16765ffd83dbSDimitry Andric 
1677*e8d8bef9SDimitry Andric Value *SCEVExpander::visitPtrToIntExpr(const SCEVPtrToIntExpr *S) {
1678*e8d8bef9SDimitry Andric   Value *V =
1679*e8d8bef9SDimitry Andric       expandCodeForImpl(S->getOperand(), S->getOperand()->getType(), false);
1680*e8d8bef9SDimitry Andric   return Builder.CreatePtrToInt(V, S->getType());
1681*e8d8bef9SDimitry Andric }
1682*e8d8bef9SDimitry Andric 
16835ffd83dbSDimitry Andric Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
16845ffd83dbSDimitry Andric   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1685*e8d8bef9SDimitry Andric   Value *V = expandCodeForImpl(
1686*e8d8bef9SDimitry Andric       S->getOperand(), SE.getEffectiveSCEVType(S->getOperand()->getType()),
1687*e8d8bef9SDimitry Andric       false);
1688*e8d8bef9SDimitry Andric   return Builder.CreateTrunc(V, Ty);
16895ffd83dbSDimitry Andric }
16905ffd83dbSDimitry Andric 
16915ffd83dbSDimitry Andric Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
16925ffd83dbSDimitry Andric   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1693*e8d8bef9SDimitry Andric   Value *V = expandCodeForImpl(
1694*e8d8bef9SDimitry Andric       S->getOperand(), SE.getEffectiveSCEVType(S->getOperand()->getType()),
1695*e8d8bef9SDimitry Andric       false);
1696*e8d8bef9SDimitry Andric   return Builder.CreateZExt(V, Ty);
16975ffd83dbSDimitry Andric }
16985ffd83dbSDimitry Andric 
16995ffd83dbSDimitry Andric Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
17005ffd83dbSDimitry Andric   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1701*e8d8bef9SDimitry Andric   Value *V = expandCodeForImpl(
1702*e8d8bef9SDimitry Andric       S->getOperand(), SE.getEffectiveSCEVType(S->getOperand()->getType()),
1703*e8d8bef9SDimitry Andric       false);
1704*e8d8bef9SDimitry Andric   return Builder.CreateSExt(V, Ty);
17055ffd83dbSDimitry Andric }
17065ffd83dbSDimitry Andric 
17075ffd83dbSDimitry Andric Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
17085ffd83dbSDimitry Andric   Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
17095ffd83dbSDimitry Andric   Type *Ty = LHS->getType();
17105ffd83dbSDimitry Andric   for (int i = S->getNumOperands()-2; i >= 0; --i) {
17115ffd83dbSDimitry Andric     // In the case of mixed integer and pointer types, do the
17125ffd83dbSDimitry Andric     // rest of the comparisons as integer.
17135ffd83dbSDimitry Andric     Type *OpTy = S->getOperand(i)->getType();
17145ffd83dbSDimitry Andric     if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
17155ffd83dbSDimitry Andric       Ty = SE.getEffectiveSCEVType(Ty);
17165ffd83dbSDimitry Andric       LHS = InsertNoopCastOfTo(LHS, Ty);
17175ffd83dbSDimitry Andric     }
1718*e8d8bef9SDimitry Andric     Value *RHS = expandCodeForImpl(S->getOperand(i), Ty, false);
17195ffd83dbSDimitry Andric     Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
17205ffd83dbSDimitry Andric     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
17215ffd83dbSDimitry Andric     LHS = Sel;
17225ffd83dbSDimitry Andric   }
17235ffd83dbSDimitry Andric   // In the case of mixed integer and pointer types, cast the
17245ffd83dbSDimitry Andric   // final result back to the pointer type.
17255ffd83dbSDimitry Andric   if (LHS->getType() != S->getType())
17265ffd83dbSDimitry Andric     LHS = InsertNoopCastOfTo(LHS, S->getType());
17275ffd83dbSDimitry Andric   return LHS;
17285ffd83dbSDimitry Andric }
17295ffd83dbSDimitry Andric 
17305ffd83dbSDimitry Andric Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
17315ffd83dbSDimitry Andric   Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
17325ffd83dbSDimitry Andric   Type *Ty = LHS->getType();
17335ffd83dbSDimitry Andric   for (int i = S->getNumOperands()-2; i >= 0; --i) {
17345ffd83dbSDimitry Andric     // In the case of mixed integer and pointer types, do the
17355ffd83dbSDimitry Andric     // rest of the comparisons as integer.
17365ffd83dbSDimitry Andric     Type *OpTy = S->getOperand(i)->getType();
17375ffd83dbSDimitry Andric     if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
17385ffd83dbSDimitry Andric       Ty = SE.getEffectiveSCEVType(Ty);
17395ffd83dbSDimitry Andric       LHS = InsertNoopCastOfTo(LHS, Ty);
17405ffd83dbSDimitry Andric     }
1741*e8d8bef9SDimitry Andric     Value *RHS = expandCodeForImpl(S->getOperand(i), Ty, false);
17425ffd83dbSDimitry Andric     Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
17435ffd83dbSDimitry Andric     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
17445ffd83dbSDimitry Andric     LHS = Sel;
17455ffd83dbSDimitry Andric   }
17465ffd83dbSDimitry Andric   // In the case of mixed integer and pointer types, cast the
17475ffd83dbSDimitry Andric   // final result back to the pointer type.
17485ffd83dbSDimitry Andric   if (LHS->getType() != S->getType())
17495ffd83dbSDimitry Andric     LHS = InsertNoopCastOfTo(LHS, S->getType());
17505ffd83dbSDimitry Andric   return LHS;
17515ffd83dbSDimitry Andric }
17525ffd83dbSDimitry Andric 
17535ffd83dbSDimitry Andric Value *SCEVExpander::visitSMinExpr(const SCEVSMinExpr *S) {
17545ffd83dbSDimitry Andric   Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
17555ffd83dbSDimitry Andric   Type *Ty = LHS->getType();
17565ffd83dbSDimitry Andric   for (int i = S->getNumOperands() - 2; i >= 0; --i) {
17575ffd83dbSDimitry Andric     // In the case of mixed integer and pointer types, do the
17585ffd83dbSDimitry Andric     // rest of the comparisons as integer.
17595ffd83dbSDimitry Andric     Type *OpTy = S->getOperand(i)->getType();
17605ffd83dbSDimitry Andric     if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
17615ffd83dbSDimitry Andric       Ty = SE.getEffectiveSCEVType(Ty);
17625ffd83dbSDimitry Andric       LHS = InsertNoopCastOfTo(LHS, Ty);
17635ffd83dbSDimitry Andric     }
1764*e8d8bef9SDimitry Andric     Value *RHS = expandCodeForImpl(S->getOperand(i), Ty, false);
17655ffd83dbSDimitry Andric     Value *ICmp = Builder.CreateICmpSLT(LHS, RHS);
17665ffd83dbSDimitry Andric     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smin");
17675ffd83dbSDimitry Andric     LHS = Sel;
17685ffd83dbSDimitry Andric   }
17695ffd83dbSDimitry Andric   // In the case of mixed integer and pointer types, cast the
17705ffd83dbSDimitry Andric   // final result back to the pointer type.
17715ffd83dbSDimitry Andric   if (LHS->getType() != S->getType())
17725ffd83dbSDimitry Andric     LHS = InsertNoopCastOfTo(LHS, S->getType());
17735ffd83dbSDimitry Andric   return LHS;
17745ffd83dbSDimitry Andric }
17755ffd83dbSDimitry Andric 
17765ffd83dbSDimitry Andric Value *SCEVExpander::visitUMinExpr(const SCEVUMinExpr *S) {
17775ffd83dbSDimitry Andric   Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
17785ffd83dbSDimitry Andric   Type *Ty = LHS->getType();
17795ffd83dbSDimitry Andric   for (int i = S->getNumOperands() - 2; i >= 0; --i) {
17805ffd83dbSDimitry Andric     // In the case of mixed integer and pointer types, do the
17815ffd83dbSDimitry Andric     // rest of the comparisons as integer.
17825ffd83dbSDimitry Andric     Type *OpTy = S->getOperand(i)->getType();
17835ffd83dbSDimitry Andric     if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
17845ffd83dbSDimitry Andric       Ty = SE.getEffectiveSCEVType(Ty);
17855ffd83dbSDimitry Andric       LHS = InsertNoopCastOfTo(LHS, Ty);
17865ffd83dbSDimitry Andric     }
1787*e8d8bef9SDimitry Andric     Value *RHS = expandCodeForImpl(S->getOperand(i), Ty, false);
17885ffd83dbSDimitry Andric     Value *ICmp = Builder.CreateICmpULT(LHS, RHS);
17895ffd83dbSDimitry Andric     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umin");
17905ffd83dbSDimitry Andric     LHS = Sel;
17915ffd83dbSDimitry Andric   }
17925ffd83dbSDimitry Andric   // In the case of mixed integer and pointer types, cast the
17935ffd83dbSDimitry Andric   // final result back to the pointer type.
17945ffd83dbSDimitry Andric   if (LHS->getType() != S->getType())
17955ffd83dbSDimitry Andric     LHS = InsertNoopCastOfTo(LHS, S->getType());
17965ffd83dbSDimitry Andric   return LHS;
17975ffd83dbSDimitry Andric }
17985ffd83dbSDimitry Andric 
1799*e8d8bef9SDimitry Andric Value *SCEVExpander::expandCodeForImpl(const SCEV *SH, Type *Ty,
1800*e8d8bef9SDimitry Andric                                        Instruction *IP, bool Root) {
18015ffd83dbSDimitry Andric   setInsertPoint(IP);
1802*e8d8bef9SDimitry Andric   Value *V = expandCodeForImpl(SH, Ty, Root);
1803*e8d8bef9SDimitry Andric   return V;
18045ffd83dbSDimitry Andric }
18055ffd83dbSDimitry Andric 
1806*e8d8bef9SDimitry Andric Value *SCEVExpander::expandCodeForImpl(const SCEV *SH, Type *Ty, bool Root) {
18075ffd83dbSDimitry Andric   // Expand the code for this SCEV.
18085ffd83dbSDimitry Andric   Value *V = expand(SH);
1809*e8d8bef9SDimitry Andric 
1810*e8d8bef9SDimitry Andric   if (PreserveLCSSA) {
1811*e8d8bef9SDimitry Andric     if (auto *Inst = dyn_cast<Instruction>(V)) {
1812*e8d8bef9SDimitry Andric       // Create a temporary instruction to at the current insertion point, so we
1813*e8d8bef9SDimitry Andric       // can hand it off to the helper to create LCSSA PHIs if required for the
1814*e8d8bef9SDimitry Andric       // new use.
1815*e8d8bef9SDimitry Andric       // FIXME: Ideally formLCSSAForInstructions (used in fixupLCSSAFormFor)
1816*e8d8bef9SDimitry Andric       // would accept a insertion point and return an LCSSA phi for that
1817*e8d8bef9SDimitry Andric       // insertion point, so there is no need to insert & remove the temporary
1818*e8d8bef9SDimitry Andric       // instruction.
1819*e8d8bef9SDimitry Andric       Instruction *Tmp;
1820*e8d8bef9SDimitry Andric       if (Inst->getType()->isIntegerTy())
1821*e8d8bef9SDimitry Andric         Tmp =
1822*e8d8bef9SDimitry Andric             cast<Instruction>(Builder.CreateAdd(Inst, Inst, "tmp.lcssa.user"));
1823*e8d8bef9SDimitry Andric       else {
1824*e8d8bef9SDimitry Andric         assert(Inst->getType()->isPointerTy());
1825*e8d8bef9SDimitry Andric         Tmp = cast<Instruction>(
1826*e8d8bef9SDimitry Andric             Builder.CreateGEP(Inst, Builder.getInt32(1), "tmp.lcssa.user"));
1827*e8d8bef9SDimitry Andric       }
1828*e8d8bef9SDimitry Andric       V = fixupLCSSAFormFor(Tmp, 0);
1829*e8d8bef9SDimitry Andric 
1830*e8d8bef9SDimitry Andric       // Clean up temporary instruction.
1831*e8d8bef9SDimitry Andric       InsertedValues.erase(Tmp);
1832*e8d8bef9SDimitry Andric       InsertedPostIncValues.erase(Tmp);
1833*e8d8bef9SDimitry Andric       Tmp->eraseFromParent();
1834*e8d8bef9SDimitry Andric     }
1835*e8d8bef9SDimitry Andric   }
1836*e8d8bef9SDimitry Andric 
1837*e8d8bef9SDimitry Andric   InsertedExpressions[std::make_pair(SH, &*Builder.GetInsertPoint())] = V;
18385ffd83dbSDimitry Andric   if (Ty) {
18395ffd83dbSDimitry Andric     assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
18405ffd83dbSDimitry Andric            "non-trivial casts should be done with the SCEVs directly!");
18415ffd83dbSDimitry Andric     V = InsertNoopCastOfTo(V, Ty);
18425ffd83dbSDimitry Andric   }
18435ffd83dbSDimitry Andric   return V;
18445ffd83dbSDimitry Andric }
18455ffd83dbSDimitry Andric 
18465ffd83dbSDimitry Andric ScalarEvolution::ValueOffsetPair
18475ffd83dbSDimitry Andric SCEVExpander::FindValueInExprValueMap(const SCEV *S,
18485ffd83dbSDimitry Andric                                       const Instruction *InsertPt) {
18495ffd83dbSDimitry Andric   SetVector<ScalarEvolution::ValueOffsetPair> *Set = SE.getSCEVValues(S);
18505ffd83dbSDimitry Andric   // If the expansion is not in CanonicalMode, and the SCEV contains any
18515ffd83dbSDimitry Andric   // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
18525ffd83dbSDimitry Andric   if (CanonicalMode || !SE.containsAddRecurrence(S)) {
18535ffd83dbSDimitry Andric     // If S is scConstant, it may be worse to reuse an existing Value.
18545ffd83dbSDimitry Andric     if (S->getSCEVType() != scConstant && Set) {
18555ffd83dbSDimitry Andric       // Choose a Value from the set which dominates the insertPt.
18565ffd83dbSDimitry Andric       // insertPt should be inside the Value's parent loop so as not to break
18575ffd83dbSDimitry Andric       // the LCSSA form.
18585ffd83dbSDimitry Andric       for (auto const &VOPair : *Set) {
18595ffd83dbSDimitry Andric         Value *V = VOPair.first;
18605ffd83dbSDimitry Andric         ConstantInt *Offset = VOPair.second;
18615ffd83dbSDimitry Andric         Instruction *EntInst = nullptr;
18625ffd83dbSDimitry Andric         if (V && isa<Instruction>(V) && (EntInst = cast<Instruction>(V)) &&
18635ffd83dbSDimitry Andric             S->getType() == V->getType() &&
18645ffd83dbSDimitry Andric             EntInst->getFunction() == InsertPt->getFunction() &&
18655ffd83dbSDimitry Andric             SE.DT.dominates(EntInst, InsertPt) &&
18665ffd83dbSDimitry Andric             (SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
18675ffd83dbSDimitry Andric              SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
18685ffd83dbSDimitry Andric           return {V, Offset};
18695ffd83dbSDimitry Andric       }
18705ffd83dbSDimitry Andric     }
18715ffd83dbSDimitry Andric   }
18725ffd83dbSDimitry Andric   return {nullptr, nullptr};
18735ffd83dbSDimitry Andric }
18745ffd83dbSDimitry Andric 
18755ffd83dbSDimitry Andric // The expansion of SCEV will either reuse a previous Value in ExprValueMap,
18765ffd83dbSDimitry Andric // or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
18775ffd83dbSDimitry Andric // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
18785ffd83dbSDimitry Andric // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
18795ffd83dbSDimitry Andric // the expansion will try to reuse Value from ExprValueMap, and only when it
18805ffd83dbSDimitry Andric // fails, expand the SCEV literally.
18815ffd83dbSDimitry Andric Value *SCEVExpander::expand(const SCEV *S) {
18825ffd83dbSDimitry Andric   // Compute an insertion point for this SCEV object. Hoist the instructions
18835ffd83dbSDimitry Andric   // as far out in the loop nest as possible.
18845ffd83dbSDimitry Andric   Instruction *InsertPt = &*Builder.GetInsertPoint();
18855ffd83dbSDimitry Andric 
18865ffd83dbSDimitry Andric   // We can move insertion point only if there is no div or rem operations
18875ffd83dbSDimitry Andric   // otherwise we are risky to move it over the check for zero denominator.
18885ffd83dbSDimitry Andric   auto SafeToHoist = [](const SCEV *S) {
18895ffd83dbSDimitry Andric     return !SCEVExprContains(S, [](const SCEV *S) {
18905ffd83dbSDimitry Andric               if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) {
18915ffd83dbSDimitry Andric                 if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS()))
18925ffd83dbSDimitry Andric                   // Division by non-zero constants can be hoisted.
18935ffd83dbSDimitry Andric                   return SC->getValue()->isZero();
18945ffd83dbSDimitry Andric                 // All other divisions should not be moved as they may be
18955ffd83dbSDimitry Andric                 // divisions by zero and should be kept within the
18965ffd83dbSDimitry Andric                 // conditions of the surrounding loops that guard their
18975ffd83dbSDimitry Andric                 // execution (see PR35406).
18985ffd83dbSDimitry Andric                 return true;
18995ffd83dbSDimitry Andric               }
19005ffd83dbSDimitry Andric               return false;
19015ffd83dbSDimitry Andric             });
19025ffd83dbSDimitry Andric   };
19035ffd83dbSDimitry Andric   if (SafeToHoist(S)) {
19045ffd83dbSDimitry Andric     for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
19055ffd83dbSDimitry Andric          L = L->getParentLoop()) {
19065ffd83dbSDimitry Andric       if (SE.isLoopInvariant(S, L)) {
19075ffd83dbSDimitry Andric         if (!L) break;
19085ffd83dbSDimitry Andric         if (BasicBlock *Preheader = L->getLoopPreheader())
19095ffd83dbSDimitry Andric           InsertPt = Preheader->getTerminator();
19105ffd83dbSDimitry Andric         else
19115ffd83dbSDimitry Andric           // LSR sets the insertion point for AddRec start/step values to the
19125ffd83dbSDimitry Andric           // block start to simplify value reuse, even though it's an invalid
19135ffd83dbSDimitry Andric           // position. SCEVExpander must correct for this in all cases.
19145ffd83dbSDimitry Andric           InsertPt = &*L->getHeader()->getFirstInsertionPt();
19155ffd83dbSDimitry Andric       } else {
19165ffd83dbSDimitry Andric         // If the SCEV is computable at this level, insert it into the header
19175ffd83dbSDimitry Andric         // after the PHIs (and after any other instructions that we've inserted
19185ffd83dbSDimitry Andric         // there) so that it is guaranteed to dominate any user inside the loop.
19195ffd83dbSDimitry Andric         if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
19205ffd83dbSDimitry Andric           InsertPt = &*L->getHeader()->getFirstInsertionPt();
1921*e8d8bef9SDimitry Andric 
19225ffd83dbSDimitry Andric         while (InsertPt->getIterator() != Builder.GetInsertPoint() &&
19235ffd83dbSDimitry Andric                (isInsertedInstruction(InsertPt) ||
1924*e8d8bef9SDimitry Andric                 isa<DbgInfoIntrinsic>(InsertPt))) {
19255ffd83dbSDimitry Andric           InsertPt = &*std::next(InsertPt->getIterator());
1926*e8d8bef9SDimitry Andric         }
19275ffd83dbSDimitry Andric         break;
19285ffd83dbSDimitry Andric       }
19295ffd83dbSDimitry Andric     }
19305ffd83dbSDimitry Andric   }
19315ffd83dbSDimitry Andric 
19325ffd83dbSDimitry Andric   // Check to see if we already expanded this here.
19335ffd83dbSDimitry Andric   auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
19345ffd83dbSDimitry Andric   if (I != InsertedExpressions.end())
19355ffd83dbSDimitry Andric     return I->second;
19365ffd83dbSDimitry Andric 
19375ffd83dbSDimitry Andric   SCEVInsertPointGuard Guard(Builder, this);
19385ffd83dbSDimitry Andric   Builder.SetInsertPoint(InsertPt);
19395ffd83dbSDimitry Andric 
19405ffd83dbSDimitry Andric   // Expand the expression into instructions.
19415ffd83dbSDimitry Andric   ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, InsertPt);
19425ffd83dbSDimitry Andric   Value *V = VO.first;
19435ffd83dbSDimitry Andric 
19445ffd83dbSDimitry Andric   if (!V)
19455ffd83dbSDimitry Andric     V = visit(S);
19465ffd83dbSDimitry Andric   else if (VO.second) {
19475ffd83dbSDimitry Andric     if (PointerType *Vty = dyn_cast<PointerType>(V->getType())) {
19485ffd83dbSDimitry Andric       Type *Ety = Vty->getPointerElementType();
19495ffd83dbSDimitry Andric       int64_t Offset = VO.second->getSExtValue();
19505ffd83dbSDimitry Andric       int64_t ESize = SE.getTypeSizeInBits(Ety);
19515ffd83dbSDimitry Andric       if ((Offset * 8) % ESize == 0) {
19525ffd83dbSDimitry Andric         ConstantInt *Idx =
19535ffd83dbSDimitry Andric             ConstantInt::getSigned(VO.second->getType(), -(Offset * 8) / ESize);
19545ffd83dbSDimitry Andric         V = Builder.CreateGEP(Ety, V, Idx, "scevgep");
19555ffd83dbSDimitry Andric       } else {
19565ffd83dbSDimitry Andric         ConstantInt *Idx =
19575ffd83dbSDimitry Andric             ConstantInt::getSigned(VO.second->getType(), -Offset);
19585ffd83dbSDimitry Andric         unsigned AS = Vty->getAddressSpace();
19595ffd83dbSDimitry Andric         V = Builder.CreateBitCast(V, Type::getInt8PtrTy(SE.getContext(), AS));
19605ffd83dbSDimitry Andric         V = Builder.CreateGEP(Type::getInt8Ty(SE.getContext()), V, Idx,
19615ffd83dbSDimitry Andric                               "uglygep");
19625ffd83dbSDimitry Andric         V = Builder.CreateBitCast(V, Vty);
19635ffd83dbSDimitry Andric       }
19645ffd83dbSDimitry Andric     } else {
19655ffd83dbSDimitry Andric       V = Builder.CreateSub(V, VO.second);
19665ffd83dbSDimitry Andric     }
19675ffd83dbSDimitry Andric   }
19685ffd83dbSDimitry Andric   // Remember the expanded value for this SCEV at this location.
19695ffd83dbSDimitry Andric   //
19705ffd83dbSDimitry Andric   // This is independent of PostIncLoops. The mapped value simply materializes
19715ffd83dbSDimitry Andric   // the expression at this insertion point. If the mapped value happened to be
19725ffd83dbSDimitry Andric   // a postinc expansion, it could be reused by a non-postinc user, but only if
19735ffd83dbSDimitry Andric   // its insertion point was already at the head of the loop.
19745ffd83dbSDimitry Andric   InsertedExpressions[std::make_pair(S, InsertPt)] = V;
19755ffd83dbSDimitry Andric   return V;
19765ffd83dbSDimitry Andric }
19775ffd83dbSDimitry Andric 
19785ffd83dbSDimitry Andric void SCEVExpander::rememberInstruction(Value *I) {
1979*e8d8bef9SDimitry Andric   auto DoInsert = [this](Value *V) {
19805ffd83dbSDimitry Andric     if (!PostIncLoops.empty())
1981*e8d8bef9SDimitry Andric       InsertedPostIncValues.insert(V);
19825ffd83dbSDimitry Andric     else
1983*e8d8bef9SDimitry Andric       InsertedValues.insert(V);
1984*e8d8bef9SDimitry Andric   };
1985*e8d8bef9SDimitry Andric   DoInsert(I);
1986*e8d8bef9SDimitry Andric 
1987*e8d8bef9SDimitry Andric   if (!PreserveLCSSA)
1988*e8d8bef9SDimitry Andric     return;
1989*e8d8bef9SDimitry Andric 
1990*e8d8bef9SDimitry Andric   if (auto *Inst = dyn_cast<Instruction>(I)) {
1991*e8d8bef9SDimitry Andric     // A new instruction has been added, which might introduce new uses outside
1992*e8d8bef9SDimitry Andric     // a defining loop. Fix LCSSA from for each operand of the new instruction,
1993*e8d8bef9SDimitry Andric     // if required.
1994*e8d8bef9SDimitry Andric     for (unsigned OpIdx = 0, OpEnd = Inst->getNumOperands(); OpIdx != OpEnd;
1995*e8d8bef9SDimitry Andric          OpIdx++)
1996*e8d8bef9SDimitry Andric       fixupLCSSAFormFor(Inst, OpIdx);
19975ffd83dbSDimitry Andric   }
19985ffd83dbSDimitry Andric }
19995ffd83dbSDimitry Andric 
20005ffd83dbSDimitry Andric /// replaceCongruentIVs - Check for congruent phis in this loop header and
20015ffd83dbSDimitry Andric /// replace them with their most canonical representative. Return the number of
20025ffd83dbSDimitry Andric /// phis eliminated.
20035ffd83dbSDimitry Andric ///
20045ffd83dbSDimitry Andric /// This does not depend on any SCEVExpander state but should be used in
20055ffd83dbSDimitry Andric /// the same context that SCEVExpander is used.
20065ffd83dbSDimitry Andric unsigned
20075ffd83dbSDimitry Andric SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
20085ffd83dbSDimitry Andric                                   SmallVectorImpl<WeakTrackingVH> &DeadInsts,
20095ffd83dbSDimitry Andric                                   const TargetTransformInfo *TTI) {
20105ffd83dbSDimitry Andric   // Find integer phis in order of increasing width.
20115ffd83dbSDimitry Andric   SmallVector<PHINode*, 8> Phis;
20125ffd83dbSDimitry Andric   for (PHINode &PN : L->getHeader()->phis())
20135ffd83dbSDimitry Andric     Phis.push_back(&PN);
20145ffd83dbSDimitry Andric 
20155ffd83dbSDimitry Andric   if (TTI)
20165ffd83dbSDimitry Andric     llvm::sort(Phis, [](Value *LHS, Value *RHS) {
20175ffd83dbSDimitry Andric       // Put pointers at the back and make sure pointer < pointer = false.
20185ffd83dbSDimitry Andric       if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
20195ffd83dbSDimitry Andric         return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
2020*e8d8bef9SDimitry Andric       return RHS->getType()->getPrimitiveSizeInBits().getFixedSize() <
2021*e8d8bef9SDimitry Andric              LHS->getType()->getPrimitiveSizeInBits().getFixedSize();
20225ffd83dbSDimitry Andric     });
20235ffd83dbSDimitry Andric 
20245ffd83dbSDimitry Andric   unsigned NumElim = 0;
20255ffd83dbSDimitry Andric   DenseMap<const SCEV *, PHINode *> ExprToIVMap;
20265ffd83dbSDimitry Andric   // Process phis from wide to narrow. Map wide phis to their truncation
20275ffd83dbSDimitry Andric   // so narrow phis can reuse them.
20285ffd83dbSDimitry Andric   for (PHINode *Phi : Phis) {
20295ffd83dbSDimitry Andric     auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
20305ffd83dbSDimitry Andric       if (Value *V = SimplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC}))
20315ffd83dbSDimitry Andric         return V;
20325ffd83dbSDimitry Andric       if (!SE.isSCEVable(PN->getType()))
20335ffd83dbSDimitry Andric         return nullptr;
20345ffd83dbSDimitry Andric       auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
20355ffd83dbSDimitry Andric       if (!Const)
20365ffd83dbSDimitry Andric         return nullptr;
20375ffd83dbSDimitry Andric       return Const->getValue();
20385ffd83dbSDimitry Andric     };
20395ffd83dbSDimitry Andric 
20405ffd83dbSDimitry Andric     // Fold constant phis. They may be congruent to other constant phis and
20415ffd83dbSDimitry Andric     // would confuse the logic below that expects proper IVs.
20425ffd83dbSDimitry Andric     if (Value *V = SimplifyPHINode(Phi)) {
20435ffd83dbSDimitry Andric       if (V->getType() != Phi->getType())
20445ffd83dbSDimitry Andric         continue;
20455ffd83dbSDimitry Andric       Phi->replaceAllUsesWith(V);
20465ffd83dbSDimitry Andric       DeadInsts.emplace_back(Phi);
20475ffd83dbSDimitry Andric       ++NumElim;
20485ffd83dbSDimitry Andric       DEBUG_WITH_TYPE(DebugType, dbgs()
20495ffd83dbSDimitry Andric                       << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
20505ffd83dbSDimitry Andric       continue;
20515ffd83dbSDimitry Andric     }
20525ffd83dbSDimitry Andric 
20535ffd83dbSDimitry Andric     if (!SE.isSCEVable(Phi->getType()))
20545ffd83dbSDimitry Andric       continue;
20555ffd83dbSDimitry Andric 
20565ffd83dbSDimitry Andric     PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
20575ffd83dbSDimitry Andric     if (!OrigPhiRef) {
20585ffd83dbSDimitry Andric       OrigPhiRef = Phi;
20595ffd83dbSDimitry Andric       if (Phi->getType()->isIntegerTy() && TTI &&
20605ffd83dbSDimitry Andric           TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
20615ffd83dbSDimitry Andric         // This phi can be freely truncated to the narrowest phi type. Map the
20625ffd83dbSDimitry Andric         // truncated expression to it so it will be reused for narrow types.
20635ffd83dbSDimitry Andric         const SCEV *TruncExpr =
20645ffd83dbSDimitry Andric           SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
20655ffd83dbSDimitry Andric         ExprToIVMap[TruncExpr] = Phi;
20665ffd83dbSDimitry Andric       }
20675ffd83dbSDimitry Andric       continue;
20685ffd83dbSDimitry Andric     }
20695ffd83dbSDimitry Andric 
20705ffd83dbSDimitry Andric     // Replacing a pointer phi with an integer phi or vice-versa doesn't make
20715ffd83dbSDimitry Andric     // sense.
20725ffd83dbSDimitry Andric     if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
20735ffd83dbSDimitry Andric       continue;
20745ffd83dbSDimitry Andric 
20755ffd83dbSDimitry Andric     if (BasicBlock *LatchBlock = L->getLoopLatch()) {
20765ffd83dbSDimitry Andric       Instruction *OrigInc = dyn_cast<Instruction>(
20775ffd83dbSDimitry Andric           OrigPhiRef->getIncomingValueForBlock(LatchBlock));
20785ffd83dbSDimitry Andric       Instruction *IsomorphicInc =
20795ffd83dbSDimitry Andric           dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
20805ffd83dbSDimitry Andric 
20815ffd83dbSDimitry Andric       if (OrigInc && IsomorphicInc) {
20825ffd83dbSDimitry Andric         // If this phi has the same width but is more canonical, replace the
20835ffd83dbSDimitry Andric         // original with it. As part of the "more canonical" determination,
20845ffd83dbSDimitry Andric         // respect a prior decision to use an IV chain.
20855ffd83dbSDimitry Andric         if (OrigPhiRef->getType() == Phi->getType() &&
20865ffd83dbSDimitry Andric             !(ChainedPhis.count(Phi) ||
20875ffd83dbSDimitry Andric               isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
20885ffd83dbSDimitry Andric             (ChainedPhis.count(Phi) ||
20895ffd83dbSDimitry Andric              isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
20905ffd83dbSDimitry Andric           std::swap(OrigPhiRef, Phi);
20915ffd83dbSDimitry Andric           std::swap(OrigInc, IsomorphicInc);
20925ffd83dbSDimitry Andric         }
20935ffd83dbSDimitry Andric         // Replacing the congruent phi is sufficient because acyclic
20945ffd83dbSDimitry Andric         // redundancy elimination, CSE/GVN, should handle the
20955ffd83dbSDimitry Andric         // rest. However, once SCEV proves that a phi is congruent,
20965ffd83dbSDimitry Andric         // it's often the head of an IV user cycle that is isomorphic
20975ffd83dbSDimitry Andric         // with the original phi. It's worth eagerly cleaning up the
20985ffd83dbSDimitry Andric         // common case of a single IV increment so that DeleteDeadPHIs
20995ffd83dbSDimitry Andric         // can remove cycles that had postinc uses.
21005ffd83dbSDimitry Andric         const SCEV *TruncExpr =
21015ffd83dbSDimitry Andric             SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
21025ffd83dbSDimitry Andric         if (OrigInc != IsomorphicInc &&
21035ffd83dbSDimitry Andric             TruncExpr == SE.getSCEV(IsomorphicInc) &&
21045ffd83dbSDimitry Andric             SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
21055ffd83dbSDimitry Andric             hoistIVInc(OrigInc, IsomorphicInc)) {
21065ffd83dbSDimitry Andric           DEBUG_WITH_TYPE(DebugType,
21075ffd83dbSDimitry Andric                           dbgs() << "INDVARS: Eliminated congruent iv.inc: "
21085ffd83dbSDimitry Andric                                  << *IsomorphicInc << '\n');
21095ffd83dbSDimitry Andric           Value *NewInc = OrigInc;
21105ffd83dbSDimitry Andric           if (OrigInc->getType() != IsomorphicInc->getType()) {
21115ffd83dbSDimitry Andric             Instruction *IP = nullptr;
21125ffd83dbSDimitry Andric             if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
21135ffd83dbSDimitry Andric               IP = &*PN->getParent()->getFirstInsertionPt();
21145ffd83dbSDimitry Andric             else
21155ffd83dbSDimitry Andric               IP = OrigInc->getNextNode();
21165ffd83dbSDimitry Andric 
21175ffd83dbSDimitry Andric             IRBuilder<> Builder(IP);
21185ffd83dbSDimitry Andric             Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
21195ffd83dbSDimitry Andric             NewInc = Builder.CreateTruncOrBitCast(
21205ffd83dbSDimitry Andric                 OrigInc, IsomorphicInc->getType(), IVName);
21215ffd83dbSDimitry Andric           }
21225ffd83dbSDimitry Andric           IsomorphicInc->replaceAllUsesWith(NewInc);
21235ffd83dbSDimitry Andric           DeadInsts.emplace_back(IsomorphicInc);
21245ffd83dbSDimitry Andric         }
21255ffd83dbSDimitry Andric       }
21265ffd83dbSDimitry Andric     }
21275ffd83dbSDimitry Andric     DEBUG_WITH_TYPE(DebugType, dbgs() << "INDVARS: Eliminated congruent iv: "
21285ffd83dbSDimitry Andric                                       << *Phi << '\n');
2129*e8d8bef9SDimitry Andric     DEBUG_WITH_TYPE(DebugType, dbgs() << "INDVARS: Original iv: "
2130*e8d8bef9SDimitry Andric                                       << *OrigPhiRef << '\n');
21315ffd83dbSDimitry Andric     ++NumElim;
21325ffd83dbSDimitry Andric     Value *NewIV = OrigPhiRef;
21335ffd83dbSDimitry Andric     if (OrigPhiRef->getType() != Phi->getType()) {
21345ffd83dbSDimitry Andric       IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
21355ffd83dbSDimitry Andric       Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
21365ffd83dbSDimitry Andric       NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
21375ffd83dbSDimitry Andric     }
21385ffd83dbSDimitry Andric     Phi->replaceAllUsesWith(NewIV);
21395ffd83dbSDimitry Andric     DeadInsts.emplace_back(Phi);
21405ffd83dbSDimitry Andric   }
21415ffd83dbSDimitry Andric   return NumElim;
21425ffd83dbSDimitry Andric }
21435ffd83dbSDimitry Andric 
21445ffd83dbSDimitry Andric Optional<ScalarEvolution::ValueOffsetPair>
21455ffd83dbSDimitry Andric SCEVExpander::getRelatedExistingExpansion(const SCEV *S, const Instruction *At,
21465ffd83dbSDimitry Andric                                           Loop *L) {
21475ffd83dbSDimitry Andric   using namespace llvm::PatternMatch;
21485ffd83dbSDimitry Andric 
21495ffd83dbSDimitry Andric   SmallVector<BasicBlock *, 4> ExitingBlocks;
21505ffd83dbSDimitry Andric   L->getExitingBlocks(ExitingBlocks);
21515ffd83dbSDimitry Andric 
21525ffd83dbSDimitry Andric   // Look for suitable value in simple conditions at the loop exits.
21535ffd83dbSDimitry Andric   for (BasicBlock *BB : ExitingBlocks) {
21545ffd83dbSDimitry Andric     ICmpInst::Predicate Pred;
21555ffd83dbSDimitry Andric     Instruction *LHS, *RHS;
21565ffd83dbSDimitry Andric 
21575ffd83dbSDimitry Andric     if (!match(BB->getTerminator(),
21585ffd83dbSDimitry Andric                m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
21595ffd83dbSDimitry Andric                     m_BasicBlock(), m_BasicBlock())))
21605ffd83dbSDimitry Andric       continue;
21615ffd83dbSDimitry Andric 
21625ffd83dbSDimitry Andric     if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
21635ffd83dbSDimitry Andric       return ScalarEvolution::ValueOffsetPair(LHS, nullptr);
21645ffd83dbSDimitry Andric 
21655ffd83dbSDimitry Andric     if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
21665ffd83dbSDimitry Andric       return ScalarEvolution::ValueOffsetPair(RHS, nullptr);
21675ffd83dbSDimitry Andric   }
21685ffd83dbSDimitry Andric 
21695ffd83dbSDimitry Andric   // Use expand's logic which is used for reusing a previous Value in
21705ffd83dbSDimitry Andric   // ExprValueMap.
21715ffd83dbSDimitry Andric   ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, At);
21725ffd83dbSDimitry Andric   if (VO.first)
21735ffd83dbSDimitry Andric     return VO;
21745ffd83dbSDimitry Andric 
21755ffd83dbSDimitry Andric   // There is potential to make this significantly smarter, but this simple
21765ffd83dbSDimitry Andric   // heuristic already gets some interesting cases.
21775ffd83dbSDimitry Andric 
21785ffd83dbSDimitry Andric   // Can not find suitable value.
21795ffd83dbSDimitry Andric   return None;
21805ffd83dbSDimitry Andric }
21815ffd83dbSDimitry Andric 
2182*e8d8bef9SDimitry Andric template<typename T> static int costAndCollectOperands(
2183*e8d8bef9SDimitry Andric   const SCEVOperand &WorkItem, const TargetTransformInfo &TTI,
2184*e8d8bef9SDimitry Andric   TargetTransformInfo::TargetCostKind CostKind,
2185*e8d8bef9SDimitry Andric   SmallVectorImpl<SCEVOperand> &Worklist) {
2186*e8d8bef9SDimitry Andric 
2187*e8d8bef9SDimitry Andric   const T *S = cast<T>(WorkItem.S);
2188*e8d8bef9SDimitry Andric   int Cost = 0;
2189*e8d8bef9SDimitry Andric   // Object to help map SCEV operands to expanded IR instructions.
2190*e8d8bef9SDimitry Andric   struct OperationIndices {
2191*e8d8bef9SDimitry Andric     OperationIndices(unsigned Opc, size_t min, size_t max) :
2192*e8d8bef9SDimitry Andric       Opcode(Opc), MinIdx(min), MaxIdx(max) { }
2193*e8d8bef9SDimitry Andric     unsigned Opcode;
2194*e8d8bef9SDimitry Andric     size_t MinIdx;
2195*e8d8bef9SDimitry Andric     size_t MaxIdx;
2196*e8d8bef9SDimitry Andric   };
2197*e8d8bef9SDimitry Andric 
2198*e8d8bef9SDimitry Andric   // Collect the operations of all the instructions that will be needed to
2199*e8d8bef9SDimitry Andric   // expand the SCEVExpr. This is so that when we come to cost the operands,
2200*e8d8bef9SDimitry Andric   // we know what the generated user(s) will be.
2201*e8d8bef9SDimitry Andric   SmallVector<OperationIndices, 2> Operations;
2202*e8d8bef9SDimitry Andric 
2203*e8d8bef9SDimitry Andric   auto CastCost = [&](unsigned Opcode) {
2204*e8d8bef9SDimitry Andric     Operations.emplace_back(Opcode, 0, 0);
2205*e8d8bef9SDimitry Andric     return TTI.getCastInstrCost(Opcode, S->getType(),
2206*e8d8bef9SDimitry Andric                                 S->getOperand(0)->getType(),
2207*e8d8bef9SDimitry Andric                                 TTI::CastContextHint::None, CostKind);
2208*e8d8bef9SDimitry Andric   };
2209*e8d8bef9SDimitry Andric 
2210*e8d8bef9SDimitry Andric   auto ArithCost = [&](unsigned Opcode, unsigned NumRequired,
2211*e8d8bef9SDimitry Andric                        unsigned MinIdx = 0, unsigned MaxIdx = 1) {
2212*e8d8bef9SDimitry Andric     Operations.emplace_back(Opcode, MinIdx, MaxIdx);
2213*e8d8bef9SDimitry Andric     return NumRequired *
2214*e8d8bef9SDimitry Andric       TTI.getArithmeticInstrCost(Opcode, S->getType(), CostKind);
2215*e8d8bef9SDimitry Andric   };
2216*e8d8bef9SDimitry Andric 
2217*e8d8bef9SDimitry Andric   auto CmpSelCost = [&](unsigned Opcode, unsigned NumRequired,
2218*e8d8bef9SDimitry Andric                         unsigned MinIdx, unsigned MaxIdx) {
2219*e8d8bef9SDimitry Andric     Operations.emplace_back(Opcode, MinIdx, MaxIdx);
2220*e8d8bef9SDimitry Andric     Type *OpType = S->getOperand(0)->getType();
2221*e8d8bef9SDimitry Andric     return NumRequired * TTI.getCmpSelInstrCost(
2222*e8d8bef9SDimitry Andric                              Opcode, OpType, CmpInst::makeCmpResultType(OpType),
2223*e8d8bef9SDimitry Andric                              CmpInst::BAD_ICMP_PREDICATE, CostKind);
2224*e8d8bef9SDimitry Andric   };
2225*e8d8bef9SDimitry Andric 
2226*e8d8bef9SDimitry Andric   switch (S->getSCEVType()) {
2227*e8d8bef9SDimitry Andric   case scCouldNotCompute:
2228*e8d8bef9SDimitry Andric     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2229*e8d8bef9SDimitry Andric   case scUnknown:
2230*e8d8bef9SDimitry Andric   case scConstant:
2231*e8d8bef9SDimitry Andric     return 0;
2232*e8d8bef9SDimitry Andric   case scPtrToInt:
2233*e8d8bef9SDimitry Andric     Cost = CastCost(Instruction::PtrToInt);
2234*e8d8bef9SDimitry Andric     break;
2235*e8d8bef9SDimitry Andric   case scTruncate:
2236*e8d8bef9SDimitry Andric     Cost = CastCost(Instruction::Trunc);
2237*e8d8bef9SDimitry Andric     break;
2238*e8d8bef9SDimitry Andric   case scZeroExtend:
2239*e8d8bef9SDimitry Andric     Cost = CastCost(Instruction::ZExt);
2240*e8d8bef9SDimitry Andric     break;
2241*e8d8bef9SDimitry Andric   case scSignExtend:
2242*e8d8bef9SDimitry Andric     Cost = CastCost(Instruction::SExt);
2243*e8d8bef9SDimitry Andric     break;
2244*e8d8bef9SDimitry Andric   case scUDivExpr: {
2245*e8d8bef9SDimitry Andric     unsigned Opcode = Instruction::UDiv;
2246*e8d8bef9SDimitry Andric     if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
2247*e8d8bef9SDimitry Andric       if (SC->getAPInt().isPowerOf2())
2248*e8d8bef9SDimitry Andric         Opcode = Instruction::LShr;
2249*e8d8bef9SDimitry Andric     Cost = ArithCost(Opcode, 1);
2250*e8d8bef9SDimitry Andric     break;
2251*e8d8bef9SDimitry Andric   }
2252*e8d8bef9SDimitry Andric   case scAddExpr:
2253*e8d8bef9SDimitry Andric     Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
2254*e8d8bef9SDimitry Andric     break;
2255*e8d8bef9SDimitry Andric   case scMulExpr:
2256*e8d8bef9SDimitry Andric     // TODO: this is a very pessimistic cost modelling for Mul,
2257*e8d8bef9SDimitry Andric     // because of Bin Pow algorithm actually used by the expander,
2258*e8d8bef9SDimitry Andric     // see SCEVExpander::visitMulExpr(), ExpandOpBinPowN().
2259*e8d8bef9SDimitry Andric     Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1);
2260*e8d8bef9SDimitry Andric     break;
2261*e8d8bef9SDimitry Andric   case scSMaxExpr:
2262*e8d8bef9SDimitry Andric   case scUMaxExpr:
2263*e8d8bef9SDimitry Andric   case scSMinExpr:
2264*e8d8bef9SDimitry Andric   case scUMinExpr: {
2265*e8d8bef9SDimitry Andric     Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
2266*e8d8bef9SDimitry Andric     Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
2267*e8d8bef9SDimitry Andric     break;
2268*e8d8bef9SDimitry Andric   }
2269*e8d8bef9SDimitry Andric   case scAddRecExpr: {
2270*e8d8bef9SDimitry Andric     // In this polynominal, we may have some zero operands, and we shouldn't
2271*e8d8bef9SDimitry Andric     // really charge for those. So how many non-zero coeffients are there?
2272*e8d8bef9SDimitry Andric     int NumTerms = llvm::count_if(S->operands(), [](const SCEV *Op) {
2273*e8d8bef9SDimitry Andric                                     return !Op->isZero();
2274*e8d8bef9SDimitry Andric                                   });
2275*e8d8bef9SDimitry Andric 
2276*e8d8bef9SDimitry Andric     assert(NumTerms >= 1 && "Polynominal should have at least one term.");
2277*e8d8bef9SDimitry Andric     assert(!(*std::prev(S->operands().end()))->isZero() &&
2278*e8d8bef9SDimitry Andric            "Last operand should not be zero");
2279*e8d8bef9SDimitry Andric 
2280*e8d8bef9SDimitry Andric     // Ignoring constant term (operand 0), how many of the coeffients are u> 1?
2281*e8d8bef9SDimitry Andric     int NumNonZeroDegreeNonOneTerms =
2282*e8d8bef9SDimitry Andric       llvm::count_if(S->operands(), [](const SCEV *Op) {
2283*e8d8bef9SDimitry Andric                       auto *SConst = dyn_cast<SCEVConstant>(Op);
2284*e8d8bef9SDimitry Andric                       return !SConst || SConst->getAPInt().ugt(1);
2285*e8d8bef9SDimitry Andric                     });
2286*e8d8bef9SDimitry Andric 
2287*e8d8bef9SDimitry Andric     // Much like with normal add expr, the polynominal will require
2288*e8d8bef9SDimitry Andric     // one less addition than the number of it's terms.
2289*e8d8bef9SDimitry Andric     int AddCost = ArithCost(Instruction::Add, NumTerms - 1,
2290*e8d8bef9SDimitry Andric                             /*MinIdx*/1, /*MaxIdx*/1);
2291*e8d8bef9SDimitry Andric     // Here, *each* one of those will require a multiplication.
2292*e8d8bef9SDimitry Andric     int MulCost = ArithCost(Instruction::Mul, NumNonZeroDegreeNonOneTerms);
2293*e8d8bef9SDimitry Andric     Cost = AddCost + MulCost;
2294*e8d8bef9SDimitry Andric 
2295*e8d8bef9SDimitry Andric     // What is the degree of this polynominal?
2296*e8d8bef9SDimitry Andric     int PolyDegree = S->getNumOperands() - 1;
2297*e8d8bef9SDimitry Andric     assert(PolyDegree >= 1 && "Should be at least affine.");
2298*e8d8bef9SDimitry Andric 
2299*e8d8bef9SDimitry Andric     // The final term will be:
2300*e8d8bef9SDimitry Andric     //   Op_{PolyDegree} * x ^ {PolyDegree}
2301*e8d8bef9SDimitry Andric     // Where  x ^ {PolyDegree}  will again require PolyDegree-1 mul operations.
2302*e8d8bef9SDimitry Andric     // Note that  x ^ {PolyDegree} = x * x ^ {PolyDegree-1}  so charging for
2303*e8d8bef9SDimitry Andric     // x ^ {PolyDegree}  will give us  x ^ {2} .. x ^ {PolyDegree-1}  for free.
2304*e8d8bef9SDimitry Andric     // FIXME: this is conservatively correct, but might be overly pessimistic.
2305*e8d8bef9SDimitry Andric     Cost += MulCost * (PolyDegree - 1);
2306*e8d8bef9SDimitry Andric     break;
2307*e8d8bef9SDimitry Andric   }
2308*e8d8bef9SDimitry Andric   }
2309*e8d8bef9SDimitry Andric 
2310*e8d8bef9SDimitry Andric   for (auto &CostOp : Operations) {
2311*e8d8bef9SDimitry Andric     for (auto SCEVOp : enumerate(S->operands())) {
2312*e8d8bef9SDimitry Andric       // Clamp the index to account for multiple IR operations being chained.
2313*e8d8bef9SDimitry Andric       size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
2314*e8d8bef9SDimitry Andric       size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
2315*e8d8bef9SDimitry Andric       Worklist.emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
2316*e8d8bef9SDimitry Andric     }
2317*e8d8bef9SDimitry Andric   }
2318*e8d8bef9SDimitry Andric   return Cost;
2319*e8d8bef9SDimitry Andric }
2320*e8d8bef9SDimitry Andric 
23215ffd83dbSDimitry Andric bool SCEVExpander::isHighCostExpansionHelper(
2322*e8d8bef9SDimitry Andric     const SCEVOperand &WorkItem, Loop *L, const Instruction &At,
2323*e8d8bef9SDimitry Andric     int &BudgetRemaining, const TargetTransformInfo &TTI,
2324*e8d8bef9SDimitry Andric     SmallPtrSetImpl<const SCEV *> &Processed,
2325*e8d8bef9SDimitry Andric     SmallVectorImpl<SCEVOperand> &Worklist) {
23265ffd83dbSDimitry Andric   if (BudgetRemaining < 0)
23275ffd83dbSDimitry Andric     return true; // Already run out of budget, give up.
23285ffd83dbSDimitry Andric 
2329*e8d8bef9SDimitry Andric   const SCEV *S = WorkItem.S;
23305ffd83dbSDimitry Andric   // Was the cost of expansion of this expression already accounted for?
2331*e8d8bef9SDimitry Andric   if (!isa<SCEVConstant>(S) && !Processed.insert(S).second)
23325ffd83dbSDimitry Andric     return false; // We have already accounted for this expression.
23335ffd83dbSDimitry Andric 
23345ffd83dbSDimitry Andric   // If we can find an existing value for this scev available at the point "At"
23355ffd83dbSDimitry Andric   // then consider the expression cheap.
23365ffd83dbSDimitry Andric   if (getRelatedExistingExpansion(S, &At, L))
23375ffd83dbSDimitry Andric     return false; // Consider the expression to be free.
23385ffd83dbSDimitry Andric 
23395ffd83dbSDimitry Andric   TargetTransformInfo::TargetCostKind CostKind =
2340*e8d8bef9SDimitry Andric       L->getHeader()->getParent()->hasMinSize()
2341*e8d8bef9SDimitry Andric           ? TargetTransformInfo::TCK_CodeSize
2342*e8d8bef9SDimitry Andric           : TargetTransformInfo::TCK_RecipThroughput;
23435ffd83dbSDimitry Andric 
23445ffd83dbSDimitry Andric   switch (S->getSCEVType()) {
2345*e8d8bef9SDimitry Andric   case scCouldNotCompute:
2346*e8d8bef9SDimitry Andric     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2347*e8d8bef9SDimitry Andric   case scUnknown:
2348*e8d8bef9SDimitry Andric     // Assume to be zero-cost.
2349*e8d8bef9SDimitry Andric     return false;
2350*e8d8bef9SDimitry Andric   case scConstant: {
2351*e8d8bef9SDimitry Andric     // Only evalulate the costs of constants when optimizing for size.
2352*e8d8bef9SDimitry Andric     if (CostKind != TargetTransformInfo::TCK_CodeSize)
2353*e8d8bef9SDimitry Andric       return 0;
2354*e8d8bef9SDimitry Andric     const APInt &Imm = cast<SCEVConstant>(S)->getAPInt();
2355*e8d8bef9SDimitry Andric     Type *Ty = S->getType();
2356*e8d8bef9SDimitry Andric     BudgetRemaining -= TTI.getIntImmCostInst(
2357*e8d8bef9SDimitry Andric         WorkItem.ParentOpcode, WorkItem.OperandIdx, Imm, Ty, CostKind);
2358*e8d8bef9SDimitry Andric     return BudgetRemaining < 0;
2359*e8d8bef9SDimitry Andric   }
23605ffd83dbSDimitry Andric   case scTruncate:
2361*e8d8bef9SDimitry Andric   case scPtrToInt:
23625ffd83dbSDimitry Andric   case scZeroExtend:
2363*e8d8bef9SDimitry Andric   case scSignExtend: {
2364*e8d8bef9SDimitry Andric     int Cost =
2365*e8d8bef9SDimitry Andric         costAndCollectOperands<SCEVCastExpr>(WorkItem, TTI, CostKind, Worklist);
2366*e8d8bef9SDimitry Andric     BudgetRemaining -= Cost;
23675ffd83dbSDimitry Andric     return false; // Will answer upon next entry into this function.
23685ffd83dbSDimitry Andric   }
2369*e8d8bef9SDimitry Andric   case scUDivExpr: {
23705ffd83dbSDimitry Andric     // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
23715ffd83dbSDimitry Andric     // HowManyLessThans produced to compute a precise expression, rather than a
23725ffd83dbSDimitry Andric     // UDiv from the user's code. If we can't find a UDiv in the code with some
23735ffd83dbSDimitry Andric     // simple searching, we need to account for it's cost.
23745ffd83dbSDimitry Andric 
23755ffd83dbSDimitry Andric     // At the beginning of this function we already tried to find existing
23765ffd83dbSDimitry Andric     // value for plain 'S'. Now try to lookup 'S + 1' since it is common
23775ffd83dbSDimitry Andric     // pattern involving division. This is just a simple search heuristic.
23785ffd83dbSDimitry Andric     if (getRelatedExistingExpansion(
23795ffd83dbSDimitry Andric             SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), &At, L))
23805ffd83dbSDimitry Andric       return false; // Consider it to be free.
23815ffd83dbSDimitry Andric 
2382*e8d8bef9SDimitry Andric     int Cost =
2383*e8d8bef9SDimitry Andric         costAndCollectOperands<SCEVUDivExpr>(WorkItem, TTI, CostKind, Worklist);
23845ffd83dbSDimitry Andric     // Need to count the cost of this UDiv.
2385*e8d8bef9SDimitry Andric     BudgetRemaining -= Cost;
23865ffd83dbSDimitry Andric     return false; // Will answer upon next entry into this function.
23875ffd83dbSDimitry Andric   }
23885ffd83dbSDimitry Andric   case scAddExpr:
23895ffd83dbSDimitry Andric   case scMulExpr:
23905ffd83dbSDimitry Andric   case scUMaxExpr:
2391*e8d8bef9SDimitry Andric   case scSMaxExpr:
23925ffd83dbSDimitry Andric   case scUMinExpr:
2393*e8d8bef9SDimitry Andric   case scSMinExpr: {
2394*e8d8bef9SDimitry Andric     assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
23955ffd83dbSDimitry Andric            "Nary expr should have more than 1 operand.");
23965ffd83dbSDimitry Andric     // The simple nary expr will require one less op (or pair of ops)
23975ffd83dbSDimitry Andric     // than the number of it's terms.
2398*e8d8bef9SDimitry Andric     int Cost =
2399*e8d8bef9SDimitry Andric         costAndCollectOperands<SCEVNAryExpr>(WorkItem, TTI, CostKind, Worklist);
2400*e8d8bef9SDimitry Andric     BudgetRemaining -= Cost;
2401*e8d8bef9SDimitry Andric     return BudgetRemaining < 0;
24025ffd83dbSDimitry Andric   }
2403*e8d8bef9SDimitry Andric   case scAddRecExpr: {
2404*e8d8bef9SDimitry Andric     assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
2405*e8d8bef9SDimitry Andric            "Polynomial should be at least linear");
2406*e8d8bef9SDimitry Andric     BudgetRemaining -= costAndCollectOperands<SCEVAddRecExpr>(
2407*e8d8bef9SDimitry Andric         WorkItem, TTI, CostKind, Worklist);
2408*e8d8bef9SDimitry Andric     return BudgetRemaining < 0;
2409*e8d8bef9SDimitry Andric   }
2410*e8d8bef9SDimitry Andric   }
2411*e8d8bef9SDimitry Andric   llvm_unreachable("Unknown SCEV kind!");
24125ffd83dbSDimitry Andric }
24135ffd83dbSDimitry Andric 
24145ffd83dbSDimitry Andric Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
24155ffd83dbSDimitry Andric                                             Instruction *IP) {
24165ffd83dbSDimitry Andric   assert(IP);
24175ffd83dbSDimitry Andric   switch (Pred->getKind()) {
24185ffd83dbSDimitry Andric   case SCEVPredicate::P_Union:
24195ffd83dbSDimitry Andric     return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
24205ffd83dbSDimitry Andric   case SCEVPredicate::P_Equal:
24215ffd83dbSDimitry Andric     return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
24225ffd83dbSDimitry Andric   case SCEVPredicate::P_Wrap: {
24235ffd83dbSDimitry Andric     auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
24245ffd83dbSDimitry Andric     return expandWrapPredicate(AddRecPred, IP);
24255ffd83dbSDimitry Andric   }
24265ffd83dbSDimitry Andric   }
24275ffd83dbSDimitry Andric   llvm_unreachable("Unknown SCEV predicate type");
24285ffd83dbSDimitry Andric }
24295ffd83dbSDimitry Andric 
24305ffd83dbSDimitry Andric Value *SCEVExpander::expandEqualPredicate(const SCEVEqualPredicate *Pred,
24315ffd83dbSDimitry Andric                                           Instruction *IP) {
2432*e8d8bef9SDimitry Andric   Value *Expr0 =
2433*e8d8bef9SDimitry Andric       expandCodeForImpl(Pred->getLHS(), Pred->getLHS()->getType(), IP, false);
2434*e8d8bef9SDimitry Andric   Value *Expr1 =
2435*e8d8bef9SDimitry Andric       expandCodeForImpl(Pred->getRHS(), Pred->getRHS()->getType(), IP, false);
24365ffd83dbSDimitry Andric 
24375ffd83dbSDimitry Andric   Builder.SetInsertPoint(IP);
24385ffd83dbSDimitry Andric   auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check");
24395ffd83dbSDimitry Andric   return I;
24405ffd83dbSDimitry Andric }
24415ffd83dbSDimitry Andric 
24425ffd83dbSDimitry Andric Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR,
24435ffd83dbSDimitry Andric                                            Instruction *Loc, bool Signed) {
24445ffd83dbSDimitry Andric   assert(AR->isAffine() && "Cannot generate RT check for "
24455ffd83dbSDimitry Andric                            "non-affine expression");
24465ffd83dbSDimitry Andric 
24475ffd83dbSDimitry Andric   SCEVUnionPredicate Pred;
24485ffd83dbSDimitry Andric   const SCEV *ExitCount =
24495ffd83dbSDimitry Andric       SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred);
24505ffd83dbSDimitry Andric 
2451*e8d8bef9SDimitry Andric   assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Invalid loop count");
24525ffd83dbSDimitry Andric 
24535ffd83dbSDimitry Andric   const SCEV *Step = AR->getStepRecurrence(SE);
24545ffd83dbSDimitry Andric   const SCEV *Start = AR->getStart();
24555ffd83dbSDimitry Andric 
24565ffd83dbSDimitry Andric   Type *ARTy = AR->getType();
24575ffd83dbSDimitry Andric   unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
24585ffd83dbSDimitry Andric   unsigned DstBits = SE.getTypeSizeInBits(ARTy);
24595ffd83dbSDimitry Andric 
24605ffd83dbSDimitry Andric   // The expression {Start,+,Step} has nusw/nssw if
24615ffd83dbSDimitry Andric   //   Step < 0, Start - |Step| * Backedge <= Start
24625ffd83dbSDimitry Andric   //   Step >= 0, Start + |Step| * Backedge > Start
24635ffd83dbSDimitry Andric   // and |Step| * Backedge doesn't unsigned overflow.
24645ffd83dbSDimitry Andric 
24655ffd83dbSDimitry Andric   IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits);
24665ffd83dbSDimitry Andric   Builder.SetInsertPoint(Loc);
2467*e8d8bef9SDimitry Andric   Value *TripCountVal = expandCodeForImpl(ExitCount, CountTy, Loc, false);
24685ffd83dbSDimitry Andric 
24695ffd83dbSDimitry Andric   IntegerType *Ty =
24705ffd83dbSDimitry Andric       IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy));
24715ffd83dbSDimitry Andric   Type *ARExpandTy = DL.isNonIntegralPointerType(ARTy) ? ARTy : Ty;
24725ffd83dbSDimitry Andric 
2473*e8d8bef9SDimitry Andric   Value *StepValue = expandCodeForImpl(Step, Ty, Loc, false);
2474*e8d8bef9SDimitry Andric   Value *NegStepValue =
2475*e8d8bef9SDimitry Andric       expandCodeForImpl(SE.getNegativeSCEV(Step), Ty, Loc, false);
2476*e8d8bef9SDimitry Andric   Value *StartValue = expandCodeForImpl(Start, ARExpandTy, Loc, false);
24775ffd83dbSDimitry Andric 
24785ffd83dbSDimitry Andric   ConstantInt *Zero =
24795ffd83dbSDimitry Andric       ConstantInt::get(Loc->getContext(), APInt::getNullValue(DstBits));
24805ffd83dbSDimitry Andric 
24815ffd83dbSDimitry Andric   Builder.SetInsertPoint(Loc);
24825ffd83dbSDimitry Andric   // Compute |Step|
24835ffd83dbSDimitry Andric   Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
24845ffd83dbSDimitry Andric   Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
24855ffd83dbSDimitry Andric 
24865ffd83dbSDimitry Andric   // Get the backedge taken count and truncate or extended to the AR type.
24875ffd83dbSDimitry Andric   Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
24885ffd83dbSDimitry Andric   auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
24895ffd83dbSDimitry Andric                                          Intrinsic::umul_with_overflow, Ty);
24905ffd83dbSDimitry Andric 
24915ffd83dbSDimitry Andric   // Compute |Step| * Backedge
24925ffd83dbSDimitry Andric   CallInst *Mul = Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
24935ffd83dbSDimitry Andric   Value *MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
24945ffd83dbSDimitry Andric   Value *OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
24955ffd83dbSDimitry Andric 
24965ffd83dbSDimitry Andric   // Compute:
24975ffd83dbSDimitry Andric   //   Start + |Step| * Backedge < Start
24985ffd83dbSDimitry Andric   //   Start - |Step| * Backedge > Start
24995ffd83dbSDimitry Andric   Value *Add = nullptr, *Sub = nullptr;
25005ffd83dbSDimitry Andric   if (PointerType *ARPtrTy = dyn_cast<PointerType>(ARExpandTy)) {
25015ffd83dbSDimitry Andric     const SCEV *MulS = SE.getSCEV(MulV);
25025ffd83dbSDimitry Andric     const SCEV *NegMulS = SE.getNegativeSCEV(MulS);
25035ffd83dbSDimitry Andric     Add = Builder.CreateBitCast(expandAddToGEP(MulS, ARPtrTy, Ty, StartValue),
25045ffd83dbSDimitry Andric                                 ARPtrTy);
25055ffd83dbSDimitry Andric     Sub = Builder.CreateBitCast(
25065ffd83dbSDimitry Andric         expandAddToGEP(NegMulS, ARPtrTy, Ty, StartValue), ARPtrTy);
25075ffd83dbSDimitry Andric   } else {
25085ffd83dbSDimitry Andric     Add = Builder.CreateAdd(StartValue, MulV);
25095ffd83dbSDimitry Andric     Sub = Builder.CreateSub(StartValue, MulV);
25105ffd83dbSDimitry Andric   }
25115ffd83dbSDimitry Andric 
25125ffd83dbSDimitry Andric   Value *EndCompareGT = Builder.CreateICmp(
25135ffd83dbSDimitry Andric       Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
25145ffd83dbSDimitry Andric 
25155ffd83dbSDimitry Andric   Value *EndCompareLT = Builder.CreateICmp(
25165ffd83dbSDimitry Andric       Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
25175ffd83dbSDimitry Andric 
25185ffd83dbSDimitry Andric   // Select the answer based on the sign of Step.
25195ffd83dbSDimitry Andric   Value *EndCheck =
25205ffd83dbSDimitry Andric       Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
25215ffd83dbSDimitry Andric 
25225ffd83dbSDimitry Andric   // If the backedge taken count type is larger than the AR type,
25235ffd83dbSDimitry Andric   // check that we don't drop any bits by truncating it. If we are
25245ffd83dbSDimitry Andric   // dropping bits, then we have overflow (unless the step is zero).
25255ffd83dbSDimitry Andric   if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) {
25265ffd83dbSDimitry Andric     auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
25275ffd83dbSDimitry Andric     auto *BackedgeCheck =
25285ffd83dbSDimitry Andric         Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
25295ffd83dbSDimitry Andric                            ConstantInt::get(Loc->getContext(), MaxVal));
25305ffd83dbSDimitry Andric     BackedgeCheck = Builder.CreateAnd(
25315ffd83dbSDimitry Andric         BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
25325ffd83dbSDimitry Andric 
25335ffd83dbSDimitry Andric     EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
25345ffd83dbSDimitry Andric   }
25355ffd83dbSDimitry Andric 
2536*e8d8bef9SDimitry Andric   return Builder.CreateOr(EndCheck, OfMul);
25375ffd83dbSDimitry Andric }
25385ffd83dbSDimitry Andric 
25395ffd83dbSDimitry Andric Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred,
25405ffd83dbSDimitry Andric                                          Instruction *IP) {
25415ffd83dbSDimitry Andric   const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
25425ffd83dbSDimitry Andric   Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
25435ffd83dbSDimitry Andric 
25445ffd83dbSDimitry Andric   // Add a check for NUSW
25455ffd83dbSDimitry Andric   if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
25465ffd83dbSDimitry Andric     NUSWCheck = generateOverflowCheck(A, IP, false);
25475ffd83dbSDimitry Andric 
25485ffd83dbSDimitry Andric   // Add a check for NSSW
25495ffd83dbSDimitry Andric   if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
25505ffd83dbSDimitry Andric     NSSWCheck = generateOverflowCheck(A, IP, true);
25515ffd83dbSDimitry Andric 
25525ffd83dbSDimitry Andric   if (NUSWCheck && NSSWCheck)
25535ffd83dbSDimitry Andric     return Builder.CreateOr(NUSWCheck, NSSWCheck);
25545ffd83dbSDimitry Andric 
25555ffd83dbSDimitry Andric   if (NUSWCheck)
25565ffd83dbSDimitry Andric     return NUSWCheck;
25575ffd83dbSDimitry Andric 
25585ffd83dbSDimitry Andric   if (NSSWCheck)
25595ffd83dbSDimitry Andric     return NSSWCheck;
25605ffd83dbSDimitry Andric 
25615ffd83dbSDimitry Andric   return ConstantInt::getFalse(IP->getContext());
25625ffd83dbSDimitry Andric }
25635ffd83dbSDimitry Andric 
25645ffd83dbSDimitry Andric Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
25655ffd83dbSDimitry Andric                                           Instruction *IP) {
25665ffd83dbSDimitry Andric   auto *BoolType = IntegerType::get(IP->getContext(), 1);
25675ffd83dbSDimitry Andric   Value *Check = ConstantInt::getNullValue(BoolType);
25685ffd83dbSDimitry Andric 
25695ffd83dbSDimitry Andric   // Loop over all checks in this set.
25705ffd83dbSDimitry Andric   for (auto Pred : Union->getPredicates()) {
25715ffd83dbSDimitry Andric     auto *NextCheck = expandCodeForPredicate(Pred, IP);
25725ffd83dbSDimitry Andric     Builder.SetInsertPoint(IP);
25735ffd83dbSDimitry Andric     Check = Builder.CreateOr(Check, NextCheck);
25745ffd83dbSDimitry Andric   }
25755ffd83dbSDimitry Andric 
25765ffd83dbSDimitry Andric   return Check;
25775ffd83dbSDimitry Andric }
25785ffd83dbSDimitry Andric 
2579*e8d8bef9SDimitry Andric Value *SCEVExpander::fixupLCSSAFormFor(Instruction *User, unsigned OpIdx) {
2580*e8d8bef9SDimitry Andric   assert(PreserveLCSSA);
2581*e8d8bef9SDimitry Andric   SmallVector<Instruction *, 1> ToUpdate;
2582*e8d8bef9SDimitry Andric 
2583*e8d8bef9SDimitry Andric   auto *OpV = User->getOperand(OpIdx);
2584*e8d8bef9SDimitry Andric   auto *OpI = dyn_cast<Instruction>(OpV);
2585*e8d8bef9SDimitry Andric   if (!OpI)
2586*e8d8bef9SDimitry Andric     return OpV;
2587*e8d8bef9SDimitry Andric 
2588*e8d8bef9SDimitry Andric   Loop *DefLoop = SE.LI.getLoopFor(OpI->getParent());
2589*e8d8bef9SDimitry Andric   Loop *UseLoop = SE.LI.getLoopFor(User->getParent());
2590*e8d8bef9SDimitry Andric   if (!DefLoop || UseLoop == DefLoop || DefLoop->contains(UseLoop))
2591*e8d8bef9SDimitry Andric     return OpV;
2592*e8d8bef9SDimitry Andric 
2593*e8d8bef9SDimitry Andric   ToUpdate.push_back(OpI);
2594*e8d8bef9SDimitry Andric   SmallVector<PHINode *, 16> PHIsToRemove;
2595*e8d8bef9SDimitry Andric   formLCSSAForInstructions(ToUpdate, SE.DT, SE.LI, &SE, Builder, &PHIsToRemove);
2596*e8d8bef9SDimitry Andric   for (PHINode *PN : PHIsToRemove) {
2597*e8d8bef9SDimitry Andric     if (!PN->use_empty())
2598*e8d8bef9SDimitry Andric       continue;
2599*e8d8bef9SDimitry Andric     InsertedValues.erase(PN);
2600*e8d8bef9SDimitry Andric     InsertedPostIncValues.erase(PN);
2601*e8d8bef9SDimitry Andric     PN->eraseFromParent();
2602*e8d8bef9SDimitry Andric   }
2603*e8d8bef9SDimitry Andric 
2604*e8d8bef9SDimitry Andric   return User->getOperand(OpIdx);
2605*e8d8bef9SDimitry Andric }
2606*e8d8bef9SDimitry Andric 
26075ffd83dbSDimitry Andric namespace {
26085ffd83dbSDimitry Andric // Search for a SCEV subexpression that is not safe to expand.  Any expression
26095ffd83dbSDimitry Andric // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
26105ffd83dbSDimitry Andric // UDiv expressions. We don't know if the UDiv is derived from an IR divide
26115ffd83dbSDimitry Andric // instruction, but the important thing is that we prove the denominator is
26125ffd83dbSDimitry Andric // nonzero before expansion.
26135ffd83dbSDimitry Andric //
26145ffd83dbSDimitry Andric // IVUsers already checks that IV-derived expressions are safe. So this check is
26155ffd83dbSDimitry Andric // only needed when the expression includes some subexpression that is not IV
26165ffd83dbSDimitry Andric // derived.
26175ffd83dbSDimitry Andric //
26185ffd83dbSDimitry Andric // Currently, we only allow division by a nonzero constant here. If this is
26195ffd83dbSDimitry Andric // inadequate, we could easily allow division by SCEVUnknown by using
26205ffd83dbSDimitry Andric // ValueTracking to check isKnownNonZero().
26215ffd83dbSDimitry Andric //
26225ffd83dbSDimitry Andric // We cannot generally expand recurrences unless the step dominates the loop
26235ffd83dbSDimitry Andric // header. The expander handles the special case of affine recurrences by
26245ffd83dbSDimitry Andric // scaling the recurrence outside the loop, but this technique isn't generally
26255ffd83dbSDimitry Andric // applicable. Expanding a nested recurrence outside a loop requires computing
26265ffd83dbSDimitry Andric // binomial coefficients. This could be done, but the recurrence has to be in a
26275ffd83dbSDimitry Andric // perfectly reduced form, which can't be guaranteed.
26285ffd83dbSDimitry Andric struct SCEVFindUnsafe {
26295ffd83dbSDimitry Andric   ScalarEvolution &SE;
26305ffd83dbSDimitry Andric   bool IsUnsafe;
26315ffd83dbSDimitry Andric 
26325ffd83dbSDimitry Andric   SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
26335ffd83dbSDimitry Andric 
26345ffd83dbSDimitry Andric   bool follow(const SCEV *S) {
26355ffd83dbSDimitry Andric     if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
26365ffd83dbSDimitry Andric       const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
26375ffd83dbSDimitry Andric       if (!SC || SC->getValue()->isZero()) {
26385ffd83dbSDimitry Andric         IsUnsafe = true;
26395ffd83dbSDimitry Andric         return false;
26405ffd83dbSDimitry Andric       }
26415ffd83dbSDimitry Andric     }
26425ffd83dbSDimitry Andric     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
26435ffd83dbSDimitry Andric       const SCEV *Step = AR->getStepRecurrence(SE);
26445ffd83dbSDimitry Andric       if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
26455ffd83dbSDimitry Andric         IsUnsafe = true;
26465ffd83dbSDimitry Andric         return false;
26475ffd83dbSDimitry Andric       }
26485ffd83dbSDimitry Andric     }
26495ffd83dbSDimitry Andric     return true;
26505ffd83dbSDimitry Andric   }
26515ffd83dbSDimitry Andric   bool isDone() const { return IsUnsafe; }
26525ffd83dbSDimitry Andric };
26535ffd83dbSDimitry Andric }
26545ffd83dbSDimitry Andric 
26555ffd83dbSDimitry Andric namespace llvm {
26565ffd83dbSDimitry Andric bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
26575ffd83dbSDimitry Andric   SCEVFindUnsafe Search(SE);
26585ffd83dbSDimitry Andric   visitAll(S, Search);
26595ffd83dbSDimitry Andric   return !Search.IsUnsafe;
26605ffd83dbSDimitry Andric }
26615ffd83dbSDimitry Andric 
26625ffd83dbSDimitry Andric bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint,
26635ffd83dbSDimitry Andric                       ScalarEvolution &SE) {
26645ffd83dbSDimitry Andric   if (!isSafeToExpand(S, SE))
26655ffd83dbSDimitry Andric     return false;
26665ffd83dbSDimitry Andric   // We have to prove that the expanded site of S dominates InsertionPoint.
26675ffd83dbSDimitry Andric   // This is easy when not in the same block, but hard when S is an instruction
26685ffd83dbSDimitry Andric   // to be expanded somewhere inside the same block as our insertion point.
26695ffd83dbSDimitry Andric   // What we really need here is something analogous to an OrderedBasicBlock,
26705ffd83dbSDimitry Andric   // but for the moment, we paper over the problem by handling two common and
26715ffd83dbSDimitry Andric   // cheap to check cases.
26725ffd83dbSDimitry Andric   if (SE.properlyDominates(S, InsertionPoint->getParent()))
26735ffd83dbSDimitry Andric     return true;
26745ffd83dbSDimitry Andric   if (SE.dominates(S, InsertionPoint->getParent())) {
26755ffd83dbSDimitry Andric     if (InsertionPoint->getParent()->getTerminator() == InsertionPoint)
26765ffd83dbSDimitry Andric       return true;
26775ffd83dbSDimitry Andric     if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
26785ffd83dbSDimitry Andric       for (const Value *V : InsertionPoint->operand_values())
26795ffd83dbSDimitry Andric         if (V == U->getValue())
26805ffd83dbSDimitry Andric           return true;
26815ffd83dbSDimitry Andric   }
26825ffd83dbSDimitry Andric   return false;
26835ffd83dbSDimitry Andric }
2684*e8d8bef9SDimitry Andric 
2685*e8d8bef9SDimitry Andric SCEVExpanderCleaner::~SCEVExpanderCleaner() {
2686*e8d8bef9SDimitry Andric   // Result is used, nothing to remove.
2687*e8d8bef9SDimitry Andric   if (ResultUsed)
2688*e8d8bef9SDimitry Andric     return;
2689*e8d8bef9SDimitry Andric 
2690*e8d8bef9SDimitry Andric   auto InsertedInstructions = Expander.getAllInsertedInstructions();
2691*e8d8bef9SDimitry Andric #ifndef NDEBUG
2692*e8d8bef9SDimitry Andric   SmallPtrSet<Instruction *, 8> InsertedSet(InsertedInstructions.begin(),
2693*e8d8bef9SDimitry Andric                                             InsertedInstructions.end());
2694*e8d8bef9SDimitry Andric   (void)InsertedSet;
2695*e8d8bef9SDimitry Andric #endif
2696*e8d8bef9SDimitry Andric   // Remove sets with value handles.
2697*e8d8bef9SDimitry Andric   Expander.clear();
2698*e8d8bef9SDimitry Andric 
2699*e8d8bef9SDimitry Andric   // Sort so that earlier instructions do not dominate later instructions.
2700*e8d8bef9SDimitry Andric   stable_sort(InsertedInstructions, [this](Instruction *A, Instruction *B) {
2701*e8d8bef9SDimitry Andric     return DT.dominates(B, A);
2702*e8d8bef9SDimitry Andric   });
2703*e8d8bef9SDimitry Andric   // Remove all inserted instructions.
2704*e8d8bef9SDimitry Andric   for (Instruction *I : InsertedInstructions) {
2705*e8d8bef9SDimitry Andric 
2706*e8d8bef9SDimitry Andric #ifndef NDEBUG
2707*e8d8bef9SDimitry Andric     assert(all_of(I->users(),
2708*e8d8bef9SDimitry Andric                   [&InsertedSet](Value *U) {
2709*e8d8bef9SDimitry Andric                     return InsertedSet.contains(cast<Instruction>(U));
2710*e8d8bef9SDimitry Andric                   }) &&
2711*e8d8bef9SDimitry Andric            "removed instruction should only be used by instructions inserted "
2712*e8d8bef9SDimitry Andric            "during expansion");
2713*e8d8bef9SDimitry Andric #endif
2714*e8d8bef9SDimitry Andric     assert(!I->getType()->isVoidTy() &&
2715*e8d8bef9SDimitry Andric            "inserted instruction should have non-void types");
2716*e8d8bef9SDimitry Andric     I->replaceAllUsesWith(UndefValue::get(I->getType()));
2717*e8d8bef9SDimitry Andric     I->eraseFromParent();
2718*e8d8bef9SDimitry Andric   }
2719*e8d8bef9SDimitry Andric }
27205ffd83dbSDimitry Andric }
2721