#include "AMDGPU.h"
#include "SIDefines.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Analysis/DomTreeUpdater.h"
#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicsAMDGPU.h"
#include "llvm/IR/Type.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Transforms/Utils/Local.h"
using namespace llvm;
#define DEBUG_TYPE "amdgpu-unify-divergent-exit-nodes"
namespace {
class AMDGPUUnifyDivergentExitNodes : public FunctionPass {
private:
const TargetTransformInfo *TTI = nullptr;
public:
static char ID;
AMDGPUUnifyDivergentExitNodes() : FunctionPass(ID) {
initializeAMDGPUUnifyDivergentExitNodesPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override;
BasicBlock *unifyReturnBlockSet(Function &F, DomTreeUpdater &DTU,
ArrayRef<BasicBlock *> ReturningBlocks,
StringRef Name);
bool runOnFunction(Function &F) override;
};
}
char AMDGPUUnifyDivergentExitNodes::ID = 0;
char &llvm::AMDGPUUnifyDivergentExitNodesID = AMDGPUUnifyDivergentExitNodes::ID;
INITIALIZE_PASS_BEGIN(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE,
"Unify divergent function exit nodes", false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
INITIALIZE_PASS_END(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE,
"Unify divergent function exit nodes", false, false)
void AMDGPUUnifyDivergentExitNodes::getAnalysisUsage(AnalysisUsage &AU) const{
if (RequireAndPreserveDomTree)
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<PostDominatorTreeWrapperPass>();
AU.addRequired<LegacyDivergenceAnalysis>();
if (RequireAndPreserveDomTree) {
AU.addPreserved<DominatorTreeWrapperPass>();
}
AU.addPreserved<LegacyDivergenceAnalysis>();
AU.addPreservedID(BreakCriticalEdgesID);
AU.addPreservedID(LowerSwitchID);
FunctionPass::getAnalysisUsage(AU);
AU.addRequired<TargetTransformInfoWrapperPass>();
}
static bool isUniformlyReached(const LegacyDivergenceAnalysis &DA,
BasicBlock &BB) {
SmallVector<BasicBlock *, 8> Stack(predecessors(&BB));
SmallPtrSet<BasicBlock *, 8> Visited;
while (!Stack.empty()) {
BasicBlock *Top = Stack.pop_back_val();
if (!DA.isUniform(Top->getTerminator()))
return false;
for (BasicBlock *Pred : predecessors(Top)) {
if (Visited.insert(Pred).second)
Stack.push_back(Pred);
}
}
return true;
}
BasicBlock *AMDGPUUnifyDivergentExitNodes::unifyReturnBlockSet(
Function &F, DomTreeUpdater &DTU, ArrayRef<BasicBlock *> ReturningBlocks,
StringRef Name) {
BasicBlock *NewRetBlock = BasicBlock::Create(F.getContext(), Name, &F);
IRBuilder<> B(NewRetBlock);
PHINode *PN = nullptr;
if (F.getReturnType()->isVoidTy()) {
B.CreateRetVoid();
} else {
PN = B.CreatePHI(F.getReturnType(), ReturningBlocks.size(),
"UnifiedRetVal");
B.CreateRet(PN);
}
std::vector<DominatorTree::UpdateType> Updates;
Updates.reserve(ReturningBlocks.size());
for (BasicBlock *BB : ReturningBlocks) {
if (PN)
PN->addIncoming(BB->getTerminator()->getOperand(0), BB);
BB->getTerminator()->eraseFromParent();
BranchInst::Create(NewRetBlock, BB);
Updates.push_back({DominatorTree::Insert, BB, NewRetBlock});
}
if (RequireAndPreserveDomTree)
DTU.applyUpdates(Updates);
Updates.clear();
for (BasicBlock *BB : ReturningBlocks) {
simplifyCFG(BB, *TTI, RequireAndPreserveDomTree ? &DTU : nullptr,
SimplifyCFGOptions().bonusInstThreshold(2));
}
return NewRetBlock;
}
bool AMDGPUUnifyDivergentExitNodes::runOnFunction(Function &F) {
DominatorTree *DT = nullptr;
if (RequireAndPreserveDomTree)
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
if (PDT.root_size() <= 1)
return false;
LegacyDivergenceAnalysis &DA = getAnalysis<LegacyDivergenceAnalysis>();
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
SmallVector<BasicBlock *, 4> ReturningBlocks;
SmallVector<BasicBlock *, 4> UnreachableBlocks;
BasicBlock *DummyReturnBB = nullptr;
bool Changed = false;
std::vector<DominatorTree::UpdateType> Updates;
for (BasicBlock *BB : PDT.roots()) {
if (isa<ReturnInst>(BB->getTerminator())) {
if (!isUniformlyReached(DA, *BB))
ReturningBlocks.push_back(BB);
} else if (isa<UnreachableInst>(BB->getTerminator())) {
if (!isUniformlyReached(DA, *BB))
UnreachableBlocks.push_back(BB);
} else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
ConstantInt *BoolTrue = ConstantInt::getTrue(F.getContext());
if (DummyReturnBB == nullptr) {
DummyReturnBB = BasicBlock::Create(F.getContext(),
"DummyReturnBlock", &F);
Type *RetTy = F.getReturnType();
Value *RetVal = RetTy->isVoidTy() ? nullptr : UndefValue::get(RetTy);
ReturnInst::Create(F.getContext(), RetVal, DummyReturnBB);
ReturningBlocks.push_back(DummyReturnBB);
}
if (BI->isUnconditional()) {
BasicBlock *LoopHeaderBB = BI->getSuccessor(0);
BI->eraseFromParent(); BranchInst::Create(LoopHeaderBB, DummyReturnBB, BoolTrue, BB);
Updates.push_back({DominatorTree::Insert, BB, DummyReturnBB});
} else { SmallVector<BasicBlock *, 2> Successors(successors(BB));
BasicBlock *TransitionBB = BB->splitBasicBlock(BI, "TransitionBlock");
Updates.reserve(Updates.size() + 2 * Successors.size() + 2);
Updates.push_back({DominatorTree::Insert, BB, TransitionBB});
for (BasicBlock *Successor : Successors) {
Updates.push_back({DominatorTree::Insert, TransitionBB, Successor});
Updates.push_back({DominatorTree::Delete, BB, Successor});
}
BB->getTerminator()->eraseFromParent();
BranchInst::Create(TransitionBB, DummyReturnBB, BoolTrue, BB);
Updates.push_back({DominatorTree::Insert, BB, DummyReturnBB});
}
Changed = true;
}
}
if (!UnreachableBlocks.empty()) {
BasicBlock *UnreachableBlock = nullptr;
if (UnreachableBlocks.size() == 1) {
UnreachableBlock = UnreachableBlocks.front();
} else {
UnreachableBlock = BasicBlock::Create(F.getContext(),
"UnifiedUnreachableBlock", &F);
new UnreachableInst(F.getContext(), UnreachableBlock);
Updates.reserve(Updates.size() + UnreachableBlocks.size());
for (BasicBlock *BB : UnreachableBlocks) {
BB->getTerminator()->eraseFromParent();
BranchInst::Create(UnreachableBlock, BB);
Updates.push_back({DominatorTree::Insert, BB, UnreachableBlock});
}
Changed = true;
}
if (!ReturningBlocks.empty()) {
Type *RetTy = F.getReturnType();
Value *RetVal = RetTy->isVoidTy() ? nullptr : UndefValue::get(RetTy);
UnreachableBlock->getTerminator()->eraseFromParent();
Function *UnreachableIntrin =
Intrinsic::getDeclaration(F.getParent(), Intrinsic::amdgcn_unreachable);
CallInst::Create(UnreachableIntrin, {}, "", UnreachableBlock);
ReturnInst::Create(F.getContext(), RetVal, UnreachableBlock);
ReturningBlocks.push_back(UnreachableBlock);
Changed = true;
}
}
DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
if (RequireAndPreserveDomTree)
DTU.applyUpdates(Updates);
Updates.clear();
if (ReturningBlocks.empty())
return Changed;
if (ReturningBlocks.size() == 1)
return Changed;
unifyReturnBlockSet(F, DTU, ReturningBlocks, "UnifiedReturnBlock");
return true;
}