blob: 8aaf844ce1b01688d3c6cbcbe30263bd26d0e3ab [file] [log] [blame]
Misha Brukman82c89b92003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +00009//
Misha Brukman82c89b92003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner138a1242001-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 Lattner2a88bb72002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner138a1242001-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 Lattneref36dfd2004-11-15 05:03:30 +000024#define DEBUG_TYPE "sccp"
Chris Lattner022103b2002-05-07 20:03:00 +000025#include "llvm/Transforms/Scalar.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000026#include "llvm/Transforms/IPO.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000027#include "llvm/Constants.h"
Chris Lattnerdd336d12004-12-11 05:15:59 +000028#include "llvm/DerivedTypes.h"
Chris Lattner9de28282003-04-25 02:50:03 +000029#include "llvm/Instructions.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000030#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000031#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000032#include "llvm/Transforms/Utils/Local.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000033#include "llvm/Support/CallSite.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000034#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/Support/Debug.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000036#include "llvm/Support/InstVisitor.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000037#include "llvm/ADT/DenseMap.h"
Chris Lattnercc56aad2007-02-02 20:57:39 +000038#include "llvm/ADT/SmallSet.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000039#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000040#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000042#include <algorithm>
Chris Lattnerd7456022004-01-09 06:02:20 +000043using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000044
Chris Lattner0e5f4992006-12-19 21:40:18 +000045STATISTIC(NumInstRemoved, "Number of instructions removed");
46STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
47
48STATISTIC(IPNumInstRemoved, "Number ofinstructions removed by IPSCCP");
49STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
50STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
51STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
52
Chris Lattner0dbfc052002-04-29 21:26:08 +000053namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000054/// LatticeVal class - This class represents the different lattice values that
55/// an LLVM value may occupy. It is a simple class with value semantics.
56///
Reid Spencer9133fe22007-02-05 23:32:05 +000057class VISIBILITY_HIDDEN LatticeVal {
Misha Brukmanfd939082005-04-21 23:48:37 +000058 enum {
Chris Lattner3bad2532006-12-20 06:21:33 +000059 /// undefined - This LLVM Value has no known value yet.
60 undefined,
61
62 /// constant - This LLVM Value has a specific constant value.
63 constant,
64
65 /// forcedconstant - This LLVM Value was thought to be undef until
66 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
67 /// with another (different) constant, it goes to overdefined, instead of
68 /// asserting.
69 forcedconstant,
70
71 /// overdefined - This instruction is not known to be constant, and we know
72 /// it has a value.
73 overdefined
74 } LatticeValue; // The current lattice position
75
Chris Lattnere9bb2df2001-12-03 22:26:30 +000076 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner138a1242001-06-27 23:38:11 +000077public:
Chris Lattneref36dfd2004-11-15 05:03:30 +000078 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000079
Chris Lattner138a1242001-06-27 23:38:11 +000080 // markOverdefined - Return true if this is a new status to be in...
81 inline bool markOverdefined() {
Chris Lattnere9bb2df2001-12-03 22:26:30 +000082 if (LatticeValue != overdefined) {
83 LatticeValue = overdefined;
Chris Lattner138a1242001-06-27 23:38:11 +000084 return true;
85 }
86 return false;
87 }
88
Chris Lattner3bad2532006-12-20 06:21:33 +000089 // markConstant - Return true if this is a new status for us.
Chris Lattnere9bb2df2001-12-03 22:26:30 +000090 inline bool markConstant(Constant *V) {
91 if (LatticeValue != constant) {
Chris Lattner3bad2532006-12-20 06:21:33 +000092 if (LatticeValue == undefined) {
93 LatticeValue = constant;
Jim Laskey52ab9042007-01-03 00:11:03 +000094 assert(V && "Marking constant with NULL");
Chris Lattner3bad2532006-12-20 06:21:33 +000095 ConstantVal = V;
96 } else {
97 assert(LatticeValue == forcedconstant &&
98 "Cannot move from overdefined to constant!");
99 // Stay at forcedconstant if the constant is the same.
100 if (V == ConstantVal) return false;
101
102 // Otherwise, we go to overdefined. Assumptions made based on the
103 // forced value are possibly wrong. Assuming this is another constant
104 // could expose a contradiction.
105 LatticeValue = overdefined;
106 }
Chris Lattner138a1242001-06-27 23:38:11 +0000107 return true;
108 } else {
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000109 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner138a1242001-06-27 23:38:11 +0000110 }
111 return false;
112 }
113
Chris Lattner3bad2532006-12-20 06:21:33 +0000114 inline void markForcedConstant(Constant *V) {
115 assert(LatticeValue == undefined && "Can't force a defined value!");
116 LatticeValue = forcedconstant;
117 ConstantVal = V;
118 }
119
120 inline bool isUndefined() const { return LatticeValue == undefined; }
121 inline bool isConstant() const {
122 return LatticeValue == constant || LatticeValue == forcedconstant;
123 }
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000124 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner138a1242001-06-27 23:38:11 +0000125
Chris Lattner1daee8b2004-01-12 03:57:30 +0000126 inline Constant *getConstant() const {
127 assert(isConstant() && "Cannot get the constant of a non-constant!");
128 return ConstantVal;
129 }
Chris Lattner138a1242001-06-27 23:38:11 +0000130};
131
Chris Lattner0dbfc052002-04-29 21:26:08 +0000132} // end anonymous namespace
Chris Lattner138a1242001-06-27 23:38:11 +0000133
134
135//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000136//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000137/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
138/// Constant Propagation.
139///
140class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattnercc56aad2007-02-02 20:57:39 +0000141 SmallSet<BasicBlock*, 16> BBExecutable;// The basic blocks that are executable
Chris Lattnerc1ec7802007-02-02 22:36:16 +0000142 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000143
Chris Lattnerdd336d12004-12-11 05:15:59 +0000144 /// GlobalValue - If we are tracking any values for the contents of a global
145 /// variable, we keep a mapping from the constant accessor to the element of
146 /// the global, to the currently known value. If the value becomes
147 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000148 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000149
Chris Lattner59acc7d2004-12-10 08:02:06 +0000150 /// TrackedFunctionRetVals - If we are tracking arguments into and the return
151 /// value out of a function, it will have an entry in this map, indicating
152 /// what the known return value for the function is.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000153 DenseMap<Function*, LatticeVal> TrackedFunctionRetVals;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000154
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000155 // The reason for two worklists is that overdefined is the lowest state
156 // on the lattice, and moving things to overdefined as fast as possible
157 // makes SCCP converge much faster.
158 // By having a separate worklist, we accomplish this because everything
159 // possibly overdefined will become overdefined at the soonest possible
160 // point.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000161 std::vector<Value*> OverdefinedInstWorkList;
162 std::vector<Value*> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000163
164
Chris Lattner697954c2002-01-20 22:54:45 +0000165 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000166
Chris Lattner1daee8b2004-01-12 03:57:30 +0000167 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
168 /// overdefined, despite the fact that the PHI node is overdefined.
169 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
170
Chris Lattner16b18fd2003-10-08 16:55:34 +0000171 /// KnownFeasibleEdges - Entries in this set are edges which have already had
172 /// PHI nodes retriggered.
173 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
174 std::set<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000175public:
176
Chris Lattner82bec2c2004-11-15 04:44:20 +0000177 /// MarkBlockExecutable - This method can be used by clients to mark all of
178 /// the blocks that are known to be intrinsically live in the processed unit.
179 void MarkBlockExecutable(BasicBlock *BB) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000180 DOUT << "Marking Block Executable: " << BB->getName() << "\n";
Chris Lattner82bec2c2004-11-15 04:44:20 +0000181 BBExecutable.insert(BB); // Basic block is executable!
182 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner0dbfc052002-04-29 21:26:08 +0000183 }
184
Chris Lattnerdd336d12004-12-11 05:15:59 +0000185 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000186 /// inform the SCCPSolver that it should track loads and stores to the
187 /// specified global variable if it can. This is only legal to call if
188 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000189 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
190 const Type *ElTy = GV->getType()->getElementType();
191 if (ElTy->isFirstClassType()) {
192 LatticeVal &IV = TrackedGlobals[GV];
193 if (!isa<UndefValue>(GV->getInitializer()))
194 IV.markConstant(GV->getInitializer());
195 }
196 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000197
198 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
199 /// and out of the specified function (which cannot have its address taken),
200 /// this method must be called.
201 void AddTrackedFunction(Function *F) {
202 assert(F->hasInternalLinkage() && "Can only track internal functions!");
203 // Add an entry, F -> undef.
204 TrackedFunctionRetVals[F];
205 }
206
Chris Lattner82bec2c2004-11-15 04:44:20 +0000207 /// Solve - Solve for constants and executable blocks.
208 ///
209 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000210
Chris Lattner3bad2532006-12-20 06:21:33 +0000211 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000212 /// that branches on undef values cannot reach any of their successors.
213 /// However, this is not a safe assumption. After we solve dataflow, this
214 /// method should be use to handle this. If this returns true, the solver
215 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000216 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000217
Chris Lattner82bec2c2004-11-15 04:44:20 +0000218 /// getExecutableBlocks - Once we have solved for constants, return the set of
219 /// blocks that is known to be executable.
Chris Lattnercc56aad2007-02-02 20:57:39 +0000220 SmallSet<BasicBlock*, 16> &getExecutableBlocks() {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000221 return BBExecutable;
222 }
223
224 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattneref36dfd2004-11-15 05:03:30 +0000225 /// LLVM values to LatticeVals.
Chris Lattnerc1ec7802007-02-02 22:36:16 +0000226 std::map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000227 return ValueState;
228 }
229
Chris Lattner0417feb2004-12-11 02:53:57 +0000230 /// getTrackedFunctionRetVals - Get the inferred return value map.
231 ///
Chris Lattnerb59673e2007-02-02 20:38:30 +0000232 const DenseMap<Function*, LatticeVal> &getTrackedFunctionRetVals() {
Chris Lattner0417feb2004-12-11 02:53:57 +0000233 return TrackedFunctionRetVals;
234 }
235
Chris Lattnerdd336d12004-12-11 05:15:59 +0000236 /// getTrackedGlobals - Get and return the set of inferred initializers for
237 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000238 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000239 return TrackedGlobals;
240 }
241
Chris Lattner57939df2007-03-04 04:50:21 +0000242 inline void markOverdefined(Value *V) {
243 markOverdefined(ValueState[V], V);
244 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000245
Chris Lattner138a1242001-06-27 23:38:11 +0000246private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000247 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000248 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000249 // the users of the instruction are updated later.
250 //
Chris Lattner59acc7d2004-12-10 08:02:06 +0000251 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000252 if (IV.markConstant(C)) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000253 DOUT << "markConstant: " << *C << ": " << *V;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000254 InstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000255 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000256 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000257
258 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
259 IV.markForcedConstant(C);
260 DOUT << "markForcedConstant: " << *C << ": " << *V;
261 InstWorkList.push_back(V);
262 }
263
Chris Lattner59acc7d2004-12-10 08:02:06 +0000264 inline void markConstant(Value *V, Constant *C) {
265 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000266 }
267
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000268 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000269 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000270 // work list so that the users of the instruction are updated later.
Misha Brukmanfd939082005-04-21 23:48:37 +0000271
Chris Lattner59acc7d2004-12-10 08:02:06 +0000272 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000273 if (IV.markOverdefined()) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000274 DEBUG(DOUT << "markOverdefined: ";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000275 if (Function *F = dyn_cast<Function>(V))
Bill Wendlingb7427032006-11-26 09:46:52 +0000276 DOUT << "Function '" << F->getName() << "'\n";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000277 else
Bill Wendlingb7427032006-11-26 09:46:52 +0000278 DOUT << *V);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000279 // Only instructions go on the work list
Chris Lattner59acc7d2004-12-10 08:02:06 +0000280 OverdefinedInstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000281 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000282 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000283
284 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
285 if (IV.isOverdefined() || MergeWithV.isUndefined())
286 return; // Noop.
287 if (MergeWithV.isOverdefined())
288 markOverdefined(IV, V);
289 else if (IV.isUndefined())
290 markConstant(IV, V, MergeWithV.getConstant());
291 else if (IV.getConstant() != MergeWithV.getConstant())
292 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000293 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000294
295 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
296 return mergeInValue(ValueState[V], V, MergeWithV);
297 }
298
Chris Lattner138a1242001-06-27 23:38:11 +0000299
Chris Lattneref36dfd2004-11-15 05:03:30 +0000300 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman5560c9d2003-08-18 14:43:39 +0000301 // This function is necessary because not all values should start out in the
Chris Lattner73e21422002-04-09 19:48:49 +0000302 // underdefined state... Argument's should be overdefined, and
Chris Lattner79df7c02002-03-26 18:01:55 +0000303 // constants should be marked as constants. If a value is not known to be an
Chris Lattner138a1242001-06-27 23:38:11 +0000304 // Instruction object, then use this accessor to get its value from the map.
305 //
Chris Lattneref36dfd2004-11-15 05:03:30 +0000306 inline LatticeVal &getValueState(Value *V) {
Chris Lattnerc1ec7802007-02-02 22:36:16 +0000307 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000308 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000309
Chris Lattner3bad2532006-12-20 06:21:33 +0000310 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner7e529e42004-11-15 05:45:33 +0000311 if (isa<UndefValue>(V)) {
312 // Nothing to do, remain undefined.
313 } else {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000314 LatticeVal &LV = ValueState[C];
315 LV.markConstant(C); // Constants are constant
316 return LV;
Chris Lattner7e529e42004-11-15 05:45:33 +0000317 }
Chris Lattner2a88bb72002-08-30 23:39:00 +0000318 }
Chris Lattner138a1242001-06-27 23:38:11 +0000319 // All others are underdefined by default...
320 return ValueState[V];
321 }
322
Misha Brukmanfd939082005-04-21 23:48:37 +0000323 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner138a1242001-06-27 23:38:11 +0000324 // work list if it is not already executable...
Misha Brukmanfd939082005-04-21 23:48:37 +0000325 //
Chris Lattner16b18fd2003-10-08 16:55:34 +0000326 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
327 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
328 return; // This edge is already known to be executable!
329
330 if (BBExecutable.count(Dest)) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000331 DOUT << "Marking Edge Executable: " << Source->getName()
332 << " -> " << Dest->getName() << "\n";
Chris Lattner16b18fd2003-10-08 16:55:34 +0000333
334 // The destination is already executable, but we just made an edge
Chris Lattner929c6fb2003-10-08 16:56:11 +0000335 // feasible that wasn't before. Revisit the PHI nodes in the block
336 // because they have potentially new operands.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000337 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
338 visitPHINode(*cast<PHINode>(I));
Chris Lattner9de28282003-04-25 02:50:03 +0000339
340 } else {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000341 MarkBlockExecutable(Dest);
Chris Lattner9de28282003-04-25 02:50:03 +0000342 }
Chris Lattner138a1242001-06-27 23:38:11 +0000343 }
344
Chris Lattner82bec2c2004-11-15 04:44:20 +0000345 // getFeasibleSuccessors - Return a vector of booleans to indicate which
346 // successors are reachable from a given terminator instruction.
347 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000348 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000349
350 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
351 // block to the 'To' basic block is currently feasible...
352 //
353 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
354
355 // OperandChangedState - This method is invoked on all of the users of an
356 // instruction that was just changed state somehow.... Based on this
357 // information, we need to update the specified user of this instruction.
358 //
359 void OperandChangedState(User *U) {
360 // Only instructions use other variable values!
361 Instruction &I = cast<Instruction>(*U);
362 if (BBExecutable.count(I.getParent())) // Inst is executable?
363 visit(I);
364 }
365
366private:
367 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000368
Misha Brukmanfd939082005-04-21 23:48:37 +0000369 // visit implementations - Something changed in this instruction... Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000370 // operand made a transition, or the instruction is newly executable. Change
371 // the value type of I to reflect these changes if appropriate.
372 //
Chris Lattner7e708292002-06-25 16:13:24 +0000373 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000374
375 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000376 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000377 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000378
Chris Lattnerb8047602002-08-14 17:53:45 +0000379 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000380 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000381 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000382 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000383 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000384 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000385 void visitShuffleVectorInst(ShuffleVectorInst &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000386
387 // Instructions that cannot be folded away...
Chris Lattnerdd336d12004-12-11 05:15:59 +0000388 void visitStoreInst (Instruction &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000389 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000390 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner59acc7d2004-12-10 08:02:06 +0000391 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
392 void visitInvokeInst (InvokeInst &II) {
393 visitCallSite(CallSite::get(&II));
394 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000395 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000396 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000397 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000398 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner7e708292002-06-25 16:13:24 +0000399 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000400 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
401 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner7e708292002-06-25 16:13:24 +0000402 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner2a632552002-04-18 15:13:15 +0000403
Chris Lattner7e708292002-06-25 16:13:24 +0000404 void visitInstruction(Instruction &I) {
Chris Lattner2a632552002-04-18 15:13:15 +0000405 // If a new instruction is added to LLVM that we don't handle...
Bill Wendlinge8156192006-12-07 01:30:32 +0000406 cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000407 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000408 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000409};
Chris Lattnerf6293092002-07-23 18:06:35 +0000410
Chris Lattnerb9a66342002-05-02 21:44:00 +0000411// getFeasibleSuccessors - Return a vector of booleans to indicate which
412// successors are reachable from a given terminator instruction.
413//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000414void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000415 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000416 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000417 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000418 if (BI->isUnconditional()) {
419 Succs[0] = true;
420 } else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000421 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000422 if (BCValue.isOverdefined() ||
Reid Spencer579dca12007-01-12 04:24:46 +0000423 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
Chris Lattner84831642004-01-12 17:40:36 +0000424 // Overdefined condition variables, and branches on unfoldable constant
425 // conditions, mean the branch could go either way.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000426 Succs[0] = Succs[1] = true;
427 } else if (BCValue.isConstant()) {
428 // Constant condition variables mean the branch can only go a single way
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000429 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000430 }
431 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000432 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000433 // Invoke instructions successors are always executable.
434 Succs[0] = Succs[1] = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000435 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000436 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000437 if (SCValue.isOverdefined() || // Overdefined condition?
438 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000439 // All destinations are executable!
Chris Lattner7e708292002-06-25 16:13:24 +0000440 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerb9a66342002-05-02 21:44:00 +0000441 } else if (SCValue.isConstant()) {
442 Constant *CPV = SCValue.getConstant();
443 // Make sure to skip the "default value" which isn't a value
444 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
445 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
446 Succs[i] = true;
447 return;
448 }
449 }
450
451 // Constant value not equal to any of the branches... must execute
452 // default branch then...
453 Succs[0] = true;
454 }
455 } else {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000456 assert(0 && "SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000457 }
458}
459
460
Chris Lattner59f0ce22002-05-02 21:18:01 +0000461// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
462// block to the 'To' basic block is currently feasible...
463//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000464bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000465 assert(BBExecutable.count(To) && "Dest should always be alive!");
466
467 // Make sure the source basic block is executable!!
468 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000469
Chris Lattnerb9a66342002-05-02 21:44:00 +0000470 // Check to make sure this edge itself is actually feasible now...
Chris Lattner7d275f42003-10-08 15:47:41 +0000471 TerminatorInst *TI = From->getTerminator();
472 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
473 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000474 return true;
Chris Lattner7d275f42003-10-08 15:47:41 +0000475 else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000476 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000477 if (BCValue.isOverdefined()) {
478 // Overdefined condition variables mean the branch could go either way.
479 return true;
480 } else if (BCValue.isConstant()) {
Chris Lattner84831642004-01-12 17:40:36 +0000481 // Not branching on an evaluatable constant?
Chris Lattner54a525d2007-01-13 00:42:58 +0000482 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
Chris Lattner84831642004-01-12 17:40:36 +0000483
Chris Lattner7d275f42003-10-08 15:47:41 +0000484 // Constant condition variables mean the branch can only go a single way
Misha Brukmanfd939082005-04-21 23:48:37 +0000485 return BI->getSuccessor(BCValue.getConstant() ==
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000486 ConstantInt::getFalse()) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000487 }
488 return false;
489 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000490 } else if (isa<InvokeInst>(TI)) {
Chris Lattner7d275f42003-10-08 15:47:41 +0000491 // Invoke instructions successors are always executable.
492 return true;
493 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000494 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000495 if (SCValue.isOverdefined()) { // Overdefined condition?
496 // All destinations are executable!
497 return true;
498 } else if (SCValue.isConstant()) {
499 Constant *CPV = SCValue.getConstant();
Chris Lattner84831642004-01-12 17:40:36 +0000500 if (!isa<ConstantInt>(CPV))
501 return true; // not a foldable constant?
502
Chris Lattner7d275f42003-10-08 15:47:41 +0000503 // Make sure to skip the "default value" which isn't a value
504 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
505 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
506 return SI->getSuccessor(i) == To;
507
508 // Constant value not equal to any of the branches... must execute
509 // default branch then...
510 return SI->getDefaultDest() == To;
511 }
512 return false;
513 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000514 cerr << "Unknown terminator instruction: " << *TI;
Chris Lattner7d275f42003-10-08 15:47:41 +0000515 abort();
516 }
Chris Lattner59f0ce22002-05-02 21:18:01 +0000517}
Chris Lattner138a1242001-06-27 23:38:11 +0000518
Chris Lattner2a632552002-04-18 15:13:15 +0000519// visit Implementations - Something changed in this instruction... Either an
Chris Lattner138a1242001-06-27 23:38:11 +0000520// operand made a transition, or the instruction is newly executable. Change
521// the value type of I to reflect these changes if appropriate. This method
522// makes sure to do the following actions:
523//
524// 1. If a phi node merges two constants in, and has conflicting value coming
525// from different branches, or if the PHI node merges in an overdefined
526// value, then the PHI node becomes overdefined.
527// 2. If a phi node merges only constants in, and they all agree on value, the
528// PHI node becomes a constant value equal to that.
529// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
530// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
531// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
532// 6. If a conditional branch has a value that is constant, make the selected
533// destination executable
534// 7. If a conditional branch has a value that is overdefined, make all
535// successors executable.
536//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000537void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000538 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000539 if (PNIV.isOverdefined()) {
540 // There may be instructions using this PHI node that are not overdefined
541 // themselves. If so, make sure that they know that the PHI node operand
542 // changed.
543 std::multimap<PHINode*, Instruction*>::iterator I, E;
544 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
545 if (I != E) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000546 SmallVector<Instruction*, 16> Users;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000547 for (; I != E; ++I) Users.push_back(I->second);
548 while (!Users.empty()) {
549 visit(Users.back());
550 Users.pop_back();
551 }
552 }
553 return; // Quick exit
554 }
Chris Lattner138a1242001-06-27 23:38:11 +0000555
Chris Lattnera2f652d2004-03-16 19:49:59 +0000556 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
557 // and slow us down a lot. Just mark them overdefined.
558 if (PN.getNumIncomingValues() > 64) {
559 markOverdefined(PNIV, &PN);
560 return;
561 }
562
Chris Lattner2a632552002-04-18 15:13:15 +0000563 // Look at all of the executable operands of the PHI node. If any of them
564 // are overdefined, the PHI becomes overdefined as well. If they are all
565 // constant, and they agree with each other, the PHI becomes the identical
566 // constant. If they are constant and don't agree, the PHI is overdefined.
567 // If there are no executable operands, the PHI remains undefined.
568 //
Chris Lattner9de28282003-04-25 02:50:03 +0000569 Constant *OperandVal = 0;
570 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000571 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000572 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000573
Chris Lattner7e708292002-06-25 16:13:24 +0000574 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner38b5ae42003-06-24 20:29:52 +0000575 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner3d405b02003-10-08 16:21:03 +0000576 markOverdefined(PNIV, &PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000577 return;
578 }
579
Chris Lattner9de28282003-04-25 02:50:03 +0000580 if (OperandVal == 0) { // Grab the first value...
581 OperandVal = IV.getConstant();
Chris Lattner2a632552002-04-18 15:13:15 +0000582 } else { // Another value is being merged in!
583 // There is already a reachable operand. If we conflict with it,
584 // then the PHI node becomes overdefined. If we agree with it, we
585 // can continue on.
Misha Brukmanfd939082005-04-21 23:48:37 +0000586
Chris Lattner2a632552002-04-18 15:13:15 +0000587 // Check to see if there are two different constants merging...
Chris Lattner9de28282003-04-25 02:50:03 +0000588 if (IV.getConstant() != OperandVal) {
Chris Lattner2a632552002-04-18 15:13:15 +0000589 // Yes there is. This means the PHI node is not constant.
590 // You must be overdefined poor PHI.
591 //
Chris Lattner3d405b02003-10-08 16:21:03 +0000592 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner2a632552002-04-18 15:13:15 +0000593 return; // I'm done analyzing you
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000594 }
Chris Lattner138a1242001-06-27 23:38:11 +0000595 }
596 }
Chris Lattner138a1242001-06-27 23:38:11 +0000597 }
598
Chris Lattner2a632552002-04-18 15:13:15 +0000599 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000600 // arguments that agree with each other(and OperandVal is the constant) or
601 // OperandVal is null because there are no defined incoming arguments. If
602 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000603 //
Chris Lattner9de28282003-04-25 02:50:03 +0000604 if (OperandVal)
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000605 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000606}
607
Chris Lattner59acc7d2004-12-10 08:02:06 +0000608void SCCPSolver::visitReturnInst(ReturnInst &I) {
609 if (I.getNumOperands() == 0) return; // Ret void
610
611 // If we are tracking the return value of this function, merge it in.
612 Function *F = I.getParent()->getParent();
613 if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000614 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Chris Lattner59acc7d2004-12-10 08:02:06 +0000615 TrackedFunctionRetVals.find(F);
616 if (TFRVI != TrackedFunctionRetVals.end() &&
617 !TFRVI->second.isOverdefined()) {
618 LatticeVal &IV = getValueState(I.getOperand(0));
619 mergeInValue(TFRVI->second, F, IV);
620 }
621 }
622}
623
624
Chris Lattner82bec2c2004-11-15 04:44:20 +0000625void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000626 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000627 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000628
Chris Lattner16b18fd2003-10-08 16:55:34 +0000629 BasicBlock *BB = TI.getParent();
630
Chris Lattnerb9a66342002-05-02 21:44:00 +0000631 // Mark all feasible successors executable...
632 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000633 if (SuccFeasible[i])
634 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000635}
636
Chris Lattner82bec2c2004-11-15 04:44:20 +0000637void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000638 Value *V = I.getOperand(0);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000639 LatticeVal &VState = getValueState(V);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000640 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000641 markOverdefined(&I);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000642 else if (VState.isConstant()) // Propagate constant value
Reid Spencer4da49122006-12-12 05:05:00 +0000643 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
644 VState.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000645}
646
Chris Lattner82bec2c2004-11-15 04:44:20 +0000647void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000648 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000649 if (CondValue.isUndefined())
650 return;
Reid Spencer579dca12007-01-12 04:24:46 +0000651 if (CondValue.isConstant()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000652 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencer579dca12007-01-12 04:24:46 +0000653 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000654 : I.getFalseValue()));
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000655 return;
656 }
657 }
658
659 // Otherwise, the condition is overdefined or a constant we can't evaluate.
660 // See if we can produce something better than overdefined based on the T/F
661 // value.
662 LatticeVal &TVal = getValueState(I.getTrueValue());
663 LatticeVal &FVal = getValueState(I.getFalseValue());
664
665 // select ?, C, C -> C.
666 if (TVal.isConstant() && FVal.isConstant() &&
667 TVal.getConstant() == FVal.getConstant()) {
668 markConstant(&I, FVal.getConstant());
669 return;
670 }
671
672 if (TVal.isUndefined()) { // select ?, undef, X -> X.
673 mergeInValue(&I, FVal);
674 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
675 mergeInValue(&I, TVal);
676 } else {
677 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000678 }
679}
680
Chris Lattner2a632552002-04-18 15:13:15 +0000681// Handle BinaryOperators and Shift Instructions...
Chris Lattner82bec2c2004-11-15 04:44:20 +0000682void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000683 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000684 if (IV.isOverdefined()) return;
685
Chris Lattneref36dfd2004-11-15 05:03:30 +0000686 LatticeVal &V1State = getValueState(I.getOperand(0));
687 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000688
Chris Lattner2a632552002-04-18 15:13:15 +0000689 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnera177c672004-12-11 23:15:19 +0000690 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
691 // operand is overdefined.
692 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
693 LatticeVal *NonOverdefVal = 0;
694 if (!V1State.isOverdefined()) {
695 NonOverdefVal = &V1State;
696 } else if (!V2State.isOverdefined()) {
697 NonOverdefVal = &V2State;
698 }
699
700 if (NonOverdefVal) {
701 if (NonOverdefVal->isUndefined()) {
702 // Could annihilate value.
703 if (I.getOpcode() == Instruction::And)
704 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +0000705 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
706 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +0000707 else
708 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera177c672004-12-11 23:15:19 +0000709 return;
710 } else {
711 if (I.getOpcode() == Instruction::And) {
712 if (NonOverdefVal->getConstant()->isNullValue()) {
713 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskey52ab9042007-01-03 00:11:03 +0000714 return; // X and 0 = 0
Chris Lattnera177c672004-12-11 23:15:19 +0000715 }
716 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000717 if (ConstantInt *CI =
718 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnera177c672004-12-11 23:15:19 +0000719 if (CI->isAllOnesValue()) {
720 markConstant(IV, &I, NonOverdefVal->getConstant());
721 return; // X or -1 = -1
722 }
723 }
724 }
725 }
726 }
727
728
Chris Lattner1daee8b2004-01-12 03:57:30 +0000729 // If both operands are PHI nodes, it is possible that this instruction has
730 // a constant value, despite the fact that the PHI node doesn't. Check for
731 // this condition now.
732 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
733 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
734 if (PN1->getParent() == PN2->getParent()) {
735 // Since the two PHI nodes are in the same basic block, they must have
736 // entries for the same predecessors. Walk the predecessor list, and
737 // if all of the incoming values are constants, and the result of
738 // evaluating this expression with all incoming value pairs is the
739 // same, then this expression is a constant even though the PHI node
740 // is not a constant!
Chris Lattneref36dfd2004-11-15 05:03:30 +0000741 LatticeVal Result;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000742 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000743 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000744 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000745 LatticeVal &In2 =
746 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000747
748 if (In1.isOverdefined() || In2.isOverdefined()) {
749 Result.markOverdefined();
750 break; // Cannot fold this operation over the PHI nodes!
751 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000752 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
753 In2.getConstant());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000754 if (Result.isUndefined())
Chris Lattnerb16689b2004-01-12 19:08:43 +0000755 Result.markConstant(V);
756 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000757 Result.markOverdefined();
758 break;
759 }
760 }
761 }
762
763 // If we found a constant value here, then we know the instruction is
764 // constant despite the fact that the PHI nodes are overdefined.
765 if (Result.isConstant()) {
766 markConstant(IV, &I, Result.getConstant());
767 // Remember that this instruction is virtually using the PHI node
768 // operands.
769 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
770 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
771 return;
772 } else if (Result.isUndefined()) {
773 return;
774 }
775
776 // Okay, this really is overdefined now. Since we might have
777 // speculatively thought that this was not overdefined before, and
778 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
779 // make sure to clean out any entries that we put there, for
780 // efficiency.
781 std::multimap<PHINode*, Instruction*>::iterator It, E;
782 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
783 while (It != E) {
784 if (It->second == &I) {
785 UsersOfOverdefinedPHIs.erase(It++);
786 } else
787 ++It;
788 }
789 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
790 while (It != E) {
791 if (It->second == &I) {
792 UsersOfOverdefinedPHIs.erase(It++);
793 } else
794 ++It;
795 }
796 }
797
798 markOverdefined(IV, &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000799 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000800 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
801 V2State.getConstant()));
Chris Lattner2a632552002-04-18 15:13:15 +0000802 }
803}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000804
Reid Spencere4d87aa2006-12-23 06:05:41 +0000805// Handle ICmpInst instruction...
806void SCCPSolver::visitCmpInst(CmpInst &I) {
807 LatticeVal &IV = ValueState[&I];
808 if (IV.isOverdefined()) return;
809
810 LatticeVal &V1State = getValueState(I.getOperand(0));
811 LatticeVal &V2State = getValueState(I.getOperand(1));
812
813 if (V1State.isOverdefined() || V2State.isOverdefined()) {
814 // If both operands are PHI nodes, it is possible that this instruction has
815 // a constant value, despite the fact that the PHI node doesn't. Check for
816 // this condition now.
817 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
818 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
819 if (PN1->getParent() == PN2->getParent()) {
820 // Since the two PHI nodes are in the same basic block, they must have
821 // entries for the same predecessors. Walk the predecessor list, and
822 // if all of the incoming values are constants, and the result of
823 // evaluating this expression with all incoming value pairs is the
824 // same, then this expression is a constant even though the PHI node
825 // is not a constant!
826 LatticeVal Result;
827 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
828 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
829 BasicBlock *InBlock = PN1->getIncomingBlock(i);
830 LatticeVal &In2 =
831 getValueState(PN2->getIncomingValueForBlock(InBlock));
832
833 if (In1.isOverdefined() || In2.isOverdefined()) {
834 Result.markOverdefined();
835 break; // Cannot fold this operation over the PHI nodes!
836 } else if (In1.isConstant() && In2.isConstant()) {
837 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
838 In1.getConstant(),
839 In2.getConstant());
840 if (Result.isUndefined())
841 Result.markConstant(V);
842 else if (Result.isConstant() && Result.getConstant() != V) {
843 Result.markOverdefined();
844 break;
845 }
846 }
847 }
848
849 // If we found a constant value here, then we know the instruction is
850 // constant despite the fact that the PHI nodes are overdefined.
851 if (Result.isConstant()) {
852 markConstant(IV, &I, Result.getConstant());
853 // Remember that this instruction is virtually using the PHI node
854 // operands.
855 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
856 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
857 return;
858 } else if (Result.isUndefined()) {
859 return;
860 }
861
862 // Okay, this really is overdefined now. Since we might have
863 // speculatively thought that this was not overdefined before, and
864 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
865 // make sure to clean out any entries that we put there, for
866 // efficiency.
867 std::multimap<PHINode*, Instruction*>::iterator It, E;
868 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
869 while (It != E) {
870 if (It->second == &I) {
871 UsersOfOverdefinedPHIs.erase(It++);
872 } else
873 ++It;
874 }
875 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
876 while (It != E) {
877 if (It->second == &I) {
878 UsersOfOverdefinedPHIs.erase(It++);
879 } else
880 ++It;
881 }
882 }
883
884 markOverdefined(IV, &I);
885 } else if (V1State.isConstant() && V2State.isConstant()) {
886 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
887 V1State.getConstant(),
888 V2State.getConstant()));
889 }
890}
891
Robert Bocchino56107e22006-01-10 19:05:05 +0000892void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +0000893 // FIXME : SCCP does not handle vectors properly.
894 markOverdefined(&I);
895 return;
896
897#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +0000898 LatticeVal &ValState = getValueState(I.getOperand(0));
899 LatticeVal &IdxState = getValueState(I.getOperand(1));
900
901 if (ValState.isOverdefined() || IdxState.isOverdefined())
902 markOverdefined(&I);
903 else if(ValState.isConstant() && IdxState.isConstant())
904 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
905 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +0000906#endif
Robert Bocchino56107e22006-01-10 19:05:05 +0000907}
908
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000909void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +0000910 // FIXME : SCCP does not handle vectors properly.
911 markOverdefined(&I);
912 return;
913#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000914 LatticeVal &ValState = getValueState(I.getOperand(0));
915 LatticeVal &EltState = getValueState(I.getOperand(1));
916 LatticeVal &IdxState = getValueState(I.getOperand(2));
917
918 if (ValState.isOverdefined() || EltState.isOverdefined() ||
919 IdxState.isOverdefined())
920 markOverdefined(&I);
921 else if(ValState.isConstant() && EltState.isConstant() &&
922 IdxState.isConstant())
923 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
924 EltState.getConstant(),
925 IdxState.getConstant()));
926 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +0000927 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +0000928 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
929 EltState.getConstant(),
930 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +0000931#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000932}
933
Chris Lattner543abdf2006-04-08 01:19:12 +0000934void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +0000935 // FIXME : SCCP does not handle vectors properly.
936 markOverdefined(&I);
937 return;
938#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +0000939 LatticeVal &V1State = getValueState(I.getOperand(0));
940 LatticeVal &V2State = getValueState(I.getOperand(1));
941 LatticeVal &MaskState = getValueState(I.getOperand(2));
942
943 if (MaskState.isUndefined() ||
944 (V1State.isUndefined() && V2State.isUndefined()))
945 return; // Undefined output if mask or both inputs undefined.
946
947 if (V1State.isOverdefined() || V2State.isOverdefined() ||
948 MaskState.isOverdefined()) {
949 markOverdefined(&I);
950 } else {
951 // A mix of constant/undef inputs.
952 Constant *V1 = V1State.isConstant() ?
953 V1State.getConstant() : UndefValue::get(I.getType());
954 Constant *V2 = V2State.isConstant() ?
955 V2State.getConstant() : UndefValue::get(I.getType());
956 Constant *Mask = MaskState.isConstant() ?
957 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
958 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
959 }
Devang Patel67a821d2006-12-04 23:54:59 +0000960#endif
Chris Lattner543abdf2006-04-08 01:19:12 +0000961}
962
Chris Lattner2a88bb72002-08-30 23:39:00 +0000963// Handle getelementptr instructions... if all operands are constants then we
964// can turn this into a getelementptr ConstantExpr.
965//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000966void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000967 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000968 if (IV.isOverdefined()) return;
969
Chris Lattnere777ff22007-02-02 20:51:48 +0000970 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +0000971 Operands.reserve(I.getNumOperands());
972
973 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000974 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +0000975 if (State.isUndefined())
976 return; // Operands are not resolved yet...
977 else if (State.isOverdefined()) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000978 markOverdefined(IV, &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000979 return;
980 }
981 assert(State.isConstant() && "Unknown state!");
982 Operands.push_back(State.getConstant());
983 }
984
985 Constant *Ptr = Operands[0];
986 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
987
Chris Lattnere777ff22007-02-02 20:51:48 +0000988 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
989 Operands.size()));
Chris Lattner2a88bb72002-08-30 23:39:00 +0000990}
Brian Gaeked0fde302003-11-11 22:41:34 +0000991
Chris Lattnerdd336d12004-12-11 05:15:59 +0000992void SCCPSolver::visitStoreInst(Instruction &SI) {
993 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
994 return;
995 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +0000996 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +0000997 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
998
999 // Get the value we are storing into the global.
1000 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1001
1002 mergeInValue(I->second, GV, PtrVal);
1003 if (I->second.isOverdefined())
1004 TrackedGlobals.erase(I); // No need to keep tracking this!
1005}
1006
1007
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001008// Handle load instructions. If the operand is a constant pointer to a constant
1009// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001010void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001011 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001012 if (IV.isOverdefined()) return;
1013
Chris Lattneref36dfd2004-11-15 05:03:30 +00001014 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001015 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1016 if (PtrVal.isConstant() && !I.isVolatile()) {
1017 Value *Ptr = PtrVal.getConstant();
Chris Lattnerc76d8032004-03-07 22:16:24 +00001018 if (isa<ConstantPointerNull>(Ptr)) {
1019 // load null -> null
1020 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1021 return;
1022 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001023
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001024 // Transform load (constant global) into the value loaded.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001025 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1026 if (GV->isConstant()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001027 if (!GV->isDeclaration()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001028 markConstant(IV, &I, GV->getInitializer());
1029 return;
1030 }
1031 } else if (!TrackedGlobals.empty()) {
1032 // If we are tracking this global, merge in the known value for it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001033 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
Chris Lattnerdd336d12004-12-11 05:15:59 +00001034 TrackedGlobals.find(GV);
1035 if (It != TrackedGlobals.end()) {
1036 mergeInValue(IV, &I, It->second);
1037 return;
1038 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001039 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001040 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001041
1042 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1043 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1044 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen9d809302005-04-23 21:38:35 +00001045 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00001046 if (GV->isConstant() && !GV->isDeclaration())
Jeff Cohen9d809302005-04-23 21:38:35 +00001047 if (Constant *V =
Chris Lattnerebe61202005-09-26 05:28:52 +00001048 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen9d809302005-04-23 21:38:35 +00001049 markConstant(IV, &I, V);
1050 return;
1051 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001052 }
1053
1054 // Otherwise we cannot say for certain what value this load will produce.
1055 // Bail out.
1056 markOverdefined(IV, &I);
1057}
Chris Lattner58b7b082004-04-13 19:43:54 +00001058
Chris Lattner59acc7d2004-12-10 08:02:06 +00001059void SCCPSolver::visitCallSite(CallSite CS) {
1060 Function *F = CS.getCalledFunction();
1061
1062 // If we are tracking this function, we must make sure to bind arguments as
1063 // appropriate.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001064 DenseMap<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001065 if (F && F->hasInternalLinkage())
1066 TFRVI = TrackedFunctionRetVals.find(F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001067
Chris Lattner59acc7d2004-12-10 08:02:06 +00001068 if (TFRVI != TrackedFunctionRetVals.end()) {
1069 // If this is the first call to the function hit, mark its entry block
1070 // executable.
1071 if (!BBExecutable.count(F->begin()))
1072 MarkBlockExecutable(F->begin());
1073
1074 CallSite::arg_iterator CAI = CS.arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +00001075 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001076 AI != E; ++AI, ++CAI) {
1077 LatticeVal &IV = ValueState[AI];
1078 if (!IV.isOverdefined())
1079 mergeInValue(IV, AI, getValueState(*CAI));
1080 }
1081 }
1082 Instruction *I = CS.getInstruction();
1083 if (I->getType() == Type::VoidTy) return;
1084
1085 LatticeVal &IV = ValueState[I];
Chris Lattner58b7b082004-04-13 19:43:54 +00001086 if (IV.isOverdefined()) return;
1087
Chris Lattner59acc7d2004-12-10 08:02:06 +00001088 // Propagate the return value of the function to the value of the instruction.
1089 if (TFRVI != TrackedFunctionRetVals.end()) {
1090 mergeInValue(IV, I, TFRVI->second);
1091 return;
1092 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001093
Reid Spencer5cbf9852007-01-30 20:08:39 +00001094 if (F == 0 || !F->isDeclaration() || !canConstantFoldCallTo(F)) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001095 markOverdefined(IV, I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001096 return;
1097 }
1098
Chris Lattnercd2492e2007-01-30 23:15:19 +00001099 SmallVector<Constant*, 8> Operands;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001100 Operands.reserve(I->getNumOperands()-1);
Chris Lattner58b7b082004-04-13 19:43:54 +00001101
Chris Lattner59acc7d2004-12-10 08:02:06 +00001102 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1103 AI != E; ++AI) {
1104 LatticeVal &State = getValueState(*AI);
Chris Lattner58b7b082004-04-13 19:43:54 +00001105 if (State.isUndefined())
1106 return; // Operands are not resolved yet...
1107 else if (State.isOverdefined()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001108 markOverdefined(IV, I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001109 return;
1110 }
1111 assert(State.isConstant() && "Unknown state!");
1112 Operands.push_back(State.getConstant());
1113 }
1114
Chris Lattnercd2492e2007-01-30 23:15:19 +00001115 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size()))
Chris Lattner59acc7d2004-12-10 08:02:06 +00001116 markConstant(IV, I, C);
Chris Lattner58b7b082004-04-13 19:43:54 +00001117 else
Chris Lattner59acc7d2004-12-10 08:02:06 +00001118 markOverdefined(IV, I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001119}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001120
1121
1122void SCCPSolver::Solve() {
1123 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001124 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001125 !OverdefinedInstWorkList.empty()) {
Chris Lattner82bec2c2004-11-15 04:44:20 +00001126 // Process the instruction work list...
1127 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001128 Value *I = OverdefinedInstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001129 OverdefinedInstWorkList.pop_back();
1130
Bill Wendlingb7427032006-11-26 09:46:52 +00001131 DOUT << "\nPopped off OI-WL: " << *I;
Misha Brukmanfd939082005-04-21 23:48:37 +00001132
Chris Lattner82bec2c2004-11-15 04:44:20 +00001133 // "I" got into the work list because it either made the transition from
1134 // bottom to constant
1135 //
1136 // Anything on this worklist that is overdefined need not be visited
1137 // since all of its users will have already been marked as overdefined
1138 // Update all of the users of this instruction's value...
1139 //
1140 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1141 UI != E; ++UI)
1142 OperandChangedState(*UI);
1143 }
1144 // Process the instruction work list...
1145 while (!InstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001146 Value *I = InstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001147 InstWorkList.pop_back();
1148
Bill Wendlingb7427032006-11-26 09:46:52 +00001149 DOUT << "\nPopped off I-WL: " << *I;
Misha Brukmanfd939082005-04-21 23:48:37 +00001150
Chris Lattner82bec2c2004-11-15 04:44:20 +00001151 // "I" got into the work list because it either made the transition from
1152 // bottom to constant
1153 //
1154 // Anything on this worklist that is overdefined need not be visited
1155 // since all of its users will have already been marked as overdefined.
1156 // Update all of the users of this instruction's value...
1157 //
1158 if (!getValueState(I).isOverdefined())
1159 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1160 UI != E; ++UI)
1161 OperandChangedState(*UI);
1162 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001163
Chris Lattner82bec2c2004-11-15 04:44:20 +00001164 // Process the basic block work list...
1165 while (!BBWorkList.empty()) {
1166 BasicBlock *BB = BBWorkList.back();
1167 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001168
Bill Wendlingb7427032006-11-26 09:46:52 +00001169 DOUT << "\nPopped off BBWL: " << *BB;
Misha Brukmanfd939082005-04-21 23:48:37 +00001170
Chris Lattner82bec2c2004-11-15 04:44:20 +00001171 // Notify all instructions in this basic block that they are newly
1172 // executable.
1173 visit(BB);
1174 }
1175 }
1176}
1177
Chris Lattner3bad2532006-12-20 06:21:33 +00001178/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001179/// that branches on undef values cannot reach any of their successors.
1180/// However, this is not a safe assumption. After we solve dataflow, this
1181/// method should be use to handle this. If this returns true, the solver
1182/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001183///
1184/// This method handles this by finding an unresolved branch and marking it one
1185/// of the edges from the block as being feasible, even though the condition
1186/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1187/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001188/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001189/// constraints on the condition of the branch, as that would impact other users
1190/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001191///
1192/// This scan also checks for values that use undefs, whose results are actually
1193/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1194/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1195/// even if X isn't defined.
1196bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001197 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1198 if (!BBExecutable.count(BB))
1199 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001200
1201 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1202 // Look for instructions which produce undef values.
1203 if (I->getType() == Type::VoidTy) continue;
1204
1205 LatticeVal &LV = getValueState(I);
1206 if (!LV.isUndefined()) continue;
1207
1208 // Get the lattice values of the first two operands for use below.
1209 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1210 LatticeVal Op1LV;
1211 if (I->getNumOperands() == 2) {
1212 // If this is a two-operand instruction, and if both operands are
1213 // undefs, the result stays undef.
1214 Op1LV = getValueState(I->getOperand(1));
1215 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1216 continue;
1217 }
1218
1219 // If this is an instructions whose result is defined even if the input is
1220 // not fully defined, propagate the information.
1221 const Type *ITy = I->getType();
1222 switch (I->getOpcode()) {
1223 default: break; // Leave the instruction as an undef.
1224 case Instruction::ZExt:
1225 // After a zero extend, we know the top part is zero. SExt doesn't have
1226 // to be handled here, because we don't know whether the top part is 1's
1227 // or 0's.
1228 assert(Op0LV.isUndefined());
1229 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1230 return true;
1231 case Instruction::Mul:
1232 case Instruction::And:
1233 // undef * X -> 0. X could be zero.
1234 // undef & X -> 0. X could be zero.
1235 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1236 return true;
1237
1238 case Instruction::Or:
1239 // undef | X -> -1. X could be -1.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001240 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1241 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001242 else
1243 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1244 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001245
1246 case Instruction::SDiv:
1247 case Instruction::UDiv:
1248 case Instruction::SRem:
1249 case Instruction::URem:
1250 // X / undef -> undef. No change.
1251 // X % undef -> undef. No change.
1252 if (Op1LV.isUndefined()) break;
1253
1254 // undef / X -> 0. X could be maxint.
1255 // undef % X -> 0. X could be 1.
1256 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1257 return true;
1258
1259 case Instruction::AShr:
1260 // undef >>s X -> undef. No change.
1261 if (Op0LV.isUndefined()) break;
1262
1263 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1264 if (Op0LV.isConstant())
1265 markForcedConstant(LV, I, Op0LV.getConstant());
1266 else
1267 markOverdefined(LV, I);
1268 return true;
1269 case Instruction::LShr:
1270 case Instruction::Shl:
1271 // undef >> X -> undef. No change.
1272 // undef << X -> undef. No change.
1273 if (Op0LV.isUndefined()) break;
1274
1275 // X >> undef -> 0. X could be 0.
1276 // X << undef -> 0. X could be 0.
1277 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1278 return true;
1279 case Instruction::Select:
1280 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1281 if (Op0LV.isUndefined()) {
1282 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1283 Op1LV = getValueState(I->getOperand(2));
1284 } else if (Op1LV.isUndefined()) {
1285 // c ? undef : undef -> undef. No change.
1286 Op1LV = getValueState(I->getOperand(2));
1287 if (Op1LV.isUndefined())
1288 break;
1289 // Otherwise, c ? undef : x -> x.
1290 } else {
1291 // Leave Op1LV as Operand(1)'s LatticeValue.
1292 }
1293
1294 if (Op1LV.isConstant())
1295 markForcedConstant(LV, I, Op1LV.getConstant());
1296 else
1297 markOverdefined(LV, I);
1298 return true;
1299 }
1300 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001301
1302 TerminatorInst *TI = BB->getTerminator();
1303 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1304 if (!BI->isConditional()) continue;
1305 if (!getValueState(BI->getCondition()).isUndefined())
1306 continue;
1307 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1308 if (!getValueState(SI->getCondition()).isUndefined())
1309 continue;
1310 } else {
1311 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001312 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001313
1314 // If the edge to the first successor isn't thought to be feasible yet, mark
1315 // it so now.
1316 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(0))))
1317 continue;
1318
1319 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1320 // and return. This will make other blocks reachable, which will allow new
1321 // values to be discovered and existing ones to be moved in the lattice.
1322 markEdgeExecutable(BB, TI->getSuccessor(0));
1323 return true;
1324 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001325
Chris Lattnerd2d86702006-10-22 05:59:17 +00001326 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001327}
1328
Chris Lattner82bec2c2004-11-15 04:44:20 +00001329
1330namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001331 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001332 //
Chris Lattner14051812004-11-15 07:15:04 +00001333 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001334 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001335 ///
Reid Spencer9133fe22007-02-05 23:32:05 +00001336 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
Devang Patel19974732007-05-03 01:11:54 +00001337 static char ID; // Pass identifcation, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +00001338 SCCP() : FunctionPass((intptr_t)&ID) {}
1339
Chris Lattner14051812004-11-15 07:15:04 +00001340 // runOnFunction - Run the Sparse Conditional Constant Propagation
1341 // algorithm, and return true if the function was modified.
1342 //
1343 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001344
Chris Lattner14051812004-11-15 07:15:04 +00001345 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1346 AU.setPreservesCFG();
1347 }
1348 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001349
Devang Patel19974732007-05-03 01:11:54 +00001350 char SCCP::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +00001351 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001352} // end anonymous namespace
1353
1354
1355// createSCCPPass - This is the public interface to this file...
1356FunctionPass *llvm::createSCCPPass() {
1357 return new SCCP();
1358}
1359
1360
Chris Lattner82bec2c2004-11-15 04:44:20 +00001361// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1362// and return true if the function was modified.
1363//
1364bool SCCP::runOnFunction(Function &F) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001365 DOUT << "SCCP on function '" << F.getName() << "'\n";
Chris Lattner82bec2c2004-11-15 04:44:20 +00001366 SCCPSolver Solver;
1367
1368 // Mark the first block of the function as being executable.
1369 Solver.MarkBlockExecutable(F.begin());
1370
Chris Lattner7e529e42004-11-15 05:45:33 +00001371 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001372 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001373 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001374
Chris Lattner82bec2c2004-11-15 04:44:20 +00001375 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001376 bool ResolvedUndefs = true;
1377 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001378 Solver.Solve();
Chris Lattner3bad2532006-12-20 06:21:33 +00001379 DOUT << "RESOLVING UNDEFs\n";
1380 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001381 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001382
Chris Lattner7e529e42004-11-15 05:45:33 +00001383 bool MadeChanges = false;
1384
1385 // If we decided that there are basic blocks that are dead in this function,
1386 // delete their contents now. Note that we cannot actually delete the blocks,
1387 // as we cannot modify the CFG of the function.
1388 //
Chris Lattnercc56aad2007-02-02 20:57:39 +00001389 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001390 SmallVector<Instruction*, 32> Insts;
Chris Lattner57939df2007-03-04 04:50:21 +00001391 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1392
Chris Lattner7e529e42004-11-15 05:45:33 +00001393 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1394 if (!ExecutableBBs.count(BB)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001395 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001396 ++NumDeadBlocks;
1397
Chris Lattner7e529e42004-11-15 05:45:33 +00001398 // Delete the instructions backwards, as it has a reduced likelihood of
1399 // having to update as many def-use and use-def chains.
Chris Lattner7e529e42004-11-15 05:45:33 +00001400 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1401 I != E; ++I)
1402 Insts.push_back(I);
1403 while (!Insts.empty()) {
1404 Instruction *I = Insts.back();
1405 Insts.pop_back();
1406 if (!I->use_empty())
1407 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1408 BB->getInstList().erase(I);
1409 MadeChanges = true;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001410 ++NumInstRemoved;
Chris Lattner7e529e42004-11-15 05:45:33 +00001411 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001412 } else {
1413 // Iterate over all of the instructions in a function, replacing them with
1414 // constants if we have found them to be of constant values.
1415 //
1416 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1417 Instruction *Inst = BI++;
1418 if (Inst->getType() != Type::VoidTy) {
1419 LatticeVal &IV = Values[Inst];
1420 if (IV.isConstant() || IV.isUndefined() &&
1421 !isa<TerminatorInst>(Inst)) {
1422 Constant *Const = IV.isConstant()
1423 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendlingb7427032006-11-26 09:46:52 +00001424 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanfd939082005-04-21 23:48:37 +00001425
Chris Lattner59acc7d2004-12-10 08:02:06 +00001426 // Replaces all of the uses of a variable with uses of the constant.
1427 Inst->replaceAllUsesWith(Const);
Misha Brukmanfd939082005-04-21 23:48:37 +00001428
Chris Lattner59acc7d2004-12-10 08:02:06 +00001429 // Delete the instruction.
1430 BB->getInstList().erase(Inst);
Misha Brukmanfd939082005-04-21 23:48:37 +00001431
Chris Lattner59acc7d2004-12-10 08:02:06 +00001432 // Hey, we just changed something!
1433 MadeChanges = true;
1434 ++NumInstRemoved;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001435 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001436 }
1437 }
1438 }
1439
1440 return MadeChanges;
1441}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001442
1443namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001444 //===--------------------------------------------------------------------===//
1445 //
1446 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1447 /// Constant Propagation.
1448 ///
Reid Spencer9133fe22007-02-05 23:32:05 +00001449 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001450 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +00001451 IPSCCP() : ModulePass((intptr_t)&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001452 bool runOnModule(Module &M);
1453 };
1454
Devang Patel19974732007-05-03 01:11:54 +00001455 char IPSCCP::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +00001456 RegisterPass<IPSCCP>
Chris Lattner59acc7d2004-12-10 08:02:06 +00001457 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1458} // end anonymous namespace
1459
1460// createIPSCCPPass - This is the public interface to this file...
1461ModulePass *llvm::createIPSCCPPass() {
1462 return new IPSCCP();
1463}
1464
1465
1466static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001467 // Delete any dead constantexpr klingons.
1468 GV->removeDeadConstantUsers();
1469
Chris Lattner59acc7d2004-12-10 08:02:06 +00001470 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1471 UI != E; ++UI)
1472 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001473 if (SI->getOperand(0) == GV || SI->isVolatile())
1474 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001475 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1476 // Make sure we are calling the function, not passing the address.
1477 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1478 for (CallSite::arg_iterator AI = CS.arg_begin(),
1479 E = CS.arg_end(); AI != E; ++AI)
1480 if (*AI == GV)
1481 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001482 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1483 if (LI->isVolatile())
1484 return true;
1485 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001486 return true;
1487 }
1488 return false;
1489}
1490
1491bool IPSCCP::runOnModule(Module &M) {
1492 SCCPSolver Solver;
1493
1494 // Loop over all functions, marking arguments to those with their addresses
1495 // taken or that are external as overdefined.
1496 //
Chris Lattner59acc7d2004-12-10 08:02:06 +00001497 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1498 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001499 if (!F->isDeclaration())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001500 Solver.MarkBlockExecutable(F->begin());
Chris Lattner7d27fc02005-04-19 19:16:19 +00001501 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1502 AI != E; ++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001503 Solver.markOverdefined(AI);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001504 } else {
1505 Solver.AddTrackedFunction(F);
1506 }
1507
Chris Lattnerdd336d12004-12-11 05:15:59 +00001508 // Loop over global variables. We inform the solver about any internal global
1509 // variables that do not have their 'addresses taken'. If they don't have
1510 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001511 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1512 G != E; ++G)
Chris Lattnerdd336d12004-12-11 05:15:59 +00001513 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1514 Solver.TrackValueOfGlobalVariable(G);
1515
Chris Lattner59acc7d2004-12-10 08:02:06 +00001516 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001517 bool ResolvedUndefs = true;
1518 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001519 Solver.Solve();
1520
Chris Lattner3bad2532006-12-20 06:21:33 +00001521 DOUT << "RESOLVING UNDEFS\n";
1522 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001523 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001524 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001525 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001526
1527 bool MadeChanges = false;
1528
1529 // Iterate over all of the instructions in the module, replacing them with
1530 // constants if we have found them to be of constant values.
1531 //
Chris Lattnercc56aad2007-02-02 20:57:39 +00001532 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001533 SmallVector<Instruction*, 32> Insts;
1534 SmallVector<BasicBlock*, 32> BlocksToErase;
Chris Lattner57939df2007-03-04 04:50:21 +00001535 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001536
Chris Lattner59acc7d2004-12-10 08:02:06 +00001537 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001538 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1539 AI != E; ++AI)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001540 if (!AI->use_empty()) {
1541 LatticeVal &IV = Values[AI];
1542 if (IV.isConstant() || IV.isUndefined()) {
1543 Constant *CST = IV.isConstant() ?
1544 IV.getConstant() : UndefValue::get(AI->getType());
Bill Wendlingb7427032006-11-26 09:46:52 +00001545 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
Misha Brukmanfd939082005-04-21 23:48:37 +00001546
Chris Lattner59acc7d2004-12-10 08:02:06 +00001547 // Replaces all of the uses of a variable with uses of the
1548 // constant.
1549 AI->replaceAllUsesWith(CST);
1550 ++IPNumArgsElimed;
1551 }
1552 }
1553
1554 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1555 if (!ExecutableBBs.count(BB)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001556 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001557 ++IPNumDeadBlocks;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001558
Chris Lattner59acc7d2004-12-10 08:02:06 +00001559 // Delete the instructions backwards, as it has a reduced likelihood of
1560 // having to update as many def-use and use-def chains.
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001561 TerminatorInst *TI = BB->getTerminator();
1562 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001563 Insts.push_back(I);
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001564
Chris Lattner59acc7d2004-12-10 08:02:06 +00001565 while (!Insts.empty()) {
1566 Instruction *I = Insts.back();
1567 Insts.pop_back();
1568 if (!I->use_empty())
1569 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1570 BB->getInstList().erase(I);
1571 MadeChanges = true;
1572 ++IPNumInstRemoved;
1573 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001574
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001575 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1576 BasicBlock *Succ = TI->getSuccessor(i);
1577 if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1578 TI->getSuccessor(i)->removePredecessor(BB);
1579 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001580 if (!TI->use_empty())
1581 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001582 BB->getInstList().erase(TI);
1583
Chris Lattner864737b2004-12-11 05:32:19 +00001584 if (&*BB != &F->front())
1585 BlocksToErase.push_back(BB);
1586 else
1587 new UnreachableInst(BB);
1588
Chris Lattner59acc7d2004-12-10 08:02:06 +00001589 } else {
1590 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1591 Instruction *Inst = BI++;
1592 if (Inst->getType() != Type::VoidTy) {
1593 LatticeVal &IV = Values[Inst];
1594 if (IV.isConstant() || IV.isUndefined() &&
1595 !isa<TerminatorInst>(Inst)) {
1596 Constant *Const = IV.isConstant()
1597 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendlingb7427032006-11-26 09:46:52 +00001598 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanfd939082005-04-21 23:48:37 +00001599
Chris Lattner59acc7d2004-12-10 08:02:06 +00001600 // Replaces all of the uses of a variable with uses of the
1601 // constant.
1602 Inst->replaceAllUsesWith(Const);
Misha Brukmanfd939082005-04-21 23:48:37 +00001603
Chris Lattner59acc7d2004-12-10 08:02:06 +00001604 // Delete the instruction.
1605 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1606 BB->getInstList().erase(Inst);
1607
1608 // Hey, we just changed something!
1609 MadeChanges = true;
1610 ++IPNumInstRemoved;
1611 }
1612 }
1613 }
1614 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001615
1616 // Now that all instructions in the function are constant folded, erase dead
1617 // blocks, because we can now use ConstantFoldTerminator to get rid of
1618 // in-edges.
1619 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1620 // If there are any PHI nodes in this successor, drop entries for BB now.
1621 BasicBlock *DeadBB = BlocksToErase[i];
1622 while (!DeadBB->use_empty()) {
1623 Instruction *I = cast<Instruction>(DeadBB->use_back());
1624 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001625 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001626 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001627 // if this is a branch or switch on undef. Fold it manually as a
1628 // branch to the first successor.
1629 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1630 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1631 "Branch should be foldable!");
1632 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1633 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1634 } else {
1635 assert(0 && "Didn't fold away reference to block!");
1636 }
1637
1638 // Make this an uncond branch to the first successor.
1639 TerminatorInst *TI = I->getParent()->getTerminator();
1640 new BranchInst(TI->getSuccessor(0), TI);
1641
1642 // Remove entries in successor phi nodes to remove edges.
1643 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1644 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1645
1646 // Remove the old terminator.
1647 TI->eraseFromParent();
1648 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001649 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001650
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001651 // Finally, delete the basic block.
1652 F->getBasicBlockList().erase(DeadBB);
1653 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001654 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001655 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001656
1657 // If we inferred constant or undef return values for a function, we replaced
1658 // all call uses with the inferred value. This means we don't need to bother
1659 // actually returning anything from the function. Replace all return
1660 // instructions with return undef.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001661 const DenseMap<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals();
1662 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner0417feb2004-12-11 02:53:57 +00001663 E = RV.end(); I != E; ++I)
1664 if (!I->second.isOverdefined() &&
1665 I->first->getReturnType() != Type::VoidTy) {
1666 Function *F = I->first;
1667 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1668 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1669 if (!isa<UndefValue>(RI->getOperand(0)))
1670 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1671 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001672
1673 // If we infered constant or undef values for globals variables, we can delete
1674 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001675 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1676 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001677 E = TG.end(); I != E; ++I) {
1678 GlobalVariable *GV = I->first;
1679 assert(!I->second.isOverdefined() &&
1680 "Overdefined values should have been taken out of the map!");
Bill Wendlingb7427032006-11-26 09:46:52 +00001681 DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
Chris Lattnerdd336d12004-12-11 05:15:59 +00001682 while (!GV->use_empty()) {
1683 StoreInst *SI = cast<StoreInst>(GV->use_back());
1684 SI->eraseFromParent();
1685 }
1686 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001687 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001688 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001689
Chris Lattner59acc7d2004-12-10 08:02:06 +00001690 return MadeChanges;
1691}