#include "llvm/Transforms/Utils/PredicateInfo.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/IR/AssemblyAnnotationWriter.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/DebugCounter.h"
#include "llvm/Support/FormattedStream.h"
#include <algorithm>
#define DEBUG_TYPE "predicateinfo"
using namespace llvm;
using namespace PatternMatch;
INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
"PredicateInfo Printer", false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
"PredicateInfo Printer", false, false)
static cl::opt<bool> VerifyPredicateInfo(
"verify-predicateinfo", cl::init(false), cl::Hidden,
cl::desc("Verify PredicateInfo in legacy printer pass."));
DEBUG_COUNTER(RenameCounter, "predicateinfo-rename",
"Controls which variables are renamed with predicateinfo");
static const unsigned MaxCondsPerBranch = 8;
namespace {
const BasicBlock *getBranchBlock(const PredicateBase *PB) {
assert(isa<PredicateWithEdge>(PB) &&
"Only branches and switches should have PHIOnly defs that "
"require branch blocks.");
return cast<PredicateWithEdge>(PB)->From;
}
static Instruction *getBranchTerminator(const PredicateBase *PB) {
assert(isa<PredicateWithEdge>(PB) &&
"Not a predicate info type we know how to get a terminator from.");
return cast<PredicateWithEdge>(PB)->From->getTerminator();
}
std::pair<BasicBlock *, BasicBlock *> getBlockEdge(const PredicateBase *PB) {
assert(isa<PredicateWithEdge>(PB) &&
"Not a predicate info type we know how to get an edge from.");
const auto *PEdge = cast<PredicateWithEdge>(PB);
return std::make_pair(PEdge->From, PEdge->To);
}
}
namespace llvm {
enum LocalNum {
LN_First,
LN_Middle,
LN_Last
};
struct ValueDFS {
int DFSIn = 0;
int DFSOut = 0;
unsigned int LocalNum = LN_Middle;
Value *Def = nullptr;
Use *U = nullptr;
PredicateBase *PInfo = nullptr;
bool EdgeOnly = false;
};
static bool valueComesBefore(const Value *A, const Value *B) {
auto *ArgA = dyn_cast_or_null<Argument>(A);
auto *ArgB = dyn_cast_or_null<Argument>(B);
if (ArgA && !ArgB)
return true;
if (ArgB && !ArgA)
return false;
if (ArgA && ArgB)
return ArgA->getArgNo() < ArgB->getArgNo();
return cast<Instruction>(A)->comesBefore(cast<Instruction>(B));
}
struct ValueDFS_Compare {
DominatorTree &DT;
ValueDFS_Compare(DominatorTree &DT) : DT(DT) {}
bool operator()(const ValueDFS &A, const ValueDFS &B) const {
if (&A == &B)
return false;
assert((A.DFSIn != B.DFSIn || A.DFSOut == B.DFSOut) &&
"Equal DFS-in numbers imply equal out numbers");
bool SameBlock = A.DFSIn == B.DFSIn;
if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
return comparePHIRelated(A, B);
bool isADef = A.Def;
bool isBDef = B.Def;
if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
return std::tie(A.DFSIn, A.LocalNum, isADef) <
std::tie(B.DFSIn, B.LocalNum, isBDef);
return localComesBefore(A, B);
}
std::pair<BasicBlock *, BasicBlock *> getBlockEdge(const ValueDFS &VD) const {
if (!VD.Def && VD.U) {
auto *PHI = cast<PHINode>(VD.U->getUser());
return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
}
return ::getBlockEdge(VD.PInfo);
}
bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
BasicBlock *ASrc, *ADest, *BSrc, *BDest;
std::tie(ASrc, ADest) = getBlockEdge(A);
std::tie(BSrc, BDest) = getBlockEdge(B);
#ifndef NDEBUG
DomTreeNode *DomASrc = DT.getNode(ASrc);
DomTreeNode *DomBSrc = DT.getNode(BSrc);
assert(DomASrc->getDFSNumIn() == (unsigned)A.DFSIn &&
"DFS numbers for A should match the ones of the source block");
assert(DomBSrc->getDFSNumIn() == (unsigned)B.DFSIn &&
"DFS numbers for B should match the ones of the source block");
assert(A.DFSIn == B.DFSIn && "Values must be in the same block");
#endif
(void)ASrc;
(void)BSrc;
DomTreeNode *DomADest = DT.getNode(ADest);
DomTreeNode *DomBDest = DT.getNode(BDest);
unsigned AIn = DomADest->getDFSNumIn();
unsigned BIn = DomBDest->getDFSNumIn();
bool isADef = A.Def;
bool isBDef = B.Def;
assert((!A.Def || !A.U) && (!B.Def || !B.U) &&
"Def and U cannot be set at the same time");
return std::tie(AIn, isADef) < std::tie(BIn, isBDef);
}
Value *getMiddleDef(const ValueDFS &VD) const {
if (VD.Def)
return VD.Def;
if (!VD.U) {
assert(VD.PInfo &&
"No def, no use, and no predicateinfo should not occur");
assert(isa<PredicateAssume>(VD.PInfo) &&
"Middle of block should only occur for assumes");
return cast<PredicateAssume>(VD.PInfo)->AssumeInst->getNextNode();
}
return nullptr;
}
const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
if (Def)
return cast<Instruction>(Def);
return cast<Instruction>(U->getUser());
}
bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
auto *ADef = getMiddleDef(A);
auto *BDef = getMiddleDef(B);
auto *ArgA = dyn_cast_or_null<Argument>(ADef);
auto *ArgB = dyn_cast_or_null<Argument>(BDef);
if (ArgA || ArgB)
return valueComesBefore(ArgA, ArgB);
auto *AInst = getDefOrUser(ADef, A.U);
auto *BInst = getDefOrUser(BDef, B.U);
return valueComesBefore(AInst, BInst);
}
};
class PredicateInfoBuilder {
struct ValueInfo {
SmallVector<PredicateBase *, 4> Infos;
};
PredicateInfo &PI;
Function &F;
DominatorTree &DT;
AssumptionCache &AC;
SmallVector<ValueInfo, 32> ValueInfos;
DenseMap<Value *, unsigned int> ValueInfoNums;
DenseSet<std::pair<BasicBlock *, BasicBlock *>> EdgeUsesOnly;
ValueInfo &getOrCreateValueInfo(Value *);
const ValueInfo &getValueInfo(Value *) const;
void processAssume(IntrinsicInst *, BasicBlock *,
SmallVectorImpl<Value *> &OpsToRename);
void processBranch(BranchInst *, BasicBlock *,
SmallVectorImpl<Value *> &OpsToRename);
void processSwitch(SwitchInst *, BasicBlock *,
SmallVectorImpl<Value *> &OpsToRename);
void renameUses(SmallVectorImpl<Value *> &OpsToRename);
void addInfoFor(SmallVectorImpl<Value *> &OpsToRename, Value *Op,
PredicateBase *PB);
typedef SmallVectorImpl<ValueDFS> ValueDFSStack;
void convertUsesToDFSOrdered(Value *, SmallVectorImpl<ValueDFS> &);
Value *materializeStack(unsigned int &, ValueDFSStack &, Value *);
bool stackIsInScope(const ValueDFSStack &, const ValueDFS &) const;
void popStackUntilDFSScope(ValueDFSStack &, const ValueDFS &);
public:
PredicateInfoBuilder(PredicateInfo &PI, Function &F, DominatorTree &DT,
AssumptionCache &AC)
: PI(PI), F(F), DT(DT), AC(AC) {
ValueInfos.resize(1);
}
void buildPredicateInfo();
};
bool PredicateInfoBuilder::stackIsInScope(const ValueDFSStack &Stack,
const ValueDFS &VDUse) const {
if (Stack.empty())
return false;
if (Stack.back().EdgeOnly) {
if (!VDUse.U)
return false;
auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
if (!PHI)
return false;
BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
if (EdgePred != getBranchBlock(Stack.back().PInfo))
return false;
return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.U);
}
return (VDUse.DFSIn >= Stack.back().DFSIn &&
VDUse.DFSOut <= Stack.back().DFSOut);
}
void PredicateInfoBuilder::popStackUntilDFSScope(ValueDFSStack &Stack,
const ValueDFS &VD) {
while (!Stack.empty() && !stackIsInScope(Stack, VD))
Stack.pop_back();
}
void PredicateInfoBuilder::convertUsesToDFSOrdered(
Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
for (auto &U : Op->uses()) {
if (auto *I = dyn_cast<Instruction>(U.getUser())) {
ValueDFS VD;
BasicBlock *IBlock;
if (auto *PN = dyn_cast<PHINode>(I)) {
IBlock = PN->getIncomingBlock(U);
VD.LocalNum = LN_Last;
} else {
IBlock = I->getParent();
VD.LocalNum = LN_Middle;
}
DomTreeNode *DomNode = DT.getNode(IBlock);
if (!DomNode)
continue;
VD.DFSIn = DomNode->getDFSNumIn();
VD.DFSOut = DomNode->getDFSNumOut();
VD.U = &U;
DFSOrderedSet.push_back(VD);
}
}
}
bool shouldRename(Value *V) {
return (isa<Instruction>(V) || isa<Argument>(V)) && !V->hasOneUse();
}
void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
auto *Op0 = Comparison->getOperand(0);
auto *Op1 = Comparison->getOperand(1);
if (Op0 == Op1)
return;
CmpOperands.push_back(Op0);
CmpOperands.push_back(Op1);
}
void PredicateInfoBuilder::addInfoFor(SmallVectorImpl<Value *> &OpsToRename,
Value *Op, PredicateBase *PB) {
auto &OperandInfo = getOrCreateValueInfo(Op);
if (OperandInfo.Infos.empty())
OpsToRename.push_back(Op);
PI.AllInfos.push_back(PB);
OperandInfo.Infos.push_back(PB);
}
void PredicateInfoBuilder::processAssume(
IntrinsicInst *II, BasicBlock *AssumeBB,
SmallVectorImpl<Value *> &OpsToRename) {
SmallVector<Value *, 4> Worklist;
SmallPtrSet<Value *, 4> Visited;
Worklist.push_back(II->getOperand(0));
while (!Worklist.empty()) {
Value *Cond = Worklist.pop_back_val();
if (!Visited.insert(Cond).second)
continue;
if (Visited.size() > MaxCondsPerBranch)
break;
Value *Op0, *Op1;
if (match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
Worklist.push_back(Op1);
Worklist.push_back(Op0);
}
SmallVector<Value *, 4> Values;
Values.push_back(Cond);
if (auto *Cmp = dyn_cast<CmpInst>(Cond))
collectCmpOps(Cmp, Values);
for (Value *V : Values) {
if (shouldRename(V)) {
auto *PA = new PredicateAssume(V, II, Cond);
addInfoFor(OpsToRename, V, PA);
}
}
}
}
void PredicateInfoBuilder::processBranch(
BranchInst *BI, BasicBlock *BranchBB,
SmallVectorImpl<Value *> &OpsToRename) {
BasicBlock *FirstBB = BI->getSuccessor(0);
BasicBlock *SecondBB = BI->getSuccessor(1);
for (BasicBlock *Succ : {FirstBB, SecondBB}) {
bool TakenEdge = Succ == FirstBB;
if (Succ == BranchBB)
continue;
SmallVector<Value *, 4> Worklist;
SmallPtrSet<Value *, 4> Visited;
Worklist.push_back(BI->getCondition());
while (!Worklist.empty()) {
Value *Cond = Worklist.pop_back_val();
if (!Visited.insert(Cond).second)
continue;
if (Visited.size() > MaxCondsPerBranch)
break;
Value *Op0, *Op1;
if (TakenEdge ? match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))
: match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
Worklist.push_back(Op1);
Worklist.push_back(Op0);
}
SmallVector<Value *, 4> Values;
Values.push_back(Cond);
if (auto *Cmp = dyn_cast<CmpInst>(Cond))
collectCmpOps(Cmp, Values);
for (Value *V : Values) {
if (shouldRename(V)) {
PredicateBase *PB =
new PredicateBranch(V, BranchBB, Succ, Cond, TakenEdge);
addInfoFor(OpsToRename, V, PB);
if (!Succ->getSinglePredecessor())
EdgeUsesOnly.insert({BranchBB, Succ});
}
}
}
}
}
void PredicateInfoBuilder::processSwitch(
SwitchInst *SI, BasicBlock *BranchBB,
SmallVectorImpl<Value *> &OpsToRename) {
Value *Op = SI->getCondition();
if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->hasOneUse())
return;
SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
BasicBlock *TargetBlock = SI->getSuccessor(i);
++SwitchEdges[TargetBlock];
}
for (auto C : SI->cases()) {
BasicBlock *TargetBlock = C.getCaseSuccessor();
if (SwitchEdges.lookup(TargetBlock) == 1) {
PredicateSwitch *PS = new PredicateSwitch(
Op, SI->getParent(), TargetBlock, C.getCaseValue(), SI);
addInfoFor(OpsToRename, Op, PS);
if (!TargetBlock->getSinglePredecessor())
EdgeUsesOnly.insert({BranchBB, TargetBlock});
}
}
}
void PredicateInfoBuilder::buildPredicateInfo() {
DT.updateDFSNumbers();
SmallVector<Value *, 8> OpsToRename;
for (auto DTN : depth_first(DT.getRootNode())) {
BasicBlock *BranchBB = DTN->getBlock();
if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
if (!BI->isConditional())
continue;
if (BI->getSuccessor(0) == BI->getSuccessor(1))
continue;
processBranch(BI, BranchBB, OpsToRename);
} else if (auto *SI = dyn_cast<SwitchInst>(BranchBB->getTerminator())) {
processSwitch(SI, BranchBB, OpsToRename);
}
}
for (auto &Assume : AC.assumptions()) {
if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
if (DT.isReachableFromEntry(II->getParent()))
processAssume(II, II->getParent(), OpsToRename);
}
renameUses(OpsToRename);
}
Value *PredicateInfoBuilder::materializeStack(unsigned int &Counter,
ValueDFSStack &RenameStack,
Value *OrigOp) {
auto RevIter = RenameStack.rbegin();
for (; RevIter != RenameStack.rend(); ++RevIter)
if (RevIter->Def)
break;
size_t Start = RevIter - RenameStack.rbegin();
for (auto RenameIter = RenameStack.end() - Start;
RenameIter != RenameStack.end(); ++RenameIter) {
auto *Op =
RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
ValueDFS &Result = *RenameIter;
auto *ValInfo = Result.PInfo;
ValInfo->RenamedOp = (RenameStack.end() - Start) == RenameStack.begin()
? OrigOp
: (RenameStack.end() - Start - 1)->Def;
if (isa<PredicateWithEdge>(ValInfo)) {
IRBuilder<> B(getBranchTerminator(ValInfo));
auto NumDecls = F.getParent()->getNumNamedValues();
Function *IF = Intrinsic::getDeclaration(
F.getParent(), Intrinsic::ssa_copy, Op->getType());
if (NumDecls != F.getParent()->getNumNamedValues())
PI.CreatedDeclarations.insert(IF);
CallInst *PIC =
B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
PI.PredicateMap.insert({PIC, ValInfo});
Result.Def = PIC;
} else {
auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
assert(PAssume &&
"Should not have gotten here without it being an assume");
IRBuilder<> B(PAssume->AssumeInst->getNextNode());
auto NumDecls = F.getParent()->getNumNamedValues();
Function *IF = Intrinsic::getDeclaration(
F.getParent(), Intrinsic::ssa_copy, Op->getType());
if (NumDecls != F.getParent()->getNumNamedValues())
PI.CreatedDeclarations.insert(IF);
CallInst *PIC = B.CreateCall(IF, Op);
PI.PredicateMap.insert({PIC, ValInfo});
Result.Def = PIC;
}
}
return RenameStack.back().Def;
}
void PredicateInfoBuilder::renameUses(SmallVectorImpl<Value *> &OpsToRename) {
ValueDFS_Compare Compare(DT);
for (auto *Op : OpsToRename) {
LLVM_DEBUG(dbgs() << "Visiting " << *Op << "\n");
unsigned Counter = 0;
SmallVector<ValueDFS, 16> OrderedUses;
const auto &ValueInfo = getValueInfo(Op);
for (auto &PossibleCopy : ValueInfo.Infos) {
ValueDFS VD;
if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
VD.LocalNum = LN_Middle;
DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
if (!DomNode)
continue;
VD.DFSIn = DomNode->getDFSNumIn();
VD.DFSOut = DomNode->getDFSNumOut();
VD.PInfo = PossibleCopy;
OrderedUses.push_back(VD);
} else if (isa<PredicateWithEdge>(PossibleCopy)) {
auto BlockEdge = getBlockEdge(PossibleCopy);
if (EdgeUsesOnly.count(BlockEdge)) {
VD.LocalNum = LN_Last;
auto *DomNode = DT.getNode(BlockEdge.first);
if (DomNode) {
VD.DFSIn = DomNode->getDFSNumIn();
VD.DFSOut = DomNode->getDFSNumOut();
VD.PInfo = PossibleCopy;
VD.EdgeOnly = true;
OrderedUses.push_back(VD);
}
} else {
VD.LocalNum = LN_First;
auto *DomNode = DT.getNode(BlockEdge.second);
if (DomNode) {
VD.DFSIn = DomNode->getDFSNumIn();
VD.DFSOut = DomNode->getDFSNumOut();
VD.PInfo = PossibleCopy;
OrderedUses.push_back(VD);
}
}
}
}
convertUsesToDFSOrdered(Op, OrderedUses);
llvm::stable_sort(OrderedUses, Compare);
SmallVector<ValueDFS, 8> RenameStack;
for (auto &VD : OrderedUses) {
bool PossibleCopy = VD.PInfo != nullptr;
if (RenameStack.empty()) {
LLVM_DEBUG(dbgs() << "Rename Stack is empty\n");
} else {
LLVM_DEBUG(dbgs() << "Rename Stack Top DFS numbers are ("
<< RenameStack.back().DFSIn << ","
<< RenameStack.back().DFSOut << ")\n");
}
LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << ","
<< VD.DFSOut << ")\n");
bool ShouldPush = (VD.Def || PossibleCopy);
bool OutOfScope = !stackIsInScope(RenameStack, VD);
if (OutOfScope || ShouldPush) {
popStackUntilDFSScope(RenameStack, VD);
if (ShouldPush) {
RenameStack.push_back(VD);
}
}
if (RenameStack.empty())
continue;
if (VD.Def || PossibleCopy)
continue;
if (!DebugCounter::shouldExecute(RenameCounter)) {
LLVM_DEBUG(dbgs() << "Skipping execution due to debug counter\n");
continue;
}
ValueDFS &Result = RenameStack.back();
if (!Result.Def)
Result.Def = materializeStack(Counter, RenameStack, Op);
LLVM_DEBUG(dbgs() << "Found replacement " << *Result.Def << " for "
<< *VD.U->get() << " in " << *(VD.U->getUser())
<< "\n");
assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) &&
"Predicateinfo def should have dominated this use");
VD.U->set(Result.Def);
}
}
}
PredicateInfoBuilder::ValueInfo &
PredicateInfoBuilder::getOrCreateValueInfo(Value *Operand) {
auto OIN = ValueInfoNums.find(Operand);
if (OIN == ValueInfoNums.end()) {
ValueInfos.resize(ValueInfos.size() + 1);
auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
assert(InsertResult.second && "Value info number already existed?");
return ValueInfos[InsertResult.first->second];
}
return ValueInfos[OIN->second];
}
const PredicateInfoBuilder::ValueInfo &
PredicateInfoBuilder::getValueInfo(Value *Operand) const {
auto OINI = ValueInfoNums.lookup(Operand);
assert(OINI != 0 && "Operand was not really in the Value Info Numbers");
assert(OINI < ValueInfos.size() &&
"Value Info Number greater than size of Value Info Table");
return ValueInfos[OINI];
}
PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT,
AssumptionCache &AC)
: F(F) {
PredicateInfoBuilder Builder(*this, F, DT, AC);
Builder.buildPredicateInfo();
}
PredicateInfo::~PredicateInfo() {
SmallPtrSet<Function *, 20> FunctionPtrs;
for (auto &F : CreatedDeclarations)
FunctionPtrs.insert(&*F);
CreatedDeclarations.clear();
for (Function *F : FunctionPtrs) {
assert(F->user_begin() == F->user_end() &&
"PredicateInfo consumer did not remove all SSA copies.");
F->eraseFromParent();
}
}
Optional<PredicateConstraint> PredicateBase::getConstraint() const {
switch (Type) {
case PT_Assume:
case PT_Branch: {
bool TrueEdge = true;
if (auto *PBranch = dyn_cast<PredicateBranch>(this))
TrueEdge = PBranch->TrueEdge;
if (Condition == RenamedOp) {
return {{CmpInst::ICMP_EQ,
TrueEdge ? ConstantInt::getTrue(Condition->getType())
: ConstantInt::getFalse(Condition->getType())}};
}
CmpInst *Cmp = dyn_cast<CmpInst>(Condition);
if (!Cmp) {
return None;
}
CmpInst::Predicate Pred;
Value *OtherOp;
if (Cmp->getOperand(0) == RenamedOp) {
Pred = Cmp->getPredicate();
OtherOp = Cmp->getOperand(1);
} else if (Cmp->getOperand(1) == RenamedOp) {
Pred = Cmp->getSwappedPredicate();
OtherOp = Cmp->getOperand(0);
} else {
return None;
}
if (!TrueEdge)
Pred = CmpInst::getInversePredicate(Pred);
return {{Pred, OtherOp}};
}
case PT_Switch:
if (Condition != RenamedOp) {
return None;
}
return {{CmpInst::ICMP_EQ, cast<PredicateSwitch>(this)->CaseValue}};
}
llvm_unreachable("Unknown predicate type");
}
void PredicateInfo::verifyPredicateInfo() const {}
char PredicateInfoPrinterLegacyPass::ID = 0;
PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass()
: FunctionPass(ID) {
initializePredicateInfoPrinterLegacyPassPass(
*PassRegistry::getPassRegistry());
}
void PredicateInfoPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AU.addRequiredTransitive<DominatorTreeWrapperPass>();
AU.addRequired<AssumptionCacheTracker>();
}
static void replaceCreatedSSACopys(PredicateInfo &PredInfo, Function &F) {
for (Instruction &Inst : llvm::make_early_inc_range(instructions(F))) {
const auto *PI = PredInfo.getPredicateInfoFor(&Inst);
auto *II = dyn_cast<IntrinsicInst>(&Inst);
if (!PI || !II || II->getIntrinsicID() != Intrinsic::ssa_copy)
continue;
Inst.replaceAllUsesWith(II->getOperand(0));
Inst.eraseFromParent();
}
}
bool PredicateInfoPrinterLegacyPass::runOnFunction(Function &F) {
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
PredInfo->print(dbgs());
if (VerifyPredicateInfo)
PredInfo->verifyPredicateInfo();
replaceCreatedSSACopys(*PredInfo, F);
return false;
}
PreservedAnalyses PredicateInfoPrinterPass::run(Function &F,
FunctionAnalysisManager &AM) {
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &AC = AM.getResult<AssumptionAnalysis>(F);
OS << "PredicateInfo for function: " << F.getName() << "\n";
auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
PredInfo->print(OS);
replaceCreatedSSACopys(*PredInfo, F);
return PreservedAnalyses::all();
}
class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter {
friend class PredicateInfo;
const PredicateInfo *PredInfo;
public:
PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
void emitBasicBlockStartAnnot(const BasicBlock *BB,
formatted_raw_ostream &OS) override {}
void emitInstructionAnnot(const Instruction *I,
formatted_raw_ostream &OS) override {
if (const auto *PI = PredInfo->getPredicateInfoFor(I)) {
OS << "; Has predicate info\n";
if (const auto *PB = dyn_cast<PredicateBranch>(PI)) {
OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge
<< " Comparison:" << *PB->Condition << " Edge: [";
PB->From->printAsOperand(OS);
OS << ",";
PB->To->printAsOperand(OS);
OS << "]";
} else if (const auto *PS = dyn_cast<PredicateSwitch>(PI)) {
OS << "; switch predicate info { CaseValue: " << *PS->CaseValue
<< " Switch:" << *PS->Switch << " Edge: [";
PS->From->printAsOperand(OS);
OS << ",";
PS->To->printAsOperand(OS);
OS << "]";
} else if (const auto *PA = dyn_cast<PredicateAssume>(PI)) {
OS << "; assume predicate info {"
<< " Comparison:" << *PA->Condition;
}
OS << ", RenamedOp: ";
PI->RenamedOp->printAsOperand(OS, false);
OS << " }\n";
}
}
};
void PredicateInfo::print(raw_ostream &OS) const {
PredicateInfoAnnotatedWriter Writer(this);
F.print(OS, &Writer);
}
void PredicateInfo::dump() const {
PredicateInfoAnnotatedWriter Writer(this);
F.print(dbgs(), &Writer);
}
PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
FunctionAnalysisManager &AM) {
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &AC = AM.getResult<AssumptionAnalysis>(F);
std::make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
return PreservedAnalyses::all();
}
}