Path: blob/main/contrib/llvm-project/llvm/lib/IR/Dominators.cpp
35233 views
//===- Dominators.cpp - Dominator Calculation -----------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements simple dominator construction algorithms for finding9// forward dominators. Postdominators are available in libanalysis, but are not10// included in libvmcore, because it's not needed. Forward dominators are11// needed to support the Verifier pass.12//13//===----------------------------------------------------------------------===//1415#include "llvm/IR/Dominators.h"16#include "llvm/ADT/StringRef.h"17#include "llvm/Config/llvm-config.h"18#include "llvm/IR/CFG.h"19#include "llvm/IR/Function.h"20#include "llvm/IR/Instruction.h"21#include "llvm/IR/Instructions.h"22#include "llvm/IR/PassManager.h"23#include "llvm/InitializePasses.h"24#include "llvm/PassRegistry.h"25#include "llvm/Support/Casting.h"26#include "llvm/Support/CommandLine.h"27#include "llvm/Support/GenericDomTreeConstruction.h"28#include "llvm/Support/raw_ostream.h"2930#include <cassert>3132namespace llvm {33class Argument;34class Constant;35class Value;36} // namespace llvm37using namespace llvm;3839bool llvm::VerifyDomInfo = false;40static cl::opt<bool, true>41VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo), cl::Hidden,42cl::desc("Verify dominator info (time consuming)"));4344#ifdef EXPENSIVE_CHECKS45static constexpr bool ExpensiveChecksEnabled = true;46#else47static constexpr bool ExpensiveChecksEnabled = false;48#endif4950bool BasicBlockEdge::isSingleEdge() const {51unsigned NumEdgesToEnd = 0;52for (const BasicBlock *Succ : successors(Start)) {53if (Succ == End)54++NumEdgesToEnd;55if (NumEdgesToEnd >= 2)56return false;57}58assert(NumEdgesToEnd == 1);59return true;60}6162//===----------------------------------------------------------------------===//63// DominatorTree Implementation64//===----------------------------------------------------------------------===//65//66// Provide public access to DominatorTree information. Implementation details67// can be found in Dominators.h, GenericDomTree.h, and68// GenericDomTreeConstruction.h.69//70//===----------------------------------------------------------------------===//7172template class llvm::DomTreeNodeBase<BasicBlock>;73template class llvm::DominatorTreeBase<BasicBlock, false>; // DomTreeBase74template class llvm::DominatorTreeBase<BasicBlock, true>; // PostDomTreeBase7576template class llvm::cfg::Update<BasicBlock *>;7778template void llvm::DomTreeBuilder::Calculate<DomTreeBuilder::BBDomTree>(79DomTreeBuilder::BBDomTree &DT);80template void81llvm::DomTreeBuilder::CalculateWithUpdates<DomTreeBuilder::BBDomTree>(82DomTreeBuilder::BBDomTree &DT, BBUpdates U);8384template void llvm::DomTreeBuilder::Calculate<DomTreeBuilder::BBPostDomTree>(85DomTreeBuilder::BBPostDomTree &DT);86// No CalculateWithUpdates<PostDomTree> instantiation, unless a usecase arises.8788template void llvm::DomTreeBuilder::InsertEdge<DomTreeBuilder::BBDomTree>(89DomTreeBuilder::BBDomTree &DT, BasicBlock *From, BasicBlock *To);90template void llvm::DomTreeBuilder::InsertEdge<DomTreeBuilder::BBPostDomTree>(91DomTreeBuilder::BBPostDomTree &DT, BasicBlock *From, BasicBlock *To);9293template void llvm::DomTreeBuilder::DeleteEdge<DomTreeBuilder::BBDomTree>(94DomTreeBuilder::BBDomTree &DT, BasicBlock *From, BasicBlock *To);95template void llvm::DomTreeBuilder::DeleteEdge<DomTreeBuilder::BBPostDomTree>(96DomTreeBuilder::BBPostDomTree &DT, BasicBlock *From, BasicBlock *To);9798template void llvm::DomTreeBuilder::ApplyUpdates<DomTreeBuilder::BBDomTree>(99DomTreeBuilder::BBDomTree &DT, DomTreeBuilder::BBDomTreeGraphDiff &,100DomTreeBuilder::BBDomTreeGraphDiff *);101template void llvm::DomTreeBuilder::ApplyUpdates<DomTreeBuilder::BBPostDomTree>(102DomTreeBuilder::BBPostDomTree &DT, DomTreeBuilder::BBPostDomTreeGraphDiff &,103DomTreeBuilder::BBPostDomTreeGraphDiff *);104105template bool llvm::DomTreeBuilder::Verify<DomTreeBuilder::BBDomTree>(106const DomTreeBuilder::BBDomTree &DT,107DomTreeBuilder::BBDomTree::VerificationLevel VL);108template bool llvm::DomTreeBuilder::Verify<DomTreeBuilder::BBPostDomTree>(109const DomTreeBuilder::BBPostDomTree &DT,110DomTreeBuilder::BBPostDomTree::VerificationLevel VL);111112bool DominatorTree::invalidate(Function &F, const PreservedAnalyses &PA,113FunctionAnalysisManager::Invalidator &) {114// Check whether the analysis, all analyses on functions, or the function's115// CFG have been preserved.116auto PAC = PA.getChecker<DominatorTreeAnalysis>();117return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||118PAC.preservedSet<CFGAnalyses>());119}120121bool DominatorTree::dominates(const BasicBlock *BB, const Use &U) const {122Instruction *UserInst = cast<Instruction>(U.getUser());123if (auto *PN = dyn_cast<PHINode>(UserInst))124// A phi use using a value from a block is dominated by the end of that125// block. Note that the phi's parent block may not be.126return dominates(BB, PN->getIncomingBlock(U));127else128return properlyDominates(BB, UserInst->getParent());129}130131// dominates - Return true if Def dominates a use in User. This performs132// the special checks necessary if Def and User are in the same basic block.133// Note that Def doesn't dominate a use in Def itself!134bool DominatorTree::dominates(const Value *DefV,135const Instruction *User) const {136const Instruction *Def = dyn_cast<Instruction>(DefV);137if (!Def) {138assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&139"Should be called with an instruction, argument or constant");140return true; // Arguments and constants dominate everything.141}142143const BasicBlock *UseBB = User->getParent();144const BasicBlock *DefBB = Def->getParent();145146// Any unreachable use is dominated, even if Def == User.147if (!isReachableFromEntry(UseBB))148return true;149150// Unreachable definitions don't dominate anything.151if (!isReachableFromEntry(DefBB))152return false;153154// An instruction doesn't dominate a use in itself.155if (Def == User)156return false;157158// The value defined by an invoke dominates an instruction only if it159// dominates every instruction in UseBB.160// A PHI is dominated only if the instruction dominates every possible use in161// the UseBB.162if (isa<InvokeInst>(Def) || isa<CallBrInst>(Def) || isa<PHINode>(User))163return dominates(Def, UseBB);164165if (DefBB != UseBB)166return dominates(DefBB, UseBB);167168return Def->comesBefore(User);169}170171// true if Def would dominate a use in any instruction in UseBB.172// note that dominates(Def, Def->getParent()) is false.173bool DominatorTree::dominates(const Instruction *Def,174const BasicBlock *UseBB) const {175const BasicBlock *DefBB = Def->getParent();176177// Any unreachable use is dominated, even if DefBB == UseBB.178if (!isReachableFromEntry(UseBB))179return true;180181// Unreachable definitions don't dominate anything.182if (!isReachableFromEntry(DefBB))183return false;184185if (DefBB == UseBB)186return false;187188// Invoke results are only usable in the normal destination, not in the189// exceptional destination.190if (const auto *II = dyn_cast<InvokeInst>(Def)) {191BasicBlock *NormalDest = II->getNormalDest();192BasicBlockEdge E(DefBB, NormalDest);193return dominates(E, UseBB);194}195196return dominates(DefBB, UseBB);197}198199bool DominatorTree::dominates(const BasicBlockEdge &BBE,200const BasicBlock *UseBB) const {201// If the BB the edge ends in doesn't dominate the use BB, then the202// edge also doesn't.203const BasicBlock *Start = BBE.getStart();204const BasicBlock *End = BBE.getEnd();205if (!dominates(End, UseBB))206return false;207208// Simple case: if the end BB has a single predecessor, the fact that it209// dominates the use block implies that the edge also does.210if (End->getSinglePredecessor())211return true;212213// The normal edge from the invoke is critical. Conceptually, what we would214// like to do is split it and check if the new block dominates the use.215// With X being the new block, the graph would look like:216//217// DefBB218// /\ . .219// / \ . .220// / \ . .221// / \ | |222// A X B C223// | \ | /224// . \|/225// . NormalDest226// .227//228// Given the definition of dominance, NormalDest is dominated by X iff X229// dominates all of NormalDest's predecessors (X, B, C in the example). X230// trivially dominates itself, so we only have to find if it dominates the231// other predecessors. Since the only way out of X is via NormalDest, X can232// only properly dominate a node if NormalDest dominates that node too.233int IsDuplicateEdge = 0;234for (const BasicBlock *BB : predecessors(End)) {235if (BB == Start) {236// If there are multiple edges between Start and End, by definition they237// can't dominate anything.238if (IsDuplicateEdge++)239return false;240continue;241}242243if (!dominates(End, BB))244return false;245}246return true;247}248249bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {250Instruction *UserInst = cast<Instruction>(U.getUser());251// A PHI in the end of the edge is dominated by it.252PHINode *PN = dyn_cast<PHINode>(UserInst);253if (PN && PN->getParent() == BBE.getEnd() &&254PN->getIncomingBlock(U) == BBE.getStart())255return true;256257// Otherwise use the edge-dominates-block query, which258// handles the crazy critical edge cases properly.259const BasicBlock *UseBB;260if (PN)261UseBB = PN->getIncomingBlock(U);262else263UseBB = UserInst->getParent();264return dominates(BBE, UseBB);265}266267bool DominatorTree::dominates(const Value *DefV, const Use &U) const {268const Instruction *Def = dyn_cast<Instruction>(DefV);269if (!Def) {270assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&271"Should be called with an instruction, argument or constant");272return true; // Arguments and constants dominate everything.273}274275Instruction *UserInst = cast<Instruction>(U.getUser());276const BasicBlock *DefBB = Def->getParent();277278// Determine the block in which the use happens. PHI nodes use279// their operands on edges; simulate this by thinking of the use280// happening at the end of the predecessor block.281const BasicBlock *UseBB;282if (PHINode *PN = dyn_cast<PHINode>(UserInst))283UseBB = PN->getIncomingBlock(U);284else285UseBB = UserInst->getParent();286287// Any unreachable use is dominated, even if Def == User.288if (!isReachableFromEntry(UseBB))289return true;290291// Unreachable definitions don't dominate anything.292if (!isReachableFromEntry(DefBB))293return false;294295// Invoke instructions define their return values on the edges to their normal296// successors, so we have to handle them specially.297// Among other things, this means they don't dominate anything in298// their own block, except possibly a phi, so we don't need to299// walk the block in any case.300if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {301BasicBlock *NormalDest = II->getNormalDest();302BasicBlockEdge E(DefBB, NormalDest);303return dominates(E, U);304}305306// If the def and use are in different blocks, do a simple CFG dominator307// tree query.308if (DefBB != UseBB)309return dominates(DefBB, UseBB);310311// Ok, def and use are in the same block. If the def is an invoke, it312// doesn't dominate anything in the block. If it's a PHI, it dominates313// everything in the block.314if (isa<PHINode>(UserInst))315return true;316317return Def->comesBefore(UserInst);318}319320bool DominatorTree::isReachableFromEntry(const Use &U) const {321Instruction *I = dyn_cast<Instruction>(U.getUser());322323// ConstantExprs aren't really reachable from the entry block, but they324// don't need to be treated like unreachable code either.325if (!I) return true;326327// PHI nodes use their operands on their incoming edges.328if (PHINode *PN = dyn_cast<PHINode>(I))329return isReachableFromEntry(PN->getIncomingBlock(U));330331// Everything else uses their operands in their own block.332return isReachableFromEntry(I->getParent());333}334335// Edge BBE1 dominates edge BBE2 if they match or BBE1 dominates start of BBE2.336bool DominatorTree::dominates(const BasicBlockEdge &BBE1,337const BasicBlockEdge &BBE2) const {338if (BBE1.getStart() == BBE2.getStart() && BBE1.getEnd() == BBE2.getEnd())339return true;340return dominates(BBE1, BBE2.getStart());341}342343Instruction *DominatorTree::findNearestCommonDominator(Instruction *I1,344Instruction *I2) const {345BasicBlock *BB1 = I1->getParent();346BasicBlock *BB2 = I2->getParent();347if (BB1 == BB2)348return I1->comesBefore(I2) ? I1 : I2;349if (!isReachableFromEntry(BB2))350return I1;351if (!isReachableFromEntry(BB1))352return I2;353BasicBlock *DomBB = findNearestCommonDominator(BB1, BB2);354if (BB1 == DomBB)355return I1;356if (BB2 == DomBB)357return I2;358return DomBB->getTerminator();359}360361//===----------------------------------------------------------------------===//362// DominatorTreeAnalysis and related pass implementations363//===----------------------------------------------------------------------===//364//365// This implements the DominatorTreeAnalysis which is used with the new pass366// manager. It also implements some methods from utility passes.367//368//===----------------------------------------------------------------------===//369370DominatorTree DominatorTreeAnalysis::run(Function &F,371FunctionAnalysisManager &) {372DominatorTree DT;373DT.recalculate(F);374return DT;375}376377AnalysisKey DominatorTreeAnalysis::Key;378379DominatorTreePrinterPass::DominatorTreePrinterPass(raw_ostream &OS) : OS(OS) {}380381PreservedAnalyses DominatorTreePrinterPass::run(Function &F,382FunctionAnalysisManager &AM) {383OS << "DominatorTree for function: " << F.getName() << "\n";384AM.getResult<DominatorTreeAnalysis>(F).print(OS);385386return PreservedAnalyses::all();387}388389PreservedAnalyses DominatorTreeVerifierPass::run(Function &F,390FunctionAnalysisManager &AM) {391auto &DT = AM.getResult<DominatorTreeAnalysis>(F);392assert(DT.verify());393(void)DT;394return PreservedAnalyses::all();395}396397//===----------------------------------------------------------------------===//398// DominatorTreeWrapperPass Implementation399//===----------------------------------------------------------------------===//400//401// The implementation details of the wrapper pass that holds a DominatorTree402// suitable for use with the legacy pass manager.403//404//===----------------------------------------------------------------------===//405406char DominatorTreeWrapperPass::ID = 0;407408DominatorTreeWrapperPass::DominatorTreeWrapperPass() : FunctionPass(ID) {409initializeDominatorTreeWrapperPassPass(*PassRegistry::getPassRegistry());410}411412INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",413"Dominator Tree Construction", true, true)414415bool DominatorTreeWrapperPass::runOnFunction(Function &F) {416DT.recalculate(F);417return false;418}419420void DominatorTreeWrapperPass::verifyAnalysis() const {421if (VerifyDomInfo)422assert(DT.verify(DominatorTree::VerificationLevel::Full));423else if (ExpensiveChecksEnabled)424assert(DT.verify(DominatorTree::VerificationLevel::Basic));425}426427void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {428DT.print(OS);429}430431432