1//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements sparse conditional constant propagation and merging:
10//
11// Specifically, this:
12// * Assumes values are constant unless proven otherwise
13// * Assumes BasicBlocks are dead unless proven otherwise
14// * Proves values to be constant, and replaces them with constants
15// * Proves conditional branches to be unconditional
16//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Transforms/Scalar/SCCP.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/AssumptionCache.h"
24#include "llvm/Analysis/DomTreeUpdater.h"
25#include "llvm/Analysis/GlobalsModRef.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
27#include "llvm/Analysis/ValueLatticeUtils.h"
28#include "llvm/Analysis/ValueTracking.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/PassManager.h"
36#include "llvm/IR/Type.h"
37#include "llvm/IR/Value.h"
38#include "llvm/Pass.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/raw_ostream.h"
41#include "llvm/Transforms/Scalar.h"
42#include "llvm/Transforms/Utils/Local.h"
43#include "llvm/Transforms/Utils/SCCPSolver.h"
44
45using namespace llvm;
46
47#define DEBUG_TYPE "sccp"
48
49STATISTIC(NumInstRemoved, "Number of instructions removed");
50STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
51STATISTIC(NumInstReplaced,
52 "Number of instructions replaced with (simpler) instruction");
53
54// runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
55// and return true if the function was modified.
56static bool runSCCP(Function &F, const DataLayout &DL,
57 const TargetLibraryInfo *TLI, DominatorTree &DT,
58 AssumptionCache &AC) {
59 LLVM_DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
60 SCCPSolver Solver(
61 DL, [TLI](Function &F) -> const TargetLibraryInfo & { return *TLI; },
62 F.getContext());
63
64 Solver.addPredicateInfo(F, DT, AC);
65
66 // While we don't do any actual inter-procedural analysis, still track
67 // return values so we can infer attributes.
68 if (canTrackReturnsInterprocedurally(F: &F))
69 Solver.addTrackedFunction(F: &F);
70
71 // Mark the first block of the function as being executable.
72 Solver.markBlockExecutable(BB: &F.front());
73
74 // Initialize arguments based on attributes.
75 for (Argument &AI : F.args())
76 Solver.trackValueOfArgument(V: &AI);
77
78 // Solve for constants.
79 bool ResolvedUndefs = true;
80 while (ResolvedUndefs) {
81 Solver.solve();
82 LLVM_DEBUG(dbgs() << "RESOLVING UNDEFs\n");
83 ResolvedUndefs = Solver.resolvedUndefsIn(F);
84 }
85
86 bool MadeChanges = false;
87
88 // If we decided that there are basic blocks that are dead in this function,
89 // delete their contents now. Note that we cannot actually delete the blocks,
90 // as we cannot modify the CFG of the function.
91
92 SmallPtrSet<Value *, 32> InsertedValues;
93 SmallVector<BasicBlock *, 8> BlocksToErase;
94 for (BasicBlock &BB : F) {
95 if (!Solver.isBlockExecutable(BB: &BB)) {
96 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << BB);
97 ++NumDeadBlocks;
98 BlocksToErase.push_back(Elt: &BB);
99 MadeChanges = true;
100 continue;
101 }
102
103 MadeChanges |= Solver.simplifyInstsInBlock(BB, InsertedValues,
104 InstRemovedStat&: NumInstRemoved, InstReplacedStat&: NumInstReplaced);
105 }
106
107 // Remove unreachable blocks and non-feasible edges.
108 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
109 for (BasicBlock *DeadBB : BlocksToErase)
110 NumInstRemoved += changeToUnreachable(I: &*DeadBB->getFirstNonPHIIt(),
111 /*PreserveLCSSA=*/false, DTU: &DTU);
112
113 BasicBlock *NewUnreachableBB = nullptr;
114 for (BasicBlock &BB : F)
115 MadeChanges |= Solver.removeNonFeasibleEdges(BB: &BB, DTU, NewUnreachableBB);
116
117 for (BasicBlock *DeadBB : BlocksToErase)
118 if (!DeadBB->hasAddressTaken())
119 DTU.deleteBB(DelBB: DeadBB);
120
121 Solver.removeSSACopies(F);
122
123 Solver.inferReturnAttributes();
124
125 return MadeChanges;
126}
127
128PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
129 const DataLayout &DL = F.getDataLayout();
130 auto &TLI = AM.getResult<TargetLibraryAnalysis>(IR&: F);
131 auto &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F);
132 auto &AC = AM.getResult<AssumptionAnalysis>(IR&: F);
133 if (!runSCCP(F, DL, TLI: &TLI, DT, AC))
134 return PreservedAnalyses::all();
135
136 auto PA = PreservedAnalyses();
137 PA.preserve<DominatorTreeAnalysis>();
138 return PA;
139}
140