#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/DivergenceAnalysis.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "divergence"
static cl::opt<bool> UseGPUDA("use-gpu-divergence-analysis", cl::init(false),
cl::Hidden,
cl::desc("turn the LegacyDivergenceAnalysis into "
"a wrapper for GPUDivergenceAnalysis"));
namespace {
class DivergencePropagator {
public:
DivergencePropagator(Function &F, TargetTransformInfo &TTI, DominatorTree &DT,
PostDominatorTree &PDT, DenseSet<const Value *> &DV,
DenseSet<const Use *> &DU)
: F(F), TTI(TTI), DT(DT), PDT(PDT), DV(DV), DU(DU) {}
void populateWithSourcesOfDivergence();
void propagate();
private:
void exploreDataDependency(Value *V);
void exploreSyncDependency(Instruction *TI);
void computeInfluenceRegion(BasicBlock *Start, BasicBlock *End,
DenseSet<BasicBlock *> &InfluenceRegion);
void findUsersOutsideInfluenceRegion(
Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion);
Function &F;
TargetTransformInfo &TTI;
DominatorTree &DT;
PostDominatorTree &PDT;
std::vector<Value *> Worklist; DenseSet<const Value *> &DV; DenseSet<const Use *> &DU; };
void DivergencePropagator::populateWithSourcesOfDivergence() {
Worklist.clear();
DV.clear();
DU.clear();
for (auto &I : instructions(F)) {
if (TTI.isSourceOfDivergence(&I)) {
Worklist.push_back(&I);
DV.insert(&I);
}
}
for (auto &Arg : F.args()) {
if (TTI.isSourceOfDivergence(&Arg)) {
Worklist.push_back(&Arg);
DV.insert(&Arg);
}
}
}
void DivergencePropagator::exploreSyncDependency(Instruction *TI) {
BasicBlock *ThisBB = TI->getParent();
if (!DT.isReachableFromEntry(ThisBB))
return;
DomTreeNode *ThisNode = PDT.getNode(ThisBB);
if (!ThisNode)
return;
BasicBlock *IPostDom = ThisNode->getIDom()->getBlock();
if (IPostDom == nullptr)
return;
for (auto I = IPostDom->begin(); isa<PHINode>(I); ++I) {
if (!cast<PHINode>(I)->hasConstantOrUndefValue() && DV.insert(&*I).second)
Worklist.push_back(&*I);
}
DenseSet<BasicBlock *> InfluenceRegion;
computeInfluenceRegion(ThisBB, IPostDom, InfluenceRegion);
BasicBlock *InfluencedBB = ThisBB;
while (InfluenceRegion.count(InfluencedBB)) {
for (auto &I : *InfluencedBB) {
if (!DV.count(&I))
findUsersOutsideInfluenceRegion(I, InfluenceRegion);
}
DomTreeNode *IDomNode = DT.getNode(InfluencedBB)->getIDom();
if (IDomNode == nullptr)
break;
InfluencedBB = IDomNode->getBlock();
}
}
void DivergencePropagator::findUsersOutsideInfluenceRegion(
Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion) {
for (Use &Use : I.uses()) {
Instruction *UserInst = cast<Instruction>(Use.getUser());
if (!InfluenceRegion.count(UserInst->getParent())) {
DU.insert(&Use);
if (DV.insert(UserInst).second)
Worklist.push_back(UserInst);
}
}
}
static void
addSuccessorsToInfluenceRegion(BasicBlock *ThisBB, BasicBlock *End,
DenseSet<BasicBlock *> &InfluenceRegion,
std::vector<BasicBlock *> &InfluenceStack) {
for (BasicBlock *Succ : successors(ThisBB)) {
if (Succ != End && InfluenceRegion.insert(Succ).second)
InfluenceStack.push_back(Succ);
}
}
void DivergencePropagator::computeInfluenceRegion(
BasicBlock *Start, BasicBlock *End,
DenseSet<BasicBlock *> &InfluenceRegion) {
assert(PDT.properlyDominates(End, Start) &&
"End does not properly dominate Start");
std::vector<BasicBlock *> InfluenceStack;
addSuccessorsToInfluenceRegion(Start, End, InfluenceRegion, InfluenceStack);
while (!InfluenceStack.empty()) {
BasicBlock *BB = InfluenceStack.back();
InfluenceStack.pop_back();
addSuccessorsToInfluenceRegion(BB, End, InfluenceRegion, InfluenceStack);
}
}
void DivergencePropagator::exploreDataDependency(Value *V) {
for (User *U : V->users()) {
if (!TTI.isAlwaysUniform(U) && DV.insert(U).second)
Worklist.push_back(U);
}
}
void DivergencePropagator::propagate() {
while (!Worklist.empty()) {
Value *V = Worklist.back();
Worklist.pop_back();
if (Instruction *I = dyn_cast<Instruction>(V)) {
if (I->isTerminator() && I->getNumSuccessors() > 1)
exploreSyncDependency(I);
}
exploreDataDependency(V);
}
}
}
char LegacyDivergenceAnalysis::ID = 0;
LegacyDivergenceAnalysis::LegacyDivergenceAnalysis() : FunctionPass(ID) {
initializeLegacyDivergenceAnalysisPass(*PassRegistry::getPassRegistry());
}
INITIALIZE_PASS_BEGIN(LegacyDivergenceAnalysis, "divergence",
"Legacy Divergence Analysis", false, true)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_END(LegacyDivergenceAnalysis, "divergence",
"Legacy Divergence Analysis", false, true)
FunctionPass *llvm::createLegacyDivergenceAnalysisPass() {
return new LegacyDivergenceAnalysis();
}
void LegacyDivergenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequiredTransitive<DominatorTreeWrapperPass>();
AU.addRequiredTransitive<PostDominatorTreeWrapperPass>();
AU.addRequiredTransitive<LoopInfoWrapperPass>();
AU.setPreservesAll();
}
bool LegacyDivergenceAnalysis::shouldUseGPUDivergenceAnalysis(
const Function &F, const TargetTransformInfo &TTI) const {
if (!(UseGPUDA || TTI.useGPUDivergenceAnalysis()))
return false;
auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
using RPOTraversal = ReversePostOrderTraversal<const Function *>;
RPOTraversal FuncRPOT(&F);
return !containsIrreducibleCFG<const BasicBlock *, const RPOTraversal,
const LoopInfo>(FuncRPOT, LI);
}
bool LegacyDivergenceAnalysis::runOnFunction(Function &F) {
auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
if (TTIWP == nullptr)
return false;
TargetTransformInfo &TTI = TTIWP->getTTI(F);
if (!TTI.hasBranchDivergence())
return false;
DivergentValues.clear();
DivergentUses.clear();
gpuDA = nullptr;
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
if (shouldUseGPUDivergenceAnalysis(F, TTI)) {
auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
gpuDA = std::make_unique<DivergenceInfo>(F, DT, PDT, LI, TTI,
true);
} else {
DivergencePropagator DP(F, TTI, DT, PDT, DivergentValues, DivergentUses);
DP.populateWithSourcesOfDivergence();
DP.propagate();
}
LLVM_DEBUG(dbgs() << "\nAfter divergence analysis on " << F.getName()
<< ":\n";
print(dbgs(), F.getParent()));
return false;
}
bool LegacyDivergenceAnalysis::isDivergent(const Value *V) const {
if (gpuDA) {
return gpuDA->isDivergent(*V);
}
return DivergentValues.count(V);
}
bool LegacyDivergenceAnalysis::isDivergentUse(const Use *U) const {
if (gpuDA) {
return gpuDA->isDivergentUse(*U);
}
return DivergentValues.count(U->get()) || DivergentUses.count(U);
}
void LegacyDivergenceAnalysis::print(raw_ostream &OS, const Module *) const {
if ((!gpuDA || !gpuDA->hasDivergence()) && DivergentValues.empty())
return;
const Function *F = nullptr;
if (!DivergentValues.empty()) {
const Value *FirstDivergentValue = *DivergentValues.begin();
if (const Argument *Arg = dyn_cast<Argument>(FirstDivergentValue)) {
F = Arg->getParent();
} else if (const Instruction *I =
dyn_cast<Instruction>(FirstDivergentValue)) {
F = I->getParent()->getParent();
} else {
llvm_unreachable("Only arguments and instructions can be divergent");
}
} else if (gpuDA) {
F = &gpuDA->getFunction();
}
if (!F)
return;
for (const auto &Arg : F->args()) {
OS << (isDivergent(&Arg) ? "DIVERGENT: " : " ");
OS << Arg << "\n";
}
for (const BasicBlock &BB : *F) {
OS << "\n " << BB.getName() << ":\n";
for (const auto &I : BB.instructionsWithoutDebug()) {
OS << (isDivergent(&I) ? "DIVERGENT: " : " ");
OS << I << "\n";
}
}
OS << "\n";
}