blob: 602f432aba8470a5677126c9d6c0ec1fd4546f38 [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 Lattner4f031622004-11-15 05:03:30 +000024#define DEBUG_TYPE "sccp"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000025#include "llvm/Transforms/Scalar.h"
Chris Lattnerb4394642004-12-10 08:02:06 +000026#include "llvm/Transforms/IPO.h"
Chris Lattner0fe5b322004-01-12 17:43:40 +000027#include "llvm/Constants.h"
Chris Lattner57698e22002-03-26 18:01:55 +000028#include "llvm/Function.h"
Chris Lattner49f74522004-01-12 04:29:41 +000029#include "llvm/GlobalVariable.h"
Chris Lattnercccc5c72003-04-25 02:50:03 +000030#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000031#include "llvm/Pass.h"
Chris Lattner0fe5b322004-01-12 17:43:40 +000032#include "llvm/Type.h"
Chris Lattner6e560792002-04-18 15:13:15 +000033#include "llvm/Support/InstVisitor.h"
Chris Lattnerff9362a2004-04-13 19:43:54 +000034#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerb4394642004-12-10 08:02:06 +000035#include "llvm/Support/CallSite.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000036#include "llvm/Support/Debug.h"
37#include "llvm/ADT/hash_map"
38#include "llvm/ADT/Statistic.h"
39#include "llvm/ADT/STLExtras.h"
Chris Lattner347389d2001-06-27 23:38:11 +000040#include <algorithm>
Chris Lattner347389d2001-06-27 23:38:11 +000041#include <set>
Chris Lattner49525f82004-01-09 06:02:20 +000042using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000043
Chris Lattner4f031622004-11-15 05:03:30 +000044// LatticeVal class - This class represents the different lattice values that an
Chris Lattnerc8e66542002-04-27 06:56:12 +000045// instruction may occupy. It is a simple class with value semantics.
Chris Lattner347389d2001-06-27 23:38:11 +000046//
Chris Lattner7d325382002-04-29 21:26:08 +000047namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000048
Chris Lattner4f031622004-11-15 05:03:30 +000049class LatticeVal {
Chris Lattner347389d2001-06-27 23:38:11 +000050 enum {
Chris Lattner3462ae32001-12-03 22:26:30 +000051 undefined, // This instruction has no known value
52 constant, // This instruction has a constant value
Chris Lattner3462ae32001-12-03 22:26:30 +000053 overdefined // This instruction has an unknown value
54 } LatticeValue; // The current lattice position
55 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000056public:
Chris Lattner4f031622004-11-15 05:03:30 +000057 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner347389d2001-06-27 23:38:11 +000058
59 // markOverdefined - Return true if this is a new status to be in...
60 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000061 if (LatticeValue != overdefined) {
62 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000063 return true;
64 }
65 return false;
66 }
67
68 // markConstant - Return true if this is a new status for us...
Chris Lattner3462ae32001-12-03 22:26:30 +000069 inline bool markConstant(Constant *V) {
70 if (LatticeValue != constant) {
71 LatticeValue = constant;
Chris Lattner347389d2001-06-27 23:38:11 +000072 ConstantVal = V;
73 return true;
74 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +000075 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +000076 }
77 return false;
78 }
79
Chris Lattner3462ae32001-12-03 22:26:30 +000080 inline bool isUndefined() const { return LatticeValue == undefined; }
81 inline bool isConstant() const { return LatticeValue == constant; }
82 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +000083
Chris Lattner05fe6842004-01-12 03:57:30 +000084 inline Constant *getConstant() const {
85 assert(isConstant() && "Cannot get the constant of a non-constant!");
86 return ConstantVal;
87 }
Chris Lattner347389d2001-06-27 23:38:11 +000088};
89
Chris Lattner7d325382002-04-29 21:26:08 +000090} // end anonymous namespace
Chris Lattner347389d2001-06-27 23:38:11 +000091
92
93//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +000094//
Chris Lattner074be1f2004-11-15 04:44:20 +000095/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
96/// Constant Propagation.
97///
98class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner7f74a562002-01-20 22:54:45 +000099 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattner4f031622004-11-15 05:03:30 +0000100 hash_map<Value*, LatticeVal> ValueState; // The state each value is in...
Chris Lattner347389d2001-06-27 23:38:11 +0000101
Chris Lattnerb4394642004-12-10 08:02:06 +0000102 /// TrackedFunctionRetVals - If we are tracking arguments into and the return
103 /// value out of a function, it will have an entry in this map, indicating
104 /// what the known return value for the function is.
105 hash_map<Function*, LatticeVal> TrackedFunctionRetVals;
106
Chris Lattnerd79334d2004-07-15 23:36:43 +0000107 // The reason for two worklists is that overdefined is the lowest state
108 // on the lattice, and moving things to overdefined as fast as possible
109 // makes SCCP converge much faster.
110 // By having a separate worklist, we accomplish this because everything
111 // possibly overdefined will become overdefined at the soonest possible
112 // point.
Chris Lattnerb4394642004-12-10 08:02:06 +0000113 std::vector<Value*> OverdefinedInstWorkList;
114 std::vector<Value*> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000115
116
Chris Lattner7f74a562002-01-20 22:54:45 +0000117 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000118
Chris Lattner05fe6842004-01-12 03:57:30 +0000119 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
120 /// overdefined, despite the fact that the PHI node is overdefined.
121 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
122
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000123 /// KnownFeasibleEdges - Entries in this set are edges which have already had
124 /// PHI nodes retriggered.
125 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
126 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000127public:
128
Chris Lattner074be1f2004-11-15 04:44:20 +0000129 /// MarkBlockExecutable - This method can be used by clients to mark all of
130 /// the blocks that are known to be intrinsically live in the processed unit.
131 void MarkBlockExecutable(BasicBlock *BB) {
132 DEBUG(std::cerr << "Marking Block Executable: " << BB->getName() << "\n");
133 BBExecutable.insert(BB); // Basic block is executable!
134 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner7d325382002-04-29 21:26:08 +0000135 }
136
Chris Lattnerb4394642004-12-10 08:02:06 +0000137 /// TrackValueOfGlobalVariableIfPossible - Clients can use this method to
138 /// inform the SCCPSolver that it should track loads and stores to the
139 /// specified global variable if it can. This is only legal to call if
140 /// performing Interprocedural SCCP.
141 void TrackValueOfGlobalVariableIfPossible(GlobalVariable *GV);
142
143 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
144 /// and out of the specified function (which cannot have its address taken),
145 /// this method must be called.
146 void AddTrackedFunction(Function *F) {
147 assert(F->hasInternalLinkage() && "Can only track internal functions!");
148 // Add an entry, F -> undef.
149 TrackedFunctionRetVals[F];
150 }
151
Chris Lattner074be1f2004-11-15 04:44:20 +0000152 /// Solve - Solve for constants and executable blocks.
153 ///
154 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000155
Chris Lattner7285f432004-12-10 20:41:50 +0000156 /// ResolveBranchesIn - While solving the dataflow for a function, we assume
157 /// that branches on undef values cannot reach any of their successors.
158 /// However, this is not a safe assumption. After we solve dataflow, this
159 /// method should be use to handle this. If this returns true, the solver
160 /// should be rerun.
161 bool ResolveBranchesIn(Function &F);
162
Chris Lattner074be1f2004-11-15 04:44:20 +0000163 /// getExecutableBlocks - Once we have solved for constants, return the set of
164 /// blocks that is known to be executable.
165 std::set<BasicBlock*> &getExecutableBlocks() {
166 return BBExecutable;
167 }
168
169 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattner4f031622004-11-15 05:03:30 +0000170 /// LLVM values to LatticeVals.
171 hash_map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000172 return ValueState;
173 }
174
Chris Lattner99e12952004-12-11 02:53:57 +0000175 /// getTrackedFunctionRetVals - Get the inferred return value map.
176 ///
177 const hash_map<Function*, LatticeVal> &getTrackedFunctionRetVals() {
178 return TrackedFunctionRetVals;
179 }
180
181
Chris Lattner347389d2001-06-27 23:38:11 +0000182private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000183 // markConstant - Make a value be marked as "constant". If the value
Chris Lattner347389d2001-06-27 23:38:11 +0000184 // is not already a constant, add it to the instruction work list so that
185 // the users of the instruction are updated later.
186 //
Chris Lattnerb4394642004-12-10 08:02:06 +0000187 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000188 if (IV.markConstant(C)) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000189 DEBUG(std::cerr << "markConstant: " << *C << ": " << *V);
190 InstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000191 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000192 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000193 inline void markConstant(Value *V, Constant *C) {
194 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000195 }
196
Chris Lattnerd79334d2004-07-15 23:36:43 +0000197 // markOverdefined - Make a value be marked as "overdefined". If the
198 // value is not already overdefined, add it to the overdefined instruction
199 // work list so that the users of the instruction are updated later.
200
Chris Lattnerb4394642004-12-10 08:02:06 +0000201 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000202 if (IV.markOverdefined()) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000203 DEBUG(std::cerr << "markOverdefined: " << *V);
Chris Lattner074be1f2004-11-15 04:44:20 +0000204 // Only instructions go on the work list
Chris Lattnerb4394642004-12-10 08:02:06 +0000205 OverdefinedInstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000206 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000207 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000208 inline void markOverdefined(Value *V) {
209 markOverdefined(ValueState[V], V);
210 }
211
212 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
213 if (IV.isOverdefined() || MergeWithV.isUndefined())
214 return; // Noop.
215 if (MergeWithV.isOverdefined())
216 markOverdefined(IV, V);
217 else if (IV.isUndefined())
218 markConstant(IV, V, MergeWithV.getConstant());
219 else if (IV.getConstant() != MergeWithV.getConstant())
220 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000221 }
222
Chris Lattner4f031622004-11-15 05:03:30 +0000223 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000224 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000225 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000226 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000227 // Instruction object, then use this accessor to get its value from the map.
228 //
Chris Lattner4f031622004-11-15 05:03:30 +0000229 inline LatticeVal &getValueState(Value *V) {
230 hash_map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000231 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner646354b2004-10-16 18:09:41 +0000232
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000233 if (Constant *CPV = dyn_cast<Constant>(V)) {
234 if (isa<UndefValue>(V)) {
235 // Nothing to do, remain undefined.
236 } else {
237 ValueState[CPV].markConstant(CPV); // Constants are constant
238 }
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000239 }
Chris Lattner347389d2001-06-27 23:38:11 +0000240 // All others are underdefined by default...
241 return ValueState[V];
242 }
243
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000244 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000245 // work list if it is not already executable...
246 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000247 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
248 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
249 return; // This edge is already known to be executable!
250
251 if (BBExecutable.count(Dest)) {
252 DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
253 << " -> " << Dest->getName() << "\n");
254
255 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000256 // feasible that wasn't before. Revisit the PHI nodes in the block
257 // because they have potentially new operands.
Chris Lattnerb4394642004-12-10 08:02:06 +0000258 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
259 visitPHINode(*cast<PHINode>(I));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000260
261 } else {
Chris Lattner074be1f2004-11-15 04:44:20 +0000262 MarkBlockExecutable(Dest);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000263 }
Chris Lattner347389d2001-06-27 23:38:11 +0000264 }
265
Chris Lattner074be1f2004-11-15 04:44:20 +0000266 // getFeasibleSuccessors - Return a vector of booleans to indicate which
267 // successors are reachable from a given terminator instruction.
268 //
269 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
270
271 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
272 // block to the 'To' basic block is currently feasible...
273 //
274 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
275
276 // OperandChangedState - This method is invoked on all of the users of an
277 // instruction that was just changed state somehow.... Based on this
278 // information, we need to update the specified user of this instruction.
279 //
280 void OperandChangedState(User *U) {
281 // Only instructions use other variable values!
282 Instruction &I = cast<Instruction>(*U);
283 if (BBExecutable.count(I.getParent())) // Inst is executable?
284 visit(I);
285 }
286
287private:
288 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000289
Chris Lattner6e560792002-04-18 15:13:15 +0000290 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000291 // operand made a transition, or the instruction is newly executable. Change
292 // the value type of I to reflect these changes if appropriate.
293 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000294 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000295
296 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000297 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000298 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000299
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000300 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000301 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000302 void visitBinaryOperator(Instruction &I);
303 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000304
305 // Instructions that cannot be folded away...
Chris Lattner113f4f42002-06-25 16:13:24 +0000306 void visitStoreInst (Instruction &I) { /*returns void*/ }
Chris Lattner49f74522004-01-12 04:29:41 +0000307 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000308 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerb4394642004-12-10 08:02:06 +0000309 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
310 void visitInvokeInst (InvokeInst &II) {
311 visitCallSite(CallSite::get(&II));
312 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000313 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000314 void visitCallSite (CallSite CS);
Chris Lattner9c58cf62003-09-08 18:54:55 +0000315 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000316 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000317 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000318 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
319 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000320 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000321
Chris Lattner113f4f42002-06-25 16:13:24 +0000322 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000323 // If a new instruction is added to LLVM that we don't handle...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000324 std::cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000325 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000326 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000327};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000328
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000329// getFeasibleSuccessors - Return a vector of booleans to indicate which
330// successors are reachable from a given terminator instruction.
331//
Chris Lattner074be1f2004-11-15 04:44:20 +0000332void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
333 std::vector<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000334 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000335 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000336 if (BI->isUnconditional()) {
337 Succs[0] = true;
338 } else {
Chris Lattner4f031622004-11-15 05:03:30 +0000339 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000340 if (BCValue.isOverdefined() ||
341 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
342 // Overdefined condition variables, and branches on unfoldable constant
343 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000344 Succs[0] = Succs[1] = true;
345 } else if (BCValue.isConstant()) {
346 // Constant condition variables mean the branch can only go a single way
347 Succs[BCValue.getConstant() == ConstantBool::False] = true;
348 }
349 }
Chris Lattner113f4f42002-06-25 16:13:24 +0000350 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000351 // Invoke instructions successors are always executable.
352 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000353 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000354 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000355 if (SCValue.isOverdefined() || // Overdefined condition?
356 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000357 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000358 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000359 } else if (SCValue.isConstant()) {
360 Constant *CPV = SCValue.getConstant();
361 // Make sure to skip the "default value" which isn't a value
362 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
363 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
364 Succs[i] = true;
365 return;
366 }
367 }
368
369 // Constant value not equal to any of the branches... must execute
370 // default branch then...
371 Succs[0] = true;
372 }
373 } else {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000374 std::cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner113f4f42002-06-25 16:13:24 +0000375 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000376 }
377}
378
379
Chris Lattner13b52e72002-05-02 21:18:01 +0000380// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
381// block to the 'To' basic block is currently feasible...
382//
Chris Lattner074be1f2004-11-15 04:44:20 +0000383bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000384 assert(BBExecutable.count(To) && "Dest should always be alive!");
385
386 // Make sure the source basic block is executable!!
387 if (!BBExecutable.count(From)) return false;
388
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000389 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000390 TerminatorInst *TI = From->getTerminator();
391 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
392 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000393 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000394 else {
Chris Lattner4f031622004-11-15 05:03:30 +0000395 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000396 if (BCValue.isOverdefined()) {
397 // Overdefined condition variables mean the branch could go either way.
398 return true;
399 } else if (BCValue.isConstant()) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000400 // Not branching on an evaluatable constant?
401 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
402
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000403 // Constant condition variables mean the branch can only go a single way
404 return BI->getSuccessor(BCValue.getConstant() ==
405 ConstantBool::False) == To;
406 }
407 return false;
408 }
409 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
410 // Invoke instructions successors are always executable.
411 return true;
412 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000413 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000414 if (SCValue.isOverdefined()) { // Overdefined condition?
415 // All destinations are executable!
416 return true;
417 } else if (SCValue.isConstant()) {
418 Constant *CPV = SCValue.getConstant();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000419 if (!isa<ConstantInt>(CPV))
420 return true; // not a foldable constant?
421
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000422 // Make sure to skip the "default value" which isn't a value
423 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
424 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
425 return SI->getSuccessor(i) == To;
426
427 // Constant value not equal to any of the branches... must execute
428 // default branch then...
429 return SI->getDefaultDest() == To;
430 }
431 return false;
432 } else {
433 std::cerr << "Unknown terminator instruction: " << *TI;
434 abort();
435 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000436}
Chris Lattner347389d2001-06-27 23:38:11 +0000437
Chris Lattner6e560792002-04-18 15:13:15 +0000438// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000439// operand made a transition, or the instruction is newly executable. Change
440// the value type of I to reflect these changes if appropriate. This method
441// makes sure to do the following actions:
442//
443// 1. If a phi node merges two constants in, and has conflicting value coming
444// from different branches, or if the PHI node merges in an overdefined
445// value, then the PHI node becomes overdefined.
446// 2. If a phi node merges only constants in, and they all agree on value, the
447// PHI node becomes a constant value equal to that.
448// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
449// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
450// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
451// 6. If a conditional branch has a value that is constant, make the selected
452// destination executable
453// 7. If a conditional branch has a value that is overdefined, make all
454// successors executable.
455//
Chris Lattner074be1f2004-11-15 04:44:20 +0000456void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner4f031622004-11-15 05:03:30 +0000457 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000458 if (PNIV.isOverdefined()) {
459 // There may be instructions using this PHI node that are not overdefined
460 // themselves. If so, make sure that they know that the PHI node operand
461 // changed.
462 std::multimap<PHINode*, Instruction*>::iterator I, E;
463 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
464 if (I != E) {
465 std::vector<Instruction*> Users;
466 Users.reserve(std::distance(I, E));
467 for (; I != E; ++I) Users.push_back(I->second);
468 while (!Users.empty()) {
469 visit(Users.back());
470 Users.pop_back();
471 }
472 }
473 return; // Quick exit
474 }
Chris Lattner347389d2001-06-27 23:38:11 +0000475
Chris Lattner7a7b1142004-03-16 19:49:59 +0000476 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
477 // and slow us down a lot. Just mark them overdefined.
478 if (PN.getNumIncomingValues() > 64) {
479 markOverdefined(PNIV, &PN);
480 return;
481 }
482
Chris Lattner6e560792002-04-18 15:13:15 +0000483 // Look at all of the executable operands of the PHI node. If any of them
484 // are overdefined, the PHI becomes overdefined as well. If they are all
485 // constant, and they agree with each other, the PHI becomes the identical
486 // constant. If they are constant and don't agree, the PHI is overdefined.
487 // If there are no executable operands, the PHI remains undefined.
488 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000489 Constant *OperandVal = 0;
490 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000491 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000492 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000493
Chris Lattner113f4f42002-06-25 16:13:24 +0000494 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000495 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000496 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000497 return;
498 }
499
Chris Lattnercccc5c72003-04-25 02:50:03 +0000500 if (OperandVal == 0) { // Grab the first value...
501 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000502 } else { // Another value is being merged in!
503 // There is already a reachable operand. If we conflict with it,
504 // then the PHI node becomes overdefined. If we agree with it, we
505 // can continue on.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000506
Chris Lattner6e560792002-04-18 15:13:15 +0000507 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000508 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000509 // Yes there is. This means the PHI node is not constant.
510 // You must be overdefined poor PHI.
511 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000512 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000513 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000514 }
Chris Lattner347389d2001-06-27 23:38:11 +0000515 }
516 }
Chris Lattner347389d2001-06-27 23:38:11 +0000517 }
518
Chris Lattner6e560792002-04-18 15:13:15 +0000519 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000520 // arguments that agree with each other(and OperandVal is the constant) or
521 // OperandVal is null because there are no defined incoming arguments. If
522 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000523 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000524 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000525 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000526}
527
Chris Lattnerb4394642004-12-10 08:02:06 +0000528void SCCPSolver::visitReturnInst(ReturnInst &I) {
529 if (I.getNumOperands() == 0) return; // Ret void
530
531 // If we are tracking the return value of this function, merge it in.
532 Function *F = I.getParent()->getParent();
533 if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
534 hash_map<Function*, LatticeVal>::iterator TFRVI =
535 TrackedFunctionRetVals.find(F);
536 if (TFRVI != TrackedFunctionRetVals.end() &&
537 !TFRVI->second.isOverdefined()) {
538 LatticeVal &IV = getValueState(I.getOperand(0));
539 mergeInValue(TFRVI->second, F, IV);
540 }
541 }
542}
543
544
Chris Lattner074be1f2004-11-15 04:44:20 +0000545void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000546 std::vector<bool> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000547 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000548
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000549 BasicBlock *BB = TI.getParent();
550
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000551 // Mark all feasible successors executable...
552 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000553 if (SuccFeasible[i])
554 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000555}
556
Chris Lattner074be1f2004-11-15 04:44:20 +0000557void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000558 Value *V = I.getOperand(0);
Chris Lattner4f031622004-11-15 05:03:30 +0000559 LatticeVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000560 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000561 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000562 else if (VState.isConstant()) // Propagate constant value
563 markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000564}
565
Chris Lattner074be1f2004-11-15 04:44:20 +0000566void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000567 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattner59db22d2004-03-12 05:52:44 +0000568 if (CondValue.isOverdefined())
569 markOverdefined(&I);
570 else if (CondValue.isConstant()) {
571 if (CondValue.getConstant() == ConstantBool::True) {
Chris Lattner4f031622004-11-15 05:03:30 +0000572 LatticeVal &Val = getValueState(I.getTrueValue());
Chris Lattner59db22d2004-03-12 05:52:44 +0000573 if (Val.isOverdefined())
574 markOverdefined(&I);
575 else if (Val.isConstant())
576 markConstant(&I, Val.getConstant());
577 } else if (CondValue.getConstant() == ConstantBool::False) {
Chris Lattner4f031622004-11-15 05:03:30 +0000578 LatticeVal &Val = getValueState(I.getFalseValue());
Chris Lattner59db22d2004-03-12 05:52:44 +0000579 if (Val.isOverdefined())
580 markOverdefined(&I);
581 else if (Val.isConstant())
582 markConstant(&I, Val.getConstant());
583 } else
584 markOverdefined(&I);
585 }
586}
587
Chris Lattner6e560792002-04-18 15:13:15 +0000588// Handle BinaryOperators and Shift Instructions...
Chris Lattner074be1f2004-11-15 04:44:20 +0000589void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000590 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000591 if (IV.isOverdefined()) return;
592
Chris Lattner4f031622004-11-15 05:03:30 +0000593 LatticeVal &V1State = getValueState(I.getOperand(0));
594 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000595
Chris Lattner6e560792002-04-18 15:13:15 +0000596 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000597 // If both operands are PHI nodes, it is possible that this instruction has
598 // a constant value, despite the fact that the PHI node doesn't. Check for
599 // this condition now.
600 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
601 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
602 if (PN1->getParent() == PN2->getParent()) {
603 // Since the two PHI nodes are in the same basic block, they must have
604 // entries for the same predecessors. Walk the predecessor list, and
605 // if all of the incoming values are constants, and the result of
606 // evaluating this expression with all incoming value pairs is the
607 // same, then this expression is a constant even though the PHI node
608 // is not a constant!
Chris Lattner4f031622004-11-15 05:03:30 +0000609 LatticeVal Result;
Chris Lattner05fe6842004-01-12 03:57:30 +0000610 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000611 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner05fe6842004-01-12 03:57:30 +0000612 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattner4f031622004-11-15 05:03:30 +0000613 LatticeVal &In2 =
614 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner05fe6842004-01-12 03:57:30 +0000615
616 if (In1.isOverdefined() || In2.isOverdefined()) {
617 Result.markOverdefined();
618 break; // Cannot fold this operation over the PHI nodes!
619 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000620 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
621 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000622 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000623 Result.markConstant(V);
624 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000625 Result.markOverdefined();
626 break;
627 }
628 }
629 }
630
631 // If we found a constant value here, then we know the instruction is
632 // constant despite the fact that the PHI nodes are overdefined.
633 if (Result.isConstant()) {
634 markConstant(IV, &I, Result.getConstant());
635 // Remember that this instruction is virtually using the PHI node
636 // operands.
637 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
638 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
639 return;
640 } else if (Result.isUndefined()) {
641 return;
642 }
643
644 // Okay, this really is overdefined now. Since we might have
645 // speculatively thought that this was not overdefined before, and
646 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
647 // make sure to clean out any entries that we put there, for
648 // efficiency.
649 std::multimap<PHINode*, Instruction*>::iterator It, E;
650 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
651 while (It != E) {
652 if (It->second == &I) {
653 UsersOfOverdefinedPHIs.erase(It++);
654 } else
655 ++It;
656 }
657 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
658 while (It != E) {
659 if (It->second == &I) {
660 UsersOfOverdefinedPHIs.erase(It++);
661 } else
662 ++It;
663 }
664 }
665
666 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000667 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000668 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
669 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000670 }
671}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000672
673// Handle getelementptr instructions... if all operands are constants then we
674// can turn this into a getelementptr ConstantExpr.
675//
Chris Lattner074be1f2004-11-15 04:44:20 +0000676void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000677 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000678 if (IV.isOverdefined()) return;
679
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000680 std::vector<Constant*> Operands;
681 Operands.reserve(I.getNumOperands());
682
683 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000684 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000685 if (State.isUndefined())
686 return; // Operands are not resolved yet...
687 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +0000688 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000689 return;
690 }
691 assert(State.isConstant() && "Unknown state!");
692 Operands.push_back(State.getConstant());
693 }
694
695 Constant *Ptr = Operands[0];
696 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
697
Chris Lattner49f74522004-01-12 04:29:41 +0000698 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000699}
Brian Gaeke960707c2003-11-11 22:41:34 +0000700
Chris Lattner49f74522004-01-12 04:29:41 +0000701/// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
702/// return the constant value being addressed by the constant expression, or
703/// null if something is funny.
704///
705static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +0000706 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner49f74522004-01-12 04:29:41 +0000707 return 0; // Do not allow stepping over the value!
708
709 // Loop over all of the operands, tracking down which value we are
710 // addressing...
711 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
712 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +0000713 ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
714 if (CS == 0) return 0;
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000715 if (CU->getValue() >= CS->getNumOperands()) return 0;
716 C = CS->getOperand(CU->getValue());
Chris Lattner49f74522004-01-12 04:29:41 +0000717 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +0000718 ConstantArray *CA = dyn_cast<ConstantArray>(C);
719 if (CA == 0) return 0;
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000720 if ((uint64_t)CS->getValue() >= CA->getNumOperands()) return 0;
721 C = CA->getOperand(CS->getValue());
Chris Lattner76b2ff42004-02-15 05:55:15 +0000722 } else
Chris Lattner49f74522004-01-12 04:29:41 +0000723 return 0;
724 return C;
725}
726
727// Handle load instructions. If the operand is a constant pointer to a constant
728// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +0000729void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000730 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000731 if (IV.isOverdefined()) return;
732
Chris Lattner4f031622004-11-15 05:03:30 +0000733 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattner49f74522004-01-12 04:29:41 +0000734 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
735 if (PtrVal.isConstant() && !I.isVolatile()) {
736 Value *Ptr = PtrVal.getConstant();
Chris Lattner538fee72004-03-07 22:16:24 +0000737 if (isa<ConstantPointerNull>(Ptr)) {
738 // load null -> null
739 markConstant(IV, &I, Constant::getNullValue(I.getType()));
740 return;
741 }
742
Chris Lattner49f74522004-01-12 04:29:41 +0000743 // Transform load (constant global) into the value loaded.
744 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr))
745 if (GV->isConstant() && !GV->isExternal()) {
746 markConstant(IV, &I, GV->getInitializer());
747 return;
748 }
749
750 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
751 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
752 if (CE->getOpcode() == Instruction::GetElementPtr)
Reid Spencerc5afc952004-07-18 00:31:05 +0000753 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
754 if (GV->isConstant() && !GV->isExternal())
755 if (Constant *V =
756 GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
757 markConstant(IV, &I, V);
758 return;
759 }
Chris Lattner49f74522004-01-12 04:29:41 +0000760 }
761
762 // Otherwise we cannot say for certain what value this load will produce.
763 // Bail out.
764 markOverdefined(IV, &I);
765}
Chris Lattnerff9362a2004-04-13 19:43:54 +0000766
Chris Lattnerb4394642004-12-10 08:02:06 +0000767void SCCPSolver::visitCallSite(CallSite CS) {
768 Function *F = CS.getCalledFunction();
769
770 // If we are tracking this function, we must make sure to bind arguments as
771 // appropriate.
772 hash_map<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
773 if (F && F->hasInternalLinkage())
774 TFRVI = TrackedFunctionRetVals.find(F);
775
776 if (TFRVI != TrackedFunctionRetVals.end()) {
777 // If this is the first call to the function hit, mark its entry block
778 // executable.
779 if (!BBExecutable.count(F->begin()))
780 MarkBlockExecutable(F->begin());
781
782 CallSite::arg_iterator CAI = CS.arg_begin();
783 for (Function::aiterator AI = F->abegin(), E = F->aend();
784 AI != E; ++AI, ++CAI) {
785 LatticeVal &IV = ValueState[AI];
786 if (!IV.isOverdefined())
787 mergeInValue(IV, AI, getValueState(*CAI));
788 }
789 }
790 Instruction *I = CS.getInstruction();
791 if (I->getType() == Type::VoidTy) return;
792
793 LatticeVal &IV = ValueState[I];
Chris Lattnerff9362a2004-04-13 19:43:54 +0000794 if (IV.isOverdefined()) return;
795
Chris Lattnerb4394642004-12-10 08:02:06 +0000796 // Propagate the return value of the function to the value of the instruction.
797 if (TFRVI != TrackedFunctionRetVals.end()) {
798 mergeInValue(IV, I, TFRVI->second);
799 return;
800 }
801
802 if (F == 0 || !F->isExternal() || !canConstantFoldCallTo(F)) {
803 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000804 return;
805 }
806
807 std::vector<Constant*> Operands;
Chris Lattnerb4394642004-12-10 08:02:06 +0000808 Operands.reserve(I->getNumOperands()-1);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000809
Chris Lattnerb4394642004-12-10 08:02:06 +0000810 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
811 AI != E; ++AI) {
812 LatticeVal &State = getValueState(*AI);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000813 if (State.isUndefined())
814 return; // Operands are not resolved yet...
815 else if (State.isOverdefined()) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000816 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000817 return;
818 }
819 assert(State.isConstant() && "Unknown state!");
820 Operands.push_back(State.getConstant());
821 }
822
823 if (Constant *C = ConstantFoldCall(F, Operands))
Chris Lattnerb4394642004-12-10 08:02:06 +0000824 markConstant(IV, I, C);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000825 else
Chris Lattnerb4394642004-12-10 08:02:06 +0000826 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000827}
Chris Lattner074be1f2004-11-15 04:44:20 +0000828
829
830void SCCPSolver::Solve() {
831 // Process the work lists until they are empty!
832 while (!BBWorkList.empty() || !InstWorkList.empty() ||
833 !OverdefinedInstWorkList.empty()) {
834 // Process the instruction work list...
835 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000836 Value *I = OverdefinedInstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +0000837 OverdefinedInstWorkList.pop_back();
838
Chris Lattnerb4394642004-12-10 08:02:06 +0000839 DEBUG(std::cerr << "\nPopped off OI-WL: " << *I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000840
841 // "I" got into the work list because it either made the transition from
842 // bottom to constant
843 //
844 // Anything on this worklist that is overdefined need not be visited
845 // since all of its users will have already been marked as overdefined
846 // Update all of the users of this instruction's value...
847 //
848 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
849 UI != E; ++UI)
850 OperandChangedState(*UI);
851 }
852 // Process the instruction work list...
853 while (!InstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000854 Value *I = InstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +0000855 InstWorkList.pop_back();
856
857 DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
858
859 // "I" got into the work list because it either made the transition from
860 // bottom to constant
861 //
862 // Anything on this worklist that is overdefined need not be visited
863 // since all of its users will have already been marked as overdefined.
864 // Update all of the users of this instruction's value...
865 //
866 if (!getValueState(I).isOverdefined())
867 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
868 UI != E; ++UI)
869 OperandChangedState(*UI);
870 }
871
872 // Process the basic block work list...
873 while (!BBWorkList.empty()) {
874 BasicBlock *BB = BBWorkList.back();
875 BBWorkList.pop_back();
876
877 DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
878
879 // Notify all instructions in this basic block that they are newly
880 // executable.
881 visit(BB);
882 }
883 }
884}
885
Chris Lattner7285f432004-12-10 20:41:50 +0000886/// ResolveBranchesIn - While solving the dataflow for a function, we assume
887/// that branches on undef values cannot reach any of their successors.
888/// However, this is not a safe assumption. After we solve dataflow, this
889/// method should be use to handle this. If this returns true, the solver
890/// should be rerun.
891bool SCCPSolver::ResolveBranchesIn(Function &F) {
892 bool BranchesResolved = false;
893 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
894 TerminatorInst *TI = BB->getTerminator();
895 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
896 if (BI->isConditional()) {
897 LatticeVal &BCValue = getValueState(BI->getCondition());
898 if (BCValue.isUndefined()) {
899 BI->setCondition(ConstantBool::True);
900 BranchesResolved = true;
901 visit(BI);
902 }
903 }
904 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
905 LatticeVal &SCValue = getValueState(SI->getCondition());
906 if (SCValue.isUndefined()) {
907 SI->setCondition(Constant::getNullValue(SI->getCondition()->getType()));
908 BranchesResolved = true;
909 visit(SI);
910 }
911 }
912 }
913 return BranchesResolved;
914}
915
Chris Lattner074be1f2004-11-15 04:44:20 +0000916
917namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +0000918 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
919 Statistic<> NumDeadBlocks ("sccp", "Number of basic blocks unreachable");
920
Chris Lattner1890f942004-11-15 07:15:04 +0000921 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +0000922 //
Chris Lattner1890f942004-11-15 07:15:04 +0000923 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
924 /// Sparse Conditional COnstant Propagator.
925 ///
926 struct SCCP : public FunctionPass {
927 // runOnFunction - Run the Sparse Conditional Constant Propagation
928 // algorithm, and return true if the function was modified.
929 //
930 bool runOnFunction(Function &F);
931
932 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
933 AU.setPreservesCFG();
934 }
935 };
Chris Lattner074be1f2004-11-15 04:44:20 +0000936
937 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
938} // end anonymous namespace
939
940
941// createSCCPPass - This is the public interface to this file...
942FunctionPass *llvm::createSCCPPass() {
943 return new SCCP();
944}
945
946
Chris Lattner074be1f2004-11-15 04:44:20 +0000947// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
948// and return true if the function was modified.
949//
950bool SCCP::runOnFunction(Function &F) {
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000951 DEBUG(std::cerr << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner074be1f2004-11-15 04:44:20 +0000952 SCCPSolver Solver;
953
954 // Mark the first block of the function as being executable.
955 Solver.MarkBlockExecutable(F.begin());
956
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000957 // Mark all arguments to the function as being overdefined.
958 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
959 for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI)
960 Values[AI].markOverdefined();
961
Chris Lattner074be1f2004-11-15 04:44:20 +0000962 // Solve for constants.
Chris Lattner7285f432004-12-10 20:41:50 +0000963 bool ResolvedBranches = true;
964 while (ResolvedBranches) {
965 Solver.Solve();
966 ResolvedBranches = Solver.ResolveBranchesIn(F);
967 }
Chris Lattner074be1f2004-11-15 04:44:20 +0000968
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000969 bool MadeChanges = false;
970
971 // If we decided that there are basic blocks that are dead in this function,
972 // delete their contents now. Note that we cannot actually delete the blocks,
973 // as we cannot modify the CFG of the function.
974 //
975 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
976 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
977 if (!ExecutableBBs.count(BB)) {
978 DEBUG(std::cerr << " BasicBlock Dead:" << *BB);
Chris Lattner9a038a32004-11-15 07:02:42 +0000979 ++NumDeadBlocks;
980
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000981 // Delete the instructions backwards, as it has a reduced likelihood of
982 // having to update as many def-use and use-def chains.
983 std::vector<Instruction*> Insts;
984 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
985 I != E; ++I)
986 Insts.push_back(I);
987 while (!Insts.empty()) {
988 Instruction *I = Insts.back();
989 Insts.pop_back();
990 if (!I->use_empty())
991 I->replaceAllUsesWith(UndefValue::get(I->getType()));
992 BB->getInstList().erase(I);
993 MadeChanges = true;
Chris Lattner9a038a32004-11-15 07:02:42 +0000994 ++NumInstRemoved;
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000995 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000996 } else {
997 // Iterate over all of the instructions in a function, replacing them with
998 // constants if we have found them to be of constant values.
999 //
1000 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1001 Instruction *Inst = BI++;
1002 if (Inst->getType() != Type::VoidTy) {
1003 LatticeVal &IV = Values[Inst];
1004 if (IV.isConstant() || IV.isUndefined() &&
1005 !isa<TerminatorInst>(Inst)) {
1006 Constant *Const = IV.isConstant()
1007 ? IV.getConstant() : UndefValue::get(Inst->getType());
Chris Lattner074be1f2004-11-15 04:44:20 +00001008 DEBUG(std::cerr << " Constant: " << *Const << " = " << *Inst);
Chris Lattnerb4394642004-12-10 08:02:06 +00001009
1010 // Replaces all of the uses of a variable with uses of the constant.
1011 Inst->replaceAllUsesWith(Const);
1012
1013 // Delete the instruction.
1014 BB->getInstList().erase(Inst);
1015
1016 // Hey, we just changed something!
1017 MadeChanges = true;
1018 ++NumInstRemoved;
Chris Lattner074be1f2004-11-15 04:44:20 +00001019 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001020 }
1021 }
1022 }
1023
1024 return MadeChanges;
1025}
Chris Lattnerb4394642004-12-10 08:02:06 +00001026
1027namespace {
1028 Statistic<> IPNumInstRemoved("ipsccp", "Number of instructions removed");
1029 Statistic<> IPNumDeadBlocks ("ipsccp", "Number of basic blocks unreachable");
1030 Statistic<> IPNumArgsElimed ("ipsccp",
1031 "Number of arguments constant propagated");
1032
1033 //===--------------------------------------------------------------------===//
1034 //
1035 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1036 /// Constant Propagation.
1037 ///
1038 struct IPSCCP : public ModulePass {
1039 bool runOnModule(Module &M);
1040 };
1041
1042 RegisterOpt<IPSCCP>
1043 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1044} // end anonymous namespace
1045
1046// createIPSCCPPass - This is the public interface to this file...
1047ModulePass *llvm::createIPSCCPPass() {
1048 return new IPSCCP();
1049}
1050
1051
1052static bool AddressIsTaken(GlobalValue *GV) {
1053 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1054 UI != E; ++UI)
1055 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1056 if (SI->getOperand(0) == GV) return true; // Storing addr of GV.
1057 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1058 // Make sure we are calling the function, not passing the address.
1059 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1060 for (CallSite::arg_iterator AI = CS.arg_begin(),
1061 E = CS.arg_end(); AI != E; ++AI)
1062 if (*AI == GV)
1063 return true;
1064 } else if (!isa<LoadInst>(*UI)) {
1065 return true;
1066 }
1067 return false;
1068}
1069
1070bool IPSCCP::runOnModule(Module &M) {
1071 SCCPSolver Solver;
1072
1073 // Loop over all functions, marking arguments to those with their addresses
1074 // taken or that are external as overdefined.
1075 //
1076 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1077 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1078 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1079 if (!F->isExternal())
1080 Solver.MarkBlockExecutable(F->begin());
1081 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1082 Values[AI].markOverdefined();
1083 } else {
1084 Solver.AddTrackedFunction(F);
1085 }
1086
1087 // Solve for constants.
Chris Lattner7285f432004-12-10 20:41:50 +00001088 bool ResolvedBranches = true;
1089 while (ResolvedBranches) {
1090 Solver.Solve();
1091
1092 ResolvedBranches = false;
1093 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1094 ResolvedBranches |= Solver.ResolveBranchesIn(*F);
1095 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001096
1097 bool MadeChanges = false;
1098
1099 // Iterate over all of the instructions in the module, replacing them with
1100 // constants if we have found them to be of constant values.
1101 //
1102 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1103 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1104 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1105 if (!AI->use_empty()) {
1106 LatticeVal &IV = Values[AI];
1107 if (IV.isConstant() || IV.isUndefined()) {
1108 Constant *CST = IV.isConstant() ?
1109 IV.getConstant() : UndefValue::get(AI->getType());
1110 DEBUG(std::cerr << "*** Arg " << *AI << " = " << *CST <<"\n");
1111
1112 // Replaces all of the uses of a variable with uses of the
1113 // constant.
1114 AI->replaceAllUsesWith(CST);
1115 ++IPNumArgsElimed;
1116 }
1117 }
1118
Chris Lattnerbae4b642004-12-10 22:29:08 +00001119 std::vector<BasicBlock*> BlocksToErase;
Chris Lattnerb4394642004-12-10 08:02:06 +00001120 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1121 if (!ExecutableBBs.count(BB)) {
1122 DEBUG(std::cerr << " BasicBlock Dead:" << *BB);
1123 ++IPNumDeadBlocks;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001124 BlocksToErase.push_back(BB);
Chris Lattner7285f432004-12-10 20:41:50 +00001125
Chris Lattnerb4394642004-12-10 08:02:06 +00001126 // Delete the instructions backwards, as it has a reduced likelihood of
1127 // having to update as many def-use and use-def chains.
1128 std::vector<Instruction*> Insts;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001129 TerminatorInst *TI = BB->getTerminator();
1130 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattnerb4394642004-12-10 08:02:06 +00001131 Insts.push_back(I);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001132
Chris Lattnerb4394642004-12-10 08:02:06 +00001133 while (!Insts.empty()) {
1134 Instruction *I = Insts.back();
1135 Insts.pop_back();
1136 if (!I->use_empty())
1137 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1138 BB->getInstList().erase(I);
1139 MadeChanges = true;
1140 ++IPNumInstRemoved;
1141 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001142
1143 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1144 BasicBlock *Succ = TI->getSuccessor(i);
1145 if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1146 TI->getSuccessor(i)->removePredecessor(BB);
1147 }
Chris Lattner99e12952004-12-11 02:53:57 +00001148 if (!TI->use_empty())
1149 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnerbae4b642004-12-10 22:29:08 +00001150 BB->getInstList().erase(TI);
1151
Chris Lattnerb4394642004-12-10 08:02:06 +00001152 } else {
1153 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1154 Instruction *Inst = BI++;
1155 if (Inst->getType() != Type::VoidTy) {
1156 LatticeVal &IV = Values[Inst];
1157 if (IV.isConstant() || IV.isUndefined() &&
1158 !isa<TerminatorInst>(Inst)) {
1159 Constant *Const = IV.isConstant()
1160 ? IV.getConstant() : UndefValue::get(Inst->getType());
1161 DEBUG(std::cerr << " Constant: " << *Const << " = " << *Inst);
1162
1163 // Replaces all of the uses of a variable with uses of the
1164 // constant.
1165 Inst->replaceAllUsesWith(Const);
1166
1167 // Delete the instruction.
1168 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1169 BB->getInstList().erase(Inst);
1170
1171 // Hey, we just changed something!
1172 MadeChanges = true;
1173 ++IPNumInstRemoved;
1174 }
1175 }
1176 }
1177 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001178
1179 // Now that all instructions in the function are constant folded, erase dead
1180 // blocks, because we can now use ConstantFoldTerminator to get rid of
1181 // in-edges.
1182 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1183 // If there are any PHI nodes in this successor, drop entries for BB now.
1184 BasicBlock *DeadBB = BlocksToErase[i];
1185 while (!DeadBB->use_empty()) {
1186 Instruction *I = cast<Instruction>(DeadBB->use_back());
1187 bool Folded = ConstantFoldTerminator(I->getParent());
1188 assert(Folded && "Didn't fold away reference to block!");
1189 }
1190
1191 // Finally, delete the basic block.
1192 F->getBasicBlockList().erase(DeadBB);
1193 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001194 }
Chris Lattner99e12952004-12-11 02:53:57 +00001195
1196 // If we inferred constant or undef return values for a function, we replaced
1197 // all call uses with the inferred value. This means we don't need to bother
1198 // actually returning anything from the function. Replace all return
1199 // instructions with return undef.
1200 const hash_map<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals();
1201 for (hash_map<Function*, LatticeVal>::const_iterator I = RV.begin(),
1202 E = RV.end(); I != E; ++I)
1203 if (!I->second.isOverdefined() &&
1204 I->first->getReturnType() != Type::VoidTy) {
1205 Function *F = I->first;
1206 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1207 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1208 if (!isa<UndefValue>(RI->getOperand(0)))
1209 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1210 }
1211
Chris Lattnerb4394642004-12-10 08:02:06 +00001212 return MadeChanges;
1213}