#include "InstCombineInternal.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/TargetFolder.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DebugCounter.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/InstCombine/InstCombiner.h"
#include <cassert>
#include <cstdint>
#include <functional>
#include <tuple>
#include <type_traits>
#include <utility>
namespace llvm {
class AssumptionCache;
class DataLayout;
class DominatorTree;
class LLVMContext;
}
using namespace llvm;
#define DEBUG_TYPE "instcombine"
STATISTIC(NegatorTotalNegationsAttempted,
"Negator: Number of negations attempted to be sinked");
STATISTIC(NegatorNumTreesNegated,
"Negator: Number of negations successfully sinked");
STATISTIC(NegatorMaxDepthVisited, "Negator: Maximal traversal depth ever "
"reached while attempting to sink negation");
STATISTIC(NegatorTimesDepthLimitReached,
"Negator: How many times did the traversal depth limit was reached "
"during sinking");
STATISTIC(
NegatorNumValuesVisited,
"Negator: Total number of values visited during attempts to sink negation");
STATISTIC(NegatorNumNegationsFoundInCache,
"Negator: How many negations did we retrieve/reuse from cache");
STATISTIC(NegatorMaxTotalValuesVisited,
"Negator: Maximal number of values ever visited while attempting to "
"sink negation");
STATISTIC(NegatorNumInstructionsCreatedTotal,
"Negator: Number of new negated instructions created, total");
STATISTIC(NegatorMaxInstructionsCreated,
"Negator: Maximal number of new instructions created during negation "
"attempt");
STATISTIC(NegatorNumInstructionsNegatedSuccess,
"Negator: Number of new negated instructions created in successful "
"negation sinking attempts");
DEBUG_COUNTER(NegatorCounter, "instcombine-negator",
"Controls Negator transformations in InstCombine pass");
static cl::opt<bool>
NegatorEnabled("instcombine-negator-enabled", cl::init(true),
cl::desc("Should we attempt to sink negations?"));
static cl::opt<unsigned>
NegatorMaxDepth("instcombine-negator-max-depth",
cl::init(NegatorDefaultMaxDepth),
cl::desc("What is the maximal lookup depth when trying to "
"check for viability of negation sinking."));
Negator::Negator(LLVMContext &C, const DataLayout &DL_, AssumptionCache &AC_,
const DominatorTree &DT_, bool IsTrulyNegation_)
: Builder(C, TargetFolder(DL_),
IRBuilderCallbackInserter([&](Instruction *I) {
++NegatorNumInstructionsCreatedTotal;
NewInstructions.push_back(I);
})),
DL(DL_), AC(AC_), DT(DT_), IsTrulyNegation(IsTrulyNegation_) {}
#if LLVM_ENABLE_STATS
Negator::~Negator() {
NegatorMaxTotalValuesVisited.updateMax(NumValuesVisitedInThisNegator);
}
#endif
std::array<Value *, 2> Negator::getSortedOperandsOfBinOp(Instruction *I) {
assert(I->getNumOperands() == 2 && "Only for binops!");
std::array<Value *, 2> Ops{I->getOperand(0), I->getOperand(1)};
if (I->isCommutative() && InstCombiner::getComplexity(I->getOperand(0)) <
InstCombiner::getComplexity(I->getOperand(1)))
std::swap(Ops[0], Ops[1]);
return Ops;
}
LLVM_NODISCARD Value *Negator::visitImpl(Value *V, unsigned Depth) {
if (match(V, m_Undef()))
return V;
if (V->getType()->isIntOrIntVectorTy(1))
return V;
Value *X;
if (match(V, m_Neg(m_Value(X))))
return X;
if (match(V, m_AnyIntegralConstant()))
return ConstantExpr::getNeg(cast<Constant>(V), false,
false);
if (!isa<Instruction>(V))
return nullptr;
if (!V->hasOneUse() && !IsTrulyNegation)
return nullptr;
auto *I = cast<Instruction>(V);
unsigned BitWidth = I->getType()->getScalarSizeInBits();
InstCombiner::BuilderTy::InsertPointGuard Guard(Builder);
Builder.SetInsertPoint(I);
switch (I->getOpcode()) {
case Instruction::Add: {
std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
if (match(Ops[1], m_One()))
return Builder.CreateNot(Ops[0], I->getName() + ".neg");
break;
}
case Instruction::Xor:
if (match(I, m_Not(m_Value(X))))
return Builder.CreateAdd(X, ConstantInt::get(X->getType(), 1),
I->getName() + ".neg");
break;
case Instruction::AShr:
case Instruction::LShr: {
const APInt *Op1Val;
if (match(I->getOperand(1), m_APInt(Op1Val)) && *Op1Val == BitWidth - 1) {
Value *BO = I->getOpcode() == Instruction::AShr
? Builder.CreateLShr(I->getOperand(0), I->getOperand(1))
: Builder.CreateAShr(I->getOperand(0), I->getOperand(1));
if (auto *NewInstr = dyn_cast<Instruction>(BO)) {
NewInstr->copyIRFlags(I);
NewInstr->setName(I->getName() + ".neg");
}
return BO;
}
break;
}
case Instruction::SExt:
case Instruction::ZExt:
if (I->getOperand(0)->getType()->isIntOrIntVectorTy(1))
return I->getOpcode() == Instruction::SExt
? Builder.CreateZExt(I->getOperand(0), I->getType(),
I->getName() + ".neg")
: Builder.CreateSExt(I->getOperand(0), I->getType(),
I->getName() + ".neg");
break;
case Instruction::Select: {
auto *Sel = cast<SelectInst>(I);
Constant *TrueC, *FalseC;
if (match(Sel->getTrueValue(), m_ImmConstant(TrueC)) &&
match(Sel->getFalseValue(), m_ImmConstant(FalseC))) {
Constant *NegTrueC = ConstantExpr::getNeg(TrueC);
Constant *NegFalseC = ConstantExpr::getNeg(FalseC);
return Builder.CreateSelect(Sel->getCondition(), NegTrueC, NegFalseC,
I->getName() + ".neg", I);
}
break;
}
default:
break; }
if (I->getOpcode() == Instruction::Sub &&
(I->hasOneUse() || match(I->getOperand(0), m_ImmConstant()))) {
return Builder.CreateSub(I->getOperand(1), I->getOperand(0),
I->getName() + ".neg");
}
if (!V->hasOneUse())
return nullptr;
switch (I->getOpcode()) {
case Instruction::And: {
Constant *ShAmt;
if (match(I, m_c_And(m_OneUse(m_TruncOrSelf(
m_LShr(m_Value(X), m_ImmConstant(ShAmt)))),
m_One()))) {
unsigned BW = X->getType()->getScalarSizeInBits();
Constant *BWMinusOne = ConstantInt::get(X->getType(), BW - 1);
Value *R = Builder.CreateShl(X, Builder.CreateSub(BWMinusOne, ShAmt));
R = Builder.CreateAShr(R, BWMinusOne);
return Builder.CreateTruncOrBitCast(R, I->getType());
}
break;
}
case Instruction::SDiv:
if (auto *Op1C = dyn_cast<Constant>(I->getOperand(1))) {
if (!Op1C->containsUndefOrPoisonElement() &&
Op1C->isNotMinSignedValue() && Op1C->isNotOneValue()) {
Value *BO =
Builder.CreateSDiv(I->getOperand(0), ConstantExpr::getNeg(Op1C),
I->getName() + ".neg");
if (auto *NewInstr = dyn_cast<Instruction>(BO))
NewInstr->setIsExact(I->isExact());
return BO;
}
}
break;
}
if (Depth > NegatorMaxDepth) {
LLVM_DEBUG(dbgs() << "Negator: reached maximal allowed traversal depth in "
<< *V << ". Giving up.\n");
++NegatorTimesDepthLimitReached;
return nullptr;
}
switch (I->getOpcode()) {
case Instruction::Freeze: {
Value *NegOp = negate(I->getOperand(0), Depth + 1);
if (!NegOp) return nullptr;
return Builder.CreateFreeze(NegOp, I->getName() + ".neg");
}
case Instruction::PHI: {
auto *PHI = cast<PHINode>(I);
SmallVector<Value *, 4> NegatedIncomingValues(PHI->getNumOperands());
for (auto I : zip(PHI->incoming_values(), NegatedIncomingValues)) {
if (!(std::get<1>(I) =
negate(std::get<0>(I), Depth + 1))) return nullptr;
}
PHINode *NegatedPHI = Builder.CreatePHI(
PHI->getType(), PHI->getNumOperands(), PHI->getName() + ".neg");
for (auto I : zip(NegatedIncomingValues, PHI->blocks()))
NegatedPHI->addIncoming(std::get<0>(I), std::get<1>(I));
return NegatedPHI;
}
case Instruction::Select: {
if (isKnownNegation(I->getOperand(1), I->getOperand(2))) {
auto *NewSelect = cast<SelectInst>(I->clone());
NewSelect->swapValues();
NewSelect->setName(I->getName() + ".neg");
Builder.Insert(NewSelect);
return NewSelect;
}
Value *NegOp1 = negate(I->getOperand(1), Depth + 1);
if (!NegOp1) return nullptr;
Value *NegOp2 = negate(I->getOperand(2), Depth + 1);
if (!NegOp2)
return nullptr;
return Builder.CreateSelect(I->getOperand(0), NegOp1, NegOp2,
I->getName() + ".neg", I);
}
case Instruction::ShuffleVector: {
auto *Shuf = cast<ShuffleVectorInst>(I);
Value *NegOp0 = negate(I->getOperand(0), Depth + 1);
if (!NegOp0) return nullptr;
Value *NegOp1 = negate(I->getOperand(1), Depth + 1);
if (!NegOp1)
return nullptr;
return Builder.CreateShuffleVector(NegOp0, NegOp1, Shuf->getShuffleMask(),
I->getName() + ".neg");
}
case Instruction::ExtractElement: {
auto *EEI = cast<ExtractElementInst>(I);
Value *NegVector = negate(EEI->getVectorOperand(), Depth + 1);
if (!NegVector) return nullptr;
return Builder.CreateExtractElement(NegVector, EEI->getIndexOperand(),
I->getName() + ".neg");
}
case Instruction::InsertElement: {
auto *IEI = cast<InsertElementInst>(I);
Value *NegVector = negate(IEI->getOperand(0), Depth + 1);
if (!NegVector) return nullptr;
Value *NegNewElt = negate(IEI->getOperand(1), Depth + 1);
if (!NegNewElt) return nullptr;
return Builder.CreateInsertElement(NegVector, NegNewElt, IEI->getOperand(2),
I->getName() + ".neg");
}
case Instruction::Trunc: {
Value *NegOp = negate(I->getOperand(0), Depth + 1);
if (!NegOp) return nullptr;
return Builder.CreateTrunc(NegOp, I->getType(), I->getName() + ".neg");
}
case Instruction::Shl: {
if (Value *NegOp0 = negate(I->getOperand(0), Depth + 1))
return Builder.CreateShl(NegOp0, I->getOperand(1), I->getName() + ".neg");
auto *Op1C = dyn_cast<Constant>(I->getOperand(1));
if (!Op1C) return nullptr;
return Builder.CreateMul(
I->getOperand(0),
ConstantExpr::getShl(Constant::getAllOnesValue(Op1C->getType()), Op1C),
I->getName() + ".neg");
}
case Instruction::Or: {
if (!haveNoCommonBitsSet(I->getOperand(0), I->getOperand(1), DL, &AC, I,
&DT))
return nullptr; std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
if (match(Ops[1], m_One()))
return Builder.CreateNot(Ops[0], I->getName() + ".neg");
LLVM_FALLTHROUGH;
}
case Instruction::Add: {
SmallVector<Value *, 2> NegatedOps, NonNegatedOps;
for (Value *Op : I->operands()) {
if (Value *NegOp = negate(Op, Depth + 1)) {
NegatedOps.emplace_back(NegOp); continue;
}
if (!IsTrulyNegation)
return nullptr;
NonNegatedOps.emplace_back(Op); }
assert((NegatedOps.size() + NonNegatedOps.size()) == 2 &&
"Internal consistency check failed.");
if (NegatedOps.size() == 2) return Builder.CreateAdd(NegatedOps[0], NegatedOps[1],
I->getName() + ".neg");
assert(IsTrulyNegation && "We should have early-exited then.");
if (NonNegatedOps.size() == 2)
return nullptr;
return Builder.CreateSub(NegatedOps[0], NonNegatedOps[0],
I->getName() + ".neg");
}
case Instruction::Xor: {
std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
if (auto *C = dyn_cast<Constant>(Ops[1])) {
Value *Xor = Builder.CreateXor(Ops[0], ConstantExpr::getNot(C));
return Builder.CreateAdd(Xor, ConstantInt::get(Xor->getType(), 1),
I->getName() + ".neg");
}
return nullptr;
}
case Instruction::Mul: {
std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
Value *NegatedOp, *OtherOp;
if (Value *NegOp1 = negate(Ops[1], Depth + 1)) {
NegatedOp = NegOp1;
OtherOp = Ops[0];
} else if (Value *NegOp0 = negate(Ops[0], Depth + 1)) {
NegatedOp = NegOp0;
OtherOp = Ops[1];
} else
return nullptr;
return Builder.CreateMul(NegatedOp, OtherOp, I->getName() + ".neg");
}
default:
return nullptr; }
llvm_unreachable("Can't get here. We always return from switch.");
}
LLVM_NODISCARD Value *Negator::negate(Value *V, unsigned Depth) {
NegatorMaxDepthVisited.updateMax(Depth);
++NegatorNumValuesVisited;
#if LLVM_ENABLE_STATS
++NumValuesVisitedInThisNegator;
#endif
#ifndef NDEBUG
Value *Placeholder = reinterpret_cast<Value *>(static_cast<uintptr_t>(-1));
#endif
auto NegationsCacheIterator = NegationsCache.find(V);
if (NegationsCacheIterator != NegationsCache.end()) {
++NegatorNumNegationsFoundInCache;
Value *NegatedV = NegationsCacheIterator->second;
assert(NegatedV != Placeholder && "Encountered a cycle during negation.");
return NegatedV;
}
#ifndef NDEBUG
NegationsCache[V] = Placeholder;
#endif
Value *NegatedV = visitImpl(V, Depth);
NegationsCache[V] = NegatedV;
return NegatedV;
}
LLVM_NODISCARD Optional<Negator::Result> Negator::run(Value *Root) {
Value *Negated = negate(Root, 0);
if (!Negated) {
for (Instruction *I : llvm::reverse(NewInstructions))
I->eraseFromParent();
return llvm::None;
}
return std::make_pair(ArrayRef<Instruction *>(NewInstructions), Negated);
}
LLVM_NODISCARD Value *Negator::Negate(bool LHSIsZero, Value *Root,
InstCombinerImpl &IC) {
++NegatorTotalNegationsAttempted;
LLVM_DEBUG(dbgs() << "Negator: attempting to sink negation into " << *Root
<< "\n");
if (!NegatorEnabled || !DebugCounter::shouldExecute(NegatorCounter))
return nullptr;
Negator N(Root->getContext(), IC.getDataLayout(), IC.getAssumptionCache(),
IC.getDominatorTree(), LHSIsZero);
Optional<Result> Res = N.run(Root);
if (!Res) { LLVM_DEBUG(dbgs() << "Negator: failed to sink negation into " << *Root
<< "\n");
return nullptr;
}
LLVM_DEBUG(dbgs() << "Negator: successfully sunk negation into " << *Root
<< "\n NEW: " << *Res->second << "\n");
++NegatorNumTreesNegated;
InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
IC.Builder.ClearInsertionPoint();
IC.Builder.SetCurrentDebugLocation(DebugLoc());
LLVM_DEBUG(dbgs() << "Negator: Propagating " << Res->first.size()
<< " instrs to InstCombine\n");
NegatorMaxInstructionsCreated.updateMax(Res->first.size());
NegatorNumInstructionsNegatedSuccess += Res->first.size();
for (Instruction *I : Res->first)
IC.Builder.Insert(I, I->getName());
return Res->second;
}