#include "AggressiveInstCombineInternal.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instruction.h"
#include "llvm/Support/KnownBits.h"
using namespace llvm;
#define DEBUG_TYPE "aggressive-instcombine"
STATISTIC(NumExprsReduced, "Number of truncations eliminated by reducing bit "
"width of expression graph");
STATISTIC(NumInstrsReduced,
"Number of instructions whose bit width was reduced");
static void getRelevantOperands(Instruction *I, SmallVectorImpl<Value *> &Ops) {
unsigned Opc = I->getOpcode();
switch (Opc) {
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
break;
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::UDiv:
case Instruction::URem:
case Instruction::InsertElement:
Ops.push_back(I->getOperand(0));
Ops.push_back(I->getOperand(1));
break;
case Instruction::ExtractElement:
Ops.push_back(I->getOperand(0));
break;
case Instruction::Select:
Ops.push_back(I->getOperand(1));
Ops.push_back(I->getOperand(2));
break;
case Instruction::PHI:
for (Value *V : cast<PHINode>(I)->incoming_values())
Ops.push_back(V);
break;
default:
llvm_unreachable("Unreachable!");
}
}
bool TruncInstCombine::buildTruncExpressionGraph() {
SmallVector<Value *, 8> Worklist;
SmallVector<Instruction *, 8> Stack;
InstInfoMap.clear();
Worklist.push_back(CurrentTruncInst->getOperand(0));
while (!Worklist.empty()) {
Value *Curr = Worklist.back();
if (isa<Constant>(Curr)) {
Worklist.pop_back();
continue;
}
auto *I = dyn_cast<Instruction>(Curr);
if (!I)
return false;
if (!Stack.empty() && Stack.back() == I) {
Worklist.pop_back();
Stack.pop_back();
InstInfoMap.insert(std::make_pair(I, Info()));
continue;
}
if (InstInfoMap.count(I)) {
Worklist.pop_back();
continue;
}
Stack.push_back(I);
unsigned Opc = I->getOpcode();
switch (Opc) {
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
break;
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::UDiv:
case Instruction::URem:
case Instruction::InsertElement:
case Instruction::ExtractElement:
case Instruction::Select: {
SmallVector<Value *, 2> Operands;
getRelevantOperands(I, Operands);
append_range(Worklist, Operands);
break;
}
case Instruction::PHI: {
SmallVector<Value *, 2> Operands;
getRelevantOperands(I, Operands);
for (auto *Op : Operands)
if (all_of(Stack, [Op](Value *V) { return Op != V; }))
Worklist.push_back(Op);
break;
}
default:
return false;
}
}
return true;
}
unsigned TruncInstCombine::getMinBitWidth() {
SmallVector<Value *, 8> Worklist;
SmallVector<Instruction *, 8> Stack;
Value *Src = CurrentTruncInst->getOperand(0);
Type *DstTy = CurrentTruncInst->getType();
unsigned TruncBitWidth = DstTy->getScalarSizeInBits();
unsigned OrigBitWidth =
CurrentTruncInst->getOperand(0)->getType()->getScalarSizeInBits();
if (isa<Constant>(Src))
return TruncBitWidth;
Worklist.push_back(Src);
InstInfoMap[cast<Instruction>(Src)].ValidBitWidth = TruncBitWidth;
while (!Worklist.empty()) {
Value *Curr = Worklist.back();
if (isa<Constant>(Curr)) {
Worklist.pop_back();
continue;
}
auto *I = cast<Instruction>(Curr);
auto &Info = InstInfoMap[I];
SmallVector<Value *, 2> Operands;
getRelevantOperands(I, Operands);
if (!Stack.empty() && Stack.back() == I) {
Worklist.pop_back();
Stack.pop_back();
for (auto *Operand : Operands)
if (auto *IOp = dyn_cast<Instruction>(Operand))
Info.MinBitWidth =
std::max(Info.MinBitWidth, InstInfoMap[IOp].MinBitWidth);
continue;
}
Stack.push_back(I);
unsigned ValidBitWidth = Info.ValidBitWidth;
Info.MinBitWidth = std::max(Info.MinBitWidth, Info.ValidBitWidth);
for (auto *Operand : Operands)
if (auto *IOp = dyn_cast<Instruction>(Operand)) {
unsigned IOpBitwidth = InstInfoMap.lookup(IOp).ValidBitWidth;
if (IOpBitwidth >= ValidBitWidth)
continue;
InstInfoMap[IOp].ValidBitWidth = ValidBitWidth;
Worklist.push_back(IOp);
}
}
unsigned MinBitWidth = InstInfoMap.lookup(cast<Instruction>(Src)).MinBitWidth;
assert(MinBitWidth >= TruncBitWidth);
if (MinBitWidth > TruncBitWidth) {
if (DstTy->isVectorTy())
return OrigBitWidth;
Type *Ty = DL.getSmallestLegalIntType(DstTy->getContext(), MinBitWidth);
MinBitWidth = Ty ? Ty->getScalarSizeInBits() : OrigBitWidth;
} else { bool FromLegal = MinBitWidth == 1 || DL.isLegalInteger(OrigBitWidth);
bool ToLegal = MinBitWidth == 1 || DL.isLegalInteger(MinBitWidth);
if (!DstTy->isVectorTy() && FromLegal && !ToLegal)
return OrigBitWidth;
}
return MinBitWidth;
}
Type *TruncInstCombine::getBestTruncatedType() {
if (!buildTruncExpressionGraph())
return nullptr;
unsigned DesiredBitWidth = 0;
for (auto Itr : InstInfoMap) {
Instruction *I = Itr.first;
if (I->hasOneUse())
continue;
bool IsExtInst = (isa<ZExtInst>(I) || isa<SExtInst>(I));
for (auto *U : I->users())
if (auto *UI = dyn_cast<Instruction>(U))
if (UI != CurrentTruncInst && !InstInfoMap.count(UI)) {
if (!IsExtInst)
return nullptr;
unsigned ExtInstBitWidth =
I->getOperand(0)->getType()->getScalarSizeInBits();
if (DesiredBitWidth && DesiredBitWidth != ExtInstBitWidth)
return nullptr;
DesiredBitWidth = ExtInstBitWidth;
}
}
unsigned OrigBitWidth =
CurrentTruncInst->getOperand(0)->getType()->getScalarSizeInBits();
for (auto &Itr : InstInfoMap) {
Instruction *I = Itr.first;
if (I->isShift()) {
KnownBits KnownRHS = computeKnownBits(I->getOperand(1));
unsigned MinBitWidth = KnownRHS.getMaxValue()
.uadd_sat(APInt(OrigBitWidth, 1))
.getLimitedValue(OrigBitWidth);
if (MinBitWidth == OrigBitWidth)
return nullptr;
if (I->getOpcode() == Instruction::LShr) {
KnownBits KnownLHS = computeKnownBits(I->getOperand(0));
MinBitWidth =
std::max(MinBitWidth, KnownLHS.getMaxValue().getActiveBits());
}
if (I->getOpcode() == Instruction::AShr) {
unsigned NumSignBits = ComputeNumSignBits(I->getOperand(0));
MinBitWidth = std::max(MinBitWidth, OrigBitWidth - NumSignBits + 1);
}
if (MinBitWidth >= OrigBitWidth)
return nullptr;
Itr.second.MinBitWidth = MinBitWidth;
}
if (I->getOpcode() == Instruction::UDiv ||
I->getOpcode() == Instruction::URem) {
unsigned MinBitWidth = 0;
for (const auto &Op : I->operands()) {
KnownBits Known = computeKnownBits(Op);
MinBitWidth =
std::max(Known.getMaxValue().getActiveBits(), MinBitWidth);
if (MinBitWidth >= OrigBitWidth)
return nullptr;
}
Itr.second.MinBitWidth = MinBitWidth;
}
}
unsigned MinBitWidth = getMinBitWidth();
if (MinBitWidth >= OrigBitWidth ||
(DesiredBitWidth && DesiredBitWidth != MinBitWidth))
return nullptr;
return IntegerType::get(CurrentTruncInst->getContext(), MinBitWidth);
}
static Type *getReducedType(Value *V, Type *Ty) {
assert(Ty && !Ty->isVectorTy() && "Expect Scalar Type");
if (auto *VTy = dyn_cast<VectorType>(V->getType()))
return VectorType::get(Ty, VTy->getElementCount());
return Ty;
}
Value *TruncInstCombine::getReducedOperand(Value *V, Type *SclTy) {
Type *Ty = getReducedType(V, SclTy);
if (auto *C = dyn_cast<Constant>(V)) {
C = ConstantExpr::getIntegerCast(C, Ty, false);
return ConstantFoldConstant(C, DL, &TLI);
}
auto *I = cast<Instruction>(V);
Info Entry = InstInfoMap.lookup(I);
assert(Entry.NewValue);
return Entry.NewValue;
}
void TruncInstCombine::ReduceExpressionGraph(Type *SclTy) {
NumInstrsReduced += InstInfoMap.size();
SmallVector<std::pair<PHINode *, PHINode *>, 2> OldNewPHINodes;
for (auto &Itr : InstInfoMap) { Instruction *I = Itr.first;
TruncInstCombine::Info &NodeInfo = Itr.second;
assert(!NodeInfo.NewValue && "Instruction has been evaluated");
IRBuilder<> Builder(I);
Value *Res = nullptr;
unsigned Opc = I->getOpcode();
switch (Opc) {
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt: {
Type *Ty = getReducedType(I, SclTy);
if (I->getOperand(0)->getType() == Ty) {
assert(!isa<TruncInst>(I) && "Cannot reach here with TruncInst");
NodeInfo.NewValue = I->getOperand(0);
continue;
}
Res = Builder.CreateIntCast(I->getOperand(0), Ty,
Opc == Instruction::SExt);
auto *Entry = find(Worklist, I);
if (Entry != Worklist.end()) {
if (auto *NewCI = dyn_cast<TruncInst>(Res))
*Entry = NewCI;
else
Worklist.erase(Entry);
} else if (auto *NewCI = dyn_cast<TruncInst>(Res))
Worklist.push_back(NewCI);
break;
}
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::UDiv:
case Instruction::URem: {
Value *LHS = getReducedOperand(I->getOperand(0), SclTy);
Value *RHS = getReducedOperand(I->getOperand(1), SclTy);
Res = Builder.CreateBinOp((Instruction::BinaryOps)Opc, LHS, RHS);
if (auto *PEO = dyn_cast<PossiblyExactOperator>(I))
if (auto *ResI = dyn_cast<Instruction>(Res))
ResI->setIsExact(PEO->isExact());
break;
}
case Instruction::ExtractElement: {
Value *Vec = getReducedOperand(I->getOperand(0), SclTy);
Value *Idx = I->getOperand(1);
Res = Builder.CreateExtractElement(Vec, Idx);
break;
}
case Instruction::InsertElement: {
Value *Vec = getReducedOperand(I->getOperand(0), SclTy);
Value *NewElt = getReducedOperand(I->getOperand(1), SclTy);
Value *Idx = I->getOperand(2);
Res = Builder.CreateInsertElement(Vec, NewElt, Idx);
break;
}
case Instruction::Select: {
Value *Op0 = I->getOperand(0);
Value *LHS = getReducedOperand(I->getOperand(1), SclTy);
Value *RHS = getReducedOperand(I->getOperand(2), SclTy);
Res = Builder.CreateSelect(Op0, LHS, RHS);
break;
}
case Instruction::PHI: {
Res = Builder.CreatePHI(getReducedType(I, SclTy), I->getNumOperands());
OldNewPHINodes.push_back(
std::make_pair(cast<PHINode>(I), cast<PHINode>(Res)));
break;
}
default:
llvm_unreachable("Unhandled instruction");
}
NodeInfo.NewValue = Res;
if (auto *ResI = dyn_cast<Instruction>(Res))
ResI->takeName(I);
}
for (auto &Node : OldNewPHINodes) {
PHINode *OldPN = Node.first;
PHINode *NewPN = Node.second;
for (auto Incoming : zip(OldPN->incoming_values(), OldPN->blocks()))
NewPN->addIncoming(getReducedOperand(std::get<0>(Incoming), SclTy),
std::get<1>(Incoming));
}
Value *Res = getReducedOperand(CurrentTruncInst->getOperand(0), SclTy);
Type *DstTy = CurrentTruncInst->getType();
if (Res->getType() != DstTy) {
IRBuilder<> Builder(CurrentTruncInst);
Res = Builder.CreateIntCast(Res, DstTy, false);
if (auto *ResI = dyn_cast<Instruction>(Res))
ResI->takeName(CurrentTruncInst);
}
CurrentTruncInst->replaceAllUsesWith(Res);
CurrentTruncInst->eraseFromParent();
for (auto &Node : OldNewPHINodes) {
PHINode *OldPN = Node.first;
OldPN->replaceAllUsesWith(PoisonValue::get(OldPN->getType()));
InstInfoMap.erase(OldPN);
OldPN->eraseFromParent();
}
for (auto &I : llvm::reverse(InstInfoMap)) {
if (I.first->use_empty())
I.first->eraseFromParent();
else
assert((isa<SExtInst>(I.first) || isa<ZExtInst>(I.first)) &&
"Only {SExt, ZExt}Inst might have unreduced users");
}
}
bool TruncInstCombine::run(Function &F) {
bool MadeIRChange = false;
for (auto &BB : F) {
if (!DT.isReachableFromEntry(&BB))
continue;
for (auto &I : BB)
if (auto *CI = dyn_cast<TruncInst>(&I))
Worklist.push_back(CI);
}
while (!Worklist.empty()) {
CurrentTruncInst = Worklist.pop_back_val();
if (Type *NewDstSclTy = getBestTruncatedType()) {
LLVM_DEBUG(
dbgs() << "ICE: TruncInstCombine reducing type of expression graph "
"dominated by: "
<< CurrentTruncInst << '\n');
ReduceExpressionGraph(NewDstSclTy);
++NumExprsReduced;
MadeIRChange = true;
}
}
return MadeIRChange;
}