#include "llvm/Transforms/Scalar/LoopFlatten.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/LoopNestAnalysis.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/LoopPassManager.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
#include "llvm/Transforms/Utils/SimplifyIndVar.h"
using namespace llvm;
using namespace llvm::PatternMatch;
#define DEBUG_TYPE "loop-flatten"
STATISTIC(NumFlattened, "Number of loops flattened");
static cl::opt<unsigned> RepeatedInstructionThreshold(
"loop-flatten-cost-threshold", cl::Hidden, cl::init(2),
cl::desc("Limit on the cost of instructions that can be repeated due to "
"loop flattening"));
static cl::opt<bool>
AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden,
cl::init(false),
cl::desc("Assume that the product of the two iteration "
"trip counts will never overflow"));
static cl::opt<bool>
WidenIV("loop-flatten-widen-iv", cl::Hidden, cl::init(true),
cl::desc("Widen the loop induction variables, if possible, so "
"overflow checks won't reject flattening"));
struct FlattenInfo {
Loop *OuterLoop = nullptr; Loop *InnerLoop = nullptr;
PHINode *InnerInductionPHI = nullptr; PHINode *OuterInductionPHI = nullptr;
Value *InnerTripCount = nullptr; Value *OuterTripCount = nullptr;
SmallPtrSet<Value *, 4> LinearIVUses;
BinaryOperator *InnerIncrement = nullptr; BinaryOperator *OuterIncrement = nullptr; BranchInst *InnerBranch = nullptr;
BranchInst *OuterBranch = nullptr;
SmallPtrSet<PHINode *, 4> InnerPHIsToTransform;
bool Widened = false;
PHINode *NarrowInnerInductionPHI = nullptr; PHINode *NarrowOuterInductionPHI = nullptr;
FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL){};
bool isNarrowInductionPhi(PHINode *Phi) {
if (!Widened)
return false;
return NarrowInnerInductionPHI == Phi || NarrowOuterInductionPHI == Phi;
}
bool isInnerLoopIncrement(User *U) {
return InnerIncrement == U;
}
bool isOuterLoopIncrement(User *U) {
return OuterIncrement == U;
}
bool isInnerLoopTest(User *U) {
return InnerBranch->getCondition() == U;
}
bool checkOuterInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
for (User *U : OuterInductionPHI->users()) {
if (isOuterLoopIncrement(U))
continue;
auto IsValidOuterPHIUses = [&] (User *U) -> bool {
LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump());
if (!ValidOuterPHIUses.count(U)) {
LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
return false;
}
LLVM_DEBUG(dbgs() << "Use is optimisable\n");
return true;
};
if (auto *V = dyn_cast<TruncInst>(U)) {
for (auto *K : V->users()) {
if (!IsValidOuterPHIUses(K))
return false;
}
continue;
}
if (!IsValidOuterPHIUses(U))
return false;
}
return true;
}
bool matchLinearIVUser(User *U, Value *InnerTripCount,
SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
LLVM_DEBUG(dbgs() << "Found use of inner induction variable: "; U->dump());
Value *MatchedMul = nullptr;
Value *MatchedItCount = nullptr;
bool IsAdd = match(U, m_c_Add(m_Specific(InnerInductionPHI),
m_Value(MatchedMul))) &&
match(MatchedMul, m_c_Mul(m_Specific(OuterInductionPHI),
m_Value(MatchedItCount)));
bool IsAddTrunc =
match(U, m_c_Add(m_Trunc(m_Specific(InnerInductionPHI)),
m_Value(MatchedMul))) &&
match(MatchedMul, m_c_Mul(m_Trunc(m_Specific(OuterInductionPHI)),
m_Value(MatchedItCount)));
if (!MatchedItCount)
return false;
if (Widened && IsAdd &&
(isa<SExtInst>(MatchedItCount) || isa<ZExtInst>(MatchedItCount))) {
assert(MatchedItCount->getType() == InnerInductionPHI->getType() &&
"Unexpected type mismatch in types after widening");
MatchedItCount = isa<SExtInst>(MatchedItCount)
? dyn_cast<SExtInst>(MatchedItCount)->getOperand(0)
: dyn_cast<ZExtInst>(MatchedItCount)->getOperand(0);
}
if ((IsAdd || IsAddTrunc) && MatchedItCount == InnerTripCount) {
LLVM_DEBUG(dbgs() << "Use is optimisable\n");
ValidOuterPHIUses.insert(MatchedMul);
LinearIVUses.insert(U);
return true;
}
LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
return false;
}
bool checkInnerInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
Value *SExtInnerTripCount = InnerTripCount;
if (Widened &&
(isa<SExtInst>(InnerTripCount) || isa<ZExtInst>(InnerTripCount)))
SExtInnerTripCount = cast<Instruction>(InnerTripCount)->getOperand(0);
for (User *U : InnerInductionPHI->users()) {
if (isInnerLoopIncrement(U))
continue;
if (isa<TruncInst>(U)) {
if (!U->hasOneUse())
return false;
U = *U->user_begin();
}
if (isInnerLoopTest(U))
continue;
if (!matchLinearIVUser(U, SExtInnerTripCount, ValidOuterPHIUses))
return false;
}
return true;
}
};
static bool
setLoopComponents(Value *&TC, Value *&TripCount, BinaryOperator *&Increment,
SmallPtrSetImpl<Instruction *> &IterationInstructions) {
TripCount = TC;
IterationInstructions.insert(Increment);
LLVM_DEBUG(dbgs() << "Found Increment: "; Increment->dump());
LLVM_DEBUG(dbgs() << "Found trip count: "; TripCount->dump());
LLVM_DEBUG(dbgs() << "Successfully found all loop components\n");
return true;
}
static bool verifyTripCount(Value *RHS, Loop *L,
SmallPtrSetImpl<Instruction *> &IterationInstructions,
PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
LLVM_DEBUG(dbgs() << "Backedge-taken count is not predictable\n");
return false;
}
const SCEV *SCEVTripCount =
SE->getTripCountFromExitCount(BackedgeTakenCount, false);
const SCEV *SCEVRHS = SE->getSCEV(RHS);
if (SCEVRHS == SCEVTripCount)
return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(RHS);
if (ConstantRHS) {
const SCEV *BackedgeTCExt = nullptr;
if (IsWidened) {
const SCEV *SCEVTripCountExt;
BackedgeTCExt = SE->getZeroExtendExpr(BackedgeTakenCount, RHS->getType());
SCEVTripCountExt = SE->getTripCountFromExitCount(BackedgeTCExt, false);
if (SCEVRHS != BackedgeTCExt && SCEVRHS != SCEVTripCountExt) {
LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
return false;
}
}
if (SCEVRHS == BackedgeTCExt || SCEVRHS == BackedgeTakenCount) {
ConstantInt *One = ConstantInt::get(ConstantRHS->getType(), 1);
Value *NewRHS = ConstantInt::get(
ConstantRHS->getContext(), ConstantRHS->getValue() + One->getValue());
return setLoopComponents(NewRHS, TripCount, Increment,
IterationInstructions);
}
return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
}
if (!IsWidened) {
LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
return false;
}
auto *TripCountInst = dyn_cast<Instruction>(RHS);
if (!TripCountInst) {
LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
return false;
}
if ((!isa<ZExtInst>(TripCountInst) && !isa<SExtInst>(TripCountInst)) ||
SE->getSCEV(TripCountInst->getOperand(0)) != SCEVTripCount) {
LLVM_DEBUG(dbgs() << "Could not find valid extended trip count\n");
return false;
}
return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
}
static bool findLoopComponents(
Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions,
PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n");
if (!L->isLoopSimplifyForm()) {
LLVM_DEBUG(dbgs() << "Loop is not in normal form\n");
return false;
}
if (!L->isCanonical(*SE)) {
LLVM_DEBUG(dbgs() << "Loop is not canonical\n");
return false;
}
BasicBlock *Latch = L->getLoopLatch();
if (L->getExitingBlock() != Latch) {
LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n");
return false;
}
InductionPHI = L->getInductionVariable(*SE);
if (!InductionPHI) {
LLVM_DEBUG(dbgs() << "Could not find induction PHI\n");
return false;
}
LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump());
bool ContinueOnTrue = L->contains(Latch->getTerminator()->getSuccessor(0));
auto IsValidPredicate = [&](ICmpInst::Predicate Pred) {
if (ContinueOnTrue)
return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT;
else
return Pred == CmpInst::ICMP_EQ;
};
ICmpInst *Compare = L->getLatchCmpInst();
if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) ||
Compare->hasNUsesOrMore(2)) {
LLVM_DEBUG(dbgs() << "Could not find valid comparison\n");
return false;
}
BackBranch = cast<BranchInst>(Latch->getTerminator());
IterationInstructions.insert(BackBranch);
LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump());
IterationInstructions.insert(Compare);
LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump());
Increment =
cast<BinaryOperator>(InductionPHI->getIncomingValueForBlock(Latch));
if (Increment->hasNUsesOrMore(3)) {
LLVM_DEBUG(dbgs() << "Could not find valid increment\n");
return false;
}
Value *RHS = Compare->getOperand(1);
return verifyTripCount(RHS, L, IterationInstructions, InductionPHI, TripCount,
Increment, BackBranch, SE, IsWidened);
}
static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI) {
SmallPtrSet<PHINode *, 4> SafeOuterPHIs;
SafeOuterPHIs.insert(FI.OuterInductionPHI);
for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) {
if (&InnerPHI == FI.InnerInductionPHI)
continue;
if (FI.isNarrowInductionPhi(&InnerPHI))
continue;
assert(InnerPHI.getNumIncomingValues() == 2);
Value *PreHeaderValue =
InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader());
Value *LatchValue =
InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch());
PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue);
if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) {
LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n");
return false;
}
PHINode *LCSSAPHI = dyn_cast<PHINode>(
OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch()));
if (!LCSSAPHI) {
LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n");
return false;
}
if (LCSSAPHI->hasConstantValue() != LatchValue) {
LLVM_DEBUG(
dbgs() << "LCSSA PHI incoming value does not match latch value\n");
return false;
}
LLVM_DEBUG(dbgs() << "PHI pair is safe:\n");
LLVM_DEBUG(dbgs() << " Inner: "; InnerPHI.dump());
LLVM_DEBUG(dbgs() << " Outer: "; OuterPHI->dump());
SafeOuterPHIs.insert(OuterPHI);
FI.InnerPHIsToTransform.insert(&InnerPHI);
}
for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) {
if (FI.isNarrowInductionPhi(&OuterPHI))
continue;
if (!SafeOuterPHIs.count(&OuterPHI)) {
LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump());
return false;
}
}
LLVM_DEBUG(dbgs() << "checkPHIs: OK\n");
return true;
}
static bool
checkOuterLoopInsts(FlattenInfo &FI,
SmallPtrSetImpl<Instruction *> &IterationInstructions,
const TargetTransformInfo *TTI) {
InstructionCost RepeatedInstrCost = 0;
for (auto *B : FI.OuterLoop->getBlocks()) {
if (FI.InnerLoop->contains(B))
continue;
for (auto &I : *B) {
if (!isa<PHINode>(&I) && !I.isTerminator() &&
!isSafeToSpeculativelyExecute(&I)) {
LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have "
"side effects: ";
I.dump());
return false;
}
if (IterationInstructions.count(&I))
continue;
BranchInst *Br = dyn_cast<BranchInst>(&I);
if (Br && Br->isUnconditional() &&
Br->getSuccessor(0) == FI.InnerLoop->getHeader())
continue;
if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI),
m_Specific(FI.InnerTripCount))))
continue;
InstructionCost Cost =
TTI->getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump());
RepeatedInstrCost += Cost;
}
}
LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: "
<< RepeatedInstrCost << "\n");
if (RepeatedInstrCost > RepeatedInstructionThreshold) {
LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n");
return false;
}
LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n");
return true;
}
static bool checkIVUsers(FlattenInfo &FI) {
SmallPtrSet<Value *, 4> ValidOuterPHIUses;
if (!FI.checkInnerInductionPhiUsers(ValidOuterPHIUses))
return false;
if (!FI.checkOuterInductionPhiUsers(ValidOuterPHIUses))
return false;
LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n";
dbgs() << "Found " << FI.LinearIVUses.size()
<< " value(s) that can be replaced:\n";
for (Value *V : FI.LinearIVUses) {
dbgs() << " ";
V->dump();
});
return true;
}
static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT,
AssumptionCache *AC) {
Function *F = FI.OuterLoop->getHeader()->getParent();
const DataLayout &DL = F->getParent()->getDataLayout();
if (AssumeNoOverflow)
return OverflowResult::NeverOverflows;
OverflowResult OR = computeOverflowForUnsignedMul(
FI.InnerTripCount, FI.OuterTripCount, DL, AC,
FI.OuterLoop->getLoopPreheader()->getTerminator(), DT);
if (OR != OverflowResult::MayOverflow)
return OR;
for (Value *V : FI.LinearIVUses) {
for (Value *U : V->users()) {
if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
for (Value *GEPUser : U->users()) {
auto *GEPUserInst = cast<Instruction>(GEPUser);
if (!isa<LoadInst>(GEPUserInst) &&
!(isa<StoreInst>(GEPUserInst) &&
GEP == GEPUserInst->getOperand(1)))
continue;
if (!isGuaranteedToExecuteForEveryIteration(GEPUserInst,
FI.InnerLoop))
continue;
if (GEP->isInBounds() &&
V->getType()->getIntegerBitWidth() >=
DL.getPointerTypeSizeInBits(GEP->getType())) {
LLVM_DEBUG(
dbgs() << "use of linear IV would be UB if overflow occurred: ";
GEP->dump());
return OverflowResult::NeverOverflows;
}
}
}
}
}
return OverflowResult::MayOverflow;
}
static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
ScalarEvolution *SE, AssumptionCache *AC,
const TargetTransformInfo *TTI) {
SmallPtrSet<Instruction *, 8> IterationInstructions;
if (!findLoopComponents(FI.InnerLoop, IterationInstructions,
FI.InnerInductionPHI, FI.InnerTripCount,
FI.InnerIncrement, FI.InnerBranch, SE, FI.Widened))
return false;
if (!findLoopComponents(FI.OuterLoop, IterationInstructions,
FI.OuterInductionPHI, FI.OuterTripCount,
FI.OuterIncrement, FI.OuterBranch, SE, FI.Widened))
return false;
if (!FI.OuterLoop->isLoopInvariant(FI.InnerTripCount)) {
LLVM_DEBUG(dbgs() << "inner loop trip count not invariant\n");
return false;
}
if (!FI.OuterLoop->isLoopInvariant(FI.OuterTripCount)) {
LLVM_DEBUG(dbgs() << "outer loop trip count not invariant\n");
return false;
}
if (!checkPHIs(FI, TTI))
return false;
if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType())
return false;
if (!checkOuterLoopInsts(FI, IterationInstructions, TTI))
return false;
if (!checkIVUsers(FI))
return false;
LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n");
return true;
}
static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
ScalarEvolution *SE, AssumptionCache *AC,
const TargetTransformInfo *TTI, LPMUpdater *U,
MemorySSAUpdater *MSSAU) {
Function *F = FI.OuterLoop->getHeader()->getParent();
LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n");
{
using namespace ore;
OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(),
FI.InnerLoop->getHeader());
OptimizationRemarkEmitter ORE(F);
Remark << "Flattened into outer loop";
ORE.emit(Remark);
}
Value *NewTripCount = BinaryOperator::CreateMul(
FI.InnerTripCount, FI.OuterTripCount, "flatten.tripcount",
FI.OuterLoop->getLoopPreheader()->getTerminator());
LLVM_DEBUG(dbgs() << "Created new trip count in preheader: ";
NewTripCount->dump());
FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
for (PHINode *PHI : FI.InnerPHIsToTransform)
PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
cast<User>(FI.OuterBranch->getCondition())->setOperand(1, NewTripCount);
BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock();
BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock();
InnerExitingBlock->getTerminator()->eraseFromParent();
BranchInst::Create(InnerExitBlock, InnerExitingBlock);
DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
if (MSSAU)
MSSAU->removeEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator());
for (Value *V : FI.LinearIVUses) {
Value *OuterValue = FI.OuterInductionPHI;
if (FI.Widened)
OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(),
"flatten.trunciv");
LLVM_DEBUG(dbgs() << "Replacing: "; V->dump(); dbgs() << "with: ";
OuterValue->dump());
V->replaceAllUsesWith(OuterValue);
}
SE->forgetLoop(FI.OuterLoop);
SE->forgetLoop(FI.InnerLoop);
if (U)
U->markLoopAsDeleted(*FI.InnerLoop, FI.InnerLoop->getName());
LI->erase(FI.InnerLoop);
NumFlattened++;
return true;
}
static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
ScalarEvolution *SE, AssumptionCache *AC,
const TargetTransformInfo *TTI) {
if (!WidenIV) {
LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n");
return false;
}
LLVM_DEBUG(dbgs() << "Try widening the IVs\n");
Module *M = FI.InnerLoop->getHeader()->getParent()->getParent();
auto &DL = M->getDataLayout();
auto *InnerType = FI.InnerInductionPHI->getType();
auto *OuterType = FI.OuterInductionPHI->getType();
unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits();
auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext());
if (InnerType != OuterType ||
InnerType->getScalarSizeInBits() >= MaxLegalSize ||
MaxLegalType->getScalarSizeInBits() <
InnerType->getScalarSizeInBits() * 2) {
LLVM_DEBUG(dbgs() << "Can't widen the IV\n");
return false;
}
SCEVExpander Rewriter(*SE, DL, "loopflatten");
SmallVector<WeakTrackingVH, 4> DeadInsts;
unsigned ElimExt = 0;
unsigned Widened = 0;
auto CreateWideIV = [&](WideIVInfo WideIV, bool &Deleted) -> bool {
PHINode *WidePhi =
createWideIV(WideIV, LI, SE, Rewriter, DT, DeadInsts, ElimExt, Widened,
true , true );
if (!WidePhi)
return false;
LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump());
LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIV.NarrowIV->dump());
Deleted = RecursivelyDeleteDeadPHINode(WideIV.NarrowIV);
return true;
};
bool Deleted;
if (!CreateWideIV({FI.InnerInductionPHI, MaxLegalType, false}, Deleted))
return false;
if (!Deleted)
FI.InnerPHIsToTransform.insert(FI.InnerInductionPHI);
if (!CreateWideIV({FI.OuterInductionPHI, MaxLegalType, false}, Deleted))
return false;
assert(Widened && "Widened IV expected");
FI.Widened = true;
FI.NarrowInnerInductionPHI = FI.InnerInductionPHI;
FI.NarrowOuterInductionPHI = FI.OuterInductionPHI;
return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI);
}
static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
ScalarEvolution *SE, AssumptionCache *AC,
const TargetTransformInfo *TTI, LPMUpdater *U,
MemorySSAUpdater *MSSAU) {
LLVM_DEBUG(
dbgs() << "Loop flattening running on outer loop "
<< FI.OuterLoop->getHeader()->getName() << " and inner loop "
<< FI.InnerLoop->getHeader()->getName() << " in "
<< FI.OuterLoop->getHeader()->getParent()->getName() << "\n");
if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI))
return false;
bool CanFlatten = CanWidenIV(FI, DT, LI, SE, AC, TTI);
if (FI.Widened && !CanFlatten)
return true;
if (CanFlatten)
return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
OverflowResult OR = checkOverflow(FI, DT, AC);
if (OR == OverflowResult::AlwaysOverflowsHigh ||
OR == OverflowResult::AlwaysOverflowsLow) {
LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n");
return false;
} else if (OR == OverflowResult::MayOverflow) {
LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n");
return false;
}
LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n");
return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
}
bool Flatten(LoopNest &LN, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE,
AssumptionCache *AC, TargetTransformInfo *TTI, LPMUpdater *U,
MemorySSAUpdater *MSSAU) {
bool Changed = false;
for (Loop *InnerLoop : LN.getLoops()) {
auto *OuterLoop = InnerLoop->getParentLoop();
if (!OuterLoop)
continue;
FlattenInfo FI(OuterLoop, InnerLoop);
Changed |= FlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
}
return Changed;
}
PreservedAnalyses LoopFlattenPass::run(LoopNest &LN, LoopAnalysisManager &LAM,
LoopStandardAnalysisResults &AR,
LPMUpdater &U) {
bool Changed = false;
Optional<MemorySSAUpdater> MSSAU;
if (AR.MSSA) {
MSSAU = MemorySSAUpdater(AR.MSSA);
if (VerifyMemorySSA)
AR.MSSA->verifyMemorySSA();
}
Changed |= Flatten(LN, &AR.DT, &AR.LI, &AR.SE, &AR.AC, &AR.TTI, &U,
MSSAU ? MSSAU.getPointer() : nullptr);
if (!Changed)
return PreservedAnalyses::all();
if (AR.MSSA && VerifyMemorySSA)
AR.MSSA->verifyMemorySSA();
auto PA = getLoopPassPreservedAnalyses();
if (AR.MSSA)
PA.preserve<MemorySSAAnalysis>();
return PA;
}
namespace {
class LoopFlattenLegacyPass : public FunctionPass {
public:
static char ID; LoopFlattenLegacyPass() : FunctionPass(ID) {
initializeLoopFlattenLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
getLoopAnalysisUsage(AU);
AU.addRequired<TargetTransformInfoWrapperPass>();
AU.addPreserved<TargetTransformInfoWrapperPass>();
AU.addRequired<AssumptionCacheTracker>();
AU.addPreserved<AssumptionCacheTracker>();
AU.addPreserved<MemorySSAWrapperPass>();
}
};
}
char LoopFlattenLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops",
false, false)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_END(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops",
false, false)
FunctionPass *llvm::createLoopFlattenPass() {
return new LoopFlattenLegacyPass();
}
bool LoopFlattenLegacyPass::runOnFunction(Function &F) {
ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
auto &TTIP = getAnalysis<TargetTransformInfoWrapperPass>();
auto *TTI = &TTIP.getTTI(F);
auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
auto *MSSA = getAnalysisIfAvailable<MemorySSAWrapperPass>();
Optional<MemorySSAUpdater> MSSAU;
if (MSSA)
MSSAU = MemorySSAUpdater(&MSSA->getMSSA());
bool Changed = false;
for (Loop *L : *LI) {
auto LN = LoopNest::getLoopNest(*L, *SE);
Changed |= Flatten(*LN, DT, LI, SE, AC, TTI, nullptr,
MSSAU ? MSSAU.getPointer() : nullptr);
}
return Changed;
}