40 using namespace PatternMatch;
42 #define DEBUG_TYPE "lazy-value-info"
50 "Lazy Value Information Analysis",
false,
true)
104 LVILatticeVal() :
Tag(undefined), Val(nullptr), Range(1,
true) {}
108 if (!isa<UndefValue>(
C))
112 static LVILatticeVal getNot(
Constant *
C) {
114 if (!isa<UndefValue>(C))
115 Res.markNotConstant(C);
120 Res.markConstantRange(std::move(CR));
123 static LVILatticeVal getOverdefined() {
125 Res.markOverdefined();
129 bool isUndefined()
const {
return Tag == undefined; }
131 bool isNotConstant()
const {
return Tag == notconstant; }
132 bool isConstantRange()
const {
return Tag == constantrange; }
133 bool isOverdefined()
const {
return Tag == overdefined; }
141 assert(isNotConstant() &&
"Cannot get the constant of a non-notconstant!");
146 assert(isConstantRange() &&
147 "Cannot get the constant-range of a non-constant-range!");
152 void markOverdefined() {
159 assert(V &&
"Marking constant with NULL");
164 if (isa<UndefValue>(V))
168 "Marking constant with different value");
175 assert(V &&
"Marking constant with NULL");
177 markConstantRange(
ConstantRange(CI->getValue()+1, CI->getValue()));
180 if (isa<UndefValue>(V))
184 "Marking constant !constant with same value");
185 assert((!isNotConstant() || getNotConstant() == V) &&
186 "Marking !constant with different value");
193 if (isConstantRange()) {
197 Range = std::move(NewR);
207 Range = std::move(NewR);
215 void mergeIn(
const LVILatticeVal &RHS,
const DataLayout &DL) {
216 if (RHS.isUndefined() || isOverdefined())
218 if (RHS.isOverdefined()) {
229 if (RHS.isConstant() && Val == RHS.Val)
235 if (isNotConstant()) {
236 if (RHS.isNotConstant() && Val == RHS.Val)
242 assert(isConstantRange() &&
"New LVILattice type?");
243 if (!RHS.isConstantRange()) {
253 markConstantRange(std::move(NewR));
263 if (Val.isUndefined())
264 return OS <<
"undefined";
265 if (Val.isOverdefined())
266 return OS <<
"overdefined";
268 if (Val.isNotConstant())
269 return OS <<
"notconstant<" << *Val.getNotConstant() <<
'>';
270 if (Val.isConstantRange())
271 return OS <<
"constantrange<" << Val.getConstantRange().getLower() <<
", "
272 << Val.getConstantRange().getUpper() <<
'>';
273 return OS <<
"constant<" << *Val.getConstant() <<
'>';
281 if (Val.isConstantRange() &&
282 Val.getConstantRange().isSingleElement())
285 if (Val.isConstant())
305 static LVILatticeVal
intersect(
const LVILatticeVal &
A,
const LVILatticeVal &
B) {
314 if (A.isOverdefined())
316 if (B.isOverdefined())
326 if (!A.isConstantRange() || !B.isConstantRange()) {
333 A.getConstantRange().intersectWith(B.getConstantRange());
337 return LVILatticeVal::getRange(std::move(Range));
346 class LazyValueInfoCache;
347 struct LVIValueHandle final :
public CallbackVH {
351 LazyValueInfoCache *Parent;
353 LVIValueHandle(
Value *V, LazyValueInfoCache *
P)
356 void deleted()
override;
357 void allUsesReplacedWith(
Value *V)
override {
366 class LazyValueInfoCache {
372 struct ValueCacheEntryTy {
373 ValueCacheEntryTy(
Value *V, LazyValueInfoCache *
P) : Handle(V, P) {}
374 LVIValueHandle Handle;
389 OverDefinedCacheTy OverDefinedCache;
393 void insertResult(
Value *Val,
BasicBlock *BB,
const LVILatticeVal &Result) {
398 if (Result.isOverdefined())
399 OverDefinedCache[BB].insert(Val);
401 auto It = ValueCache.find_as(Val);
402 if (It == ValueCache.end()) {
403 ValueCache[Val] = make_unique<ValueCacheEntryTy>(Val,
this);
404 It = ValueCache.find_as(Val);
405 assert(It != ValueCache.end() &&
"Val was just added to the map!");
407 It->second->BlockVals[BB] = Result;
412 auto ODI = OverDefinedCache.find(BB);
414 if (ODI == OverDefinedCache.end())
417 return ODI->second.count(V);
421 if (isOverdefined(V, BB))
424 auto I = ValueCache.find_as(V);
425 if (
I == ValueCache.end())
428 return I->second->BlockVals.count(BB);
432 if (isOverdefined(V, BB))
433 return LVILatticeVal::getOverdefined();
435 auto I = ValueCache.find_as(V);
436 if (
I == ValueCache.end())
437 return LVILatticeVal();
438 auto BBI =
I->second->BlockVals.find(BB);
439 if (BBI ==
I->second->BlockVals.end())
440 return LVILatticeVal();
448 OverDefinedCache.clear();
452 void eraseValue(
Value *V);
463 friend struct LVIValueHandle;
467 void LazyValueInfoCache::eraseValue(
Value *V) {
468 for (
auto I = OverDefinedCache.begin(),
E = OverDefinedCache.end();
I !=
E;) {
474 if (ValueSet.
empty())
475 OverDefinedCache.erase(Iter);
481 void LVIValueHandle::deleted() {
484 Parent->eraseValue(*
this);
487 void LazyValueInfoCache::eraseBlock(
BasicBlock *BB) {
490 if (I == SeenBlocks.
end())
494 auto ODI = OverDefinedCache.find(BB);
495 if (ODI != OverDefinedCache.end())
496 OverDefinedCache.erase(ODI);
498 for (
auto &I : ValueCache)
499 I.second->BlockVals.
erase(BB);
502 void LazyValueInfoCache::threadEdgeImpl(
BasicBlock *OldSucc,
514 std::vector<BasicBlock*> worklist;
515 worklist.push_back(OldSucc);
517 auto I = OverDefinedCache.
find(OldSucc);
518 if (I == OverDefinedCache.
end())
526 while (!worklist.empty()) {
531 if (ToUpdate == NewSucc)
continue;
534 auto OI = OverDefinedCache.find(ToUpdate);
535 if (OI == OverDefinedCache.end())
539 bool changed =
false;
540 for (
Value *V : ValsToClear) {
541 if (!ValueSet.
erase(V))
548 if (ValueSet.
empty()) {
549 OverDefinedCache.erase(OI);
554 if (!changed)
continue;
564 class LazyValueInfoImpl;
566 LazyValueInfoImpl *LVIImpl;
574 LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *
L,
DominatorTree &DTree)
575 : LVIImpl(L), DT(DTree) {}
577 virtual void emitBasicBlockStartAnnot(
const BasicBlock *BB,
580 virtual void emitInstructionAnnot(
const Instruction *I,
588 class LazyValueInfoImpl {
591 LazyValueInfoCache TheCache;
603 bool pushBlockValue(
const std::pair<BasicBlock *, Value *> &BV) {
604 if (!BlockValueSet.insert(BV).second)
607 DEBUG(
dbgs() <<
"PUSH: " << *BV.second <<
" in " << BV.first->getName()
609 BlockValueStack.push_back(BV);
619 LVILatticeVal &Result,
Instruction *CxtI =
nullptr);
626 bool solveBlockValueImpl(LVILatticeVal &Res,
Value *Val,
BasicBlock *BB);
627 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
Value *Val,
BasicBlock *BB);
629 bool solveBlockValueSelect(LVILatticeVal &BBLV,
SelectInst *S,
631 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV,
BinaryOperator *BBI,
633 bool solveBlockValueCast(LVILatticeVal &BBLV,
CastInst *CI,
635 void intersectAssumeOrGuardBlockValueConstantRange(
Value *Val,
664 LazyValueInfoAnnotatedWriter Writer(
this, DTree);
665 F.
print(OS, &Writer);
671 TheCache.eraseBlock(BB);
680 : AC(AC), DL(DL), DT(DT) {}
687 BlockValueStack.begin(), BlockValueStack.end());
689 unsigned processedCount = 0;
690 while (!BlockValueStack.empty()) {
701 DEBUG(
dbgs() <<
"Giving up on stack because we are getting too deep\n");
703 while (!StartingStack.empty()) {
704 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
705 TheCache.insertResult(e.second, e.first,
706 LVILatticeVal::getOverdefined());
707 StartingStack.pop_back();
709 BlockValueSet.clear();
710 BlockValueStack.clear();
713 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
714 assert(BlockValueSet.count(e) &&
"Stack value should be in BlockValueSet!");
716 if (solveBlockValue(e.second, e.first)) {
718 assert(BlockValueStack.back() == e &&
"Nothing should have been pushed!");
719 assert(TheCache.hasCachedValueInfo(e.second, e.first) &&
720 "Result should be in cache!");
722 DEBUG(
dbgs() <<
"POP " << *e.second <<
" in " << e.first->getName()
723 <<
" = " << TheCache.getCachedValueInfo(e.second, e.first) <<
"\n");
725 BlockValueStack.pop_back();
726 BlockValueSet.erase(e);
729 assert(BlockValueStack.back() != e &&
"Stack should have been pushed!");
736 if (isa<Constant>(Val))
739 return TheCache.hasCachedValueInfo(Val, BB);
742 LVILatticeVal LazyValueInfoImpl::getBlockValue(
Value *Val,
BasicBlock *BB) {
745 return LVILatticeVal::get(
VC);
747 return TheCache.getCachedValueInfo(Val, BB);
755 case Instruction::Invoke:
757 if (isa<IntegerType>(BBI->
getType())) {
763 return LVILatticeVal::getOverdefined();
767 if (isa<Constant>(Val))
770 if (TheCache.hasCachedValueInfo(Val, BB)) {
773 <<
"' val=" << TheCache.getCachedValueInfo(Val, BB) <<
'\n');
784 if (!solveBlockValueImpl(Res, Val, BB))
788 TheCache.insertResult(Val, BB, Res);
792 bool LazyValueInfoImpl::solveBlockValueImpl(LVILatticeVal &Res,
797 return solveBlockValueNonLocal(Res, Val, BB);
799 if (
PHINode *PN = dyn_cast<PHINode>(BBI))
800 return solveBlockValuePHINode(Res, PN, BB);
802 if (
auto *SI = dyn_cast<SelectInst>(BBI))
803 return solveBlockValueSelect(Res, SI, BB);
820 if (
auto *CI = dyn_cast<CastInst>(BBI))
821 return solveBlockValueCast(Res, CI, BB);
824 if (BO && isa<ConstantInt>(BO->
getOperand(1)))
825 return solveBlockValueBinaryOp(Res, BO, BB);
829 <<
"' - unknown inst def found.\n");
835 if (
LoadInst *
L = dyn_cast<LoadInst>(I)) {
836 return L->getPointerAddressSpace() == 0 &&
838 L->getModule()->getDataLayout()) == Ptr;
840 if (
StoreInst *S = dyn_cast<StoreInst>(I)) {
841 return S->getPointerAddressSpace() == 0 &&
843 S->getModule()->getDataLayout()) == Ptr;
846 if (
MI->isVolatile())
return false;
850 if (!Len || Len->
isZero())
return false;
852 if (
MI->getDestAddressSpace() == 0)
854 MI->getModule()->getDataLayout()) == Ptr)
857 if (MTI->getSourceAddressSpace() == 0)
859 MTI->getModule()->getDataLayout()) == Ptr)
883 bool LazyValueInfoImpl::solveBlockValueNonLocal(LVILatticeVal &BBLV,
885 LVILatticeVal Result;
890 assert(isa<Argument>(Val) &&
"Unknown live-in to the entry block");
898 Result = LVILatticeVal::getOverdefined();
914 LVILatticeVal EdgeResult;
915 if (!getEdgeValue(Val, *PI, BB, EdgeResult))
919 Result.mergeIn(EdgeResult, DL);
923 if (Result.isOverdefined()) {
925 <<
"' - overdefined because of pred (non local).\n");
940 assert(!Result.isOverdefined());
945 bool LazyValueInfoImpl::solveBlockValuePHINode(LVILatticeVal &BBLV,
947 LVILatticeVal Result;
955 LVILatticeVal EdgeResult;
959 if (!getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN))
963 Result.mergeIn(EdgeResult, DL);
967 if (Result.isOverdefined()) {
969 <<
"' - overdefined because of pred (local).\n");
977 assert(!Result.isOverdefined() &&
"Possible PHI in entry block?");
983 bool isTrueDest =
true);
987 void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
993 for (
auto &AssumeVH : AC->assumptionsFor(Val)) {
996 auto *I = cast<CallInst>(AssumeVH);
1006 if (!GuardDecl || GuardDecl->use_empty())
1011 Value *Cond =
nullptr;
1012 if (
match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
m_Value(Cond))))
1017 bool LazyValueInfoImpl::solveBlockValueSelect(LVILatticeVal &BBLV,
1022 if (pushBlockValue(std::make_pair(BB, SI->
getTrueValue())))
1024 BBLV = LVILatticeVal::getOverdefined();
1027 LVILatticeVal TrueVal = getBlockValue(SI->
getTrueValue(), BB);
1030 if (TrueVal.isOverdefined()) {
1031 BBLV = LVILatticeVal::getOverdefined();
1036 if (pushBlockValue(std::make_pair(BB, SI->
getFalseValue())))
1038 BBLV = LVILatticeVal::getOverdefined();
1041 LVILatticeVal FalseVal = getBlockValue(SI->
getFalseValue(), BB);
1044 if (FalseVal.isOverdefined()) {
1045 BBLV = LVILatticeVal::getOverdefined();
1049 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
1052 Value *LHS =
nullptr;
1053 Value *RHS =
nullptr;
1064 return TrueCR.
smin(FalseCR);
1066 return TrueCR.
umin(FalseCR);
1068 return TrueCR.
smax(FalseCR);
1070 return TrueCR.
umax(FalseCR);
1073 BBLV = LVILatticeVal::getRange(ResultCR);
1097 if (
auto *ICI = dyn_cast<ICmpInst>(Cond)) {
1099 Value *
A = ICI->getOperand(0);
1100 if (
ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
1114 auto ResNot = addConstants(CIBase, CIAdded);
1116 LVILatticeVal::getNot(ResNot));
1122 auto ResNot = addConstants(CIBase, CIAdded);
1124 LVILatticeVal::getNot(ResNot));
1131 LVILatticeVal Result;
1132 Result.mergeIn(TrueVal, DL);
1133 Result.mergeIn(FalseVal, DL);
1138 bool LazyValueInfoImpl::solveBlockValueCast(LVILatticeVal &BBLV,
1144 BBLV = LVILatticeVal::getOverdefined();
1152 case Instruction::Trunc:
1153 case Instruction::SExt:
1154 case Instruction::ZExt:
1155 case Instruction::BitCast:
1160 <<
"' - overdefined (unknown cast).\n");
1161 BBLV = LVILatticeVal::getOverdefined();
1169 if (pushBlockValue(std::make_pair(BB, CI->
getOperand(0))))
1173 const unsigned OperandBitWidth =
1177 LVILatticeVal LHSVal = getBlockValue(CI->
getOperand(0), BB);
1178 intersectAssumeOrGuardBlockValueConstantRange(CI->
getOperand(0), LHSVal,
1180 if (LHSVal.isConstantRange())
1181 LHSRange = LHSVal.getConstantRange();
1194 bool LazyValueInfoImpl::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
1199 "all operands to binary operators are sized");
1206 case Instruction::Sub:
1207 case Instruction::Mul:
1208 case Instruction::UDiv:
1209 case Instruction::Shl:
1210 case Instruction::LShr:
1211 case Instruction::And:
1212 case Instruction::Or:
1218 <<
"' - overdefined (unknown binary operator).\n");
1219 BBLV = LVILatticeVal::getOverdefined();
1227 if (pushBlockValue(std::make_pair(BB, BO->
getOperand(0))))
1231 const unsigned OperandBitWidth =
1235 LVILatticeVal LHSVal = getBlockValue(BO->
getOperand(0), BB);
1236 intersectAssumeOrGuardBlockValueConstantRange(BO->
getOperand(0), LHSVal,
1238 if (LHSVal.isConstantRange())
1239 LHSRange = LHSVal.getConstantRange();
1249 BBLV = LVILatticeVal::getRange(LHSRange.
binaryOp(BinOp, RHSRange));
1259 if (isa<Constant>(RHS)) {
1264 return LVILatticeVal::get(cast<Constant>(RHS));
1266 return LVILatticeVal::getNot(cast<Constant>(RHS));
1271 return LVILatticeVal::getOverdefined();
1291 if (LHS == Val || Offset) {
1297 else if (
Instruction *I = dyn_cast<Instruction>(RHS))
1310 return LVILatticeVal::getRange(std::move(TrueValues));
1313 return LVILatticeVal::getOverdefined();
1316 static LVILatticeVal
1320 static LVILatticeVal
1323 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1331 if (!BO || (isTrueDest && BO->
getOpcode() != BinaryOperator::And) ||
1332 (!isTrueDest && BO->
getOpcode() != BinaryOperator::Or))
1333 return LVILatticeVal::getOverdefined();
1340 static LVILatticeVal
1343 auto I = Visited.
find(Cond);
1344 if (I != Visited.
end())
1348 Visited[Cond] = Result;
1353 assert(Cond &&
"precondition");
1368 if (BI->isConditional() &&
1369 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1370 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1371 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1372 "BBTo isn't a successor of BBFrom");
1376 if (BI->getCondition() == Val) {
1385 if (!Result.isOverdefined())
1396 bool DefaultCase = SI->getDefaultDest() == BBTo;
1400 for (
auto Case : SI->cases()) {
1405 if (Case.getCaseSuccessor() != BBTo)
1407 }
else if (Case.getCaseSuccessor() == BBTo)
1408 EdgesVals = EdgesVals.
unionWith(EdgeVal);
1410 Result = LVILatticeVal::getRange(std::move(EdgesVals));
1422 if (
Constant *
VC = dyn_cast<Constant>(Val)) {
1423 Result = LVILatticeVal::get(
VC);
1427 LVILatticeVal LocalResult;
1431 LocalResult = LVILatticeVal::getOverdefined();
1435 Result = LocalResult;
1439 if (!hasBlockValue(Val, BBFrom)) {
1440 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1443 Result = LocalResult;
1448 LVILatticeVal
InBlock = getBlockValue(Val, BBFrom);
1449 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock,
1459 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
1461 Result =
intersect(LocalResult, InBlock);
1465 LVILatticeVal LazyValueInfoImpl::getValueInBlock(
Value *V,
BasicBlock *BB,
1467 DEBUG(
dbgs() <<
"LVI Getting block end value " << *V <<
" at '"
1470 assert(BlockValueStack.empty() && BlockValueSet.empty());
1471 if (!hasBlockValue(V, BB)) {
1472 pushBlockValue(std::make_pair(BB, V));
1475 LVILatticeVal Result = getBlockValue(V, BB);
1476 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1478 DEBUG(
dbgs() <<
" Result = " << Result <<
"\n");
1483 DEBUG(
dbgs() <<
"LVI Getting value " << *V <<
" at '"
1486 if (
auto *C = dyn_cast<Constant>(V))
1487 return LVILatticeVal::get(C);
1489 LVILatticeVal Result = LVILatticeVal::getOverdefined();
1490 if (
auto *I = dyn_cast<Instruction>(V))
1492 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1494 DEBUG(
dbgs() <<
" Result = " << Result <<
"\n");
1498 LVILatticeVal LazyValueInfoImpl::
1501 DEBUG(
dbgs() <<
"LVI Getting edge value " << *V <<
" from '"
1504 LVILatticeVal Result;
1505 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
1507 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1509 assert(WasFastQuery &&
"More work to do after problem solved?");
1512 DEBUG(
dbgs() <<
" Result = " << Result <<
"\n");
1518 TheCache.threadEdgeImpl(OldSucc, NewSucc);
1530 assert(DL &&
"getCache() called with a null DataLayout");
1531 PImpl =
new LazyValueInfoImpl(AC, *DL, DT);
1533 return *
static_cast<LazyValueInfoImpl*
>(PImpl);
1537 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1541 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1542 Info.DT = DTWP ? &DTWP->
getDomTree() :
nullptr;
1543 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1546 getImpl(Info.PImpl, Info.AC, &DL, Info.DT).clear();
1565 delete &
getImpl(PImpl, AC,
nullptr);
1601 if (isa<AllocaInst>(V))
1613 LVILatticeVal Result =
1614 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1616 if (Result.isConstant())
1617 return Result.getConstant();
1618 if (Result.isConstantRange()) {
1631 LVILatticeVal Result =
1632 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1633 if (Result.isUndefined())
1635 if (Result.isConstantRange())
1636 return Result.getConstantRange();
1639 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1640 "ConstantInt value must be represented as constantrange");
1650 LVILatticeVal Result =
1651 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1653 if (Result.isConstant())
1654 return Result.getConstant();
1655 if (Result.isConstantRange()) {
1669 LVILatticeVal Result =
1670 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1672 if (Result.isUndefined())
1674 if (Result.isConstantRange())
1675 return Result.getConstantRange();
1678 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1679 "ConstantInt value must be represented as constantrange");
1684 const LVILatticeVal &Val,
1690 if (Val.isConstant()) {
1692 if (
ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1697 if (Val.isConstantRange()) {
1726 if (Val.isNotConstant()) {
1732 Val.getNotConstant(),
C, DL,
1739 Val.getNotConstant(),
C, DL,
1757 LVILatticeVal Result =
1758 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1778 LVILatticeVal Result =
getImpl(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
1818 if (
auto *PHI = dyn_cast<PHINode>(V))
1819 if (PHI->getParent() == BB) {
1821 for (
unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1822 Value *Incoming = PHI->getIncomingValue(i);
1823 BasicBlock *PredBB = PHI->getIncomingBlock(i);
1825 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1830 Baseline = (i == 0) ? Result
1831 : (Baseline == Result ? Baseline : Unknown);
1832 if (Baseline == Unknown)
1835 if (Baseline != Unknown)
1842 if (!isa<Instruction>(V) ||
1843 cast<Instruction>(V)->
getParent() != BB) {
1847 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1848 if (Baseline != Unknown) {
1850 while (++PI != PE) {
1851 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1852 if (Ret != Baseline)
break;
1868 getImpl(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1875 getImpl(PImpl, AC, &DL, DT).eraseBlock(BB);
1882 getImpl(PImpl, AC, DL, DT).printLVI(F, DTree, OS);
1887 void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
1891 for (
auto &Arg :
F->args()) {
1892 LVILatticeVal Result = LVIImpl->getValueInBlock(
1893 const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
1894 if (Result.isUndefined())
1896 OS <<
"; LatticeVal for: '" << Arg <<
"' is: " << Result <<
"\n";
1904 void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
1914 auto printResult = [&](
const BasicBlock *BB) {
1915 if (!BlocksContainingLVI.
insert(BB).second)
1917 LVILatticeVal Result = LVIImpl->getValueInBlock(
1918 const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
1919 OS <<
"; LatticeVal for: '" << *I <<
"' in BB: '";
1921 OS <<
"' is: " << Result <<
"\n";
1924 printResult(ParentBB);
1928 if (DT.dominates(ParentBB, BBSucc))
1929 printResult(BBSucc);
1932 for (
auto *U : I->users())
1933 if (
auto *UseI = dyn_cast<Instruction>(U))
1934 if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
1935 printResult(UseI->getParent());
1956 bool runOnFunction(
Function &
F)
override {
1957 dbgs() <<
"LVI for function '" << F.
getName() <<
"':\n";
1958 auto &LVI = getAnalysis<LazyValueInfoWrapperPass>().getLVI();
1959 auto &DTree = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1960 LVI.printLVI(F, DTree,
dbgs());
1968 "Lazy Value Info Printer Pass",
false,
false)
Pass interface - Implemented by all 'passes'.
A parsed version of the target data layout string in and methods for querying it. ...
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr)
static bool isConstant(const MachineInstr &MI)
static IntegerType * getInt1Ty(LLVMContext &C)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
ConstantRange getConstantRange(Value *V, BasicBlock *BB, Instruction *CxtI=nullptr)
Return the ConstantRange constraint that is known to hold for the specified value at the end of the s...
const Instruction & back() const
Wrapper around LazyValueInfo.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
Implements a dense probed hash-table based set.
ilist_iterator< OptionsT,!IsReverse, IsConst > getReverse() const
Get a reverse iterator to the same node.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of .assume calls within a function.
bool erase(const ValueT &V)
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr)
Return true if it is valid to use the assumptions provided by an assume intrinsic, I, at the point in the control-flow identified by the context instruction, CxtI.
bool isSingleElement() const
Return true if this set contains exactly one member.
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
print alias Alias Set Printer
static const unsigned MaxProcessedPerValue
ConstantRange smax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed maximum of a value in thi...
StringRef getName() const
Return a constant reference to the value's name.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
bool match(Val *V, const Pattern &P)
static LVILatticeVal getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest=true)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Constant * getConstant(Value *V, BasicBlock *BB, Instruction *CxtI=nullptr)
Determine whether the specified value is known to be a constant at the end of the specified block...
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
This class represents the LLVM 'select' instruction.
This is the base class for all instructions that perform data casts.
const APInt & getValue() const
Return the constant as an APInt value reference.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C, const LVILatticeVal &Val, const DataLayout &DL, TargetLibraryInfo *TLI)
lazy value Lazy Value Information false
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
lazy value Lazy Value Information Analysis
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Result run(Function &F, FunctionAnalysisManager &FAM)
static LVILatticeVal intersect(const LVILatticeVal &A, const LVILatticeVal &B)
Combine two sets of facts about the same value into a single set of facts.
DominatorTree & getDomTree()
static bool isKnownNonConstant(Value *V)
Returns true if we can statically tell that this value will never be a "useful" constant.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom, BasicBlock *BBTo, LVILatticeVal &Result)
Compute the value of Val on the edge BBFrom -> BBTo.
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
ConstantRange unionWith(const ConstantRange &CR) const
Return the range that results from the union of this range with another range.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
An instruction for storing to memory.
ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
FunctionPass * createLazyValueInfoPass()
createLazyValueInfoPass - This creates an instance of the LazyValueInfo pass.
static LVILatticeVal getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest, DenseMap< Value *, LVILatticeVal > &Visited)
Class to represent pointers.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Interval::succ_iterator succ_end(Interval *I)
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
iterator find(const_arg_type_t< KeyT > Val)
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
A set of analyses that are preserved following a run of a transformation pass.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Constant * getConstantOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Determine whether the specified value is known to be a constant on the specified edge.
bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type. ...
ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM Basic Block Representation.
static LVILatticeVal getFromRangeMetadata(Instruction *BBI)
Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
const Value * getCondition() const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation events in the new pass manager.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
static bool hasSingleValue(const LVILatticeVal &Val)
Returns true if this lattice value represents at most one possible value.
ConstantRange castOp(Instruction::CastOps CastOp, uint32_t BitWidth) const
Return a new range representing the possible values resulting from an application of the specified ca...
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
ConstantRange binaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other) const
Return a new range representing the possible values resulting from an application of the specified bi...
FunctionPass class - This class is used to implement most global optimizations.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Value * getOperand(unsigned i) const
Interval::pred_iterator pred_end(Interval *I)
self_iterator getIterator()
unsigned getIntegerBitWidth() const
Predicate getPredicate() const
Return the predicate for this instruction.
LLVM_NODISCARD bool empty() const
bool isEmptySet() const
Return true if this set contains no members.
ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
bool isPointerTy() const
True if this is an instance of PointerType.
LLVMContext & getContext() const
All values hold a context through their type.
const Value * getTrueValue() const
Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCompareInstOperands - Attempt to constant fold a compare instruction (icmp/fcmp) with the...
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
Tristate
This is used to return true/false/dunno results.
Tristate getPredicateOnEdge(unsigned Pred, Value *V, Constant *C, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Determine whether the specified value comparison with a constant is known to be true or false on the ...
Tristate getPredicateAt(unsigned Pred, Value *V, Constant *C, Instruction *CxtI)
Determine whether the specified value comparison with a constant is known to be true or false at the ...
A function analysis which provides an AssumptionCache.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
BinaryOps getOpcode() const
This is the common base class for memset/memcpy/memmove.
static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
SelectPatternFlavor Flavor
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
ConstantRange inverse() const
Return a new range that is the logical not of the current set.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
Provides information about what library functions are available for the current target.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
This class represents a range of values.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
const BasicBlock & getEntryBlock() const
ConstantRange umin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned minimum of a value in ...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class for arbitrary precision integers.
bool isIntegerTy() const
True if this is an instance of IntegerType.
void setPreservesAll()
Set by analyses that do not transform their input at all.
static void clear(coro::Shape &Shape)
static LVILatticeVal getValueFromICmpCondition(Value *Val, ICmpInst *ICI, bool isTrueDest)
INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass,"lazy-value-info","Lazy Value Information Analysis", false, true) INITIALIZE_PASS_END(LazyValueInfoWrapperPass
llvm_unreachable("Unknown RegBank!")
ConstantRange umax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned maximum of a value in ...
This class wraps the llvm.memcpy/memmove intrinsics.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
bool isKnownNonNull(const Value *V)
Return true if this pointer couldn't possibly be null by its definition.
void threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, BasicBlock *NewSucc)
Inform the analysis cache that we have threaded an edge from PredBB to OldSucc to be from PredBB to N...
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
iterator find(const_arg_type_t< ValueT > V)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Solution solve(PBQPRAGraph &G)
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
void eraseBlock(BasicBlock *BB)
Inform the analysis cache that we have erased a block.
API to communicate dependencies between analyses during invalidation.
Analysis pass providing the TargetLibraryInfo.
This pass computes, caches, and vends lazy value constraint information.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This templated class represents "all analyses that operate over \<a particular IR unit\>" (e...
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
ConstantRange smin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed minimum of a value in thi...
static const Function * getParent(const Value *V)
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
This class implements an extremely fast bulk output stream that can only output to a stream...
static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB)
Return true if the allocation associated with Val is ever dereferenced within the given basic block...
const Value * getFalseValue() const
Value handle with callbacks on RAUW and destruction.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS)
Print the Analysis.
ConstantRange getConstantRangeOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Return the ConstantRage constraint that is known to hold for the specified value on the specified edg...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static LazyValueInfoImpl & getImpl(void *&PImpl, AssumptionCache *AC, const DataLayout *DL, DominatorTree *DT=nullptr)
This lazily constructs the LazyValueInfoImpl.
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Trigger the invalidation of some other analysis pass if not already handled and return whether it was...
A special type used by analysis passes to provide an address that identifies that particular analysis...
const BasicBlock * getParent() const
void initializeLazyValueInfoPrinterPass(PassRegistry &)
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the function to an output stream with an optional AssemblyAnnotationWriter. ...
Analysis to compute lazy value information.
static bool InBlock(const Value *V, const BasicBlock *BB)
#define LLVM_ATTRIBUTE_USED