#include "llvm/Transforms/Utils/LowerSwitch.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/LazyValueInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <limits>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "lower-switch"
namespace {
struct IntRange {
int64_t Low, High;
};
}
namespace {
bool IsInRanges(const IntRange &R, const std::vector<IntRange> &Ranges) {
auto I = llvm::lower_bound(
Ranges, R, [](IntRange A, IntRange B) { return A.High < B.High; });
return I != Ranges.end() && I->Low <= R.Low;
}
struct CaseRange {
ConstantInt *Low;
ConstantInt *High;
BasicBlock *BB;
CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
: Low(low), High(high), BB(bb) {}
};
using CaseVector = std::vector<CaseRange>;
using CaseItr = std::vector<CaseRange>::iterator;
struct CaseCmp {
bool operator()(const CaseRange &C1, const CaseRange &C2) {
const ConstantInt *CI1 = cast<const ConstantInt>(C1.Low);
const ConstantInt *CI2 = cast<const ConstantInt>(C2.High);
return CI1->getValue().slt(CI2->getValue());
}
};
LLVM_ATTRIBUTE_USED
raw_ostream &operator<<(raw_ostream &O, const CaseVector &C) {
O << "[";
for (CaseVector::const_iterator B = C.begin(), E = C.end(); B != E;) {
O << "[" << B->Low->getValue() << ", " << B->High->getValue() << "]";
if (++B != E)
O << ", ";
}
return O << "]";
}
void FixPhis(
BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
const unsigned NumMergedCases = std::numeric_limits<unsigned>::max()) {
for (auto &I : SuccBB->phis()) {
PHINode *PN = cast<PHINode>(&I);
unsigned Idx = 0, E = PN->getNumIncomingValues();
unsigned LocalNumMergedCases = NumMergedCases;
for (; Idx != E && NewBB; ++Idx) {
if (PN->getIncomingBlock(Idx) == OrigBB) {
PN->setIncomingBlock(Idx, NewBB);
break;
}
}
if (NewBB)
++Idx;
SmallVector<unsigned, 8> Indices;
for (; LocalNumMergedCases > 0 && Idx < E; ++Idx)
if (PN->getIncomingBlock(Idx) == OrigBB) {
Indices.push_back(Idx);
LocalNumMergedCases--;
}
for (unsigned III : llvm::reverse(Indices))
PN->removeIncomingValue(III);
}
}
BasicBlock *NewLeafBlock(CaseRange &Leaf, Value *Val, ConstantInt *LowerBound,
ConstantInt *UpperBound, BasicBlock *OrigBlock,
BasicBlock *Default) {
Function *F = OrigBlock->getParent();
BasicBlock *NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
ICmpInst *Comp = nullptr;
if (Leaf.Low == Leaf.High) {
Comp =
new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val, Leaf.Low, "SwitchLeaf");
} else {
if (Leaf.Low == LowerBound) {
Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
"SwitchLeaf");
} else if (Leaf.High == UpperBound) {
Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SGE, Val, Leaf.Low,
"SwitchLeaf");
} else if (Leaf.Low->isZero()) {
Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
"SwitchLeaf");
} else {
Constant *NegLo = ConstantExpr::getNeg(Leaf.Low);
Instruction *Add = BinaryOperator::CreateAdd(
Val, NegLo, Val->getName() + ".off", NewLeaf);
Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
"SwitchLeaf");
}
}
BasicBlock *Succ = Leaf.BB;
BranchInst::Create(Succ, Default, Comp, NewLeaf);
for (auto &I : Default->phis()) {
PHINode *PN = cast<PHINode>(&I);
auto *V = PN->getIncomingValueForBlock(OrigBlock);
PN->addIncoming(V, NewLeaf);
}
for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
PHINode *PN = cast<PHINode>(I);
uint64_t Range = Leaf.High->getSExtValue() - Leaf.Low->getSExtValue();
for (uint64_t j = 0; j < Range; ++j) {
PN->removeIncomingValue(OrigBlock);
}
int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
assert(BlockIdx != -1 && "Switch didn't go to this successor??");
PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
}
return NewLeaf;
}
BasicBlock *SwitchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
ConstantInt *UpperBound, Value *Val,
BasicBlock *Predecessor, BasicBlock *OrigBlock,
BasicBlock *Default,
const std::vector<IntRange> &UnreachableRanges) {
assert(LowerBound && UpperBound && "Bounds must be initialized");
unsigned Size = End - Begin;
if (Size == 1) {
if (Begin->Low == LowerBound && Begin->High == UpperBound) {
unsigned NumMergedCases = 0;
NumMergedCases = UpperBound->getSExtValue() - LowerBound->getSExtValue();
FixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
return Begin->BB;
}
return NewLeafBlock(*Begin, Val, LowerBound, UpperBound, OrigBlock,
Default);
}
unsigned Mid = Size / 2;
std::vector<CaseRange> LHS(Begin, Begin + Mid);
LLVM_DEBUG(dbgs() << "LHS: " << LHS << "\n");
std::vector<CaseRange> RHS(Begin + Mid, End);
LLVM_DEBUG(dbgs() << "RHS: " << RHS << "\n");
CaseRange &Pivot = *(Begin + Mid);
LLVM_DEBUG(dbgs() << "Pivot ==> [" << Pivot.Low->getValue() << ", "
<< Pivot.High->getValue() << "]\n");
ConstantInt *NewLowerBound = Pivot.Low;
ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
NewLowerBound->getValue() - 1);
if (!UnreachableRanges.empty()) {
int64_t GapLow = LHS.back().High->getSExtValue() + 1;
int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
IntRange Gap = { GapLow, GapHigh };
if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
NewUpperBound = LHS.back().High;
}
LLVM_DEBUG(dbgs() << "LHS Bounds ==> [" << LowerBound->getSExtValue() << ", "
<< NewUpperBound->getSExtValue() << "]\n"
<< "RHS Bounds ==> [" << NewLowerBound->getSExtValue()
<< ", " << UpperBound->getSExtValue() << "]\n");
Function* F = OrigBlock->getParent();
BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Val, Pivot.Low, "Pivot");
BasicBlock *LBranch =
SwitchConvert(LHS.begin(), LHS.end(), LowerBound, NewUpperBound, Val,
NewNode, OrigBlock, Default, UnreachableRanges);
BasicBlock *RBranch =
SwitchConvert(RHS.begin(), RHS.end(), NewLowerBound, UpperBound, Val,
NewNode, OrigBlock, Default, UnreachableRanges);
F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
NewNode->getInstList().push_back(Comp);
BranchInst::Create(LBranch, RBranch, Comp, NewNode);
return NewNode;
}
unsigned Clusterify(CaseVector &Cases, SwitchInst *SI) {
unsigned NumSimpleCases = 0;
for (auto Case : SI->cases()) {
if (Case.getCaseSuccessor() == SI->getDefaultDest())
continue;
Cases.push_back(CaseRange(Case.getCaseValue(), Case.getCaseValue(),
Case.getCaseSuccessor()));
++NumSimpleCases;
}
llvm::sort(Cases, CaseCmp());
if (Cases.size() >= 2) {
CaseItr I = Cases.begin();
for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
int64_t nextValue = J->Low->getSExtValue();
int64_t currentValue = I->High->getSExtValue();
BasicBlock* nextBB = J->BB;
BasicBlock* currentBB = I->BB;
assert(nextValue > currentValue && "Cases should be strictly ascending");
if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
I->High = J->High;
} else if (++I != J) {
*I = *J;
}
}
Cases.erase(std::next(I), Cases.end());
}
return NumSimpleCases;
}
void ProcessSwitchInst(SwitchInst *SI,
SmallPtrSetImpl<BasicBlock *> &DeleteList,
AssumptionCache *AC, LazyValueInfo *LVI) {
BasicBlock *OrigBlock = SI->getParent();
Function *F = OrigBlock->getParent();
Value *Val = SI->getCondition(); BasicBlock* Default = SI->getDefaultDest();
if ((OrigBlock != &F->getEntryBlock() && pred_empty(OrigBlock)) ||
OrigBlock->getSinglePredecessor() == OrigBlock) {
DeleteList.insert(OrigBlock);
return;
}
CaseVector Cases;
const unsigned NumSimpleCases = Clusterify(Cases, SI);
LLVM_DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
<< ". Total non-default cases: " << NumSimpleCases
<< "\nCase clusters: " << Cases << "\n");
if (Cases.empty()) {
BranchInst::Create(Default, OrigBlock);
FixPhis(Default, OrigBlock, OrigBlock);
SI->eraseFromParent();
return;
}
ConstantInt *LowerBound = nullptr;
ConstantInt *UpperBound = nullptr;
bool DefaultIsUnreachableFromSwitch = false;
if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
LowerBound = Cases.front().Low;
UpperBound = Cases.back().High;
DefaultIsUnreachableFromSwitch = true;
} else {
const DataLayout &DL = F->getParent()->getDataLayout();
KnownBits Known = computeKnownBits(Val, DL, 0, AC, SI);
ConstantRange KnownBitsRange =
ConstantRange::fromKnownBits(Known, false);
const ConstantRange LVIRange = LVI->getConstantRange(Val, SI);
ConstantRange ValRange = KnownBitsRange.intersectWith(LVIRange);
APInt Low = Cases.front().Low->getValue();
APInt High = Cases.back().High->getValue();
APInt Min = APIntOps::smin(ValRange.getSignedMin(), Low);
APInt Max = APIntOps::smax(ValRange.getSignedMax(), High);
LowerBound = ConstantInt::get(SI->getContext(), Min);
UpperBound = ConstantInt::get(SI->getContext(), Max);
DefaultIsUnreachableFromSwitch = (Min + (NumSimpleCases - 1) == Max);
}
std::vector<IntRange> UnreachableRanges;
if (DefaultIsUnreachableFromSwitch) {
DenseMap<BasicBlock *, unsigned> Popularity;
unsigned MaxPop = 0;
BasicBlock *PopSucc = nullptr;
IntRange R = {std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::max()};
UnreachableRanges.push_back(R);
for (const auto &I : Cases) {
int64_t Low = I.Low->getSExtValue();
int64_t High = I.High->getSExtValue();
IntRange &LastRange = UnreachableRanges.back();
if (LastRange.Low == Low) {
UnreachableRanges.pop_back();
} else {
assert(Low > LastRange.Low);
LastRange.High = Low - 1;
}
if (High != std::numeric_limits<int64_t>::max()) {
IntRange R = { High + 1, std::numeric_limits<int64_t>::max() };
UnreachableRanges.push_back(R);
}
int64_t N = High - Low + 1;
unsigned &Pop = Popularity[I.BB];
if ((Pop += N) > MaxPop) {
MaxPop = Pop;
PopSucc = I.BB;
}
}
#ifndef NDEBUG
for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
I != E; ++I) {
assert(I->Low <= I->High);
auto Next = I + 1;
if (Next != E) {
assert(Next->Low > I->High);
}
}
#endif
const unsigned NumDefaultEdges = SI->getNumCases() + 1 - NumSimpleCases;
for (unsigned I = 0; I < NumDefaultEdges; ++I)
Default->removePredecessor(OrigBlock);
assert(MaxPop > 0 && PopSucc);
Default = PopSucc;
llvm::erase_if(Cases,
[PopSucc](const CaseRange &R) { return R.BB == PopSucc; });
if (Cases.empty()) {
BranchInst::Create(Default, OrigBlock);
SI->eraseFromParent();
for (unsigned I = 0 ; I < (MaxPop - 1) ; ++I)
PopSucc->removePredecessor(OrigBlock);
return;
}
Val = SI->getCondition();
}
BasicBlock *SwitchBlock =
SwitchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
OrigBlock, OrigBlock, Default, UnreachableRanges);
if (SwitchBlock != Default)
FixPhis(Default, OrigBlock, nullptr);
BranchInst::Create(SwitchBlock, OrigBlock);
BasicBlock *OldDefault = SI->getDefaultDest();
OrigBlock->getInstList().erase(SI);
if (pred_empty(OldDefault))
DeleteList.insert(OldDefault);
}
bool LowerSwitch(Function &F, LazyValueInfo *LVI, AssumptionCache *AC) {
bool Changed = false;
SmallPtrSet<BasicBlock *, 8> DeleteList;
for (BasicBlock &Cur : llvm::make_early_inc_range(F)) {
if (DeleteList.count(&Cur))
continue;
if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur.getTerminator())) {
Changed = true;
ProcessSwitchInst(SI, DeleteList, AC, LVI);
}
}
for (BasicBlock *BB : DeleteList) {
LVI->eraseBlock(BB);
DeleteDeadBlock(BB);
}
return Changed;
}
class LowerSwitchLegacyPass : public FunctionPass {
public:
static char ID;
LowerSwitchLegacyPass() : FunctionPass(ID) {
initializeLowerSwitchLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<LazyValueInfoWrapperPass>();
}
};
}
char LowerSwitchLegacyPass::ID = 0;
char &llvm::LowerSwitchID = LowerSwitchLegacyPass::ID;
INITIALIZE_PASS_BEGIN(LowerSwitchLegacyPass, "lowerswitch",
"Lower SwitchInst's to branches", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
INITIALIZE_PASS_END(LowerSwitchLegacyPass, "lowerswitch",
"Lower SwitchInst's to branches", false, false)
FunctionPass *llvm::createLowerSwitchPass() {
return new LowerSwitchLegacyPass();
}
bool LowerSwitchLegacyPass::runOnFunction(Function &F) {
LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>();
AssumptionCache *AC = ACT ? &ACT->getAssumptionCache(F) : nullptr;
return LowerSwitch(F, LVI, AC);
}
PreservedAnalyses LowerSwitchPass::run(Function &F,
FunctionAnalysisManager &AM) {
LazyValueInfo *LVI = &AM.getResult<LazyValueAnalysis>(F);
AssumptionCache *AC = AM.getCachedResult<AssumptionAnalysis>(F);
return LowerSwitch(F, LVI, AC) ? PreservedAnalyses::none()
: PreservedAnalyses::all();
}