25#include "llvm/ADT/ScopeExit.h"
26#include "llvm/Support/Casting.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/DebugLog.h"
32#define DEBUG_TYPE "dead-code-analysis"
49 os << (live ?
"live" :
"dead");
56 if (pp->isBlockStart()) {
59 solver->
enqueue({pp, analysis});
65 }
else if (
auto *latticeAnchor =
66 llvm::dyn_cast_if_present<GenericLatticeAnchor *>(
anchor)) {
68 if (
auto *edge = dyn_cast<CFGEdge>(latticeAnchor)) {
83 os <<
"predecessors:";
103 if (!inputs.empty()) {
104 ValueRange &curInputs = successorInputs[predecessor];
105 if (curInputs != inputs) {
118 return FusedLoc::get(
139 LDBG() <<
"Initializing DeadCodeAnalysis for top-level op: "
148 LDBG() <<
"Marked entry block live for region in op: "
154 initializeSymbolCallables(top);
156 return initializeRecursively(top);
159void DeadCodeAnalysis::initializeSymbolCallables(
Operation *top) {
160 LDBG() <<
"[init] Entering initializeSymbolCallables for top-level op: "
164 auto walkFn = [&](
Operation *symTable,
bool allUsesVisible) {
165 LDBG() <<
"[init] Processing symbol table op: "
168 Block *symbolTableBlock = &symbolTableRegion.
front();
170 bool foundSymbolCallable =
false;
171 for (
auto callable : symbolTableBlock->
getOps<CallableOpInterface>()) {
172 LDBG() <<
"[init] Found CallableOpInterface: "
175 Region *callableRegion = callable.getCallableRegion();
178 auto symbol = dyn_cast<SymbolOpInterface>(callable.getOperation());
184 if (symbol.isPublic() || (!allUsesVisible && symbol.isNested())) {
188 LDBG() <<
"[init] Marked callable as having unknown predecessors: "
192 foundSymbolCallable =
true;
196 if (!foundSymbolCallable)
200 std::optional<SymbolTable::UseRange> uses =
205 LDBG() <<
"[init] Could not gather symbol uses, conservatively marking "
206 "all nested callables as having unknown predecessors";
207 return top->
walk([&](CallableOpInterface callable) {
211 LDBG() <<
"[init] Marked nested callable as "
212 "having unknown predecessors: "
218 for (
const SymbolTable::SymbolUse &use : *uses) {
219 if (isa<CallOpInterface>(use.getUser()))
223 Operation *symbol = symbolTable.lookupSymbolIn(top, use.getSymbolRef());
228 LDBG() <<
"[init] Found non-call use for symbol, "
229 "marked as having unknown predecessors: "
230 << OpWithFlags(symbol, OpPrintingFlags().skipRegions());
235 LDBG() <<
"[init] Finished initializeSymbolCallables for top-level op: "
236 << OpWithFlags(top, OpPrintingFlags().skipRegions());
243 isa<RegionBranchOpInterface, CallableOpInterface>(op->
getParentOp()) &&
247LogicalResult DeadCodeAnalysis::initializeRecursively(Operation *op) {
248 LDBG() <<
"[init] Entering initializeRecursively for op: "
249 << OpWithFlags(op, OpPrintingFlags().skipRegions());
253 LDBG() <<
"[init] Visiting op with control-flow semantics: "
254 << OpWithFlags(op, OpPrintingFlags().skipRegions());
259 ->blockContentSubscribe(
this);
269 bool savedHasSymbolTable = hasSymbolTable;
270 auto restoreHasSymbolTable =
271 llvm::make_scope_exit([&]() { hasSymbolTable = savedHasSymbolTable; });
272 if (!hasSymbolTable && op->
hasTrait<OpTrait::SymbolTable>())
273 hasSymbolTable =
true;
276 LDBG() <<
"[init] Recursing into region of op: "
277 << OpWithFlags(op, OpPrintingFlags().skipRegions());
278 for (Operation &nestedOp : region.getOps()) {
279 LDBG() <<
"[init] Recursing into nested op: "
280 << OpWithFlags(&nestedOp, OpPrintingFlags().skipRegions());
281 if (
failed(initializeRecursively(&nestedOp)))
286 LDBG() <<
"[init] Finished initializeRecursively for op: "
287 << OpWithFlags(op, OpPrintingFlags().skipRegions());
291void DeadCodeAnalysis::markEdgeLive(
Block *from,
Block *to) {
292 LDBG() <<
"Marking edge live from block " << from <<
" to block " << to;
300void DeadCodeAnalysis::markEntryBlocksLive(Operation *op) {
301 LDBG() <<
"Marking entry blocks live for op: "
302 << OpWithFlags(op, OpPrintingFlags().skipRegions());
309 LDBG() <<
"Marked entry block live for region in op: "
310 << OpWithFlags(op, OpPrintingFlags().skipRegions());
315 LDBG() <<
"Visiting program point: " << *point;
319 LDBG() <<
"Visiting operation: "
326 LDBG() <<
"Parent block not live, skipping op: "
332 if (
auto call = dyn_cast<CallOpInterface>(op)) {
333 LDBG() <<
"Visiting call operation: "
335 visitCallOperation(call);
341 if (
auto branch = dyn_cast<RegionBranchOpInterface>(op)) {
342 LDBG() <<
"Visiting region branch operation: "
344 visitRegionBranchOperation(branch);
347 }
else if (
auto callable = dyn_cast<CallableOpInterface>(op)) {
348 LDBG() <<
"Visiting callable operation: "
355 if (!callsites->allPredecessorsKnown() ||
356 !callsites->getKnownPredecessors().empty())
357 markEntryBlocksLive(callable);
361 LDBG() <<
"Marking all entry blocks live for op: "
363 markEntryBlocksLive(op);
368 if (
auto branch = dyn_cast<RegionBranchOpInterface>(op->
getParentOp())) {
369 LDBG() <<
"Visiting region terminator: "
372 visitRegionTerminator(op, branch);
373 }
else if (
auto callable =
374 dyn_cast<CallableOpInterface>(op->
getParentOp())) {
375 LDBG() <<
"Visiting callable terminator: "
378 visitCallableTerminator(op, callable);
384 if (
auto branch = dyn_cast<BranchOpInterface>(op)) {
385 LDBG() <<
"Visiting branch operation: "
387 visitBranchOperation(branch);
391 LDBG() <<
"Marking all successors live for op: "
394 markEdgeLive(op->
getBlock(), successor);
401void DeadCodeAnalysis::visitCallOperation(CallOpInterface call) {
402 LDBG() <<
"visitCallOperation: "
407 callableOp = call.resolveCallableInTable(&symbolTable);
410 <<
"No symbol table present in analysis scope, can't resolve callable";
413 const auto isExternalCallable = [
this](
Operation *op) {
418 if (
auto callable = dyn_cast<CallableOpInterface>(op))
419 return !callable.getCallableRegion();
426 if (isa_and_nonnull<SymbolOpInterface>(callableOp) &&
427 !isExternalCallable(callableOp)) {
432 LDBG() <<
"Added callsite as predecessor for callable: "
439 LDBG() <<
"Marked call op's predecessors as unknown for: "
447std::optional<SmallVector<Attribute>>
448DeadCodeAnalysis::getOperandValues(Operation *op) {
449 SmallVector<Attribute> operands;
455 if (cv->
getValue().isUninitialized())
457 operands.push_back(cv->
getValue().getConstantValue());
462void DeadCodeAnalysis::visitBranchOperation(BranchOpInterface branch) {
463 LDBG() <<
"visitBranchOperation: "
464 << OpWithFlags(branch.getOperation(), OpPrintingFlags().skipRegions());
466 std::optional<SmallVector<Attribute>> operands = getOperandValues(branch);
470 if (
Block *successor = branch.getSuccessorForOperands(*operands)) {
471 markEdgeLive(branch->getBlock(), successor);
472 LDBG() <<
"Branch has single successor: " << successor;
475 for (
Block *successor : branch->getSuccessors())
476 markEdgeLive(branch->getBlock(), successor);
477 LDBG() <<
"Branch has multiple/all successors live";
481void DeadCodeAnalysis::visitRegionBranchOperation(
482 RegionBranchOpInterface branch) {
483 LDBG() <<
"visitRegionBranchOperation: "
484 << OpWithFlags(branch.getOperation(), OpPrintingFlags().skipRegions());
486 std::optional<SmallVector<Attribute>> operands = getOperandValues(branch);
490 SmallVector<RegionSuccessor> successors;
491 branch.getEntrySuccessorRegions(*operands, successors);
493 visitRegionBranchEdges(branch, branch.getOperation(), successors);
496void DeadCodeAnalysis::visitRegionTerminator(Operation *op,
497 RegionBranchOpInterface branch) {
498 LDBG() <<
"visitRegionTerminator: " << *op;
499 std::optional<SmallVector<Attribute>> operands = getOperandValues(op);
503 SmallVector<RegionSuccessor> successors;
504 auto terminator = dyn_cast<RegionBranchTerminatorOpInterface>(op);
507 terminator.getSuccessorRegions(*operands, successors);
508 visitRegionBranchEdges(branch, op, successors);
511void DeadCodeAnalysis::visitRegionBranchEdges(
512 RegionBranchOpInterface regionBranchOp, Operation *predecessorOp,
513 const SmallVector<RegionSuccessor> &successors) {
514 for (
const RegionSuccessor &successor : successors) {
516 ProgramPoint *point =
517 successor.getSuccessor()
524 LDBG() <<
"Marked region successor live: " << *point;
530 predecessors->join(predecessorOp, successor.getSuccessorInputs()));
531 LDBG() <<
"Added region branch as predecessor for successor: " << *point;
535void DeadCodeAnalysis::visitCallableTerminator(Operation *op,
536 CallableOpInterface callable) {
537 LDBG() <<
"visitCallableTerminator: " << *op;
541 bool canResolve = op->
hasTrait<OpTrait::ReturnLike>();
542 for (Operation *predecessor : callsites->getKnownPredecessors()) {
543 assert(isa<CallOpInterface>(predecessor));
548 LDBG() <<
"Added callable terminator as predecessor for callsite: "
549 << OpWithFlags(predecessor, OpPrintingFlags().skipRegions());
554 predecessors->setHasUnknownPredecessors());
555 LDBG() <<
"Could not resolve callable terminator for callsite: "
556 << OpWithFlags(predecessor, OpPrintingFlags().skipRegions());
static bool isRegionOrCallableReturn(Operation *op)
Returns true if the operation is a returning terminator in region control-flow or the terminator of a...
virtual void onUpdate(DataFlowSolver *solver) const
This function is called by the solver when the analysis state is updated to enqueue more work items.
LatticeAnchor anchor
The lattice anchor to which the state belongs.
friend class DataFlowSolver
Allow the framework to access the dependents.
Block represents an ordered list of Operations.
iterator_range< op_iterator< OpT > > getOps()
Return an iterator range over the operations within this block that are of 'OpT'.
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Operation * getTerminator()
Get the terminator operation of this block.
void print(raw_ostream &os)
Base class for all data-flow analyses.
ProgramPoint * getProgramPointBefore(Operation *op)
Get a uniqued program point instance.
void propagateIfChanged(AnalysisState *state, ChangeResult changed)
Propagate an update to a state if it changed.
StateT * getOrCreate(AnchorT anchor)
Get the analysis state associated with the lattice anchor.
ProgramPoint * getProgramPointAfter(Operation *op)
DataFlowAnalysis(DataFlowSolver &solver)
Create an analysis with a reference to the parent solver.
AnchorT * getLatticeAnchor(Args &&...args)
Get or create a custom lattice anchor.
void registerAnchorKind()
Register a custom lattice anchor class.
friend class DataFlowSolver
Allow the data-flow solver to access the internals of this class.
const StateT * getOrCreateFor(ProgramPoint *dependent, AnchorT anchor)
Get a read-only analysis state for the given point and create a dependency on dependent.
void enqueue(WorkItem item)
Push a work item onto the worklist.
ProgramPoint * getProgramPointBefore(Operation *op)
Get a uniqued program point instance.
ProgramPoint * getProgramPointAfter(Operation *op)
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Set of flags used to control the behavior of the various IR print methods (e.g.
A trait used to provide symbol table functionalities to a region operation.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Operation is the basic unit of execution within MLIR.
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
unsigned getNumSuccessors()
Block * getBlock()
Returns the operation block that contains this operation.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
unsigned getNumOperands()
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
operand_range getOperands()
Returns an iterator on the underlying Value's.
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
SuccessorRange getSuccessors()
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Location getLoc()
Return a location for this region.
static void walkSymbolTables(Operation *op, bool allSymUsesVisible, function_ref< void(Operation *, bool)> callback)
Walks all symbol table operations nested within, and including, op.
static std::optional< UseRange > getSymbolUses(Operation *from)
Get an iterator range for all of the uses, for any symbol, that are nested within the given operation...
This class provides an abstraction over the different types of ranges over Values.
void useDefSubscribe(DataFlowAnalysis *analysis)
Subscribe an analysis to updates of the lattice.
Location getLoc() const override
Get a fused location of both blocks.
Block * getTo() const
Get the target block.
Block * getFrom() const
Get the block from which the edge originates.
void print(raw_ostream &os) const override
Print the blocks between the control-flow edge.
DeadCodeAnalysis(DataFlowSolver &solver)
LogicalResult visit(ProgramPoint *point) override
Visit an operation with control-flow semantics and deduce which of its successors are live.
LogicalResult initialize(Operation *top) override
Initialize the analysis by visiting every operation with potential control-flow semantics.
void onUpdate(DataFlowSolver *solver) const override
When the state of the lattice anchor is changed to live, re-invoke subscribed analyses on the operati...
ChangeResult setToLive()
Set the state of the lattice anchor to live.
void print(raw_ostream &os) const override
Print the liveness.
ValueT & getValue()
Return the value held by this lattice.
ArrayRef< Operation * > getKnownPredecessors() const
Get the known predecessors.
bool allPredecessorsKnown() const
Returns true if all predecessors are known.
void print(raw_ostream &os) const override
Print the known predecessors.
ChangeResult join(Operation *predecessor)
Add a known predecessor.
Include the generated interface declarations.
ChangeResult
A result type used to indicate if a change happened.
Program point represents a specific location in the execution of a program.
bool isBlockStart() const
Operation * getPrevOp() const
Get the previous operation of this program point.