blob: d22a1e286bfb3d37dcc11cf8a5d9f36ef8f3f8c9 [file] [log] [blame]
Misha Brukman373086d2003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
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 Lattner91dbae62004-12-11 05:15:59 +000028#include "llvm/DerivedTypes.h"
Chris Lattnercccc5c72003-04-25 02:50:03 +000029#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000030#include "llvm/Pass.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000031#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerff9362a2004-04-13 19:43:54 +000032#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerb4394642004-12-10 08:02:06 +000033#include "llvm/Support/CallSite.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000034#include "llvm/Support/Debug.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000035#include "llvm/Support/InstVisitor.h"
Chris Lattner067d6072007-02-02 20:38:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattner0d74d3c2007-01-30 23:15:19 +000037#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000038#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 Lattner79a42ac2006-12-19 21:40:18 +000044STATISTIC(NumInstRemoved, "Number of instructions removed");
45STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
46
47STATISTIC(IPNumInstRemoved, "Number ofinstructions removed by IPSCCP");
48STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
49STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
50STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
51
Chris Lattner7d325382002-04-29 21:26:08 +000052namespace {
Chris Lattner1847f6d2006-12-20 06:21:33 +000053/// LatticeVal class - This class represents the different lattice values that
54/// an LLVM value may occupy. It is a simple class with value semantics.
55///
Chris Lattner4f031622004-11-15 05:03:30 +000056class LatticeVal {
Misha Brukmanb1c93172005-04-21 23:48:37 +000057 enum {
Chris Lattner1847f6d2006-12-20 06:21:33 +000058 /// undefined - This LLVM Value has no known value yet.
59 undefined,
60
61 /// constant - This LLVM Value has a specific constant value.
62 constant,
63
64 /// forcedconstant - This LLVM Value was thought to be undef until
65 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
66 /// with another (different) constant, it goes to overdefined, instead of
67 /// asserting.
68 forcedconstant,
69
70 /// overdefined - This instruction is not known to be constant, and we know
71 /// it has a value.
72 overdefined
73 } LatticeValue; // The current lattice position
74
Chris Lattner3462ae32001-12-03 22:26:30 +000075 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000076public:
Chris Lattner4f031622004-11-15 05:03:30 +000077 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner1847f6d2006-12-20 06:21:33 +000078
Chris Lattner347389d2001-06-27 23:38:11 +000079 // markOverdefined - Return true if this is a new status to be in...
80 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000081 if (LatticeValue != overdefined) {
82 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000083 return true;
84 }
85 return false;
86 }
87
Chris Lattner1847f6d2006-12-20 06:21:33 +000088 // markConstant - Return true if this is a new status for us.
Chris Lattner3462ae32001-12-03 22:26:30 +000089 inline bool markConstant(Constant *V) {
90 if (LatticeValue != constant) {
Chris Lattner1847f6d2006-12-20 06:21:33 +000091 if (LatticeValue == undefined) {
92 LatticeValue = constant;
Jim Laskeyc4ba9c12007-01-03 00:11:03 +000093 assert(V && "Marking constant with NULL");
Chris Lattner1847f6d2006-12-20 06:21:33 +000094 ConstantVal = V;
95 } else {
96 assert(LatticeValue == forcedconstant &&
97 "Cannot move from overdefined to constant!");
98 // Stay at forcedconstant if the constant is the same.
99 if (V == ConstantVal) return false;
100
101 // Otherwise, we go to overdefined. Assumptions made based on the
102 // forced value are possibly wrong. Assuming this is another constant
103 // could expose a contradiction.
104 LatticeValue = overdefined;
105 }
Chris Lattner347389d2001-06-27 23:38:11 +0000106 return true;
107 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +0000108 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +0000109 }
110 return false;
111 }
112
Chris Lattner1847f6d2006-12-20 06:21:33 +0000113 inline void markForcedConstant(Constant *V) {
114 assert(LatticeValue == undefined && "Can't force a defined value!");
115 LatticeValue = forcedconstant;
116 ConstantVal = V;
117 }
118
119 inline bool isUndefined() const { return LatticeValue == undefined; }
120 inline bool isConstant() const {
121 return LatticeValue == constant || LatticeValue == forcedconstant;
122 }
Chris Lattner3462ae32001-12-03 22:26:30 +0000123 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +0000124
Chris Lattner05fe6842004-01-12 03:57:30 +0000125 inline Constant *getConstant() const {
126 assert(isConstant() && "Cannot get the constant of a non-constant!");
127 return ConstantVal;
128 }
Chris Lattner347389d2001-06-27 23:38:11 +0000129};
130
Chris Lattner7d325382002-04-29 21:26:08 +0000131} // end anonymous namespace
Chris Lattner347389d2001-06-27 23:38:11 +0000132
133
134//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000135//
Chris Lattner074be1f2004-11-15 04:44:20 +0000136/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
137/// Constant Propagation.
138///
139class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner7f74a562002-01-20 22:54:45 +0000140 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattner067d6072007-02-02 20:38:30 +0000141 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner347389d2001-06-27 23:38:11 +0000142
Chris Lattner91dbae62004-12-11 05:15:59 +0000143 /// GlobalValue - If we are tracking any values for the contents of a global
144 /// variable, we keep a mapping from the constant accessor to the element of
145 /// the global, to the currently known value. If the value becomes
146 /// overdefined, it's entry is simply removed from this map.
Chris Lattner067d6072007-02-02 20:38:30 +0000147 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattner91dbae62004-12-11 05:15:59 +0000148
Chris Lattnerb4394642004-12-10 08:02:06 +0000149 /// TrackedFunctionRetVals - If we are tracking arguments into and the return
150 /// value out of a function, it will have an entry in this map, indicating
151 /// what the known return value for the function is.
Chris Lattner067d6072007-02-02 20:38:30 +0000152 DenseMap<Function*, LatticeVal> TrackedFunctionRetVals;
Chris Lattnerb4394642004-12-10 08:02:06 +0000153
Chris Lattnerd79334d2004-07-15 23:36:43 +0000154 // The reason for two worklists is that overdefined is the lowest state
155 // on the lattice, and moving things to overdefined as fast as possible
156 // makes SCCP converge much faster.
157 // By having a separate worklist, we accomplish this because everything
158 // possibly overdefined will become overdefined at the soonest possible
159 // point.
Chris Lattnerb4394642004-12-10 08:02:06 +0000160 std::vector<Value*> OverdefinedInstWorkList;
161 std::vector<Value*> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000162
163
Chris Lattner7f74a562002-01-20 22:54:45 +0000164 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000165
Chris Lattner05fe6842004-01-12 03:57:30 +0000166 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
167 /// overdefined, despite the fact that the PHI node is overdefined.
168 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
169
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000170 /// KnownFeasibleEdges - Entries in this set are edges which have already had
171 /// PHI nodes retriggered.
172 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
173 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000174public:
175
Chris Lattner074be1f2004-11-15 04:44:20 +0000176 /// MarkBlockExecutable - This method can be used by clients to mark all of
177 /// the blocks that are known to be intrinsically live in the processed unit.
178 void MarkBlockExecutable(BasicBlock *BB) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000179 DOUT << "Marking Block Executable: " << BB->getName() << "\n";
Chris Lattner074be1f2004-11-15 04:44:20 +0000180 BBExecutable.insert(BB); // Basic block is executable!
181 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner7d325382002-04-29 21:26:08 +0000182 }
183
Chris Lattner91dbae62004-12-11 05:15:59 +0000184 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000185 /// inform the SCCPSolver that it should track loads and stores to the
186 /// specified global variable if it can. This is only legal to call if
187 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000188 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
189 const Type *ElTy = GV->getType()->getElementType();
190 if (ElTy->isFirstClassType()) {
191 LatticeVal &IV = TrackedGlobals[GV];
192 if (!isa<UndefValue>(GV->getInitializer()))
193 IV.markConstant(GV->getInitializer());
194 }
195 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000196
197 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
198 /// and out of the specified function (which cannot have its address taken),
199 /// this method must be called.
200 void AddTrackedFunction(Function *F) {
201 assert(F->hasInternalLinkage() && "Can only track internal functions!");
202 // Add an entry, F -> undef.
203 TrackedFunctionRetVals[F];
204 }
205
Chris Lattner074be1f2004-11-15 04:44:20 +0000206 /// Solve - Solve for constants and executable blocks.
207 ///
208 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000209
Chris Lattner1847f6d2006-12-20 06:21:33 +0000210 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000211 /// that branches on undef values cannot reach any of their successors.
212 /// However, this is not a safe assumption. After we solve dataflow, this
213 /// method should be use to handle this. If this returns true, the solver
214 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000215 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000216
Chris Lattner074be1f2004-11-15 04:44:20 +0000217 /// getExecutableBlocks - Once we have solved for constants, return the set of
218 /// blocks that is known to be executable.
219 std::set<BasicBlock*> &getExecutableBlocks() {
220 return BBExecutable;
221 }
222
223 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattner4f031622004-11-15 05:03:30 +0000224 /// LLVM values to LatticeVals.
Chris Lattner067d6072007-02-02 20:38:30 +0000225 DenseMap<Value*, LatticeVal> &getValueMapping() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000226 return ValueState;
227 }
228
Chris Lattner99e12952004-12-11 02:53:57 +0000229 /// getTrackedFunctionRetVals - Get the inferred return value map.
230 ///
Chris Lattner067d6072007-02-02 20:38:30 +0000231 const DenseMap<Function*, LatticeVal> &getTrackedFunctionRetVals() {
Chris Lattner99e12952004-12-11 02:53:57 +0000232 return TrackedFunctionRetVals;
233 }
234
Chris Lattner91dbae62004-12-11 05:15:59 +0000235 /// getTrackedGlobals - Get and return the set of inferred initializers for
236 /// global variables.
Chris Lattner067d6072007-02-02 20:38:30 +0000237 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattner91dbae62004-12-11 05:15:59 +0000238 return TrackedGlobals;
239 }
240
Chris Lattner99e12952004-12-11 02:53:57 +0000241
Chris Lattner347389d2001-06-27 23:38:11 +0000242private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000243 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000244 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000245 // the users of the instruction are updated later.
246 //
Chris Lattnerb4394642004-12-10 08:02:06 +0000247 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000248 if (IV.markConstant(C)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000249 DOUT << "markConstant: " << *C << ": " << *V;
Chris Lattnerb4394642004-12-10 08:02:06 +0000250 InstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000251 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000252 }
Chris Lattner1847f6d2006-12-20 06:21:33 +0000253
254 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
255 IV.markForcedConstant(C);
256 DOUT << "markForcedConstant: " << *C << ": " << *V;
257 InstWorkList.push_back(V);
258 }
259
Chris Lattnerb4394642004-12-10 08:02:06 +0000260 inline void markConstant(Value *V, Constant *C) {
261 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000262 }
263
Chris Lattnerd79334d2004-07-15 23:36:43 +0000264 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000265 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000266 // work list so that the users of the instruction are updated later.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000267
Chris Lattnerb4394642004-12-10 08:02:06 +0000268 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000269 if (IV.markOverdefined()) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000270 DEBUG(DOUT << "markOverdefined: ";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000271 if (Function *F = dyn_cast<Function>(V))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000272 DOUT << "Function '" << F->getName() << "'\n";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000273 else
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000274 DOUT << *V);
Chris Lattner074be1f2004-11-15 04:44:20 +0000275 // Only instructions go on the work list
Chris Lattnerb4394642004-12-10 08:02:06 +0000276 OverdefinedInstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000277 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000278 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000279 inline void markOverdefined(Value *V) {
280 markOverdefined(ValueState[V], V);
281 }
282
283 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
284 if (IV.isOverdefined() || MergeWithV.isUndefined())
285 return; // Noop.
286 if (MergeWithV.isOverdefined())
287 markOverdefined(IV, V);
288 else if (IV.isUndefined())
289 markConstant(IV, V, MergeWithV.getConstant());
290 else if (IV.getConstant() != MergeWithV.getConstant())
291 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000292 }
Chris Lattner06a0ed12006-02-08 02:38:11 +0000293
294 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
295 return mergeInValue(ValueState[V], V, MergeWithV);
296 }
297
Chris Lattner347389d2001-06-27 23:38:11 +0000298
Chris Lattner4f031622004-11-15 05:03:30 +0000299 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000300 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000301 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000302 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000303 // Instruction object, then use this accessor to get its value from the map.
304 //
Chris Lattner4f031622004-11-15 05:03:30 +0000305 inline LatticeVal &getValueState(Value *V) {
Chris Lattner067d6072007-02-02 20:38:30 +0000306 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000307 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner646354b2004-10-16 18:09:41 +0000308
Chris Lattner1847f6d2006-12-20 06:21:33 +0000309 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000310 if (isa<UndefValue>(V)) {
311 // Nothing to do, remain undefined.
312 } else {
Chris Lattner067d6072007-02-02 20:38:30 +0000313 LatticeVal &LV = ValueState[C];
314 LV.markConstant(C); // Constants are constant
315 return LV;
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000316 }
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000317 }
Chris Lattner347389d2001-06-27 23:38:11 +0000318 // All others are underdefined by default...
319 return ValueState[V];
320 }
321
Misha Brukmanb1c93172005-04-21 23:48:37 +0000322 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000323 // work list if it is not already executable...
Misha Brukmanb1c93172005-04-21 23:48:37 +0000324 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000325 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
326 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
327 return; // This edge is already known to be executable!
328
329 if (BBExecutable.count(Dest)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000330 DOUT << "Marking Edge Executable: " << Source->getName()
331 << " -> " << Dest->getName() << "\n";
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000332
333 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000334 // feasible that wasn't before. Revisit the PHI nodes in the block
335 // because they have potentially new operands.
Chris Lattnerb4394642004-12-10 08:02:06 +0000336 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
337 visitPHINode(*cast<PHINode>(I));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000338
339 } else {
Chris Lattner074be1f2004-11-15 04:44:20 +0000340 MarkBlockExecutable(Dest);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000341 }
Chris Lattner347389d2001-06-27 23:38:11 +0000342 }
343
Chris Lattner074be1f2004-11-15 04:44:20 +0000344 // getFeasibleSuccessors - Return a vector of booleans to indicate which
345 // successors are reachable from a given terminator instruction.
346 //
347 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
348
349 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
350 // block to the 'To' basic block is currently feasible...
351 //
352 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
353
354 // OperandChangedState - This method is invoked on all of the users of an
355 // instruction that was just changed state somehow.... Based on this
356 // information, we need to update the specified user of this instruction.
357 //
358 void OperandChangedState(User *U) {
359 // Only instructions use other variable values!
360 Instruction &I = cast<Instruction>(*U);
361 if (BBExecutable.count(I.getParent())) // Inst is executable?
362 visit(I);
363 }
364
365private:
366 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000367
Misha Brukmanb1c93172005-04-21 23:48:37 +0000368 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000369 // operand made a transition, or the instruction is newly executable. Change
370 // the value type of I to reflect these changes if appropriate.
371 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000372 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000373
374 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000375 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000376 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000377
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000378 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000379 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000380 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000381 void visitCmpInst(CmpInst &I);
Robert Bocchinobd518d12006-01-10 19:05:05 +0000382 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino6dce2502006-01-17 20:06:55 +0000383 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner17bd6052006-04-08 01:19:12 +0000384 void visitShuffleVectorInst(ShuffleVectorInst &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000385
386 // Instructions that cannot be folded away...
Chris Lattner91dbae62004-12-11 05:15:59 +0000387 void visitStoreInst (Instruction &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000388 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000389 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerb4394642004-12-10 08:02:06 +0000390 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
391 void visitInvokeInst (InvokeInst &II) {
392 visitCallSite(CallSite::get(&II));
393 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000394 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000395 void visitCallSite (CallSite CS);
Chris Lattner9c58cf62003-09-08 18:54:55 +0000396 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000397 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000398 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000399 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
400 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000401 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000402
Chris Lattner113f4f42002-06-25 16:13:24 +0000403 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000404 // If a new instruction is added to LLVM that we don't handle...
Bill Wendlingf3baad32006-12-07 01:30:32 +0000405 cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000406 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000407 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000408};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000409
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000410// getFeasibleSuccessors - Return a vector of booleans to indicate which
411// successors are reachable from a given terminator instruction.
412//
Chris Lattner074be1f2004-11-15 04:44:20 +0000413void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
414 std::vector<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000415 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000416 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000417 if (BI->isUnconditional()) {
418 Succs[0] = true;
419 } else {
Chris Lattner4f031622004-11-15 05:03:30 +0000420 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000421 if (BCValue.isOverdefined() ||
Reid Spencercddc9df2007-01-12 04:24:46 +0000422 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000423 // Overdefined condition variables, and branches on unfoldable constant
424 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000425 Succs[0] = Succs[1] = true;
426 } else if (BCValue.isConstant()) {
427 // Constant condition variables mean the branch can only go a single way
Zhou Sheng75b871f2007-01-11 12:24:14 +0000428 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000429 }
430 }
Reid Spencerde46e482006-11-02 20:25:50 +0000431 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000432 // Invoke instructions successors are always executable.
433 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000434 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000435 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000436 if (SCValue.isOverdefined() || // Overdefined condition?
437 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000438 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000439 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000440 } else if (SCValue.isConstant()) {
441 Constant *CPV = SCValue.getConstant();
442 // Make sure to skip the "default value" which isn't a value
443 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
444 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
445 Succs[i] = true;
446 return;
447 }
448 }
449
450 // Constant value not equal to any of the branches... must execute
451 // default branch then...
452 Succs[0] = true;
453 }
454 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000455 cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner113f4f42002-06-25 16:13:24 +0000456 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000457 }
458}
459
460
Chris Lattner13b52e72002-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 Lattner074be1f2004-11-15 04:44:20 +0000464bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-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 Brukmanb1c93172005-04-21 23:48:37 +0000469
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000470 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000471 TerminatorInst *TI = From->getTerminator();
472 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
473 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000474 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000475 else {
Chris Lattner4f031622004-11-15 05:03:30 +0000476 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner71ac22ff2003-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 Lattnerfe992d42004-01-12 17:40:36 +0000481 // Not branching on an evaluatable constant?
Chris Lattnerff7434a2007-01-13 00:42:58 +0000482 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
Chris Lattnerfe992d42004-01-12 17:40:36 +0000483
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000484 // Constant condition variables mean the branch can only go a single way
Misha Brukmanb1c93172005-04-21 23:48:37 +0000485 return BI->getSuccessor(BCValue.getConstant() ==
Zhou Sheng75b871f2007-01-11 12:24:14 +0000486 ConstantInt::getFalse()) == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000487 }
488 return false;
489 }
Reid Spencerde46e482006-11-02 20:25:50 +0000490 } else if (isa<InvokeInst>(TI)) {
Chris Lattner71ac22ff2003-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 Lattner4f031622004-11-15 05:03:30 +0000494 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner71ac22ff2003-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 Lattnerfe992d42004-01-12 17:40:36 +0000500 if (!isa<ConstantInt>(CPV))
501 return true; // not a foldable constant?
502
Chris Lattner71ac22ff2003-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 Wendlingf3baad32006-12-07 01:30:32 +0000514 cerr << "Unknown terminator instruction: " << *TI;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000515 abort();
516 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000517}
Chris Lattner347389d2001-06-27 23:38:11 +0000518
Chris Lattner6e560792002-04-18 15:13:15 +0000519// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-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 Lattner074be1f2004-11-15 04:44:20 +0000537void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner4f031622004-11-15 05:03:30 +0000538 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-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) {
546 std::vector<Instruction*> Users;
547 Users.reserve(std::distance(I, E));
548 for (; I != E; ++I) Users.push_back(I->second);
549 while (!Users.empty()) {
550 visit(Users.back());
551 Users.pop_back();
552 }
553 }
554 return; // Quick exit
555 }
Chris Lattner347389d2001-06-27 23:38:11 +0000556
Chris Lattner7a7b1142004-03-16 19:49:59 +0000557 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
558 // and slow us down a lot. Just mark them overdefined.
559 if (PN.getNumIncomingValues() > 64) {
560 markOverdefined(PNIV, &PN);
561 return;
562 }
563
Chris Lattner6e560792002-04-18 15:13:15 +0000564 // Look at all of the executable operands of the PHI node. If any of them
565 // are overdefined, the PHI becomes overdefined as well. If they are all
566 // constant, and they agree with each other, the PHI becomes the identical
567 // constant. If they are constant and don't agree, the PHI is overdefined.
568 // If there are no executable operands, the PHI remains undefined.
569 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000570 Constant *OperandVal = 0;
571 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000572 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000573 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000574
Chris Lattner113f4f42002-06-25 16:13:24 +0000575 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000576 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000577 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000578 return;
579 }
580
Chris Lattnercccc5c72003-04-25 02:50:03 +0000581 if (OperandVal == 0) { // Grab the first value...
582 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000583 } else { // Another value is being merged in!
584 // There is already a reachable operand. If we conflict with it,
585 // then the PHI node becomes overdefined. If we agree with it, we
586 // can continue on.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000587
Chris Lattner6e560792002-04-18 15:13:15 +0000588 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000589 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000590 // Yes there is. This means the PHI node is not constant.
591 // You must be overdefined poor PHI.
592 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000593 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000594 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000595 }
Chris Lattner347389d2001-06-27 23:38:11 +0000596 }
597 }
Chris Lattner347389d2001-06-27 23:38:11 +0000598 }
599
Chris Lattner6e560792002-04-18 15:13:15 +0000600 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000601 // arguments that agree with each other(and OperandVal is the constant) or
602 // OperandVal is null because there are no defined incoming arguments. If
603 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000604 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000605 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000606 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000607}
608
Chris Lattnerb4394642004-12-10 08:02:06 +0000609void SCCPSolver::visitReturnInst(ReturnInst &I) {
610 if (I.getNumOperands() == 0) return; // Ret void
611
612 // If we are tracking the return value of this function, merge it in.
613 Function *F = I.getParent()->getParent();
614 if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
Chris Lattner067d6072007-02-02 20:38:30 +0000615 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Chris Lattnerb4394642004-12-10 08:02:06 +0000616 TrackedFunctionRetVals.find(F);
617 if (TFRVI != TrackedFunctionRetVals.end() &&
618 !TFRVI->second.isOverdefined()) {
619 LatticeVal &IV = getValueState(I.getOperand(0));
620 mergeInValue(TFRVI->second, F, IV);
621 }
622 }
623}
624
625
Chris Lattner074be1f2004-11-15 04:44:20 +0000626void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000627 std::vector<bool> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000628 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000629
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000630 BasicBlock *BB = TI.getParent();
631
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000632 // Mark all feasible successors executable...
633 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000634 if (SuccFeasible[i])
635 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000636}
637
Chris Lattner074be1f2004-11-15 04:44:20 +0000638void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000639 Value *V = I.getOperand(0);
Chris Lattner4f031622004-11-15 05:03:30 +0000640 LatticeVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000641 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000642 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000643 else if (VState.isConstant()) // Propagate constant value
Reid Spencerb341b082006-12-12 05:05:00 +0000644 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
645 VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000646}
647
Chris Lattner074be1f2004-11-15 04:44:20 +0000648void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000649 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000650 if (CondValue.isUndefined())
651 return;
Reid Spencercddc9df2007-01-12 04:24:46 +0000652 if (CondValue.isConstant()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000653 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencercddc9df2007-01-12 04:24:46 +0000654 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng75b871f2007-01-11 12:24:14 +0000655 : I.getFalseValue()));
Chris Lattner06a0ed12006-02-08 02:38:11 +0000656 return;
657 }
658 }
659
660 // Otherwise, the condition is overdefined or a constant we can't evaluate.
661 // See if we can produce something better than overdefined based on the T/F
662 // value.
663 LatticeVal &TVal = getValueState(I.getTrueValue());
664 LatticeVal &FVal = getValueState(I.getFalseValue());
665
666 // select ?, C, C -> C.
667 if (TVal.isConstant() && FVal.isConstant() &&
668 TVal.getConstant() == FVal.getConstant()) {
669 markConstant(&I, FVal.getConstant());
670 return;
671 }
672
673 if (TVal.isUndefined()) { // select ?, undef, X -> X.
674 mergeInValue(&I, FVal);
675 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
676 mergeInValue(&I, TVal);
677 } else {
678 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000679 }
680}
681
Chris Lattner6e560792002-04-18 15:13:15 +0000682// Handle BinaryOperators and Shift Instructions...
Chris Lattner074be1f2004-11-15 04:44:20 +0000683void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000684 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000685 if (IV.isOverdefined()) return;
686
Chris Lattner4f031622004-11-15 05:03:30 +0000687 LatticeVal &V1State = getValueState(I.getOperand(0));
688 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000689
Chris Lattner6e560792002-04-18 15:13:15 +0000690 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnercbc01612004-12-11 23:15:19 +0000691 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
692 // operand is overdefined.
693 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
694 LatticeVal *NonOverdefVal = 0;
695 if (!V1State.isOverdefined()) {
696 NonOverdefVal = &V1State;
697 } else if (!V2State.isOverdefined()) {
698 NonOverdefVal = &V2State;
699 }
700
701 if (NonOverdefVal) {
702 if (NonOverdefVal->isUndefined()) {
703 // Could annihilate value.
704 if (I.getOpcode() == Instruction::And)
705 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattner806adaf2007-01-04 02:12:40 +0000706 else if (const PackedType *PT = dyn_cast<PackedType>(I.getType()))
707 markConstant(IV, &I, ConstantPacked::getAllOnesValue(PT));
708 else
709 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnercbc01612004-12-11 23:15:19 +0000710 return;
711 } else {
712 if (I.getOpcode() == Instruction::And) {
713 if (NonOverdefVal->getConstant()->isNullValue()) {
714 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskeyc4ba9c12007-01-03 00:11:03 +0000715 return; // X and 0 = 0
Chris Lattnercbc01612004-12-11 23:15:19 +0000716 }
717 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000718 if (ConstantInt *CI =
719 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnercbc01612004-12-11 23:15:19 +0000720 if (CI->isAllOnesValue()) {
721 markConstant(IV, &I, NonOverdefVal->getConstant());
722 return; // X or -1 = -1
723 }
724 }
725 }
726 }
727 }
728
729
Chris Lattner05fe6842004-01-12 03:57:30 +0000730 // If both operands are PHI nodes, it is possible that this instruction has
731 // a constant value, despite the fact that the PHI node doesn't. Check for
732 // this condition now.
733 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
734 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
735 if (PN1->getParent() == PN2->getParent()) {
736 // Since the two PHI nodes are in the same basic block, they must have
737 // entries for the same predecessors. Walk the predecessor list, and
738 // if all of the incoming values are constants, and the result of
739 // evaluating this expression with all incoming value pairs is the
740 // same, then this expression is a constant even though the PHI node
741 // is not a constant!
Chris Lattner4f031622004-11-15 05:03:30 +0000742 LatticeVal Result;
Chris Lattner05fe6842004-01-12 03:57:30 +0000743 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000744 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner05fe6842004-01-12 03:57:30 +0000745 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattner4f031622004-11-15 05:03:30 +0000746 LatticeVal &In2 =
747 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner05fe6842004-01-12 03:57:30 +0000748
749 if (In1.isOverdefined() || In2.isOverdefined()) {
750 Result.markOverdefined();
751 break; // Cannot fold this operation over the PHI nodes!
752 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000753 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
754 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000755 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000756 Result.markConstant(V);
757 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000758 Result.markOverdefined();
759 break;
760 }
761 }
762 }
763
764 // If we found a constant value here, then we know the instruction is
765 // constant despite the fact that the PHI nodes are overdefined.
766 if (Result.isConstant()) {
767 markConstant(IV, &I, Result.getConstant());
768 // Remember that this instruction is virtually using the PHI node
769 // operands.
770 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
771 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
772 return;
773 } else if (Result.isUndefined()) {
774 return;
775 }
776
777 // Okay, this really is overdefined now. Since we might have
778 // speculatively thought that this was not overdefined before, and
779 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
780 // make sure to clean out any entries that we put there, for
781 // efficiency.
782 std::multimap<PHINode*, Instruction*>::iterator It, E;
783 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
784 while (It != E) {
785 if (It->second == &I) {
786 UsersOfOverdefinedPHIs.erase(It++);
787 } else
788 ++It;
789 }
790 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
791 while (It != E) {
792 if (It->second == &I) {
793 UsersOfOverdefinedPHIs.erase(It++);
794 } else
795 ++It;
796 }
797 }
798
799 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000800 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000801 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
802 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000803 }
804}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000805
Reid Spencer266e42b2006-12-23 06:05:41 +0000806// Handle ICmpInst instruction...
807void SCCPSolver::visitCmpInst(CmpInst &I) {
808 LatticeVal &IV = ValueState[&I];
809 if (IV.isOverdefined()) return;
810
811 LatticeVal &V1State = getValueState(I.getOperand(0));
812 LatticeVal &V2State = getValueState(I.getOperand(1));
813
814 if (V1State.isOverdefined() || V2State.isOverdefined()) {
815 // If both operands are PHI nodes, it is possible that this instruction has
816 // a constant value, despite the fact that the PHI node doesn't. Check for
817 // this condition now.
818 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
819 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
820 if (PN1->getParent() == PN2->getParent()) {
821 // Since the two PHI nodes are in the same basic block, they must have
822 // entries for the same predecessors. Walk the predecessor list, and
823 // if all of the incoming values are constants, and the result of
824 // evaluating this expression with all incoming value pairs is the
825 // same, then this expression is a constant even though the PHI node
826 // is not a constant!
827 LatticeVal Result;
828 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
829 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
830 BasicBlock *InBlock = PN1->getIncomingBlock(i);
831 LatticeVal &In2 =
832 getValueState(PN2->getIncomingValueForBlock(InBlock));
833
834 if (In1.isOverdefined() || In2.isOverdefined()) {
835 Result.markOverdefined();
836 break; // Cannot fold this operation over the PHI nodes!
837 } else if (In1.isConstant() && In2.isConstant()) {
838 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
839 In1.getConstant(),
840 In2.getConstant());
841 if (Result.isUndefined())
842 Result.markConstant(V);
843 else if (Result.isConstant() && Result.getConstant() != V) {
844 Result.markOverdefined();
845 break;
846 }
847 }
848 }
849
850 // If we found a constant value here, then we know the instruction is
851 // constant despite the fact that the PHI nodes are overdefined.
852 if (Result.isConstant()) {
853 markConstant(IV, &I, Result.getConstant());
854 // Remember that this instruction is virtually using the PHI node
855 // operands.
856 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
857 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
858 return;
859 } else if (Result.isUndefined()) {
860 return;
861 }
862
863 // Okay, this really is overdefined now. Since we might have
864 // speculatively thought that this was not overdefined before, and
865 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
866 // make sure to clean out any entries that we put there, for
867 // efficiency.
868 std::multimap<PHINode*, Instruction*>::iterator It, E;
869 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
870 while (It != E) {
871 if (It->second == &I) {
872 UsersOfOverdefinedPHIs.erase(It++);
873 } else
874 ++It;
875 }
876 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
877 while (It != E) {
878 if (It->second == &I) {
879 UsersOfOverdefinedPHIs.erase(It++);
880 } else
881 ++It;
882 }
883 }
884
885 markOverdefined(IV, &I);
886 } else if (V1State.isConstant() && V2State.isConstant()) {
887 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
888 V1State.getConstant(),
889 V2State.getConstant()));
890 }
891}
892
Robert Bocchinobd518d12006-01-10 19:05:05 +0000893void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000894 // FIXME : SCCP does not handle vectors properly.
895 markOverdefined(&I);
896 return;
897
898#if 0
Robert Bocchinobd518d12006-01-10 19:05:05 +0000899 LatticeVal &ValState = getValueState(I.getOperand(0));
900 LatticeVal &IdxState = getValueState(I.getOperand(1));
901
902 if (ValState.isOverdefined() || IdxState.isOverdefined())
903 markOverdefined(&I);
904 else if(ValState.isConstant() && IdxState.isConstant())
905 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
906 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000907#endif
Robert Bocchinobd518d12006-01-10 19:05:05 +0000908}
909
Robert Bocchino6dce2502006-01-17 20:06:55 +0000910void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000911 // FIXME : SCCP does not handle vectors properly.
912 markOverdefined(&I);
913 return;
914#if 0
Robert Bocchino6dce2502006-01-17 20:06:55 +0000915 LatticeVal &ValState = getValueState(I.getOperand(0));
916 LatticeVal &EltState = getValueState(I.getOperand(1));
917 LatticeVal &IdxState = getValueState(I.getOperand(2));
918
919 if (ValState.isOverdefined() || EltState.isOverdefined() ||
920 IdxState.isOverdefined())
921 markOverdefined(&I);
922 else if(ValState.isConstant() && EltState.isConstant() &&
923 IdxState.isConstant())
924 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
925 EltState.getConstant(),
926 IdxState.getConstant()));
927 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel21efc732006-12-04 23:54:59 +0000928 IdxState.isConstant())
Robert Bocchino6dce2502006-01-17 20:06:55 +0000929 markConstant(&I, ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
930 EltState.getConstant(),
931 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000932#endif
Robert Bocchino6dce2502006-01-17 20:06:55 +0000933}
934
Chris Lattner17bd6052006-04-08 01:19:12 +0000935void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000936 // FIXME : SCCP does not handle vectors properly.
937 markOverdefined(&I);
938 return;
939#if 0
Chris Lattner17bd6052006-04-08 01:19:12 +0000940 LatticeVal &V1State = getValueState(I.getOperand(0));
941 LatticeVal &V2State = getValueState(I.getOperand(1));
942 LatticeVal &MaskState = getValueState(I.getOperand(2));
943
944 if (MaskState.isUndefined() ||
945 (V1State.isUndefined() && V2State.isUndefined()))
946 return; // Undefined output if mask or both inputs undefined.
947
948 if (V1State.isOverdefined() || V2State.isOverdefined() ||
949 MaskState.isOverdefined()) {
950 markOverdefined(&I);
951 } else {
952 // A mix of constant/undef inputs.
953 Constant *V1 = V1State.isConstant() ?
954 V1State.getConstant() : UndefValue::get(I.getType());
955 Constant *V2 = V2State.isConstant() ?
956 V2State.getConstant() : UndefValue::get(I.getType());
957 Constant *Mask = MaskState.isConstant() ?
958 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
959 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
960 }
Devang Patel21efc732006-12-04 23:54:59 +0000961#endif
Chris Lattner17bd6052006-04-08 01:19:12 +0000962}
963
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000964// Handle getelementptr instructions... if all operands are constants then we
965// can turn this into a getelementptr ConstantExpr.
966//
Chris Lattner074be1f2004-11-15 04:44:20 +0000967void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000968 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000969 if (IV.isOverdefined()) return;
970
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000971 std::vector<Constant*> Operands;
972 Operands.reserve(I.getNumOperands());
973
974 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000975 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000976 if (State.isUndefined())
977 return; // Operands are not resolved yet...
978 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +0000979 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000980 return;
981 }
982 assert(State.isConstant() && "Unknown state!");
983 Operands.push_back(State.getConstant());
984 }
985
986 Constant *Ptr = Operands[0];
987 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
988
Misha Brukmanb1c93172005-04-21 23:48:37 +0000989 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000990}
Brian Gaeke960707c2003-11-11 22:41:34 +0000991
Chris Lattner91dbae62004-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 Lattner067d6072007-02-02 20:38:30 +0000996 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-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 Lattner49f74522004-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 Lattner074be1f2004-11-15 04:44:20 +00001010void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +00001011 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001012 if (IV.isOverdefined()) return;
1013
Chris Lattner4f031622004-11-15 05:03:30 +00001014 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattner49f74522004-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 Lattner538fee72004-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 Brukmanb1c93172005-04-21 23:48:37 +00001023
Chris Lattner49f74522004-01-12 04:29:41 +00001024 // Transform load (constant global) into the value loaded.
Chris Lattner91dbae62004-12-11 05:15:59 +00001025 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1026 if (GV->isConstant()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00001027 if (!GV->isDeclaration()) {
Chris Lattner91dbae62004-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 Lattner067d6072007-02-02 20:38:30 +00001033 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
Chris Lattner91dbae62004-12-11 05:15:59 +00001034 TrackedGlobals.find(GV);
1035 if (It != TrackedGlobals.end()) {
1036 mergeInValue(IV, &I, It->second);
1037 return;
1038 }
Chris Lattner49f74522004-01-12 04:29:41 +00001039 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001040 }
Chris Lattner49f74522004-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 Cohen82639852005-04-23 21:38:35 +00001045 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00001046 if (GV->isConstant() && !GV->isDeclaration())
Jeff Cohen82639852005-04-23 21:38:35 +00001047 if (Constant *V =
Chris Lattner02ae21e2005-09-26 05:28:52 +00001048 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen82639852005-04-23 21:38:35 +00001049 markConstant(IV, &I, V);
1050 return;
1051 }
Chris Lattner49f74522004-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 Lattnerff9362a2004-04-13 19:43:54 +00001058
Chris Lattnerb4394642004-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 Lattner067d6072007-02-02 20:38:30 +00001064 DenseMap<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
Chris Lattnerb4394642004-12-10 08:02:06 +00001065 if (F && F->hasInternalLinkage())
1066 TFRVI = TrackedFunctionRetVals.find(F);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001067
Chris Lattnerb4394642004-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 Lattner531f9e92005-03-15 04:54:21 +00001075 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
Chris Lattnerb4394642004-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 Lattnerff9362a2004-04-13 19:43:54 +00001086 if (IV.isOverdefined()) return;
1087
Chris Lattnerb4394642004-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 Brukmanb1c93172005-04-21 23:48:37 +00001093
Reid Spencer5301e7c2007-01-30 20:08:39 +00001094 if (F == 0 || !F->isDeclaration() || !canConstantFoldCallTo(F)) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001095 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001096 return;
1097 }
1098
Chris Lattner0d74d3c2007-01-30 23:15:19 +00001099 SmallVector<Constant*, 8> Operands;
Chris Lattnerb4394642004-12-10 08:02:06 +00001100 Operands.reserve(I->getNumOperands()-1);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001101
Chris Lattnerb4394642004-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 Lattnerff9362a2004-04-13 19:43:54 +00001105 if (State.isUndefined())
1106 return; // Operands are not resolved yet...
1107 else if (State.isOverdefined()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001108 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001109 return;
1110 }
1111 assert(State.isConstant() && "Unknown state!");
1112 Operands.push_back(State.getConstant());
1113 }
1114
Chris Lattner0d74d3c2007-01-30 23:15:19 +00001115 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size()))
Chris Lattnerb4394642004-12-10 08:02:06 +00001116 markConstant(IV, I, C);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001117 else
Chris Lattnerb4394642004-12-10 08:02:06 +00001118 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001119}
Chris Lattner074be1f2004-11-15 04:44:20 +00001120
1121
1122void SCCPSolver::Solve() {
1123 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001124 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001125 !OverdefinedInstWorkList.empty()) {
Chris Lattner074be1f2004-11-15 04:44:20 +00001126 // Process the instruction work list...
1127 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001128 Value *I = OverdefinedInstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001129 OverdefinedInstWorkList.pop_back();
1130
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001131 DOUT << "\nPopped off OI-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001132
Chris Lattner074be1f2004-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 Lattnerb4394642004-12-10 08:02:06 +00001146 Value *I = InstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001147 InstWorkList.pop_back();
1148
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001149 DOUT << "\nPopped off I-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001150
Chris Lattner074be1f2004-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 Brukmanb1c93172005-04-21 23:48:37 +00001163
Chris Lattner074be1f2004-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 Brukmanb1c93172005-04-21 23:48:37 +00001168
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001169 DOUT << "\nPopped off BBWL: " << *BB;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001170
Chris Lattner074be1f2004-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 Lattner1847f6d2006-12-20 06:21:33 +00001178/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-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 Lattneraf170962006-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 Lattner1847f6d2006-12-20 06:21:33 +00001188/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001189/// constraints on the condition of the branch, as that would impact other users
1190/// of the value.
Chris Lattner1847f6d2006-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 Lattneraf170962006-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 Lattner1847f6d2006-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.
Chris Lattner806adaf2007-01-04 02:12:40 +00001240 if (const PackedType *PTy = dyn_cast<PackedType>(ITy))
1241 markForcedConstant(LV, I, ConstantPacked::getAllOnesValue(PTy));
1242 else
1243 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1244 return true;
Chris Lattner1847f6d2006-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 Lattneraf170962006-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 Lattner7285f432004-12-10 20:41:50 +00001312 }
Chris Lattneraf170962006-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 Lattner2f687fd2004-12-11 06:05:53 +00001325
Chris Lattneraf170962006-10-22 05:59:17 +00001326 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001327}
1328
Chris Lattner074be1f2004-11-15 04:44:20 +00001329
1330namespace {
Chris Lattner1890f942004-11-15 07:15:04 +00001331 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +00001332 //
Chris Lattner1890f942004-11-15 07:15:04 +00001333 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spencere8a74ee2006-12-31 22:26:06 +00001334 /// Sparse Conditional Constant Propagator.
Chris Lattner1890f942004-11-15 07:15:04 +00001335 ///
1336 struct SCCP : public FunctionPass {
1337 // runOnFunction - Run the Sparse Conditional Constant Propagation
1338 // algorithm, and return true if the function was modified.
1339 //
1340 bool runOnFunction(Function &F);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001341
Chris Lattner1890f942004-11-15 07:15:04 +00001342 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1343 AU.setPreservesCFG();
1344 }
1345 };
Chris Lattner074be1f2004-11-15 04:44:20 +00001346
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001347 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner074be1f2004-11-15 04:44:20 +00001348} // end anonymous namespace
1349
1350
1351// createSCCPPass - This is the public interface to this file...
1352FunctionPass *llvm::createSCCPPass() {
1353 return new SCCP();
1354}
1355
1356
Chris Lattner074be1f2004-11-15 04:44:20 +00001357// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1358// and return true if the function was modified.
1359//
1360bool SCCP::runOnFunction(Function &F) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001361 DOUT << "SCCP on function '" << F.getName() << "'\n";
Chris Lattner074be1f2004-11-15 04:44:20 +00001362 SCCPSolver Solver;
1363
1364 // Mark the first block of the function as being executable.
1365 Solver.MarkBlockExecutable(F.begin());
1366
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001367 // Mark all arguments to the function as being overdefined.
Chris Lattner067d6072007-02-02 20:38:30 +00001368 DenseMap<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner531f9e92005-03-15 04:54:21 +00001369 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; ++AI)
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001370 Values[AI].markOverdefined();
1371
Chris Lattner074be1f2004-11-15 04:44:20 +00001372 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001373 bool ResolvedUndefs = true;
1374 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001375 Solver.Solve();
Chris Lattner1847f6d2006-12-20 06:21:33 +00001376 DOUT << "RESOLVING UNDEFs\n";
1377 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001378 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001379
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001380 bool MadeChanges = false;
1381
1382 // If we decided that there are basic blocks that are dead in this function,
1383 // delete their contents now. Note that we cannot actually delete the blocks,
1384 // as we cannot modify the CFG of the function.
1385 //
1386 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1387 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1388 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001389 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattner9a038a32004-11-15 07:02:42 +00001390 ++NumDeadBlocks;
1391
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001392 // Delete the instructions backwards, as it has a reduced likelihood of
1393 // having to update as many def-use and use-def chains.
1394 std::vector<Instruction*> Insts;
1395 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1396 I != E; ++I)
1397 Insts.push_back(I);
1398 while (!Insts.empty()) {
1399 Instruction *I = Insts.back();
1400 Insts.pop_back();
1401 if (!I->use_empty())
1402 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1403 BB->getInstList().erase(I);
1404 MadeChanges = true;
Chris Lattner9a038a32004-11-15 07:02:42 +00001405 ++NumInstRemoved;
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001406 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001407 } else {
1408 // Iterate over all of the instructions in a function, replacing them with
1409 // constants if we have found them to be of constant values.
1410 //
1411 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1412 Instruction *Inst = BI++;
1413 if (Inst->getType() != Type::VoidTy) {
1414 LatticeVal &IV = Values[Inst];
1415 if (IV.isConstant() || IV.isUndefined() &&
1416 !isa<TerminatorInst>(Inst)) {
1417 Constant *Const = IV.isConstant()
1418 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001419 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001420
Chris Lattnerb4394642004-12-10 08:02:06 +00001421 // Replaces all of the uses of a variable with uses of the constant.
1422 Inst->replaceAllUsesWith(Const);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001423
Chris Lattnerb4394642004-12-10 08:02:06 +00001424 // Delete the instruction.
1425 BB->getInstList().erase(Inst);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001426
Chris Lattnerb4394642004-12-10 08:02:06 +00001427 // Hey, we just changed something!
1428 MadeChanges = true;
1429 ++NumInstRemoved;
Chris Lattner074be1f2004-11-15 04:44:20 +00001430 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001431 }
1432 }
1433 }
1434
1435 return MadeChanges;
1436}
Chris Lattnerb4394642004-12-10 08:02:06 +00001437
1438namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +00001439 //===--------------------------------------------------------------------===//
1440 //
1441 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1442 /// Constant Propagation.
1443 ///
1444 struct IPSCCP : public ModulePass {
1445 bool runOnModule(Module &M);
1446 };
1447
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001448 RegisterPass<IPSCCP>
Chris Lattnerb4394642004-12-10 08:02:06 +00001449 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1450} // end anonymous namespace
1451
1452// createIPSCCPPass - This is the public interface to this file...
1453ModulePass *llvm::createIPSCCPPass() {
1454 return new IPSCCP();
1455}
1456
1457
1458static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001459 // Delete any dead constantexpr klingons.
1460 GV->removeDeadConstantUsers();
1461
Chris Lattnerb4394642004-12-10 08:02:06 +00001462 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1463 UI != E; ++UI)
1464 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001465 if (SI->getOperand(0) == GV || SI->isVolatile())
1466 return true; // Storing addr of GV.
Chris Lattnerb4394642004-12-10 08:02:06 +00001467 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1468 // Make sure we are calling the function, not passing the address.
1469 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1470 for (CallSite::arg_iterator AI = CS.arg_begin(),
1471 E = CS.arg_end(); AI != E; ++AI)
1472 if (*AI == GV)
1473 return true;
Chris Lattner91dbae62004-12-11 05:15:59 +00001474 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1475 if (LI->isVolatile())
1476 return true;
1477 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001478 return true;
1479 }
1480 return false;
1481}
1482
1483bool IPSCCP::runOnModule(Module &M) {
1484 SCCPSolver Solver;
1485
1486 // Loop over all functions, marking arguments to those with their addresses
1487 // taken or that are external as overdefined.
1488 //
Chris Lattner067d6072007-02-02 20:38:30 +00001489 DenseMap<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattnerb4394642004-12-10 08:02:06 +00001490 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1491 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00001492 if (!F->isDeclaration())
Chris Lattnerb4394642004-12-10 08:02:06 +00001493 Solver.MarkBlockExecutable(F->begin());
Chris Lattner8cb10a12005-04-19 19:16:19 +00001494 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1495 AI != E; ++AI)
Chris Lattnerb4394642004-12-10 08:02:06 +00001496 Values[AI].markOverdefined();
1497 } else {
1498 Solver.AddTrackedFunction(F);
1499 }
1500
Chris Lattner91dbae62004-12-11 05:15:59 +00001501 // Loop over global variables. We inform the solver about any internal global
1502 // variables that do not have their 'addresses taken'. If they don't have
1503 // their addresses taken, we can propagate constants through them.
Chris Lattner8cb10a12005-04-19 19:16:19 +00001504 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1505 G != E; ++G)
Chris Lattner91dbae62004-12-11 05:15:59 +00001506 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1507 Solver.TrackValueOfGlobalVariable(G);
1508
Chris Lattnerb4394642004-12-10 08:02:06 +00001509 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001510 bool ResolvedUndefs = true;
1511 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001512 Solver.Solve();
1513
Chris Lattner1847f6d2006-12-20 06:21:33 +00001514 DOUT << "RESOLVING UNDEFS\n";
1515 ResolvedUndefs = false;
Chris Lattner7285f432004-12-10 20:41:50 +00001516 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner1847f6d2006-12-20 06:21:33 +00001517 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattner7285f432004-12-10 20:41:50 +00001518 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001519
1520 bool MadeChanges = false;
1521
1522 // Iterate over all of the instructions in the module, replacing them with
1523 // constants if we have found them to be of constant values.
1524 //
1525 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1526 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001527 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1528 AI != E; ++AI)
Chris Lattnerb4394642004-12-10 08:02:06 +00001529 if (!AI->use_empty()) {
1530 LatticeVal &IV = Values[AI];
1531 if (IV.isConstant() || IV.isUndefined()) {
1532 Constant *CST = IV.isConstant() ?
1533 IV.getConstant() : UndefValue::get(AI->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001534 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
Misha Brukmanb1c93172005-04-21 23:48:37 +00001535
Chris Lattnerb4394642004-12-10 08:02:06 +00001536 // Replaces all of the uses of a variable with uses of the
1537 // constant.
1538 AI->replaceAllUsesWith(CST);
1539 ++IPNumArgsElimed;
1540 }
1541 }
1542
Chris Lattnerbae4b642004-12-10 22:29:08 +00001543 std::vector<BasicBlock*> BlocksToErase;
Chris Lattnerb4394642004-12-10 08:02:06 +00001544 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1545 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001546 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattnerb4394642004-12-10 08:02:06 +00001547 ++IPNumDeadBlocks;
Chris Lattner7285f432004-12-10 20:41:50 +00001548
Chris Lattnerb4394642004-12-10 08:02:06 +00001549 // Delete the instructions backwards, as it has a reduced likelihood of
1550 // having to update as many def-use and use-def chains.
1551 std::vector<Instruction*> Insts;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001552 TerminatorInst *TI = BB->getTerminator();
1553 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattnerb4394642004-12-10 08:02:06 +00001554 Insts.push_back(I);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001555
Chris Lattnerb4394642004-12-10 08:02:06 +00001556 while (!Insts.empty()) {
1557 Instruction *I = Insts.back();
1558 Insts.pop_back();
1559 if (!I->use_empty())
1560 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1561 BB->getInstList().erase(I);
1562 MadeChanges = true;
1563 ++IPNumInstRemoved;
1564 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001565
Chris Lattnerbae4b642004-12-10 22:29:08 +00001566 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1567 BasicBlock *Succ = TI->getSuccessor(i);
1568 if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1569 TI->getSuccessor(i)->removePredecessor(BB);
1570 }
Chris Lattner99e12952004-12-11 02:53:57 +00001571 if (!TI->use_empty())
1572 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnerbae4b642004-12-10 22:29:08 +00001573 BB->getInstList().erase(TI);
1574
Chris Lattner8525ebe2004-12-11 05:32:19 +00001575 if (&*BB != &F->front())
1576 BlocksToErase.push_back(BB);
1577 else
1578 new UnreachableInst(BB);
1579
Chris Lattnerb4394642004-12-10 08:02:06 +00001580 } else {
1581 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1582 Instruction *Inst = BI++;
1583 if (Inst->getType() != Type::VoidTy) {
1584 LatticeVal &IV = Values[Inst];
1585 if (IV.isConstant() || IV.isUndefined() &&
1586 !isa<TerminatorInst>(Inst)) {
1587 Constant *Const = IV.isConstant()
1588 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001589 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001590
Chris Lattnerb4394642004-12-10 08:02:06 +00001591 // Replaces all of the uses of a variable with uses of the
1592 // constant.
1593 Inst->replaceAllUsesWith(Const);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001594
Chris Lattnerb4394642004-12-10 08:02:06 +00001595 // Delete the instruction.
1596 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1597 BB->getInstList().erase(Inst);
1598
1599 // Hey, we just changed something!
1600 MadeChanges = true;
1601 ++IPNumInstRemoved;
1602 }
1603 }
1604 }
1605 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001606
1607 // Now that all instructions in the function are constant folded, erase dead
1608 // blocks, because we can now use ConstantFoldTerminator to get rid of
1609 // in-edges.
1610 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1611 // If there are any PHI nodes in this successor, drop entries for BB now.
1612 BasicBlock *DeadBB = BlocksToErase[i];
1613 while (!DeadBB->use_empty()) {
1614 Instruction *I = cast<Instruction>(DeadBB->use_back());
1615 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001616 if (!Folded) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001617 // The constant folder may not have been able to fold the terminator
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001618 // if this is a branch or switch on undef. Fold it manually as a
1619 // branch to the first successor.
1620 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1621 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1622 "Branch should be foldable!");
1623 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1624 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1625 } else {
1626 assert(0 && "Didn't fold away reference to block!");
1627 }
1628
1629 // Make this an uncond branch to the first successor.
1630 TerminatorInst *TI = I->getParent()->getTerminator();
1631 new BranchInst(TI->getSuccessor(0), TI);
1632
1633 // Remove entries in successor phi nodes to remove edges.
1634 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1635 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1636
1637 // Remove the old terminator.
1638 TI->eraseFromParent();
1639 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001640 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001641
Chris Lattnerbae4b642004-12-10 22:29:08 +00001642 // Finally, delete the basic block.
1643 F->getBasicBlockList().erase(DeadBB);
1644 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001645 }
Chris Lattner99e12952004-12-11 02:53:57 +00001646
1647 // If we inferred constant or undef return values for a function, we replaced
1648 // all call uses with the inferred value. This means we don't need to bother
1649 // actually returning anything from the function. Replace all return
1650 // instructions with return undef.
Chris Lattner067d6072007-02-02 20:38:30 +00001651 const DenseMap<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals();
1652 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner99e12952004-12-11 02:53:57 +00001653 E = RV.end(); I != E; ++I)
1654 if (!I->second.isOverdefined() &&
1655 I->first->getReturnType() != Type::VoidTy) {
1656 Function *F = I->first;
1657 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1658 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1659 if (!isa<UndefValue>(RI->getOperand(0)))
1660 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1661 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001662
1663 // If we infered constant or undef values for globals variables, we can delete
1664 // the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00001665 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1666 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00001667 E = TG.end(); I != E; ++I) {
1668 GlobalVariable *GV = I->first;
1669 assert(!I->second.isOverdefined() &&
1670 "Overdefined values should have been taken out of the map!");
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001671 DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
Chris Lattner91dbae62004-12-11 05:15:59 +00001672 while (!GV->use_empty()) {
1673 StoreInst *SI = cast<StoreInst>(GV->use_back());
1674 SI->eraseFromParent();
1675 }
1676 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00001677 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00001678 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001679
Chris Lattnerb4394642004-12-10 08:02:06 +00001680 return MadeChanges;
1681}