#include "llvm/Analysis/LazyValueInfo.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueLattice.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/AssemblyAnnotationWriter.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "lazy-value-info"
static const unsigned MaxProcessedPerValue = 500;
char LazyValueInfoWrapperPass::ID = 0;
LazyValueInfoWrapperPass::LazyValueInfoWrapperPass() : FunctionPass(ID) {
initializeLazyValueInfoWrapperPassPass(*PassRegistry::getPassRegistry());
}
INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
"Lazy Value Information Analysis", false, true)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
"Lazy Value Information Analysis", false, true)
namespace llvm {
FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
}
AnalysisKey LazyValueAnalysis::Key;
static bool hasSingleValue(const ValueLatticeElement &Val) {
if (Val.isConstantRange() &&
Val.getConstantRange().isSingleElement())
return true;
if (Val.isConstant())
return true;
return false;
}
static ValueLatticeElement intersect(const ValueLatticeElement &A,
const ValueLatticeElement &B) {
if (A.isUnknown())
return A;
if (B.isUnknown())
return B;
if (A.isOverdefined())
return B;
if (B.isOverdefined())
return A;
if (hasSingleValue(A))
return A;
if (hasSingleValue(B))
return B;
if (!A.isConstantRange() || !B.isConstantRange()) {
return A;
}
ConstantRange Range =
A.getConstantRange().intersectWith(B.getConstantRange());
return ValueLatticeElement::getRange(
std::move(Range), A.isConstantRangeIncludingUndef() ||
B.isConstantRangeIncludingUndef());
}
namespace {
class LazyValueInfoCache;
struct LVIValueHandle final : public CallbackVH {
LazyValueInfoCache *Parent;
LVIValueHandle(Value *V, LazyValueInfoCache *P = nullptr)
: CallbackVH(V), Parent(P) { }
void deleted() override;
void allUsesReplacedWith(Value *V) override {
deleted();
}
};
}
namespace {
using NonNullPointerSet = SmallDenseSet<AssertingVH<Value>, 2>;
class LazyValueInfoCache {
struct BlockCacheEntry {
SmallDenseMap<AssertingVH<Value>, ValueLatticeElement, 4> LatticeElements;
SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
Optional<NonNullPointerSet> NonNullPointers;
};
DenseMap<PoisoningVH<BasicBlock>, std::unique_ptr<BlockCacheEntry>>
BlockCache;
DenseSet<LVIValueHandle, DenseMapInfo<Value *>> ValueHandles;
const BlockCacheEntry *getBlockEntry(BasicBlock *BB) const {
auto It = BlockCache.find_as(BB);
if (It == BlockCache.end())
return nullptr;
return It->second.get();
}
BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
auto It = BlockCache.find_as(BB);
if (It == BlockCache.end())
It = BlockCache.insert({ BB, std::make_unique<BlockCacheEntry>() })
.first;
return It->second.get();
}
void addValueHandle(Value *Val) {
auto HandleIt = ValueHandles.find_as(Val);
if (HandleIt == ValueHandles.end())
ValueHandles.insert({ Val, this });
}
public:
void insertResult(Value *Val, BasicBlock *BB,
const ValueLatticeElement &Result) {
BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
if (Result.isOverdefined())
Entry->OverDefined.insert(Val);
else
Entry->LatticeElements.insert({ Val, Result });
addValueHandle(Val);
}
Optional<ValueLatticeElement> getCachedValueInfo(Value *V,
BasicBlock *BB) const {
const BlockCacheEntry *Entry = getBlockEntry(BB);
if (!Entry)
return None;
if (Entry->OverDefined.count(V))
return ValueLatticeElement::getOverdefined();
auto LatticeIt = Entry->LatticeElements.find_as(V);
if (LatticeIt == Entry->LatticeElements.end())
return None;
return LatticeIt->second;
}
bool isNonNullAtEndOfBlock(
Value *V, BasicBlock *BB,
function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
if (!Entry->NonNullPointers) {
Entry->NonNullPointers = InitFn(BB);
for (Value *V : *Entry->NonNullPointers)
addValueHandle(V);
}
return Entry->NonNullPointers->count(V);
}
void clear() {
BlockCache.clear();
ValueHandles.clear();
}
void eraseValue(Value *V);
void eraseBlock(BasicBlock *BB);
void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
};
}
void LazyValueInfoCache::eraseValue(Value *V) {
for (auto &Pair : BlockCache) {
Pair.second->LatticeElements.erase(V);
Pair.second->OverDefined.erase(V);
if (Pair.second->NonNullPointers)
Pair.second->NonNullPointers->erase(V);
}
auto HandleIt = ValueHandles.find_as(V);
if (HandleIt != ValueHandles.end())
ValueHandles.erase(HandleIt);
}
void LVIValueHandle::deleted() {
Parent->eraseValue(*this);
}
void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
BlockCache.erase(BB);
}
void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
BasicBlock *NewSucc) {
std::vector<BasicBlock*> worklist;
worklist.push_back(OldSucc);
const BlockCacheEntry *Entry = getBlockEntry(OldSucc);
if (!Entry || Entry->OverDefined.empty())
return; SmallVector<Value *, 4> ValsToClear(Entry->OverDefined.begin(),
Entry->OverDefined.end());
while (!worklist.empty()) {
BasicBlock *ToUpdate = worklist.back();
worklist.pop_back();
if (ToUpdate == NewSucc) continue;
auto OI = BlockCache.find_as(ToUpdate);
if (OI == BlockCache.end() || OI->second->OverDefined.empty())
continue;
auto &ValueSet = OI->second->OverDefined;
bool changed = false;
for (Value *V : ValsToClear) {
if (!ValueSet.erase(V))
continue;
changed = true;
}
if (!changed) continue;
llvm::append_range(worklist, successors(ToUpdate));
}
}
namespace {
class LazyValueInfoImpl;
class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
LazyValueInfoImpl *LVIImpl;
DominatorTree &DT;
public:
LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
: LVIImpl(L), DT(DTree) {}
void emitBasicBlockStartAnnot(const BasicBlock *BB,
formatted_raw_ostream &OS) override;
void emitInstructionAnnot(const Instruction *I,
formatted_raw_ostream &OS) override;
};
}
namespace {
class LazyValueInfoImpl {
LazyValueInfoCache TheCache;
SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
if (!BlockValueSet.insert(BV).second)
return false;
LLVM_DEBUG(dbgs() << "PUSH: " << *BV.second << " in "
<< BV.first->getName() << "\n");
BlockValueStack.push_back(BV);
return true;
}
AssumptionCache *AC; const DataLayout &DL;
Function *GuardDecl;
Optional<ValueLatticeElement> getBlockValue(Value *Val, BasicBlock *BB,
Instruction *CxtI);
Optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
BasicBlock *T, Instruction *CxtI = nullptr);
bool solveBlockValue(Value *Val, BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueImpl(Value *Val, BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueNonLocal(Value *Val,
BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValuePHINode(PHINode *PN,
BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueSelect(SelectInst *S,
BasicBlock *BB);
Optional<ConstantRange> getRangeFor(Value *V, Instruction *CxtI,
BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
Instruction *I, BasicBlock *BB,
std::function<ConstantRange(const ConstantRange &,
const ConstantRange &)> OpFn);
Optional<ValueLatticeElement> solveBlockValueBinaryOp(BinaryOperator *BBI,
BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueCast(CastInst *CI,
BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueOverflowIntrinsic(
WithOverflowInst *WO, BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueIntrinsic(IntrinsicInst *II,
BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueExtractValue(
ExtractValueInst *EVI, BasicBlock *BB);
bool isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB);
void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
ValueLatticeElement &BBLV,
Instruction *BBI);
void solve();
public:
ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB,
Instruction *CxtI = nullptr);
ValueLatticeElement getValueAt(Value *V, Instruction *CxtI);
ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB,
BasicBlock *ToBB,
Instruction *CxtI = nullptr);
void clear() {
TheCache.clear();
}
void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
LazyValueInfoAnnotatedWriter Writer(this, DTree);
F.print(OS, &Writer);
}
void eraseBlock(BasicBlock *BB) {
TheCache.eraseBlock(BB);
}
void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
Function *GuardDecl)
: AC(AC), DL(DL), GuardDecl(GuardDecl) {}
};
}
void LazyValueInfoImpl::solve() {
SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
BlockValueStack.begin(), BlockValueStack.end());
unsigned processedCount = 0;
while (!BlockValueStack.empty()) {
processedCount++;
if (processedCount > MaxProcessedPerValue) {
LLVM_DEBUG(
dbgs() << "Giving up on stack because we are getting too deep\n");
while (!StartingStack.empty()) {
std::pair<BasicBlock *, Value *> &e = StartingStack.back();
TheCache.insertResult(e.second, e.first,
ValueLatticeElement::getOverdefined());
StartingStack.pop_back();
}
BlockValueSet.clear();
BlockValueStack.clear();
return;
}
std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
if (solveBlockValue(e.second, e.first)) {
assert(BlockValueStack.back() == e && "Nothing should have been pushed!");
#ifndef NDEBUG
Optional<ValueLatticeElement> BBLV =
TheCache.getCachedValueInfo(e.second, e.first);
assert(BBLV && "Result should be in cache!");
LLVM_DEBUG(
dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "
<< *BBLV << "\n");
#endif
BlockValueStack.pop_back();
BlockValueSet.erase(e);
} else {
assert(BlockValueStack.back() != e && "Stack should have been pushed!");
}
}
}
Optional<ValueLatticeElement> LazyValueInfoImpl::getBlockValue(
Value *Val, BasicBlock *BB, Instruction *CxtI) {
if (Constant *VC = dyn_cast<Constant>(Val))
return ValueLatticeElement::get(VC);
if (Optional<ValueLatticeElement> OptLatticeVal =
TheCache.getCachedValueInfo(Val, BB)) {
intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CxtI);
return OptLatticeVal;
}
if (!pushBlockValue({ BB, Val }))
return ValueLatticeElement::getOverdefined();
return None;
}
static ValueLatticeElement getFromRangeMetadata(Instruction *BBI) {
switch (BBI->getOpcode()) {
default: break;
case Instruction::Load:
case Instruction::Call:
case Instruction::Invoke:
if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
if (isa<IntegerType>(BBI->getType())) {
return ValueLatticeElement::getRange(
getConstantRangeFromMetadata(*Ranges));
}
break;
};
return ValueLatticeElement::getOverdefined();
}
bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
assert(!isa<Constant>(Val) && "Value should not be constant");
assert(!TheCache.getCachedValueInfo(Val, BB) &&
"Value should not be in cache");
Optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
if (!Res)
return false;
TheCache.insertResult(Val, BB, *Res);
return true;
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueImpl(
Value *Val, BasicBlock *BB) {
Instruction *BBI = dyn_cast<Instruction>(Val);
if (!BBI || BBI->getParent() != BB)
return solveBlockValueNonLocal(Val, BB);
if (PHINode *PN = dyn_cast<PHINode>(BBI))
return solveBlockValuePHINode(PN, BB);
if (auto *SI = dyn_cast<SelectInst>(BBI))
return solveBlockValueSelect(SI, BB);
PointerType *PT = dyn_cast<PointerType>(BBI->getType());
if (PT && isKnownNonZero(BBI, DL))
return ValueLatticeElement::getNot(ConstantPointerNull::get(PT));
if (BBI->getType()->isIntegerTy()) {
if (auto *CI = dyn_cast<CastInst>(BBI))
return solveBlockValueCast(CI, BB);
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
return solveBlockValueBinaryOp(BO, BB);
if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
return solveBlockValueExtractValue(EVI, BB);
if (auto *II = dyn_cast<IntrinsicInst>(BBI))
return solveBlockValueIntrinsic(II, BB);
}
LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - unknown inst def found.\n");
return getFromRangeMetadata(BBI);
}
static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet) {
if (Ptr->getType()->getPointerAddressSpace() == 0)
PtrSet.insert(getUnderlyingObject(Ptr));
}
static void AddNonNullPointersByInstruction(
Instruction *I, NonNullPointerSet &PtrSet) {
if (LoadInst *L = dyn_cast<LoadInst>(I)) {
AddNonNullPointer(L->getPointerOperand(), PtrSet);
} else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
AddNonNullPointer(S->getPointerOperand(), PtrSet);
} else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
if (MI->isVolatile()) return;
ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
if (!Len || Len->isZero()) return;
AddNonNullPointer(MI->getRawDest(), PtrSet);
if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
AddNonNullPointer(MTI->getRawSource(), PtrSet);
}
}
bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
if (NullPointerIsDefined(BB->getParent(),
Val->getType()->getPointerAddressSpace()))
return false;
Val = Val->stripInBoundsOffsets();
return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
NonNullPointerSet NonNullPointers;
for (Instruction &I : *BB)
AddNonNullPointersByInstruction(&I, NonNullPointers);
return NonNullPointers;
});
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueNonLocal(
Value *Val, BasicBlock *BB) {
ValueLatticeElement Result;
if (BB->isEntryBlock()) {
assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
return ValueLatticeElement::getOverdefined();
}
for (BasicBlock *Pred : predecessors(BB)) {
Optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
if (!EdgeResult)
return None;
Result.mergeIn(*EdgeResult);
if (Result.isOverdefined()) {
LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - overdefined because of pred (non local).\n");
return Result;
}
}
assert(!Result.isOverdefined());
return Result;
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValuePHINode(
PHINode *PN, BasicBlock *BB) {
ValueLatticeElement Result;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
BasicBlock *PhiBB = PN->getIncomingBlock(i);
Value *PhiVal = PN->getIncomingValue(i);
Optional<ValueLatticeElement> EdgeResult =
getEdgeValue(PhiVal, PhiBB, BB, PN);
if (!EdgeResult)
return None;
Result.mergeIn(*EdgeResult);
if (Result.isOverdefined()) {
LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - overdefined because of pred (local).\n");
return Result;
}
}
assert(!Result.isOverdefined() && "Possible PHI in entry block?");
return Result;
}
static ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
bool isTrueDest = true);
void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
if (!BBI)
return;
BasicBlock *BB = BBI->getParent();
for (auto &AssumeVH : AC->assumptionsFor(Val)) {
if (!AssumeVH)
continue;
auto *I = cast<CallInst>(AssumeVH);
if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
continue;
BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
}
if (GuardDecl && !GuardDecl->use_empty() &&
BBI->getIterator() != BB->begin()) {
for (Instruction &I : make_range(std::next(BBI->getIterator().getReverse()),
BB->rend())) {
Value *Cond = nullptr;
if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
}
}
if (BBLV.isOverdefined()) {
PointerType *PTy = dyn_cast<PointerType>(Val->getType());
if (PTy && BB->getTerminator() == BBI &&
isNonNullAtEndOfBlock(Val, BB))
BBLV = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
}
}
static ConstantRange getConstantRangeOrFull(const ValueLatticeElement &Val,
Type *Ty, const DataLayout &DL) {
if (Val.isConstantRange())
return Val.getConstantRange();
return ConstantRange::getFull(DL.getTypeSizeInBits(Ty));
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueSelect(
SelectInst *SI, BasicBlock *BB) {
Optional<ValueLatticeElement> OptTrueVal =
getBlockValue(SI->getTrueValue(), BB, SI);
if (!OptTrueVal)
return None;
ValueLatticeElement &TrueVal = *OptTrueVal;
Optional<ValueLatticeElement> OptFalseVal =
getBlockValue(SI->getFalseValue(), BB, SI);
if (!OptFalseVal)
return None;
ValueLatticeElement &FalseVal = *OptFalseVal;
if (TrueVal.isConstantRange() || FalseVal.isConstantRange()) {
const ConstantRange &TrueCR =
getConstantRangeOrFull(TrueVal, SI->getType(), DL);
const ConstantRange &FalseCR =
getConstantRangeOrFull(FalseVal, SI->getType(), DL);
Value *LHS = nullptr;
Value *RHS = nullptr;
SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
((LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) ||
(RHS == SI->getTrueValue() && LHS == SI->getFalseValue()))) {
ConstantRange ResultCR = [&]() {
switch (SPR.Flavor) {
default:
llvm_unreachable("unexpected minmax type!");
case SPF_SMIN: return TrueCR.smin(FalseCR);
case SPF_UMIN: return TrueCR.umin(FalseCR);
case SPF_SMAX: return TrueCR.smax(FalseCR);
case SPF_UMAX: return TrueCR.umax(FalseCR);
};
}();
return ValueLatticeElement::getRange(
ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
FalseVal.isConstantRangeIncludingUndef());
}
if (SPR.Flavor == SPF_ABS) {
if (LHS == SI->getTrueValue())
return ValueLatticeElement::getRange(
TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
if (LHS == SI->getFalseValue())
return ValueLatticeElement::getRange(
FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
}
if (SPR.Flavor == SPF_NABS) {
ConstantRange Zero(APInt::getZero(TrueCR.getBitWidth()));
if (LHS == SI->getTrueValue())
return ValueLatticeElement::getRange(
Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
if (LHS == SI->getFalseValue())
return ValueLatticeElement::getRange(
Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
}
}
Value *Cond = SI->getCondition();
TrueVal = intersect(TrueVal,
getValueFromCondition(SI->getTrueValue(), Cond, true));
FalseVal = intersect(FalseVal,
getValueFromCondition(SI->getFalseValue(), Cond, false));
ValueLatticeElement Result = TrueVal;
Result.mergeIn(FalseVal);
return Result;
}
Optional<ConstantRange> LazyValueInfoImpl::getRangeFor(Value *V,
Instruction *CxtI,
BasicBlock *BB) {
Optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CxtI);
if (!OptVal)
return None;
return getConstantRangeOrFull(*OptVal, V->getType(), DL);
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueCast(
CastInst *CI, BasicBlock *BB) {
if (!CI->getOperand(0)->getType()->isSized())
return ValueLatticeElement::getOverdefined();
switch (CI->getOpcode()) {
case Instruction::Trunc:
case Instruction::SExt:
case Instruction::ZExt:
case Instruction::BitCast:
break;
default:
LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - overdefined (unknown cast).\n");
return ValueLatticeElement::getOverdefined();
}
Optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
if (!LHSRes)
return None;
const ConstantRange &LHSRange = LHSRes.value();
const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth();
return ValueLatticeElement::getRange(LHSRange.castOp(CI->getOpcode(),
ResultBitWidth));
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
Instruction *I, BasicBlock *BB,
std::function<ConstantRange(const ConstantRange &,
const ConstantRange &)> OpFn) {
Optional<ConstantRange> LHSRes = getRangeFor(I->getOperand(0), I, BB);
Optional<ConstantRange> RHSRes = getRangeFor(I->getOperand(1), I, BB);
if (!LHSRes || !RHSRes)
return None;
const ConstantRange &LHSRange = LHSRes.value();
const ConstantRange &RHSRange = RHSRes.value();
return ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOp(
BinaryOperator *BO, BasicBlock *BB) {
assert(BO->getOperand(0)->getType()->isSized() &&
"all operands to binary operators are sized");
if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
unsigned NoWrapKind = 0;
if (OBO->hasNoUnsignedWrap())
NoWrapKind |= OverflowingBinaryOperator::NoUnsignedWrap;
if (OBO->hasNoSignedWrap())
NoWrapKind |= OverflowingBinaryOperator::NoSignedWrap;
return solveBlockValueBinaryOpImpl(
BO, BB,
[BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
});
}
return solveBlockValueBinaryOpImpl(
BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
return CR1.binaryOp(BO->getOpcode(), CR2);
});
}
Optional<ValueLatticeElement>
LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
BasicBlock *BB) {
return solveBlockValueBinaryOpImpl(
WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
return CR1.binaryOp(WO->getBinaryOp(), CR2);
});
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueIntrinsic(
IntrinsicInst *II, BasicBlock *BB) {
if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - unknown intrinsic.\n");
return getFromRangeMetadata(II);
}
SmallVector<ConstantRange, 2> OpRanges;
for (Value *Op : II->args()) {
Optional<ConstantRange> Range = getRangeFor(Op, II, BB);
if (!Range)
return None;
OpRanges.push_back(*Range);
}
return ValueLatticeElement::getRange(
ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges));
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueExtractValue(
ExtractValueInst *EVI, BasicBlock *BB) {
if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
return solveBlockValueOverflowIntrinsic(WO, BB);
if (Value *V = simplifyExtractValueInst(
EVI->getAggregateOperand(), EVI->getIndices(),
EVI->getModule()->getDataLayout()))
return getBlockValue(V, BB, EVI);
LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - overdefined (unknown extractvalue).\n");
return ValueLatticeElement::getOverdefined();
}
static bool matchICmpOperand(APInt &Offset, Value *LHS, Value *Val,
ICmpInst::Predicate Pred) {
if (LHS == Val)
return true;
const APInt *C;
if (match(LHS, m_Add(m_Specific(Val), m_APInt(C)))) {
Offset = *C;
return true;
}
if (match(Val, m_Add(m_Specific(LHS), m_APInt(C)))) {
Offset = -*C;
return true;
}
if (match(LHS, m_c_Or(m_Specific(Val), m_Value())) &&
(Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE))
return true;
if (match(LHS, m_c_And(m_Specific(Val), m_Value())) &&
(Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE))
return true;
return false;
}
static ValueLatticeElement getValueFromSimpleICmpCondition(
CmpInst::Predicate Pred, Value *RHS, const APInt &Offset) {
ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
true);
if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
RHSRange = ConstantRange(CI->getValue());
else if (Instruction *I = dyn_cast<Instruction>(RHS))
if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
RHSRange = getConstantRangeFromMetadata(*Ranges);
ConstantRange TrueValues =
ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
return ValueLatticeElement::getRange(TrueValues.subtract(Offset));
}
static ValueLatticeElement getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
bool isTrueDest) {
Value *LHS = ICI->getOperand(0);
Value *RHS = ICI->getOperand(1);
CmpInst::Predicate EdgePred =
isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
if (isa<Constant>(RHS)) {
if (ICI->isEquality() && LHS == Val) {
if (EdgePred == ICmpInst::ICMP_EQ)
return ValueLatticeElement::get(cast<Constant>(RHS));
else if (!isa<UndefValue>(RHS))
return ValueLatticeElement::getNot(cast<Constant>(RHS));
}
}
Type *Ty = Val->getType();
if (!Ty->isIntegerTy())
return ValueLatticeElement::getOverdefined();
unsigned BitWidth = Ty->getScalarSizeInBits();
APInt Offset(BitWidth, 0);
if (matchICmpOperand(Offset, LHS, Val, EdgePred))
return getValueFromSimpleICmpCondition(EdgePred, RHS, Offset);
CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(EdgePred);
if (matchICmpOperand(Offset, RHS, Val, SwappedPred))
return getValueFromSimpleICmpCondition(SwappedPred, LHS, Offset);
const APInt *Mask, *C;
if (match(LHS, m_And(m_Specific(Val), m_APInt(Mask))) &&
match(RHS, m_APInt(C))) {
if (EdgePred == ICmpInst::ICMP_EQ) {
KnownBits Known;
Known.Zero = ~*C & *Mask;
Known.One = *C & *Mask;
return ValueLatticeElement::getRange(
ConstantRange::fromKnownBits(Known, false));
}
if (EdgePred == ICmpInst::ICMP_NE && !Mask->isZero() && C->isZero()) {
return ValueLatticeElement::getRange(ConstantRange::getNonEmpty(
APInt::getOneBitSet(BitWidth, Mask->countTrailingZeros()),
APInt::getZero(BitWidth)));
}
}
if (match(LHS, m_CombineOr(m_URem(m_Specific(Val), m_Value()),
m_Trunc(m_Specific(Val)))) &&
match(RHS, m_APInt(C))) {
ConstantRange CR = ConstantRange::makeExactICmpRegion(EdgePred, *C);
if (!CR.isEmptySet())
return ValueLatticeElement::getRange(ConstantRange::getNonEmpty(
CR.getUnsignedMin().zext(BitWidth), APInt(BitWidth, 0)));
}
return ValueLatticeElement::getOverdefined();
}
static ValueLatticeElement getValueFromOverflowCondition(
Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
const APInt *C;
if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
return ValueLatticeElement::getOverdefined();
ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
WO->getBinaryOp(), *C, WO->getNoWrapKind());
if (IsTrueDest)
NWR = NWR.inverse();
return ValueLatticeElement::getRange(NWR);
}
static Optional<ValueLatticeElement>
getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
bool isRevisit,
SmallDenseMap<Value *, ValueLatticeElement> &Visited,
SmallVectorImpl<Value *> &Worklist) {
if (!isRevisit) {
if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
return getValueFromICmpCondition(Val, ICI, isTrueDest);
if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
return getValueFromOverflowCondition(Val, WO, isTrueDest);
}
Value *L, *R;
bool IsAnd;
if (match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))))
IsAnd = true;
else if (match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
IsAnd = false;
else
return ValueLatticeElement::getOverdefined();
auto LV = Visited.find(L);
auto RV = Visited.find(R);
if ((isTrueDest ^ IsAnd) && (LV != Visited.end())) {
ValueLatticeElement V = LV->second;
if (V.isOverdefined())
return V;
if (RV != Visited.end()) {
V.mergeIn(RV->second);
return V;
}
}
if (LV == Visited.end() || RV == Visited.end()) {
assert(!isRevisit);
if (LV == Visited.end())
Worklist.push_back(L);
if (RV == Visited.end())
Worklist.push_back(R);
return None;
}
return intersect(LV->second, RV->second);
}
ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
bool isTrueDest) {
assert(Cond && "precondition");
SmallDenseMap<Value*, ValueLatticeElement> Visited;
SmallVector<Value *> Worklist;
Worklist.push_back(Cond);
do {
Value *CurrentCond = Worklist.back();
auto Iter =
Visited.try_emplace(CurrentCond, ValueLatticeElement::getOverdefined());
bool isRevisit = !Iter.second;
Optional<ValueLatticeElement> Result = getValueFromConditionImpl(
Val, CurrentCond, isTrueDest, isRevisit, Visited, Worklist);
if (Result) {
Visited[CurrentCond] = *Result;
Worklist.pop_back();
}
} while (!Worklist.empty());
auto Result = Visited.find(Cond);
assert(Result != Visited.end());
return Result->second;
}
static bool usesOperand(User *Usr, Value *Op) {
return is_contained(Usr->operands(), Op);
}
static bool isOperationFoldable(User *Usr) {
return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
}
static ValueLatticeElement constantFoldUser(User *Usr, Value *Op,
const APInt &OpConstVal,
const DataLayout &DL) {
assert(isOperationFoldable(Usr) && "Precondition");
Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
if (auto *CI = dyn_cast<CastInst>(Usr)) {
assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
if (auto *C = dyn_cast_or_null<ConstantInt>(
simplifyCastInst(CI->getOpcode(), OpConst,
CI->getDestTy(), DL))) {
return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
}
} else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
bool Op0Match = BO->getOperand(0) == Op;
bool Op1Match = BO->getOperand(1) == Op;
assert((Op0Match || Op1Match) &&
"Operand 0 nor Operand 1 isn't a match");
Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
if (auto *C = dyn_cast_or_null<ConstantInt>(
simplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
}
} else if (isa<FreezeInst>(Usr)) {
assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op");
return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
}
return ValueLatticeElement::getOverdefined();
}
static Optional<ValueLatticeElement> getEdgeValueLocal(Value *Val,
BasicBlock *BBFrom,
BasicBlock *BBTo) {
if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
if (BI->isConditional() &&
BI->getSuccessor(0) != BI->getSuccessor(1)) {
bool isTrueDest = BI->getSuccessor(0) == BBTo;
assert(BI->getSuccessor(!isTrueDest) == BBTo &&
"BBTo isn't a successor of BBFrom");
Value *Condition = BI->getCondition();
if (Condition == Val)
return ValueLatticeElement::get(ConstantInt::get(
Type::getInt1Ty(Val->getContext()), isTrueDest));
ValueLatticeElement Result = getValueFromCondition(Val, Condition,
isTrueDest);
if (!Result.isOverdefined())
return Result;
if (User *Usr = dyn_cast<User>(Val)) {
assert(Result.isOverdefined() && "Result isn't overdefined");
if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
const DataLayout &DL = BBTo->getModule()->getDataLayout();
if (usesOperand(Usr, Condition)) {
APInt ConditionVal(1, isTrueDest ? 1 : 0);
Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
} else {
for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
Value *Op = Usr->getOperand(i);
ValueLatticeElement OpLatticeVal =
getValueFromCondition(Op, Condition, isTrueDest);
if (Optional<APInt> OpConst = OpLatticeVal.asConstantInteger()) {
Result = constantFoldUser(Usr, Op, *OpConst, DL);
break;
}
}
}
}
}
if (!Result.isOverdefined())
return Result;
}
}
if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Value *Condition = SI->getCondition();
if (!isa<IntegerType>(Val->getType()))
return None;
bool ValUsesConditionAndMayBeFoldable = false;
if (Condition != Val) {
if (User *Usr = dyn_cast<User>(Val))
ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
usesOperand(Usr, Condition);
if (!ValUsesConditionAndMayBeFoldable)
return None;
}
assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
"Condition != Val nor Val doesn't use Condition");
bool DefaultCase = SI->getDefaultDest() == BBTo;
unsigned BitWidth = Val->getType()->getIntegerBitWidth();
ConstantRange EdgesVals(BitWidth, DefaultCase);
for (auto Case : SI->cases()) {
APInt CaseValue = Case.getCaseValue()->getValue();
ConstantRange EdgeVal(CaseValue);
if (ValUsesConditionAndMayBeFoldable) {
User *Usr = cast<User>(Val);
const DataLayout &DL = BBTo->getModule()->getDataLayout();
ValueLatticeElement EdgeLatticeVal =
constantFoldUser(Usr, Condition, CaseValue, DL);
if (EdgeLatticeVal.isOverdefined())
return None;
EdgeVal = EdgeLatticeVal.getConstantRange();
}
if (DefaultCase) {
if (Case.getCaseSuccessor() != BBTo && Condition == Val)
EdgesVals = EdgesVals.difference(EdgeVal);
} else if (Case.getCaseSuccessor() == BBTo)
EdgesVals = EdgesVals.unionWith(EdgeVal);
}
return ValueLatticeElement::getRange(std::move(EdgesVals));
}
return None;
}
Optional<ValueLatticeElement> LazyValueInfoImpl::getEdgeValue(
Value *Val, BasicBlock *BBFrom, BasicBlock *BBTo, Instruction *CxtI) {
if (Constant *VC = dyn_cast<Constant>(Val))
return ValueLatticeElement::get(VC);
ValueLatticeElement LocalResult =
getEdgeValueLocal(Val, BBFrom, BBTo)
.value_or(ValueLatticeElement::getOverdefined());
if (hasSingleValue(LocalResult))
return LocalResult;
Optional<ValueLatticeElement> OptInBlock =
getBlockValue(Val, BBFrom, BBFrom->getTerminator());
if (!OptInBlock)
return None;
ValueLatticeElement &InBlock = *OptInBlock;
intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
return intersect(LocalResult, InBlock);
}
ValueLatticeElement LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
Instruction *CxtI) {
LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
<< BB->getName() << "'\n");
assert(BlockValueStack.empty() && BlockValueSet.empty());
Optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CxtI);
if (!OptResult) {
solve();
OptResult = getBlockValue(V, BB, CxtI);
assert(OptResult && "Value not available after solving");
}
ValueLatticeElement Result = *OptResult;
LLVM_DEBUG(dbgs() << " Result = " << Result << "\n");
return Result;
}
ValueLatticeElement LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()
<< "'\n");
if (auto *C = dyn_cast<Constant>(V))
return ValueLatticeElement::get(C);
ValueLatticeElement Result = ValueLatticeElement::getOverdefined();
if (auto *I = dyn_cast<Instruction>(V))
Result = getFromRangeMetadata(I);
intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
LLVM_DEBUG(dbgs() << " Result = " << Result << "\n");
return Result;
}
ValueLatticeElement LazyValueInfoImpl::
getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
Instruction *CxtI) {
LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
<< FromBB->getName() << "' to '" << ToBB->getName()
<< "'\n");
Optional<ValueLatticeElement> Result = getEdgeValue(V, FromBB, ToBB, CxtI);
if (!Result) {
solve();
Result = getEdgeValue(V, FromBB, ToBB, CxtI);
assert(Result && "More work to do after problem solved?");
}
LLVM_DEBUG(dbgs() << " Result = " << *Result << "\n");
return *Result;
}
void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
BasicBlock *NewSucc) {
TheCache.threadEdgeImpl(OldSucc, NewSucc);
}
static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
const Module *M) {
if (!PImpl) {
assert(M && "getCache() called with a null Module");
const DataLayout &DL = M->getDataLayout();
Function *GuardDecl = M->getFunction(
Intrinsic::getName(Intrinsic::experimental_guard));
PImpl = new LazyValueInfoImpl(AC, DL, GuardDecl);
}
return *static_cast<LazyValueInfoImpl*>(PImpl);
}
bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
if (Info.PImpl)
getImpl(Info.PImpl, Info.AC, F.getParent()).clear();
return false;
}
void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<TargetLibraryInfoWrapperPass>();
}
LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
void LazyValueInfo::releaseMemory() {
if (PImpl) {
delete &getImpl(PImpl, AC, nullptr);
PImpl = nullptr;
}
}
bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
FunctionAnalysisManager::Invalidator &Inv) {
auto PAC = PA.getChecker<LazyValueAnalysis>();
if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
return true;
return false;
}
void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
LazyValueInfo LazyValueAnalysis::run(Function &F,
FunctionAnalysisManager &FAM) {
auto &AC = FAM.getResult<AssumptionAnalysis>(F);
auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
return LazyValueInfo(&AC, &F.getParent()->getDataLayout(), &TLI);
}
static bool isKnownNonConstant(Value *V) {
V = V->stripPointerCasts();
if (isa<AllocaInst>(V))
return true;
return false;
}
Constant *LazyValueInfo::getConstant(Value *V, Instruction *CxtI) {
if (isKnownNonConstant(V))
return nullptr;
BasicBlock *BB = CxtI->getParent();
ValueLatticeElement Result =
getImpl(PImpl, AC, BB->getModule()).getValueInBlock(V, BB, CxtI);
if (Result.isConstant())
return Result.getConstant();
if (Result.isConstantRange()) {
const ConstantRange &CR = Result.getConstantRange();
if (const APInt *SingleVal = CR.getSingleElement())
return ConstantInt::get(V->getContext(), *SingleVal);
}
return nullptr;
}
ConstantRange LazyValueInfo::getConstantRange(Value *V, Instruction *CxtI,
bool UndefAllowed) {
assert(V->getType()->isIntegerTy());
unsigned Width = V->getType()->getIntegerBitWidth();
BasicBlock *BB = CxtI->getParent();
ValueLatticeElement Result =
getImpl(PImpl, AC, BB->getModule()).getValueInBlock(V, BB, CxtI);
if (Result.isUnknown())
return ConstantRange::getEmpty(Width);
if (Result.isConstantRange(UndefAllowed))
return Result.getConstantRange(UndefAllowed);
assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
"ConstantInt value must be represented as constantrange");
return ConstantRange::getFull(Width);
}
Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
BasicBlock *ToBB,
Instruction *CxtI) {
Module *M = FromBB->getModule();
ValueLatticeElement Result =
getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
if (Result.isConstant())
return Result.getConstant();
if (Result.isConstantRange()) {
const ConstantRange &CR = Result.getConstantRange();
if (const APInt *SingleVal = CR.getSingleElement())
return ConstantInt::get(V->getContext(), *SingleVal);
}
return nullptr;
}
ConstantRange LazyValueInfo::getConstantRangeOnEdge(Value *V,
BasicBlock *FromBB,
BasicBlock *ToBB,
Instruction *CxtI) {
unsigned Width = V->getType()->getIntegerBitWidth();
Module *M = FromBB->getModule();
ValueLatticeElement Result =
getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
if (Result.isUnknown())
return ConstantRange::getEmpty(Width);
if (Result.isConstantRange())
return Result.getConstantRange();
assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
"ConstantInt value must be represented as constantrange");
return ConstantRange::getFull(Width);
}
static LazyValueInfo::Tristate
getPredicateResult(unsigned Pred, Constant *C, const ValueLatticeElement &Val,
const DataLayout &DL, TargetLibraryInfo *TLI) {
Constant *Res = nullptr;
if (Val.isConstant()) {
Res = ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL, TLI);
if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
return LazyValueInfo::Unknown;
}
if (Val.isConstantRange()) {
ConstantInt *CI = dyn_cast<ConstantInt>(C);
if (!CI) return LazyValueInfo::Unknown;
const ConstantRange &CR = Val.getConstantRange();
if (Pred == ICmpInst::ICMP_EQ) {
if (!CR.contains(CI->getValue()))
return LazyValueInfo::False;
if (CR.isSingleElement())
return LazyValueInfo::True;
} else if (Pred == ICmpInst::ICMP_NE) {
if (!CR.contains(CI->getValue()))
return LazyValueInfo::True;
if (CR.isSingleElement())
return LazyValueInfo::False;
} else {
ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
(ICmpInst::Predicate)Pred, CI->getValue());
if (TrueValues.contains(CR))
return LazyValueInfo::True;
if (TrueValues.inverse().contains(CR))
return LazyValueInfo::False;
}
return LazyValueInfo::Unknown;
}
if (Val.isNotConstant()) {
if (Pred == ICmpInst::ICMP_EQ) {
Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Val.getNotConstant(), C, DL,
TLI);
if (Res->isNullValue())
return LazyValueInfo::False;
} else if (Pred == ICmpInst::ICMP_NE) {
Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Val.getNotConstant(), C, DL,
TLI);
if (Res->isNullValue())
return LazyValueInfo::True;
}
return LazyValueInfo::Unknown;
}
return LazyValueInfo::Unknown;
}
LazyValueInfo::Tristate
LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
BasicBlock *FromBB, BasicBlock *ToBB,
Instruction *CxtI) {
Module *M = FromBB->getModule();
ValueLatticeElement Result =
getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
return getPredicateResult(Pred, C, Result, M->getDataLayout(), TLI);
}
LazyValueInfo::Tristate
LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
Instruction *CxtI, bool UseBlockValue) {
Module *M = CxtI->getModule();
const DataLayout &DL = M->getDataLayout();
if (V->getType()->isPointerTy() && C->isNullValue() &&
isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
if (Pred == ICmpInst::ICMP_EQ)
return LazyValueInfo::False;
else if (Pred == ICmpInst::ICMP_NE)
return LazyValueInfo::True;
}
ValueLatticeElement Result = UseBlockValue
? getImpl(PImpl, AC, M).getValueInBlock(V, CxtI->getParent(), CxtI)
: getImpl(PImpl, AC, M).getValueAt(V, CxtI);
Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
if (Ret != Unknown)
return Ret;
BasicBlock *BB = CxtI->getParent();
pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
if (PI == PE)
return Unknown;
if (auto *PHI = dyn_cast<PHINode>(V))
if (PHI->getParent() == BB) {
Tristate Baseline = Unknown;
for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
Value *Incoming = PHI->getIncomingValue(i);
BasicBlock *PredBB = PHI->getIncomingBlock(i);
Tristate Result =
getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, CxtI);
Baseline = (i == 0) ? Result
: (Baseline == Result ? Baseline
: Unknown);
if (Baseline == Unknown)
break;
}
if (Baseline != Unknown)
return Baseline;
}
if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB) {
Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
if (Baseline != Unknown) {
while (++PI != PE) {
Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
if (Ret != Baseline)
break;
}
if (PI == PE) {
return Baseline;
}
}
}
return Unknown;
}
LazyValueInfo::Tristate LazyValueInfo::getPredicateAt(unsigned P, Value *LHS,
Value *RHS,
Instruction *CxtI,
bool UseBlockValue) {
CmpInst::Predicate Pred = (CmpInst::Predicate)P;
if (auto *C = dyn_cast<Constant>(RHS))
return getPredicateAt(P, LHS, C, CxtI, UseBlockValue);
if (auto *C = dyn_cast<Constant>(LHS))
return getPredicateAt(CmpInst::getSwappedPredicate(Pred), RHS, C, CxtI,
UseBlockValue);
return LazyValueInfo::Unknown;
}
void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
BasicBlock *NewSucc) {
if (PImpl) {
getImpl(PImpl, AC, PredBB->getModule())
.threadEdge(PredBB, OldSucc, NewSucc);
}
}
void LazyValueInfo::eraseBlock(BasicBlock *BB) {
if (PImpl) {
getImpl(PImpl, AC, BB->getModule()).eraseBlock(BB);
}
}
void LazyValueInfo::clear(const Module *M) {
if (PImpl) {
getImpl(PImpl, AC, M).clear();
}
}
void LazyValueInfo::printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
if (PImpl) {
getImpl(PImpl, AC, F.getParent()).printLVI(F, DTree, OS);
}
}
void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
const BasicBlock *BB, formatted_raw_ostream &OS) {
auto *F = BB->getParent();
for (const auto &Arg : F->args()) {
ValueLatticeElement Result = LVIImpl->getValueInBlock(
const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
if (Result.isUnknown())
continue;
OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
}
}
void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
const Instruction *I, formatted_raw_ostream &OS) {
auto *ParentBB = I->getParent();
SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
auto printResult = [&](const BasicBlock *BB) {
if (!BlocksContainingLVI.insert(BB).second)
return;
ValueLatticeElement Result = LVIImpl->getValueInBlock(
const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
OS << "; LatticeVal for: '" << *I << "' in BB: '";
BB->printAsOperand(OS, false);
OS << "' is: " << Result << "\n";
};
printResult(ParentBB);
for (const auto *BBSucc : successors(ParentBB))
if (DT.dominates(ParentBB, BBSucc))
printResult(BBSucc);
for (const auto *U : I->users())
if (auto *UseI = dyn_cast<Instruction>(U))
if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
printResult(UseI->getParent());
}
namespace {
class LazyValueInfoPrinter : public FunctionPass {
public:
static char ID; LazyValueInfoPrinter() : FunctionPass(ID) {
initializeLazyValueInfoPrinterPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
AU.addRequired<LazyValueInfoWrapperPass>();
AU.addRequired<DominatorTreeWrapperPass>();
}
bool runOnFunction(Function &F) override {
dbgs() << "LVI for function '" << F.getName() << "':\n";
auto &LVI = getAnalysis<LazyValueInfoWrapperPass>().getLVI();
auto &DTree = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
LVI.printLVI(F, DTree, dbgs());
return false;
}
};
}
char LazyValueInfoPrinter::ID = 0;
INITIALIZE_PASS_BEGIN(LazyValueInfoPrinter, "print-lazy-value-info",
"Lazy Value Info Printer Pass", false, false)
INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
INITIALIZE_PASS_END(LazyValueInfoPrinter, "print-lazy-value-info",
"Lazy Value Info Printer Pass", false, false)