blob: 40c4dbb45fc522e970d26b008c6879caefe3e0c7 [file] [log] [blame]
Misha Brukman373086d2003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +00009//
Misha Brukman373086d2003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner347389d2001-06-27 23:38:11 +000011//
12// Specifically, this:
13// * Assumes values are constant unless proven otherwise
14// * Assumes BasicBlocks are dead unless proven otherwise
15// * Proves values to be constant, and replaces them with constants
Chris Lattnerdd6522e2002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner347389d2001-06-27 23:38:11 +000017//
18// Notice that:
19// * This pass has a habit of making definitions be dead. It is a good idea
20// to to run a DCE pass sometime after running this pass.
21//
22//===----------------------------------------------------------------------===//
23
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000024#include "llvm/Transforms/Scalar.h"
Chris Lattner0fe5b322004-01-12 17:43:40 +000025#include "llvm/Constants.h"
Chris Lattner57698e22002-03-26 18:01:55 +000026#include "llvm/Function.h"
Chris Lattner49f74522004-01-12 04:29:41 +000027#include "llvm/GlobalVariable.h"
Chris Lattnercccc5c72003-04-25 02:50:03 +000028#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000029#include "llvm/Pass.h"
Chris Lattner0fe5b322004-01-12 17:43:40 +000030#include "llvm/Type.h"
Chris Lattner6e560792002-04-18 15:13:15 +000031#include "llvm/Support/InstVisitor.h"
Chris Lattnerff9362a2004-04-13 19:43:54 +000032#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
34#include "llvm/ADT/hash_map"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/STLExtras.h"
Chris Lattner347389d2001-06-27 23:38:11 +000037#include <algorithm>
Chris Lattner347389d2001-06-27 23:38:11 +000038#include <set>
Chris Lattner49525f82004-01-09 06:02:20 +000039using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000040
Chris Lattner347389d2001-06-27 23:38:11 +000041// InstVal class - This class represents the different lattice values that an
Chris Lattnerc8e66542002-04-27 06:56:12 +000042// instruction may occupy. It is a simple class with value semantics.
Chris Lattner347389d2001-06-27 23:38:11 +000043//
Chris Lattner7d325382002-04-29 21:26:08 +000044namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000045 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
46
Chris Lattner347389d2001-06-27 23:38:11 +000047class InstVal {
48 enum {
Chris Lattner3462ae32001-12-03 22:26:30 +000049 undefined, // This instruction has no known value
50 constant, // This instruction has a constant value
Chris Lattner3462ae32001-12-03 22:26:30 +000051 overdefined // This instruction has an unknown value
52 } LatticeValue; // The current lattice position
53 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000054public:
Chris Lattner3462ae32001-12-03 22:26:30 +000055 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner347389d2001-06-27 23:38:11 +000056
57 // markOverdefined - Return true if this is a new status to be in...
58 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000059 if (LatticeValue != overdefined) {
60 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000061 return true;
62 }
63 return false;
64 }
65
66 // markConstant - Return true if this is a new status for us...
Chris Lattner3462ae32001-12-03 22:26:30 +000067 inline bool markConstant(Constant *V) {
68 if (LatticeValue != constant) {
69 LatticeValue = constant;
Chris Lattner347389d2001-06-27 23:38:11 +000070 ConstantVal = V;
71 return true;
72 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +000073 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +000074 }
75 return false;
76 }
77
Chris Lattner3462ae32001-12-03 22:26:30 +000078 inline bool isUndefined() const { return LatticeValue == undefined; }
79 inline bool isConstant() const { return LatticeValue == constant; }
80 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +000081
Chris Lattner05fe6842004-01-12 03:57:30 +000082 inline Constant *getConstant() const {
83 assert(isConstant() && "Cannot get the constant of a non-constant!");
84 return ConstantVal;
85 }
Chris Lattner347389d2001-06-27 23:38:11 +000086};
87
Chris Lattner7d325382002-04-29 21:26:08 +000088} // end anonymous namespace
Chris Lattner347389d2001-06-27 23:38:11 +000089
90
91//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +000092//
Chris Lattner074be1f2004-11-15 04:44:20 +000093/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
94/// Constant Propagation.
95///
96class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner7f74a562002-01-20 22:54:45 +000097 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattnerd79334d2004-07-15 23:36:43 +000098 hash_map<Value*, InstVal> ValueState; // The state each value is in...
Chris Lattner347389d2001-06-27 23:38:11 +000099
Chris Lattnerd79334d2004-07-15 23:36:43 +0000100 // The reason for two worklists is that overdefined is the lowest state
101 // on the lattice, and moving things to overdefined as fast as possible
102 // makes SCCP converge much faster.
103 // By having a separate worklist, we accomplish this because everything
104 // possibly overdefined will become overdefined at the soonest possible
105 // point.
106 std::vector<Instruction*> OverdefinedInstWorkList;// The overdefined
107 // instruction work list
Chris Lattnerd66a6e32002-05-07 04:29:32 +0000108 std::vector<Instruction*> InstWorkList;// The instruction work list
Chris Lattnerd79334d2004-07-15 23:36:43 +0000109
110
Chris Lattner7f74a562002-01-20 22:54:45 +0000111 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000112
Chris Lattner05fe6842004-01-12 03:57:30 +0000113 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
114 /// overdefined, despite the fact that the PHI node is overdefined.
115 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
116
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000117 /// KnownFeasibleEdges - Entries in this set are edges which have already had
118 /// PHI nodes retriggered.
119 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
120 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000121public:
122
Chris Lattner074be1f2004-11-15 04:44:20 +0000123 /// MarkBlockExecutable - This method can be used by clients to mark all of
124 /// the blocks that are known to be intrinsically live in the processed unit.
125 void MarkBlockExecutable(BasicBlock *BB) {
126 DEBUG(std::cerr << "Marking Block Executable: " << BB->getName() << "\n");
127 BBExecutable.insert(BB); // Basic block is executable!
128 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner7d325382002-04-29 21:26:08 +0000129 }
130
Chris Lattner074be1f2004-11-15 04:44:20 +0000131 /// Solve - Solve for constants and executable blocks.
132 ///
133 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000134
Chris Lattner074be1f2004-11-15 04:44:20 +0000135 /// getExecutableBlocks - Once we have solved for constants, return the set of
136 /// blocks that is known to be executable.
137 std::set<BasicBlock*> &getExecutableBlocks() {
138 return BBExecutable;
139 }
140
141 /// getValueMapping - Once we have solved for constants, return the mapping of
142 /// LLVM values to InstVals.
143 hash_map<Value*, InstVal> &getValueMapping() {
144 return ValueState;
145 }
146
Chris Lattner347389d2001-06-27 23:38:11 +0000147private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000148 // markConstant - Make a value be marked as "constant". If the value
Chris Lattner347389d2001-06-27 23:38:11 +0000149 // is not already a constant, add it to the instruction work list so that
150 // the users of the instruction are updated later.
151 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000152 inline void markConstant(InstVal &IV, Instruction *I, Constant *C) {
153 if (IV.markConstant(C)) {
154 DEBUG(std::cerr << "markConstant: " << *C << ": " << *I);
Chris Lattnerd66a6e32002-05-07 04:29:32 +0000155 InstWorkList.push_back(I);
Chris Lattner347389d2001-06-27 23:38:11 +0000156 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000157 }
158 inline void markConstant(Instruction *I, Constant *C) {
159 markConstant(ValueState[I], I, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000160 }
161
Chris Lattnerd79334d2004-07-15 23:36:43 +0000162 // markOverdefined - Make a value be marked as "overdefined". If the
163 // value is not already overdefined, add it to the overdefined instruction
164 // work list so that the users of the instruction are updated later.
165
Chris Lattner7324f7c2003-10-08 16:21:03 +0000166 inline void markOverdefined(InstVal &IV, Instruction *I) {
167 if (IV.markOverdefined()) {
168 DEBUG(std::cerr << "markOverdefined: " << *I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000169 // Only instructions go on the work list
170 OverdefinedInstWorkList.push_back(I);
Chris Lattner347389d2001-06-27 23:38:11 +0000171 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000172 }
173 inline void markOverdefined(Instruction *I) {
174 markOverdefined(ValueState[I], I);
Chris Lattner347389d2001-06-27 23:38:11 +0000175 }
176
177 // getValueState - Return the InstVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000178 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000179 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000180 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000181 // Instruction object, then use this accessor to get its value from the map.
182 //
183 inline InstVal &getValueState(Value *V) {
Chris Lattnerd79334d2004-07-15 23:36:43 +0000184 hash_map<Value*, InstVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000185 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner646354b2004-10-16 18:09:41 +0000186
187 if (isa<UndefValue>(V)) {
188 // Nothing to do, remain undefined.
189 } else if (Constant *CPV = dyn_cast<Constant>(V)) {
190 ValueState[CPV].markConstant(CPV); // Constants are constant
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000191 } else if (isa<Argument>(V)) { // Arguments are overdefined
Chris Lattner347389d2001-06-27 23:38:11 +0000192 ValueState[V].markOverdefined();
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000193 }
Chris Lattner347389d2001-06-27 23:38:11 +0000194 // All others are underdefined by default...
195 return ValueState[V];
196 }
197
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000198 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000199 // work list if it is not already executable...
200 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000201 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
202 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
203 return; // This edge is already known to be executable!
204
205 if (BBExecutable.count(Dest)) {
206 DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
207 << " -> " << Dest->getName() << "\n");
208
209 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000210 // feasible that wasn't before. Revisit the PHI nodes in the block
211 // because they have potentially new operands.
Reid Spencer66149462004-09-15 17:06:42 +0000212 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I) {
213 PHINode *PN = cast<PHINode>(I);
Chris Lattner3c982762003-04-25 03:35:10 +0000214 visitPHINode(*PN);
Reid Spencer66149462004-09-15 17:06:42 +0000215 }
Chris Lattnercccc5c72003-04-25 02:50:03 +0000216
217 } else {
Chris Lattner074be1f2004-11-15 04:44:20 +0000218 MarkBlockExecutable(Dest);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000219 }
Chris Lattner347389d2001-06-27 23:38:11 +0000220 }
221
Chris Lattner074be1f2004-11-15 04:44:20 +0000222 // getFeasibleSuccessors - Return a vector of booleans to indicate which
223 // successors are reachable from a given terminator instruction.
224 //
225 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
226
227 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
228 // block to the 'To' basic block is currently feasible...
229 //
230 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
231
232 // OperandChangedState - This method is invoked on all of the users of an
233 // instruction that was just changed state somehow.... Based on this
234 // information, we need to update the specified user of this instruction.
235 //
236 void OperandChangedState(User *U) {
237 // Only instructions use other variable values!
238 Instruction &I = cast<Instruction>(*U);
239 if (BBExecutable.count(I.getParent())) // Inst is executable?
240 visit(I);
241 }
242
243private:
244 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000245
Chris Lattner6e560792002-04-18 15:13:15 +0000246 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000247 // operand made a transition, or the instruction is newly executable. Change
248 // the value type of I to reflect these changes if appropriate.
249 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000250 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000251
252 // Terminators
Chris Lattner113f4f42002-06-25 16:13:24 +0000253 void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
254 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000255
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000256 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000257 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000258 void visitBinaryOperator(Instruction &I);
259 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000260
261 // Instructions that cannot be folded away...
Chris Lattner113f4f42002-06-25 16:13:24 +0000262 void visitStoreInst (Instruction &I) { /*returns void*/ }
Chris Lattner49f74522004-01-12 04:29:41 +0000263 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000264 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000265 void visitCallInst (CallInst &I);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000266 void visitInvokeInst (TerminatorInst &I) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000267 if (I.getType() != Type::VoidTy) markOverdefined(&I);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000268 visitTerminatorInst(I);
269 }
Chris Lattner9c58cf62003-09-08 18:54:55 +0000270 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000271 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000272 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000273 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
274 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000275 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000276
Chris Lattner113f4f42002-06-25 16:13:24 +0000277 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000278 // If a new instruction is added to LLVM that we don't handle...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000279 std::cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000280 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000281 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000282};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000283
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000284// getFeasibleSuccessors - Return a vector of booleans to indicate which
285// successors are reachable from a given terminator instruction.
286//
Chris Lattner074be1f2004-11-15 04:44:20 +0000287void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
288 std::vector<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000289 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000290 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000291 if (BI->isUnconditional()) {
292 Succs[0] = true;
293 } else {
294 InstVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000295 if (BCValue.isOverdefined() ||
296 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
297 // Overdefined condition variables, and branches on unfoldable constant
298 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000299 Succs[0] = Succs[1] = true;
300 } else if (BCValue.isConstant()) {
301 // Constant condition variables mean the branch can only go a single way
302 Succs[BCValue.getConstant() == ConstantBool::False] = true;
303 }
304 }
Chris Lattner113f4f42002-06-25 16:13:24 +0000305 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000306 // Invoke instructions successors are always executable.
307 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000308 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000309 InstVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000310 if (SCValue.isOverdefined() || // Overdefined condition?
311 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000312 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000313 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000314 } else if (SCValue.isConstant()) {
315 Constant *CPV = SCValue.getConstant();
316 // Make sure to skip the "default value" which isn't a value
317 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
318 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
319 Succs[i] = true;
320 return;
321 }
322 }
323
324 // Constant value not equal to any of the branches... must execute
325 // default branch then...
326 Succs[0] = true;
327 }
328 } else {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000329 std::cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner113f4f42002-06-25 16:13:24 +0000330 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000331 }
332}
333
334
Chris Lattner13b52e72002-05-02 21:18:01 +0000335// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
336// block to the 'To' basic block is currently feasible...
337//
Chris Lattner074be1f2004-11-15 04:44:20 +0000338bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000339 assert(BBExecutable.count(To) && "Dest should always be alive!");
340
341 // Make sure the source basic block is executable!!
342 if (!BBExecutable.count(From)) return false;
343
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000344 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000345 TerminatorInst *TI = From->getTerminator();
346 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
347 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000348 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000349 else {
350 InstVal &BCValue = getValueState(BI->getCondition());
351 if (BCValue.isOverdefined()) {
352 // Overdefined condition variables mean the branch could go either way.
353 return true;
354 } else if (BCValue.isConstant()) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000355 // Not branching on an evaluatable constant?
356 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
357
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000358 // Constant condition variables mean the branch can only go a single way
359 return BI->getSuccessor(BCValue.getConstant() ==
360 ConstantBool::False) == To;
361 }
362 return false;
363 }
364 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
365 // Invoke instructions successors are always executable.
366 return true;
367 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
368 InstVal &SCValue = getValueState(SI->getCondition());
369 if (SCValue.isOverdefined()) { // Overdefined condition?
370 // All destinations are executable!
371 return true;
372 } else if (SCValue.isConstant()) {
373 Constant *CPV = SCValue.getConstant();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000374 if (!isa<ConstantInt>(CPV))
375 return true; // not a foldable constant?
376
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000377 // Make sure to skip the "default value" which isn't a value
378 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
379 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
380 return SI->getSuccessor(i) == To;
381
382 // Constant value not equal to any of the branches... must execute
383 // default branch then...
384 return SI->getDefaultDest() == To;
385 }
386 return false;
387 } else {
388 std::cerr << "Unknown terminator instruction: " << *TI;
389 abort();
390 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000391}
Chris Lattner347389d2001-06-27 23:38:11 +0000392
Chris Lattner6e560792002-04-18 15:13:15 +0000393// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000394// operand made a transition, or the instruction is newly executable. Change
395// the value type of I to reflect these changes if appropriate. This method
396// makes sure to do the following actions:
397//
398// 1. If a phi node merges two constants in, and has conflicting value coming
399// from different branches, or if the PHI node merges in an overdefined
400// value, then the PHI node becomes overdefined.
401// 2. If a phi node merges only constants in, and they all agree on value, the
402// PHI node becomes a constant value equal to that.
403// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
404// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
405// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
406// 6. If a conditional branch has a value that is constant, make the selected
407// destination executable
408// 7. If a conditional branch has a value that is overdefined, make all
409// successors executable.
410//
Chris Lattner074be1f2004-11-15 04:44:20 +0000411void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000412 InstVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000413 if (PNIV.isOverdefined()) {
414 // There may be instructions using this PHI node that are not overdefined
415 // themselves. If so, make sure that they know that the PHI node operand
416 // changed.
417 std::multimap<PHINode*, Instruction*>::iterator I, E;
418 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
419 if (I != E) {
420 std::vector<Instruction*> Users;
421 Users.reserve(std::distance(I, E));
422 for (; I != E; ++I) Users.push_back(I->second);
423 while (!Users.empty()) {
424 visit(Users.back());
425 Users.pop_back();
426 }
427 }
428 return; // Quick exit
429 }
Chris Lattner347389d2001-06-27 23:38:11 +0000430
Chris Lattner7a7b1142004-03-16 19:49:59 +0000431 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
432 // and slow us down a lot. Just mark them overdefined.
433 if (PN.getNumIncomingValues() > 64) {
434 markOverdefined(PNIV, &PN);
435 return;
436 }
437
Chris Lattner6e560792002-04-18 15:13:15 +0000438 // Look at all of the executable operands of the PHI node. If any of them
439 // are overdefined, the PHI becomes overdefined as well. If they are all
440 // constant, and they agree with each other, the PHI becomes the identical
441 // constant. If they are constant and don't agree, the PHI is overdefined.
442 // If there are no executable operands, the PHI remains undefined.
443 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000444 Constant *OperandVal = 0;
445 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
446 InstVal &IV = getValueState(PN.getIncomingValue(i));
447 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000448
Chris Lattner113f4f42002-06-25 16:13:24 +0000449 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000450 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000451 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000452 return;
453 }
454
Chris Lattnercccc5c72003-04-25 02:50:03 +0000455 if (OperandVal == 0) { // Grab the first value...
456 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000457 } else { // Another value is being merged in!
458 // There is already a reachable operand. If we conflict with it,
459 // then the PHI node becomes overdefined. If we agree with it, we
460 // can continue on.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000461
Chris Lattner6e560792002-04-18 15:13:15 +0000462 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000463 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000464 // Yes there is. This means the PHI node is not constant.
465 // You must be overdefined poor PHI.
466 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000467 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000468 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000469 }
Chris Lattner347389d2001-06-27 23:38:11 +0000470 }
471 }
Chris Lattner347389d2001-06-27 23:38:11 +0000472 }
473
Chris Lattner6e560792002-04-18 15:13:15 +0000474 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000475 // arguments that agree with each other(and OperandVal is the constant) or
476 // OperandVal is null because there are no defined incoming arguments. If
477 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000478 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000479 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000480 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000481}
482
Chris Lattner074be1f2004-11-15 04:44:20 +0000483void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000484 std::vector<bool> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000485 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000486
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000487 BasicBlock *BB = TI.getParent();
488
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000489 // Mark all feasible successors executable...
490 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000491 if (SuccFeasible[i])
492 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000493}
494
Chris Lattner074be1f2004-11-15 04:44:20 +0000495void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000496 Value *V = I.getOperand(0);
Chris Lattner6e560792002-04-18 15:13:15 +0000497 InstVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000498 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000499 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000500 else if (VState.isConstant()) // Propagate constant value
501 markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000502}
503
Chris Lattner074be1f2004-11-15 04:44:20 +0000504void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner59db22d2004-03-12 05:52:44 +0000505 InstVal &CondValue = getValueState(I.getCondition());
506 if (CondValue.isOverdefined())
507 markOverdefined(&I);
508 else if (CondValue.isConstant()) {
509 if (CondValue.getConstant() == ConstantBool::True) {
510 InstVal &Val = getValueState(I.getTrueValue());
511 if (Val.isOverdefined())
512 markOverdefined(&I);
513 else if (Val.isConstant())
514 markConstant(&I, Val.getConstant());
515 } else if (CondValue.getConstant() == ConstantBool::False) {
516 InstVal &Val = getValueState(I.getFalseValue());
517 if (Val.isOverdefined())
518 markOverdefined(&I);
519 else if (Val.isConstant())
520 markConstant(&I, Val.getConstant());
521 } else
522 markOverdefined(&I);
523 }
524}
525
Chris Lattner6e560792002-04-18 15:13:15 +0000526// Handle BinaryOperators and Shift Instructions...
Chris Lattner074be1f2004-11-15 04:44:20 +0000527void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000528 InstVal &IV = ValueState[&I];
529 if (IV.isOverdefined()) return;
530
Chris Lattner113f4f42002-06-25 16:13:24 +0000531 InstVal &V1State = getValueState(I.getOperand(0));
532 InstVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000533
Chris Lattner6e560792002-04-18 15:13:15 +0000534 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000535 // If both operands are PHI nodes, it is possible that this instruction has
536 // a constant value, despite the fact that the PHI node doesn't. Check for
537 // this condition now.
538 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
539 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
540 if (PN1->getParent() == PN2->getParent()) {
541 // Since the two PHI nodes are in the same basic block, they must have
542 // entries for the same predecessors. Walk the predecessor list, and
543 // if all of the incoming values are constants, and the result of
544 // evaluating this expression with all incoming value pairs is the
545 // same, then this expression is a constant even though the PHI node
546 // is not a constant!
547 InstVal Result;
548 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
549 InstVal &In1 = getValueState(PN1->getIncomingValue(i));
550 BasicBlock *InBlock = PN1->getIncomingBlock(i);
551 InstVal &In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
552
553 if (In1.isOverdefined() || In2.isOverdefined()) {
554 Result.markOverdefined();
555 break; // Cannot fold this operation over the PHI nodes!
556 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000557 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
558 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000559 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000560 Result.markConstant(V);
561 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000562 Result.markOverdefined();
563 break;
564 }
565 }
566 }
567
568 // If we found a constant value here, then we know the instruction is
569 // constant despite the fact that the PHI nodes are overdefined.
570 if (Result.isConstant()) {
571 markConstant(IV, &I, Result.getConstant());
572 // Remember that this instruction is virtually using the PHI node
573 // operands.
574 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
575 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
576 return;
577 } else if (Result.isUndefined()) {
578 return;
579 }
580
581 // Okay, this really is overdefined now. Since we might have
582 // speculatively thought that this was not overdefined before, and
583 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
584 // make sure to clean out any entries that we put there, for
585 // efficiency.
586 std::multimap<PHINode*, Instruction*>::iterator It, E;
587 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
588 while (It != E) {
589 if (It->second == &I) {
590 UsersOfOverdefinedPHIs.erase(It++);
591 } else
592 ++It;
593 }
594 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
595 while (It != E) {
596 if (It->second == &I) {
597 UsersOfOverdefinedPHIs.erase(It++);
598 } else
599 ++It;
600 }
601 }
602
603 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000604 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000605 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
606 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000607 }
608}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000609
610// Handle getelementptr instructions... if all operands are constants then we
611// can turn this into a getelementptr ConstantExpr.
612//
Chris Lattner074be1f2004-11-15 04:44:20 +0000613void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner49f74522004-01-12 04:29:41 +0000614 InstVal &IV = ValueState[&I];
615 if (IV.isOverdefined()) return;
616
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000617 std::vector<Constant*> Operands;
618 Operands.reserve(I.getNumOperands());
619
620 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
621 InstVal &State = getValueState(I.getOperand(i));
622 if (State.isUndefined())
623 return; // Operands are not resolved yet...
624 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +0000625 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000626 return;
627 }
628 assert(State.isConstant() && "Unknown state!");
629 Operands.push_back(State.getConstant());
630 }
631
632 Constant *Ptr = Operands[0];
633 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
634
Chris Lattner49f74522004-01-12 04:29:41 +0000635 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000636}
Brian Gaeke960707c2003-11-11 22:41:34 +0000637
Chris Lattner49f74522004-01-12 04:29:41 +0000638/// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
639/// return the constant value being addressed by the constant expression, or
640/// null if something is funny.
641///
642static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +0000643 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner49f74522004-01-12 04:29:41 +0000644 return 0; // Do not allow stepping over the value!
645
646 // Loop over all of the operands, tracking down which value we are
647 // addressing...
648 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
649 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +0000650 ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
651 if (CS == 0) return 0;
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000652 if (CU->getValue() >= CS->getNumOperands()) return 0;
653 C = CS->getOperand(CU->getValue());
Chris Lattner49f74522004-01-12 04:29:41 +0000654 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +0000655 ConstantArray *CA = dyn_cast<ConstantArray>(C);
656 if (CA == 0) return 0;
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000657 if ((uint64_t)CS->getValue() >= CA->getNumOperands()) return 0;
658 C = CA->getOperand(CS->getValue());
Chris Lattner76b2ff42004-02-15 05:55:15 +0000659 } else
Chris Lattner49f74522004-01-12 04:29:41 +0000660 return 0;
661 return C;
662}
663
664// Handle load instructions. If the operand is a constant pointer to a constant
665// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +0000666void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner49f74522004-01-12 04:29:41 +0000667 InstVal &IV = ValueState[&I];
668 if (IV.isOverdefined()) return;
669
670 InstVal &PtrVal = getValueState(I.getOperand(0));
671 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
672 if (PtrVal.isConstant() && !I.isVolatile()) {
673 Value *Ptr = PtrVal.getConstant();
Chris Lattner538fee72004-03-07 22:16:24 +0000674 if (isa<ConstantPointerNull>(Ptr)) {
675 // load null -> null
676 markConstant(IV, &I, Constant::getNullValue(I.getType()));
677 return;
678 }
679
Chris Lattner49f74522004-01-12 04:29:41 +0000680 // Transform load (constant global) into the value loaded.
681 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr))
682 if (GV->isConstant() && !GV->isExternal()) {
683 markConstant(IV, &I, GV->getInitializer());
684 return;
685 }
686
687 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
688 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
689 if (CE->getOpcode() == Instruction::GetElementPtr)
Reid Spencerc5afc952004-07-18 00:31:05 +0000690 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
691 if (GV->isConstant() && !GV->isExternal())
692 if (Constant *V =
693 GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
694 markConstant(IV, &I, V);
695 return;
696 }
Chris Lattner49f74522004-01-12 04:29:41 +0000697 }
698
699 // Otherwise we cannot say for certain what value this load will produce.
700 // Bail out.
701 markOverdefined(IV, &I);
702}
Chris Lattnerff9362a2004-04-13 19:43:54 +0000703
Chris Lattner074be1f2004-11-15 04:44:20 +0000704void SCCPSolver::visitCallInst(CallInst &I) {
Chris Lattnerff9362a2004-04-13 19:43:54 +0000705 InstVal &IV = ValueState[&I];
706 if (IV.isOverdefined()) return;
707
708 Function *F = I.getCalledFunction();
709 if (F == 0 || !canConstantFoldCallTo(F)) {
710 markOverdefined(IV, &I);
711 return;
712 }
713
714 std::vector<Constant*> Operands;
715 Operands.reserve(I.getNumOperands()-1);
716
717 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
718 InstVal &State = getValueState(I.getOperand(i));
719 if (State.isUndefined())
720 return; // Operands are not resolved yet...
721 else if (State.isOverdefined()) {
722 markOverdefined(IV, &I);
723 return;
724 }
725 assert(State.isConstant() && "Unknown state!");
726 Operands.push_back(State.getConstant());
727 }
728
729 if (Constant *C = ConstantFoldCall(F, Operands))
730 markConstant(IV, &I, C);
731 else
732 markOverdefined(IV, &I);
733}
Chris Lattner074be1f2004-11-15 04:44:20 +0000734
735
736void SCCPSolver::Solve() {
737 // Process the work lists until they are empty!
738 while (!BBWorkList.empty() || !InstWorkList.empty() ||
739 !OverdefinedInstWorkList.empty()) {
740 // Process the instruction work list...
741 while (!OverdefinedInstWorkList.empty()) {
742 Instruction *I = OverdefinedInstWorkList.back();
743 OverdefinedInstWorkList.pop_back();
744
745 DEBUG(std::cerr << "\nPopped off OI-WL: " << I);
746
747 // "I" got into the work list because it either made the transition from
748 // bottom to constant
749 //
750 // Anything on this worklist that is overdefined need not be visited
751 // since all of its users will have already been marked as overdefined
752 // Update all of the users of this instruction's value...
753 //
754 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
755 UI != E; ++UI)
756 OperandChangedState(*UI);
757 }
758 // Process the instruction work list...
759 while (!InstWorkList.empty()) {
760 Instruction *I = InstWorkList.back();
761 InstWorkList.pop_back();
762
763 DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
764
765 // "I" got into the work list because it either made the transition from
766 // bottom to constant
767 //
768 // Anything on this worklist that is overdefined need not be visited
769 // since all of its users will have already been marked as overdefined.
770 // Update all of the users of this instruction's value...
771 //
772 if (!getValueState(I).isOverdefined())
773 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
774 UI != E; ++UI)
775 OperandChangedState(*UI);
776 }
777
778 // Process the basic block work list...
779 while (!BBWorkList.empty()) {
780 BasicBlock *BB = BBWorkList.back();
781 BBWorkList.pop_back();
782
783 DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
784
785 // Notify all instructions in this basic block that they are newly
786 // executable.
787 visit(BB);
788 }
789 }
790}
791
792
793namespace {
794//===----------------------------------------------------------------------===//
795//
796/// SCCP Class - This class does all of the work of Sparse Conditional Constant
797/// Propagation.
798///
799class SCCP : public FunctionPass, public InstVisitor<SCCP> {
800public:
801
802 // runOnFunction - Run the Sparse Conditional Constant Propagation algorithm,
803 // and return true if the function was modified.
804 //
805 bool runOnFunction(Function &F);
806
807 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
808 AU.setPreservesCFG();
809 }
810};
811
812 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
813} // end anonymous namespace
814
815
816// createSCCPPass - This is the public interface to this file...
817FunctionPass *llvm::createSCCPPass() {
818 return new SCCP();
819}
820
821
822//===----------------------------------------------------------------------===//
823// SCCP Class Implementation
824
825
826// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
827// and return true if the function was modified.
828//
829bool SCCP::runOnFunction(Function &F) {
830 SCCPSolver Solver;
831
832 // Mark the first block of the function as being executable.
833 Solver.MarkBlockExecutable(F.begin());
834
835 // Solve for constants.
836 Solver.Solve();
837
838 DEBUG(std::cerr << "SCCP on function '" << F.getName() << "'\n");
839 DEBUG(std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
840 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
841 if (!ExecutableBBs.count(I))
842 std::cerr << " BasicBlock Dead:" << *I);
843
844 // Iterate over all of the instructions in a function, replacing them with
845 // constants if we have found them to be of constant values.
846 //
847 bool MadeChanges = false;
848 hash_map<Value*, InstVal> &Values = Solver.getValueMapping();
849 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
850 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
851 Instruction *Inst = BI++;
852 if (Inst->getType() != Type::VoidTy) {
853 InstVal &IV = Values[Inst];
854 if (IV.isConstant() || IV.isUndefined()) {
855 Constant *Const;
856 if (IV.isConstant()) {
857 Const = IV.getConstant();
858 DEBUG(std::cerr << " Constant: " << *Const << " = " << *Inst);
859 } else {
860 Const = UndefValue::get(Inst->getType());
861 DEBUG(std::cerr << " Undefined: " << *Inst);
862 }
863
864 // Replaces all of the uses of a variable with uses of the constant.
865 Inst->replaceAllUsesWith(Const);
866
867 // Delete the instruction.
868 BB->getInstList().erase(Inst);
869
870 // Hey, we just changed something!
871 MadeChanges = true;
872 ++NumInstRemoved;
873 }
874 }
875 }
876
877 return MadeChanges;
878}
879
880