blob: 41174808100c8765afdc1a6b2c6157fe9b9238af [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 Lattner6e560792002-04-18 15:13:15 +000031#include "llvm/Support/InstVisitor.h"
Chris Lattnerff9362a2004-04-13 19:43:54 +000032#include "llvm/Transforms/Utils/Local.h"
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"
35#include "llvm/ADT/hash_map"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/STLExtras.h"
Chris Lattner347389d2001-06-27 23:38:11 +000038#include <algorithm>
Chris Lattner347389d2001-06-27 23:38:11 +000039#include <set>
Chris Lattner49525f82004-01-09 06:02:20 +000040using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000041
Chris Lattner79a42ac2006-12-19 21:40:18 +000042STATISTIC(NumInstRemoved, "Number of instructions removed");
43STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
44
45STATISTIC(IPNumInstRemoved, "Number ofinstructions removed by IPSCCP");
46STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
47STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
48STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
49
Chris Lattner7d325382002-04-29 21:26:08 +000050namespace {
Chris Lattner1847f6d2006-12-20 06:21:33 +000051/// LatticeVal class - This class represents the different lattice values that
52/// an LLVM value may occupy. It is a simple class with value semantics.
53///
Chris Lattner4f031622004-11-15 05:03:30 +000054class LatticeVal {
Misha Brukmanb1c93172005-04-21 23:48:37 +000055 enum {
Chris Lattner1847f6d2006-12-20 06:21:33 +000056 /// undefined - This LLVM Value has no known value yet.
57 undefined,
58
59 /// constant - This LLVM Value has a specific constant value.
60 constant,
61
62 /// forcedconstant - This LLVM Value was thought to be undef until
63 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
64 /// with another (different) constant, it goes to overdefined, instead of
65 /// asserting.
66 forcedconstant,
67
68 /// overdefined - This instruction is not known to be constant, and we know
69 /// it has a value.
70 overdefined
71 } LatticeValue; // The current lattice position
72
Chris Lattner3462ae32001-12-03 22:26:30 +000073 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000074public:
Chris Lattner4f031622004-11-15 05:03:30 +000075 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner1847f6d2006-12-20 06:21:33 +000076
Chris Lattner347389d2001-06-27 23:38:11 +000077 // markOverdefined - Return true if this is a new status to be in...
78 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000079 if (LatticeValue != overdefined) {
80 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000081 return true;
82 }
83 return false;
84 }
85
Chris Lattner1847f6d2006-12-20 06:21:33 +000086 // markConstant - Return true if this is a new status for us.
Chris Lattner3462ae32001-12-03 22:26:30 +000087 inline bool markConstant(Constant *V) {
88 if (LatticeValue != constant) {
Chris Lattner1847f6d2006-12-20 06:21:33 +000089 if (LatticeValue == undefined) {
90 LatticeValue = constant;
Jim Laskeyc4ba9c12007-01-03 00:11:03 +000091 assert(V && "Marking constant with NULL");
Chris Lattner1847f6d2006-12-20 06:21:33 +000092 ConstantVal = V;
93 } else {
94 assert(LatticeValue == forcedconstant &&
95 "Cannot move from overdefined to constant!");
96 // Stay at forcedconstant if the constant is the same.
97 if (V == ConstantVal) return false;
98
99 // Otherwise, we go to overdefined. Assumptions made based on the
100 // forced value are possibly wrong. Assuming this is another constant
101 // could expose a contradiction.
102 LatticeValue = overdefined;
103 }
Chris Lattner347389d2001-06-27 23:38:11 +0000104 return true;
105 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +0000106 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +0000107 }
108 return false;
109 }
110
Chris Lattner1847f6d2006-12-20 06:21:33 +0000111 inline void markForcedConstant(Constant *V) {
112 assert(LatticeValue == undefined && "Can't force a defined value!");
113 LatticeValue = forcedconstant;
114 ConstantVal = V;
115 }
116
117 inline bool isUndefined() const { return LatticeValue == undefined; }
118 inline bool isConstant() const {
119 return LatticeValue == constant || LatticeValue == forcedconstant;
120 }
Chris Lattner3462ae32001-12-03 22:26:30 +0000121 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +0000122
Chris Lattner05fe6842004-01-12 03:57:30 +0000123 inline Constant *getConstant() const {
124 assert(isConstant() && "Cannot get the constant of a non-constant!");
125 return ConstantVal;
126 }
Chris Lattner347389d2001-06-27 23:38:11 +0000127};
128
Chris Lattner7d325382002-04-29 21:26:08 +0000129} // end anonymous namespace
Chris Lattner347389d2001-06-27 23:38:11 +0000130
131
132//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000133//
Chris Lattner074be1f2004-11-15 04:44:20 +0000134/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
135/// Constant Propagation.
136///
137class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner7f74a562002-01-20 22:54:45 +0000138 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattner4f031622004-11-15 05:03:30 +0000139 hash_map<Value*, LatticeVal> ValueState; // The state each value is in...
Chris Lattner347389d2001-06-27 23:38:11 +0000140
Chris Lattner91dbae62004-12-11 05:15:59 +0000141 /// GlobalValue - If we are tracking any values for the contents of a global
142 /// variable, we keep a mapping from the constant accessor to the element of
143 /// the global, to the currently known value. If the value becomes
144 /// overdefined, it's entry is simply removed from this map.
145 hash_map<GlobalVariable*, LatticeVal> TrackedGlobals;
146
Chris Lattnerb4394642004-12-10 08:02:06 +0000147 /// TrackedFunctionRetVals - If we are tracking arguments into and the return
148 /// value out of a function, it will have an entry in this map, indicating
149 /// what the known return value for the function is.
150 hash_map<Function*, LatticeVal> TrackedFunctionRetVals;
151
Chris Lattnerd79334d2004-07-15 23:36:43 +0000152 // The reason for two worklists is that overdefined is the lowest state
153 // on the lattice, and moving things to overdefined as fast as possible
154 // makes SCCP converge much faster.
155 // By having a separate worklist, we accomplish this because everything
156 // possibly overdefined will become overdefined at the soonest possible
157 // point.
Chris Lattnerb4394642004-12-10 08:02:06 +0000158 std::vector<Value*> OverdefinedInstWorkList;
159 std::vector<Value*> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000160
161
Chris Lattner7f74a562002-01-20 22:54:45 +0000162 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000163
Chris Lattner05fe6842004-01-12 03:57:30 +0000164 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
165 /// overdefined, despite the fact that the PHI node is overdefined.
166 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
167
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000168 /// KnownFeasibleEdges - Entries in this set are edges which have already had
169 /// PHI nodes retriggered.
170 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
171 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000172public:
173
Chris Lattner074be1f2004-11-15 04:44:20 +0000174 /// MarkBlockExecutable - This method can be used by clients to mark all of
175 /// the blocks that are known to be intrinsically live in the processed unit.
176 void MarkBlockExecutable(BasicBlock *BB) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000177 DOUT << "Marking Block Executable: " << BB->getName() << "\n";
Chris Lattner074be1f2004-11-15 04:44:20 +0000178 BBExecutable.insert(BB); // Basic block is executable!
179 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner7d325382002-04-29 21:26:08 +0000180 }
181
Chris Lattner91dbae62004-12-11 05:15:59 +0000182 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000183 /// inform the SCCPSolver that it should track loads and stores to the
184 /// specified global variable if it can. This is only legal to call if
185 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000186 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
187 const Type *ElTy = GV->getType()->getElementType();
188 if (ElTy->isFirstClassType()) {
189 LatticeVal &IV = TrackedGlobals[GV];
190 if (!isa<UndefValue>(GV->getInitializer()))
191 IV.markConstant(GV->getInitializer());
192 }
193 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000194
195 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
196 /// and out of the specified function (which cannot have its address taken),
197 /// this method must be called.
198 void AddTrackedFunction(Function *F) {
199 assert(F->hasInternalLinkage() && "Can only track internal functions!");
200 // Add an entry, F -> undef.
201 TrackedFunctionRetVals[F];
202 }
203
Chris Lattner074be1f2004-11-15 04:44:20 +0000204 /// Solve - Solve for constants and executable blocks.
205 ///
206 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000207
Chris Lattner1847f6d2006-12-20 06:21:33 +0000208 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000209 /// that branches on undef values cannot reach any of their successors.
210 /// However, this is not a safe assumption. After we solve dataflow, this
211 /// method should be use to handle this. If this returns true, the solver
212 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000213 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000214
Chris Lattner074be1f2004-11-15 04:44:20 +0000215 /// getExecutableBlocks - Once we have solved for constants, return the set of
216 /// blocks that is known to be executable.
217 std::set<BasicBlock*> &getExecutableBlocks() {
218 return BBExecutable;
219 }
220
221 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattner4f031622004-11-15 05:03:30 +0000222 /// LLVM values to LatticeVals.
223 hash_map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000224 return ValueState;
225 }
226
Chris Lattner99e12952004-12-11 02:53:57 +0000227 /// getTrackedFunctionRetVals - Get the inferred return value map.
228 ///
229 const hash_map<Function*, LatticeVal> &getTrackedFunctionRetVals() {
230 return TrackedFunctionRetVals;
231 }
232
Chris Lattner91dbae62004-12-11 05:15:59 +0000233 /// getTrackedGlobals - Get and return the set of inferred initializers for
234 /// global variables.
235 const hash_map<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
236 return TrackedGlobals;
237 }
238
Chris Lattner99e12952004-12-11 02:53:57 +0000239
Chris Lattner347389d2001-06-27 23:38:11 +0000240private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000241 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000242 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000243 // the users of the instruction are updated later.
244 //
Chris Lattnerb4394642004-12-10 08:02:06 +0000245 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000246 if (IV.markConstant(C)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000247 DOUT << "markConstant: " << *C << ": " << *V;
Chris Lattnerb4394642004-12-10 08:02:06 +0000248 InstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000249 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000250 }
Chris Lattner1847f6d2006-12-20 06:21:33 +0000251
252 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
253 IV.markForcedConstant(C);
254 DOUT << "markForcedConstant: " << *C << ": " << *V;
255 InstWorkList.push_back(V);
256 }
257
Chris Lattnerb4394642004-12-10 08:02:06 +0000258 inline void markConstant(Value *V, Constant *C) {
259 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000260 }
261
Chris Lattnerd79334d2004-07-15 23:36:43 +0000262 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000263 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000264 // work list so that the users of the instruction are updated later.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000265
Chris Lattnerb4394642004-12-10 08:02:06 +0000266 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000267 if (IV.markOverdefined()) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000268 DEBUG(DOUT << "markOverdefined: ";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000269 if (Function *F = dyn_cast<Function>(V))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000270 DOUT << "Function '" << F->getName() << "'\n";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000271 else
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000272 DOUT << *V);
Chris Lattner074be1f2004-11-15 04:44:20 +0000273 // Only instructions go on the work list
Chris Lattnerb4394642004-12-10 08:02:06 +0000274 OverdefinedInstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000275 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000276 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000277 inline void markOverdefined(Value *V) {
278 markOverdefined(ValueState[V], V);
279 }
280
281 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
282 if (IV.isOverdefined() || MergeWithV.isUndefined())
283 return; // Noop.
284 if (MergeWithV.isOverdefined())
285 markOverdefined(IV, V);
286 else if (IV.isUndefined())
287 markConstant(IV, V, MergeWithV.getConstant());
288 else if (IV.getConstant() != MergeWithV.getConstant())
289 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000290 }
Chris Lattner06a0ed12006-02-08 02:38:11 +0000291
292 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
293 return mergeInValue(ValueState[V], V, MergeWithV);
294 }
295
Chris Lattner347389d2001-06-27 23:38:11 +0000296
Chris Lattner4f031622004-11-15 05:03:30 +0000297 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000298 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000299 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000300 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000301 // Instruction object, then use this accessor to get its value from the map.
302 //
Chris Lattner4f031622004-11-15 05:03:30 +0000303 inline LatticeVal &getValueState(Value *V) {
304 hash_map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000305 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner646354b2004-10-16 18:09:41 +0000306
Chris Lattner1847f6d2006-12-20 06:21:33 +0000307 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000308 if (isa<UndefValue>(V)) {
309 // Nothing to do, remain undefined.
310 } else {
Chris Lattner1847f6d2006-12-20 06:21:33 +0000311 ValueState[C].markConstant(C); // Constants are constant
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000312 }
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000313 }
Chris Lattner347389d2001-06-27 23:38:11 +0000314 // All others are underdefined by default...
315 return ValueState[V];
316 }
317
Misha Brukmanb1c93172005-04-21 23:48:37 +0000318 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000319 // work list if it is not already executable...
Misha Brukmanb1c93172005-04-21 23:48:37 +0000320 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000321 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
322 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
323 return; // This edge is already known to be executable!
324
325 if (BBExecutable.count(Dest)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000326 DOUT << "Marking Edge Executable: " << Source->getName()
327 << " -> " << Dest->getName() << "\n";
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000328
329 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000330 // feasible that wasn't before. Revisit the PHI nodes in the block
331 // because they have potentially new operands.
Chris Lattnerb4394642004-12-10 08:02:06 +0000332 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
333 visitPHINode(*cast<PHINode>(I));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000334
335 } else {
Chris Lattner074be1f2004-11-15 04:44:20 +0000336 MarkBlockExecutable(Dest);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000337 }
Chris Lattner347389d2001-06-27 23:38:11 +0000338 }
339
Chris Lattner074be1f2004-11-15 04:44:20 +0000340 // getFeasibleSuccessors - Return a vector of booleans to indicate which
341 // successors are reachable from a given terminator instruction.
342 //
343 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
344
345 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
346 // block to the 'To' basic block is currently feasible...
347 //
348 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
349
350 // OperandChangedState - This method is invoked on all of the users of an
351 // instruction that was just changed state somehow.... Based on this
352 // information, we need to update the specified user of this instruction.
353 //
354 void OperandChangedState(User *U) {
355 // Only instructions use other variable values!
356 Instruction &I = cast<Instruction>(*U);
357 if (BBExecutable.count(I.getParent())) // Inst is executable?
358 visit(I);
359 }
360
361private:
362 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000363
Misha Brukmanb1c93172005-04-21 23:48:37 +0000364 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000365 // operand made a transition, or the instruction is newly executable. Change
366 // the value type of I to reflect these changes if appropriate.
367 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000368 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000369
370 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000371 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000372 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000373
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000374 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000375 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000376 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000377 void visitCmpInst(CmpInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000378 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Robert Bocchinobd518d12006-01-10 19:05:05 +0000379 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino6dce2502006-01-17 20:06:55 +0000380 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner17bd6052006-04-08 01:19:12 +0000381 void visitShuffleVectorInst(ShuffleVectorInst &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000382
383 // Instructions that cannot be folded away...
Chris Lattner91dbae62004-12-11 05:15:59 +0000384 void visitStoreInst (Instruction &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000385 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000386 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerb4394642004-12-10 08:02:06 +0000387 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
388 void visitInvokeInst (InvokeInst &II) {
389 visitCallSite(CallSite::get(&II));
390 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000391 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000392 void visitCallSite (CallSite CS);
Chris Lattner9c58cf62003-09-08 18:54:55 +0000393 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000394 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000395 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000396 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
397 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000398 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000399
Chris Lattner113f4f42002-06-25 16:13:24 +0000400 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000401 // If a new instruction is added to LLVM that we don't handle...
Bill Wendlingf3baad32006-12-07 01:30:32 +0000402 cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000403 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000404 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000405};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000406
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000407// getFeasibleSuccessors - Return a vector of booleans to indicate which
408// successors are reachable from a given terminator instruction.
409//
Chris Lattner074be1f2004-11-15 04:44:20 +0000410void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
411 std::vector<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000412 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000413 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000414 if (BI->isUnconditional()) {
415 Succs[0] = true;
416 } else {
Chris Lattner4f031622004-11-15 05:03:30 +0000417 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000418 if (BCValue.isOverdefined() ||
419 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
420 // Overdefined condition variables, and branches on unfoldable constant
421 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000422 Succs[0] = Succs[1] = true;
423 } else if (BCValue.isConstant()) {
424 // Constant condition variables mean the branch can only go a single way
Chris Lattner6ab03f62006-09-28 23:35:22 +0000425 Succs[BCValue.getConstant() == ConstantBool::getFalse()] = true;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000426 }
427 }
Reid Spencerde46e482006-11-02 20:25:50 +0000428 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000429 // Invoke instructions successors are always executable.
430 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000431 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000432 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000433 if (SCValue.isOverdefined() || // Overdefined condition?
434 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000435 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000436 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000437 } else if (SCValue.isConstant()) {
438 Constant *CPV = SCValue.getConstant();
439 // Make sure to skip the "default value" which isn't a value
440 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
441 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
442 Succs[i] = true;
443 return;
444 }
445 }
446
447 // Constant value not equal to any of the branches... must execute
448 // default branch then...
449 Succs[0] = true;
450 }
451 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000452 cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner113f4f42002-06-25 16:13:24 +0000453 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000454 }
455}
456
457
Chris Lattner13b52e72002-05-02 21:18:01 +0000458// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
459// block to the 'To' basic block is currently feasible...
460//
Chris Lattner074be1f2004-11-15 04:44:20 +0000461bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000462 assert(BBExecutable.count(To) && "Dest should always be alive!");
463
464 // Make sure the source basic block is executable!!
465 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000466
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000467 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000468 TerminatorInst *TI = From->getTerminator();
469 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
470 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000471 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000472 else {
Chris Lattner4f031622004-11-15 05:03:30 +0000473 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000474 if (BCValue.isOverdefined()) {
475 // Overdefined condition variables mean the branch could go either way.
476 return true;
477 } else if (BCValue.isConstant()) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000478 // Not branching on an evaluatable constant?
479 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
480
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000481 // Constant condition variables mean the branch can only go a single way
Misha Brukmanb1c93172005-04-21 23:48:37 +0000482 return BI->getSuccessor(BCValue.getConstant() ==
Chris Lattner6ab03f62006-09-28 23:35:22 +0000483 ConstantBool::getFalse()) == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000484 }
485 return false;
486 }
Reid Spencerde46e482006-11-02 20:25:50 +0000487 } else if (isa<InvokeInst>(TI)) {
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000488 // Invoke instructions successors are always executable.
489 return true;
490 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000491 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000492 if (SCValue.isOverdefined()) { // Overdefined condition?
493 // All destinations are executable!
494 return true;
495 } else if (SCValue.isConstant()) {
496 Constant *CPV = SCValue.getConstant();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000497 if (!isa<ConstantInt>(CPV))
498 return true; // not a foldable constant?
499
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000500 // Make sure to skip the "default value" which isn't a value
501 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
502 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
503 return SI->getSuccessor(i) == To;
504
505 // Constant value not equal to any of the branches... must execute
506 // default branch then...
507 return SI->getDefaultDest() == To;
508 }
509 return false;
510 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000511 cerr << "Unknown terminator instruction: " << *TI;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000512 abort();
513 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000514}
Chris Lattner347389d2001-06-27 23:38:11 +0000515
Chris Lattner6e560792002-04-18 15:13:15 +0000516// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000517// operand made a transition, or the instruction is newly executable. Change
518// the value type of I to reflect these changes if appropriate. This method
519// makes sure to do the following actions:
520//
521// 1. If a phi node merges two constants in, and has conflicting value coming
522// from different branches, or if the PHI node merges in an overdefined
523// value, then the PHI node becomes overdefined.
524// 2. If a phi node merges only constants in, and they all agree on value, the
525// PHI node becomes a constant value equal to that.
526// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
527// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
528// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
529// 6. If a conditional branch has a value that is constant, make the selected
530// destination executable
531// 7. If a conditional branch has a value that is overdefined, make all
532// successors executable.
533//
Chris Lattner074be1f2004-11-15 04:44:20 +0000534void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner4f031622004-11-15 05:03:30 +0000535 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000536 if (PNIV.isOverdefined()) {
537 // There may be instructions using this PHI node that are not overdefined
538 // themselves. If so, make sure that they know that the PHI node operand
539 // changed.
540 std::multimap<PHINode*, Instruction*>::iterator I, E;
541 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
542 if (I != E) {
543 std::vector<Instruction*> Users;
544 Users.reserve(std::distance(I, E));
545 for (; I != E; ++I) Users.push_back(I->second);
546 while (!Users.empty()) {
547 visit(Users.back());
548 Users.pop_back();
549 }
550 }
551 return; // Quick exit
552 }
Chris Lattner347389d2001-06-27 23:38:11 +0000553
Chris Lattner7a7b1142004-03-16 19:49:59 +0000554 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
555 // and slow us down a lot. Just mark them overdefined.
556 if (PN.getNumIncomingValues() > 64) {
557 markOverdefined(PNIV, &PN);
558 return;
559 }
560
Chris Lattner6e560792002-04-18 15:13:15 +0000561 // Look at all of the executable operands of the PHI node. If any of them
562 // are overdefined, the PHI becomes overdefined as well. If they are all
563 // constant, and they agree with each other, the PHI becomes the identical
564 // constant. If they are constant and don't agree, the PHI is overdefined.
565 // If there are no executable operands, the PHI remains undefined.
566 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000567 Constant *OperandVal = 0;
568 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000569 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000570 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000571
Chris Lattner113f4f42002-06-25 16:13:24 +0000572 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000573 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000574 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000575 return;
576 }
577
Chris Lattnercccc5c72003-04-25 02:50:03 +0000578 if (OperandVal == 0) { // Grab the first value...
579 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000580 } else { // Another value is being merged in!
581 // There is already a reachable operand. If we conflict with it,
582 // then the PHI node becomes overdefined. If we agree with it, we
583 // can continue on.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000584
Chris Lattner6e560792002-04-18 15:13:15 +0000585 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000586 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000587 // Yes there is. This means the PHI node is not constant.
588 // You must be overdefined poor PHI.
589 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000590 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000591 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000592 }
Chris Lattner347389d2001-06-27 23:38:11 +0000593 }
594 }
Chris Lattner347389d2001-06-27 23:38:11 +0000595 }
596
Chris Lattner6e560792002-04-18 15:13:15 +0000597 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000598 // arguments that agree with each other(and OperandVal is the constant) or
599 // OperandVal is null because there are no defined incoming arguments. If
600 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000601 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000602 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000603 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000604}
605
Chris Lattnerb4394642004-12-10 08:02:06 +0000606void SCCPSolver::visitReturnInst(ReturnInst &I) {
607 if (I.getNumOperands() == 0) return; // Ret void
608
609 // If we are tracking the return value of this function, merge it in.
610 Function *F = I.getParent()->getParent();
611 if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
612 hash_map<Function*, LatticeVal>::iterator TFRVI =
613 TrackedFunctionRetVals.find(F);
614 if (TFRVI != TrackedFunctionRetVals.end() &&
615 !TFRVI->second.isOverdefined()) {
616 LatticeVal &IV = getValueState(I.getOperand(0));
617 mergeInValue(TFRVI->second, F, IV);
618 }
619 }
620}
621
622
Chris Lattner074be1f2004-11-15 04:44:20 +0000623void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000624 std::vector<bool> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000625 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000626
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000627 BasicBlock *BB = TI.getParent();
628
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000629 // Mark all feasible successors executable...
630 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000631 if (SuccFeasible[i])
632 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000633}
634
Chris Lattner074be1f2004-11-15 04:44:20 +0000635void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000636 Value *V = I.getOperand(0);
Chris Lattner4f031622004-11-15 05:03:30 +0000637 LatticeVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000638 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000639 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000640 else if (VState.isConstant()) // Propagate constant value
Reid Spencerb341b082006-12-12 05:05:00 +0000641 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
642 VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000643}
644
Chris Lattner074be1f2004-11-15 04:44:20 +0000645void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000646 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000647 if (CondValue.isUndefined())
648 return;
649 if (CondValue.isConstant()) {
Chris Lattner6ab03f62006-09-28 23:35:22 +0000650 if (ConstantBool *CondCB = dyn_cast<ConstantBool>(CondValue.getConstant())){
651 mergeInValue(&I, getValueState(CondCB->getValue() ? I.getTrueValue()
652 : I.getFalseValue()));
Chris Lattner06a0ed12006-02-08 02:38:11 +0000653 return;
654 }
655 }
656
657 // Otherwise, the condition is overdefined or a constant we can't evaluate.
658 // See if we can produce something better than overdefined based on the T/F
659 // value.
660 LatticeVal &TVal = getValueState(I.getTrueValue());
661 LatticeVal &FVal = getValueState(I.getFalseValue());
662
663 // select ?, C, C -> C.
664 if (TVal.isConstant() && FVal.isConstant() &&
665 TVal.getConstant() == FVal.getConstant()) {
666 markConstant(&I, FVal.getConstant());
667 return;
668 }
669
670 if (TVal.isUndefined()) { // select ?, undef, X -> X.
671 mergeInValue(&I, FVal);
672 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
673 mergeInValue(&I, TVal);
674 } else {
675 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000676 }
677}
678
Chris Lattner6e560792002-04-18 15:13:15 +0000679// Handle BinaryOperators and Shift Instructions...
Chris Lattner074be1f2004-11-15 04:44:20 +0000680void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000681 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000682 if (IV.isOverdefined()) return;
683
Chris Lattner4f031622004-11-15 05:03:30 +0000684 LatticeVal &V1State = getValueState(I.getOperand(0));
685 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000686
Chris Lattner6e560792002-04-18 15:13:15 +0000687 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnercbc01612004-12-11 23:15:19 +0000688 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
689 // operand is overdefined.
690 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
691 LatticeVal *NonOverdefVal = 0;
692 if (!V1State.isOverdefined()) {
693 NonOverdefVal = &V1State;
694 } else if (!V2State.isOverdefined()) {
695 NonOverdefVal = &V2State;
696 }
697
698 if (NonOverdefVal) {
699 if (NonOverdefVal->isUndefined()) {
700 // Could annihilate value.
701 if (I.getOpcode() == Instruction::And)
702 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattner806adaf2007-01-04 02:12:40 +0000703 else if (const PackedType *PT = dyn_cast<PackedType>(I.getType()))
704 markConstant(IV, &I, ConstantPacked::getAllOnesValue(PT));
705 else
706 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnercbc01612004-12-11 23:15:19 +0000707 return;
708 } else {
709 if (I.getOpcode() == Instruction::And) {
710 if (NonOverdefVal->getConstant()->isNullValue()) {
711 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskeyc4ba9c12007-01-03 00:11:03 +0000712 return; // X and 0 = 0
Chris Lattnercbc01612004-12-11 23:15:19 +0000713 }
714 } else {
715 if (ConstantIntegral *CI =
716 dyn_cast<ConstantIntegral>(NonOverdefVal->getConstant()))
717 if (CI->isAllOnesValue()) {
718 markConstant(IV, &I, NonOverdefVal->getConstant());
719 return; // X or -1 = -1
720 }
721 }
722 }
723 }
724 }
725
726
Chris Lattner05fe6842004-01-12 03:57:30 +0000727 // If both operands are PHI nodes, it is possible that this instruction has
728 // a constant value, despite the fact that the PHI node doesn't. Check for
729 // this condition now.
730 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
731 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
732 if (PN1->getParent() == PN2->getParent()) {
733 // Since the two PHI nodes are in the same basic block, they must have
734 // entries for the same predecessors. Walk the predecessor list, and
735 // if all of the incoming values are constants, and the result of
736 // evaluating this expression with all incoming value pairs is the
737 // same, then this expression is a constant even though the PHI node
738 // is not a constant!
Chris Lattner4f031622004-11-15 05:03:30 +0000739 LatticeVal Result;
Chris Lattner05fe6842004-01-12 03:57:30 +0000740 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000741 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner05fe6842004-01-12 03:57:30 +0000742 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattner4f031622004-11-15 05:03:30 +0000743 LatticeVal &In2 =
744 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner05fe6842004-01-12 03:57:30 +0000745
746 if (In1.isOverdefined() || In2.isOverdefined()) {
747 Result.markOverdefined();
748 break; // Cannot fold this operation over the PHI nodes!
749 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000750 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
751 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000752 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000753 Result.markConstant(V);
754 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000755 Result.markOverdefined();
756 break;
757 }
758 }
759 }
760
761 // If we found a constant value here, then we know the instruction is
762 // constant despite the fact that the PHI nodes are overdefined.
763 if (Result.isConstant()) {
764 markConstant(IV, &I, Result.getConstant());
765 // Remember that this instruction is virtually using the PHI node
766 // operands.
767 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
768 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
769 return;
770 } else if (Result.isUndefined()) {
771 return;
772 }
773
774 // Okay, this really is overdefined now. Since we might have
775 // speculatively thought that this was not overdefined before, and
776 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
777 // make sure to clean out any entries that we put there, for
778 // efficiency.
779 std::multimap<PHINode*, Instruction*>::iterator It, E;
780 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
781 while (It != E) {
782 if (It->second == &I) {
783 UsersOfOverdefinedPHIs.erase(It++);
784 } else
785 ++It;
786 }
787 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
788 while (It != E) {
789 if (It->second == &I) {
790 UsersOfOverdefinedPHIs.erase(It++);
791 } else
792 ++It;
793 }
794 }
795
796 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000797 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000798 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
799 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000800 }
801}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000802
Reid Spencer266e42b2006-12-23 06:05:41 +0000803// Handle ICmpInst instruction...
804void SCCPSolver::visitCmpInst(CmpInst &I) {
805 LatticeVal &IV = ValueState[&I];
806 if (IV.isOverdefined()) return;
807
808 LatticeVal &V1State = getValueState(I.getOperand(0));
809 LatticeVal &V2State = getValueState(I.getOperand(1));
810
811 if (V1State.isOverdefined() || V2State.isOverdefined()) {
812 // If both operands are PHI nodes, it is possible that this instruction has
813 // a constant value, despite the fact that the PHI node doesn't. Check for
814 // this condition now.
815 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
816 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
817 if (PN1->getParent() == PN2->getParent()) {
818 // Since the two PHI nodes are in the same basic block, they must have
819 // entries for the same predecessors. Walk the predecessor list, and
820 // if all of the incoming values are constants, and the result of
821 // evaluating this expression with all incoming value pairs is the
822 // same, then this expression is a constant even though the PHI node
823 // is not a constant!
824 LatticeVal Result;
825 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
826 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
827 BasicBlock *InBlock = PN1->getIncomingBlock(i);
828 LatticeVal &In2 =
829 getValueState(PN2->getIncomingValueForBlock(InBlock));
830
831 if (In1.isOverdefined() || In2.isOverdefined()) {
832 Result.markOverdefined();
833 break; // Cannot fold this operation over the PHI nodes!
834 } else if (In1.isConstant() && In2.isConstant()) {
835 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
836 In1.getConstant(),
837 In2.getConstant());
838 if (Result.isUndefined())
839 Result.markConstant(V);
840 else if (Result.isConstant() && Result.getConstant() != V) {
841 Result.markOverdefined();
842 break;
843 }
844 }
845 }
846
847 // If we found a constant value here, then we know the instruction is
848 // constant despite the fact that the PHI nodes are overdefined.
849 if (Result.isConstant()) {
850 markConstant(IV, &I, Result.getConstant());
851 // Remember that this instruction is virtually using the PHI node
852 // operands.
853 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
854 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
855 return;
856 } else if (Result.isUndefined()) {
857 return;
858 }
859
860 // Okay, this really is overdefined now. Since we might have
861 // speculatively thought that this was not overdefined before, and
862 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
863 // make sure to clean out any entries that we put there, for
864 // efficiency.
865 std::multimap<PHINode*, Instruction*>::iterator It, E;
866 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
867 while (It != E) {
868 if (It->second == &I) {
869 UsersOfOverdefinedPHIs.erase(It++);
870 } else
871 ++It;
872 }
873 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
874 while (It != E) {
875 if (It->second == &I) {
876 UsersOfOverdefinedPHIs.erase(It++);
877 } else
878 ++It;
879 }
880 }
881
882 markOverdefined(IV, &I);
883 } else if (V1State.isConstant() && V2State.isConstant()) {
884 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
885 V1State.getConstant(),
886 V2State.getConstant()));
887 }
888}
889
Robert Bocchinobd518d12006-01-10 19:05:05 +0000890void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000891 // FIXME : SCCP does not handle vectors properly.
892 markOverdefined(&I);
893 return;
894
895#if 0
Robert Bocchinobd518d12006-01-10 19:05:05 +0000896 LatticeVal &ValState = getValueState(I.getOperand(0));
897 LatticeVal &IdxState = getValueState(I.getOperand(1));
898
899 if (ValState.isOverdefined() || IdxState.isOverdefined())
900 markOverdefined(&I);
901 else if(ValState.isConstant() && IdxState.isConstant())
902 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
903 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000904#endif
Robert Bocchinobd518d12006-01-10 19:05:05 +0000905}
906
Robert Bocchino6dce2502006-01-17 20:06:55 +0000907void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000908 // FIXME : SCCP does not handle vectors properly.
909 markOverdefined(&I);
910 return;
911#if 0
Robert Bocchino6dce2502006-01-17 20:06:55 +0000912 LatticeVal &ValState = getValueState(I.getOperand(0));
913 LatticeVal &EltState = getValueState(I.getOperand(1));
914 LatticeVal &IdxState = getValueState(I.getOperand(2));
915
916 if (ValState.isOverdefined() || EltState.isOverdefined() ||
917 IdxState.isOverdefined())
918 markOverdefined(&I);
919 else if(ValState.isConstant() && EltState.isConstant() &&
920 IdxState.isConstant())
921 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
922 EltState.getConstant(),
923 IdxState.getConstant()));
924 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel21efc732006-12-04 23:54:59 +0000925 IdxState.isConstant())
Robert Bocchino6dce2502006-01-17 20:06:55 +0000926 markConstant(&I, ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
927 EltState.getConstant(),
928 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000929#endif
Robert Bocchino6dce2502006-01-17 20:06:55 +0000930}
931
Chris Lattner17bd6052006-04-08 01:19:12 +0000932void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000933 // FIXME : SCCP does not handle vectors properly.
934 markOverdefined(&I);
935 return;
936#if 0
Chris Lattner17bd6052006-04-08 01:19:12 +0000937 LatticeVal &V1State = getValueState(I.getOperand(0));
938 LatticeVal &V2State = getValueState(I.getOperand(1));
939 LatticeVal &MaskState = getValueState(I.getOperand(2));
940
941 if (MaskState.isUndefined() ||
942 (V1State.isUndefined() && V2State.isUndefined()))
943 return; // Undefined output if mask or both inputs undefined.
944
945 if (V1State.isOverdefined() || V2State.isOverdefined() ||
946 MaskState.isOverdefined()) {
947 markOverdefined(&I);
948 } else {
949 // A mix of constant/undef inputs.
950 Constant *V1 = V1State.isConstant() ?
951 V1State.getConstant() : UndefValue::get(I.getType());
952 Constant *V2 = V2State.isConstant() ?
953 V2State.getConstant() : UndefValue::get(I.getType());
954 Constant *Mask = MaskState.isConstant() ?
955 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
956 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
957 }
Devang Patel21efc732006-12-04 23:54:59 +0000958#endif
Chris Lattner17bd6052006-04-08 01:19:12 +0000959}
960
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000961// Handle getelementptr instructions... if all operands are constants then we
962// can turn this into a getelementptr ConstantExpr.
963//
Chris Lattner074be1f2004-11-15 04:44:20 +0000964void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000965 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000966 if (IV.isOverdefined()) return;
967
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000968 std::vector<Constant*> Operands;
969 Operands.reserve(I.getNumOperands());
970
971 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000972 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000973 if (State.isUndefined())
974 return; // Operands are not resolved yet...
975 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +0000976 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000977 return;
978 }
979 assert(State.isConstant() && "Unknown state!");
980 Operands.push_back(State.getConstant());
981 }
982
983 Constant *Ptr = Operands[0];
984 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
985
Misha Brukmanb1c93172005-04-21 23:48:37 +0000986 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000987}
Brian Gaeke960707c2003-11-11 22:41:34 +0000988
Chris Lattner91dbae62004-12-11 05:15:59 +0000989void SCCPSolver::visitStoreInst(Instruction &SI) {
990 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
991 return;
992 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
993 hash_map<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
994 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
995
996 // Get the value we are storing into the global.
997 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
998
999 mergeInValue(I->second, GV, PtrVal);
1000 if (I->second.isOverdefined())
1001 TrackedGlobals.erase(I); // No need to keep tracking this!
1002}
1003
1004
Chris Lattner49f74522004-01-12 04:29:41 +00001005// Handle load instructions. If the operand is a constant pointer to a constant
1006// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001007void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +00001008 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001009 if (IV.isOverdefined()) return;
1010
Chris Lattner4f031622004-11-15 05:03:30 +00001011 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattner49f74522004-01-12 04:29:41 +00001012 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1013 if (PtrVal.isConstant() && !I.isVolatile()) {
1014 Value *Ptr = PtrVal.getConstant();
Chris Lattner538fee72004-03-07 22:16:24 +00001015 if (isa<ConstantPointerNull>(Ptr)) {
1016 // load null -> null
1017 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1018 return;
1019 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001020
Chris Lattner49f74522004-01-12 04:29:41 +00001021 // Transform load (constant global) into the value loaded.
Chris Lattner91dbae62004-12-11 05:15:59 +00001022 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1023 if (GV->isConstant()) {
1024 if (!GV->isExternal()) {
1025 markConstant(IV, &I, GV->getInitializer());
1026 return;
1027 }
1028 } else if (!TrackedGlobals.empty()) {
1029 // If we are tracking this global, merge in the known value for it.
1030 hash_map<GlobalVariable*, LatticeVal>::iterator It =
1031 TrackedGlobals.find(GV);
1032 if (It != TrackedGlobals.end()) {
1033 mergeInValue(IV, &I, It->second);
1034 return;
1035 }
Chris Lattner49f74522004-01-12 04:29:41 +00001036 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001037 }
Chris Lattner49f74522004-01-12 04:29:41 +00001038
1039 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1040 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1041 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen82639852005-04-23 21:38:35 +00001042 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
1043 if (GV->isConstant() && !GV->isExternal())
1044 if (Constant *V =
Chris Lattner02ae21e2005-09-26 05:28:52 +00001045 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen82639852005-04-23 21:38:35 +00001046 markConstant(IV, &I, V);
1047 return;
1048 }
Chris Lattner49f74522004-01-12 04:29:41 +00001049 }
1050
1051 // Otherwise we cannot say for certain what value this load will produce.
1052 // Bail out.
1053 markOverdefined(IV, &I);
1054}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001055
Chris Lattnerb4394642004-12-10 08:02:06 +00001056void SCCPSolver::visitCallSite(CallSite CS) {
1057 Function *F = CS.getCalledFunction();
1058
1059 // If we are tracking this function, we must make sure to bind arguments as
1060 // appropriate.
1061 hash_map<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
1062 if (F && F->hasInternalLinkage())
1063 TFRVI = TrackedFunctionRetVals.find(F);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001064
Chris Lattnerb4394642004-12-10 08:02:06 +00001065 if (TFRVI != TrackedFunctionRetVals.end()) {
1066 // If this is the first call to the function hit, mark its entry block
1067 // executable.
1068 if (!BBExecutable.count(F->begin()))
1069 MarkBlockExecutable(F->begin());
1070
1071 CallSite::arg_iterator CAI = CS.arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +00001072 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
Chris Lattnerb4394642004-12-10 08:02:06 +00001073 AI != E; ++AI, ++CAI) {
1074 LatticeVal &IV = ValueState[AI];
1075 if (!IV.isOverdefined())
1076 mergeInValue(IV, AI, getValueState(*CAI));
1077 }
1078 }
1079 Instruction *I = CS.getInstruction();
1080 if (I->getType() == Type::VoidTy) return;
1081
1082 LatticeVal &IV = ValueState[I];
Chris Lattnerff9362a2004-04-13 19:43:54 +00001083 if (IV.isOverdefined()) return;
1084
Chris Lattnerb4394642004-12-10 08:02:06 +00001085 // Propagate the return value of the function to the value of the instruction.
1086 if (TFRVI != TrackedFunctionRetVals.end()) {
1087 mergeInValue(IV, I, TFRVI->second);
1088 return;
1089 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001090
Chris Lattnerb4394642004-12-10 08:02:06 +00001091 if (F == 0 || !F->isExternal() || !canConstantFoldCallTo(F)) {
1092 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001093 return;
1094 }
1095
1096 std::vector<Constant*> Operands;
Chris Lattnerb4394642004-12-10 08:02:06 +00001097 Operands.reserve(I->getNumOperands()-1);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001098
Chris Lattnerb4394642004-12-10 08:02:06 +00001099 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1100 AI != E; ++AI) {
1101 LatticeVal &State = getValueState(*AI);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001102 if (State.isUndefined())
1103 return; // Operands are not resolved yet...
1104 else if (State.isOverdefined()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001105 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001106 return;
1107 }
1108 assert(State.isConstant() && "Unknown state!");
1109 Operands.push_back(State.getConstant());
1110 }
1111
1112 if (Constant *C = ConstantFoldCall(F, Operands))
Chris Lattnerb4394642004-12-10 08:02:06 +00001113 markConstant(IV, I, C);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001114 else
Chris Lattnerb4394642004-12-10 08:02:06 +00001115 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001116}
Chris Lattner074be1f2004-11-15 04:44:20 +00001117
1118
1119void SCCPSolver::Solve() {
1120 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001121 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001122 !OverdefinedInstWorkList.empty()) {
Chris Lattner074be1f2004-11-15 04:44:20 +00001123 // Process the instruction work list...
1124 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001125 Value *I = OverdefinedInstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001126 OverdefinedInstWorkList.pop_back();
1127
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001128 DOUT << "\nPopped off OI-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001129
Chris Lattner074be1f2004-11-15 04:44:20 +00001130 // "I" got into the work list because it either made the transition from
1131 // bottom to constant
1132 //
1133 // Anything on this worklist that is overdefined need not be visited
1134 // since all of its users will have already been marked as overdefined
1135 // Update all of the users of this instruction's value...
1136 //
1137 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1138 UI != E; ++UI)
1139 OperandChangedState(*UI);
1140 }
1141 // Process the instruction work list...
1142 while (!InstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001143 Value *I = InstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001144 InstWorkList.pop_back();
1145
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001146 DOUT << "\nPopped off I-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001147
Chris Lattner074be1f2004-11-15 04:44:20 +00001148 // "I" got into the work list because it either made the transition from
1149 // bottom to constant
1150 //
1151 // Anything on this worklist that is overdefined need not be visited
1152 // since all of its users will have already been marked as overdefined.
1153 // Update all of the users of this instruction's value...
1154 //
1155 if (!getValueState(I).isOverdefined())
1156 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1157 UI != E; ++UI)
1158 OperandChangedState(*UI);
1159 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001160
Chris Lattner074be1f2004-11-15 04:44:20 +00001161 // Process the basic block work list...
1162 while (!BBWorkList.empty()) {
1163 BasicBlock *BB = BBWorkList.back();
1164 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001165
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001166 DOUT << "\nPopped off BBWL: " << *BB;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001167
Chris Lattner074be1f2004-11-15 04:44:20 +00001168 // Notify all instructions in this basic block that they are newly
1169 // executable.
1170 visit(BB);
1171 }
1172 }
1173}
1174
Chris Lattner1847f6d2006-12-20 06:21:33 +00001175/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001176/// that branches on undef values cannot reach any of their successors.
1177/// However, this is not a safe assumption. After we solve dataflow, this
1178/// method should be use to handle this. If this returns true, the solver
1179/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001180///
1181/// This method handles this by finding an unresolved branch and marking it one
1182/// of the edges from the block as being feasible, even though the condition
1183/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1184/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001185/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001186/// constraints on the condition of the branch, as that would impact other users
1187/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001188///
1189/// This scan also checks for values that use undefs, whose results are actually
1190/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1191/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1192/// even if X isn't defined.
1193bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattneraf170962006-10-22 05:59:17 +00001194 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1195 if (!BBExecutable.count(BB))
1196 continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001197
1198 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1199 // Look for instructions which produce undef values.
1200 if (I->getType() == Type::VoidTy) continue;
1201
1202 LatticeVal &LV = getValueState(I);
1203 if (!LV.isUndefined()) continue;
1204
1205 // Get the lattice values of the first two operands for use below.
1206 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1207 LatticeVal Op1LV;
1208 if (I->getNumOperands() == 2) {
1209 // If this is a two-operand instruction, and if both operands are
1210 // undefs, the result stays undef.
1211 Op1LV = getValueState(I->getOperand(1));
1212 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1213 continue;
1214 }
1215
1216 // If this is an instructions whose result is defined even if the input is
1217 // not fully defined, propagate the information.
1218 const Type *ITy = I->getType();
1219 switch (I->getOpcode()) {
1220 default: break; // Leave the instruction as an undef.
1221 case Instruction::ZExt:
1222 // After a zero extend, we know the top part is zero. SExt doesn't have
1223 // to be handled here, because we don't know whether the top part is 1's
1224 // or 0's.
1225 assert(Op0LV.isUndefined());
1226 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1227 return true;
1228 case Instruction::Mul:
1229 case Instruction::And:
1230 // undef * X -> 0. X could be zero.
1231 // undef & X -> 0. X could be zero.
1232 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1233 return true;
1234
1235 case Instruction::Or:
1236 // undef | X -> -1. X could be -1.
Chris Lattner806adaf2007-01-04 02:12:40 +00001237 if (const PackedType *PTy = dyn_cast<PackedType>(ITy))
1238 markForcedConstant(LV, I, ConstantPacked::getAllOnesValue(PTy));
1239 else
1240 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1241 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001242
1243 case Instruction::SDiv:
1244 case Instruction::UDiv:
1245 case Instruction::SRem:
1246 case Instruction::URem:
1247 // X / undef -> undef. No change.
1248 // X % undef -> undef. No change.
1249 if (Op1LV.isUndefined()) break;
1250
1251 // undef / X -> 0. X could be maxint.
1252 // undef % X -> 0. X could be 1.
1253 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1254 return true;
1255
1256 case Instruction::AShr:
1257 // undef >>s X -> undef. No change.
1258 if (Op0LV.isUndefined()) break;
1259
1260 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1261 if (Op0LV.isConstant())
1262 markForcedConstant(LV, I, Op0LV.getConstant());
1263 else
1264 markOverdefined(LV, I);
1265 return true;
1266 case Instruction::LShr:
1267 case Instruction::Shl:
1268 // undef >> X -> undef. No change.
1269 // undef << X -> undef. No change.
1270 if (Op0LV.isUndefined()) break;
1271
1272 // X >> undef -> 0. X could be 0.
1273 // X << undef -> 0. X could be 0.
1274 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1275 return true;
1276 case Instruction::Select:
1277 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1278 if (Op0LV.isUndefined()) {
1279 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1280 Op1LV = getValueState(I->getOperand(2));
1281 } else if (Op1LV.isUndefined()) {
1282 // c ? undef : undef -> undef. No change.
1283 Op1LV = getValueState(I->getOperand(2));
1284 if (Op1LV.isUndefined())
1285 break;
1286 // Otherwise, c ? undef : x -> x.
1287 } else {
1288 // Leave Op1LV as Operand(1)'s LatticeValue.
1289 }
1290
1291 if (Op1LV.isConstant())
1292 markForcedConstant(LV, I, Op1LV.getConstant());
1293 else
1294 markOverdefined(LV, I);
1295 return true;
1296 }
1297 }
Chris Lattneraf170962006-10-22 05:59:17 +00001298
1299 TerminatorInst *TI = BB->getTerminator();
1300 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1301 if (!BI->isConditional()) continue;
1302 if (!getValueState(BI->getCondition()).isUndefined())
1303 continue;
1304 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1305 if (!getValueState(SI->getCondition()).isUndefined())
1306 continue;
1307 } else {
1308 continue;
Chris Lattner7285f432004-12-10 20:41:50 +00001309 }
Chris Lattneraf170962006-10-22 05:59:17 +00001310
1311 // If the edge to the first successor isn't thought to be feasible yet, mark
1312 // it so now.
1313 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(0))))
1314 continue;
1315
1316 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1317 // and return. This will make other blocks reachable, which will allow new
1318 // values to be discovered and existing ones to be moved in the lattice.
1319 markEdgeExecutable(BB, TI->getSuccessor(0));
1320 return true;
1321 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001322
Chris Lattneraf170962006-10-22 05:59:17 +00001323 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001324}
1325
Chris Lattner074be1f2004-11-15 04:44:20 +00001326
1327namespace {
Chris Lattner1890f942004-11-15 07:15:04 +00001328 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +00001329 //
Chris Lattner1890f942004-11-15 07:15:04 +00001330 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spencere8a74ee2006-12-31 22:26:06 +00001331 /// Sparse Conditional Constant Propagator.
Chris Lattner1890f942004-11-15 07:15:04 +00001332 ///
1333 struct SCCP : public FunctionPass {
1334 // runOnFunction - Run the Sparse Conditional Constant Propagation
1335 // algorithm, and return true if the function was modified.
1336 //
1337 bool runOnFunction(Function &F);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001338
Chris Lattner1890f942004-11-15 07:15:04 +00001339 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1340 AU.setPreservesCFG();
1341 }
1342 };
Chris Lattner074be1f2004-11-15 04:44:20 +00001343
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001344 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner074be1f2004-11-15 04:44:20 +00001345} // end anonymous namespace
1346
1347
1348// createSCCPPass - This is the public interface to this file...
1349FunctionPass *llvm::createSCCPPass() {
1350 return new SCCP();
1351}
1352
1353
Chris Lattner074be1f2004-11-15 04:44:20 +00001354// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1355// and return true if the function was modified.
1356//
1357bool SCCP::runOnFunction(Function &F) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001358 DOUT << "SCCP on function '" << F.getName() << "'\n";
Chris Lattner074be1f2004-11-15 04:44:20 +00001359 SCCPSolver Solver;
1360
1361 // Mark the first block of the function as being executable.
1362 Solver.MarkBlockExecutable(F.begin());
1363
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001364 // Mark all arguments to the function as being overdefined.
1365 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner531f9e92005-03-15 04:54:21 +00001366 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; ++AI)
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001367 Values[AI].markOverdefined();
1368
Chris Lattner074be1f2004-11-15 04:44:20 +00001369 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001370 bool ResolvedUndefs = true;
1371 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001372 Solver.Solve();
Chris Lattner1847f6d2006-12-20 06:21:33 +00001373 DOUT << "RESOLVING UNDEFs\n";
1374 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001375 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001376
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001377 bool MadeChanges = false;
1378
1379 // If we decided that there are basic blocks that are dead in this function,
1380 // delete their contents now. Note that we cannot actually delete the blocks,
1381 // as we cannot modify the CFG of the function.
1382 //
1383 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1384 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1385 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001386 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattner9a038a32004-11-15 07:02:42 +00001387 ++NumDeadBlocks;
1388
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001389 // Delete the instructions backwards, as it has a reduced likelihood of
1390 // having to update as many def-use and use-def chains.
1391 std::vector<Instruction*> Insts;
1392 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1393 I != E; ++I)
1394 Insts.push_back(I);
1395 while (!Insts.empty()) {
1396 Instruction *I = Insts.back();
1397 Insts.pop_back();
1398 if (!I->use_empty())
1399 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1400 BB->getInstList().erase(I);
1401 MadeChanges = true;
Chris Lattner9a038a32004-11-15 07:02:42 +00001402 ++NumInstRemoved;
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001403 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001404 } else {
1405 // Iterate over all of the instructions in a function, replacing them with
1406 // constants if we have found them to be of constant values.
1407 //
1408 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1409 Instruction *Inst = BI++;
1410 if (Inst->getType() != Type::VoidTy) {
1411 LatticeVal &IV = Values[Inst];
1412 if (IV.isConstant() || IV.isUndefined() &&
1413 !isa<TerminatorInst>(Inst)) {
1414 Constant *Const = IV.isConstant()
1415 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001416 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001417
Chris Lattnerb4394642004-12-10 08:02:06 +00001418 // Replaces all of the uses of a variable with uses of the constant.
1419 Inst->replaceAllUsesWith(Const);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001420
Chris Lattnerb4394642004-12-10 08:02:06 +00001421 // Delete the instruction.
1422 BB->getInstList().erase(Inst);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001423
Chris Lattnerb4394642004-12-10 08:02:06 +00001424 // Hey, we just changed something!
1425 MadeChanges = true;
1426 ++NumInstRemoved;
Chris Lattner074be1f2004-11-15 04:44:20 +00001427 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001428 }
1429 }
1430 }
1431
1432 return MadeChanges;
1433}
Chris Lattnerb4394642004-12-10 08:02:06 +00001434
1435namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +00001436 //===--------------------------------------------------------------------===//
1437 //
1438 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1439 /// Constant Propagation.
1440 ///
1441 struct IPSCCP : public ModulePass {
1442 bool runOnModule(Module &M);
1443 };
1444
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001445 RegisterPass<IPSCCP>
Chris Lattnerb4394642004-12-10 08:02:06 +00001446 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1447} // end anonymous namespace
1448
1449// createIPSCCPPass - This is the public interface to this file...
1450ModulePass *llvm::createIPSCCPPass() {
1451 return new IPSCCP();
1452}
1453
1454
1455static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001456 // Delete any dead constantexpr klingons.
1457 GV->removeDeadConstantUsers();
1458
Chris Lattnerb4394642004-12-10 08:02:06 +00001459 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1460 UI != E; ++UI)
1461 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001462 if (SI->getOperand(0) == GV || SI->isVolatile())
1463 return true; // Storing addr of GV.
Chris Lattnerb4394642004-12-10 08:02:06 +00001464 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1465 // Make sure we are calling the function, not passing the address.
1466 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1467 for (CallSite::arg_iterator AI = CS.arg_begin(),
1468 E = CS.arg_end(); AI != E; ++AI)
1469 if (*AI == GV)
1470 return true;
Chris Lattner91dbae62004-12-11 05:15:59 +00001471 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1472 if (LI->isVolatile())
1473 return true;
1474 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001475 return true;
1476 }
1477 return false;
1478}
1479
1480bool IPSCCP::runOnModule(Module &M) {
1481 SCCPSolver Solver;
1482
1483 // Loop over all functions, marking arguments to those with their addresses
1484 // taken or that are external as overdefined.
1485 //
1486 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1487 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1488 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1489 if (!F->isExternal())
1490 Solver.MarkBlockExecutable(F->begin());
Chris Lattner8cb10a12005-04-19 19:16:19 +00001491 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1492 AI != E; ++AI)
Chris Lattnerb4394642004-12-10 08:02:06 +00001493 Values[AI].markOverdefined();
1494 } else {
1495 Solver.AddTrackedFunction(F);
1496 }
1497
Chris Lattner91dbae62004-12-11 05:15:59 +00001498 // Loop over global variables. We inform the solver about any internal global
1499 // variables that do not have their 'addresses taken'. If they don't have
1500 // their addresses taken, we can propagate constants through them.
Chris Lattner8cb10a12005-04-19 19:16:19 +00001501 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1502 G != E; ++G)
Chris Lattner91dbae62004-12-11 05:15:59 +00001503 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1504 Solver.TrackValueOfGlobalVariable(G);
1505
Chris Lattnerb4394642004-12-10 08:02:06 +00001506 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001507 bool ResolvedUndefs = true;
1508 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001509 Solver.Solve();
1510
Chris Lattner1847f6d2006-12-20 06:21:33 +00001511 DOUT << "RESOLVING UNDEFS\n";
1512 ResolvedUndefs = false;
Chris Lattner7285f432004-12-10 20:41:50 +00001513 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner1847f6d2006-12-20 06:21:33 +00001514 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattner7285f432004-12-10 20:41:50 +00001515 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001516
1517 bool MadeChanges = false;
1518
1519 // Iterate over all of the instructions in the module, replacing them with
1520 // constants if we have found them to be of constant values.
1521 //
1522 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1523 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001524 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1525 AI != E; ++AI)
Chris Lattnerb4394642004-12-10 08:02:06 +00001526 if (!AI->use_empty()) {
1527 LatticeVal &IV = Values[AI];
1528 if (IV.isConstant() || IV.isUndefined()) {
1529 Constant *CST = IV.isConstant() ?
1530 IV.getConstant() : UndefValue::get(AI->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001531 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
Misha Brukmanb1c93172005-04-21 23:48:37 +00001532
Chris Lattnerb4394642004-12-10 08:02:06 +00001533 // Replaces all of the uses of a variable with uses of the
1534 // constant.
1535 AI->replaceAllUsesWith(CST);
1536 ++IPNumArgsElimed;
1537 }
1538 }
1539
Chris Lattnerbae4b642004-12-10 22:29:08 +00001540 std::vector<BasicBlock*> BlocksToErase;
Chris Lattnerb4394642004-12-10 08:02:06 +00001541 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1542 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001543 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattnerb4394642004-12-10 08:02:06 +00001544 ++IPNumDeadBlocks;
Chris Lattner7285f432004-12-10 20:41:50 +00001545
Chris Lattnerb4394642004-12-10 08:02:06 +00001546 // Delete the instructions backwards, as it has a reduced likelihood of
1547 // having to update as many def-use and use-def chains.
1548 std::vector<Instruction*> Insts;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001549 TerminatorInst *TI = BB->getTerminator();
1550 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattnerb4394642004-12-10 08:02:06 +00001551 Insts.push_back(I);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001552
Chris Lattnerb4394642004-12-10 08:02:06 +00001553 while (!Insts.empty()) {
1554 Instruction *I = Insts.back();
1555 Insts.pop_back();
1556 if (!I->use_empty())
1557 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1558 BB->getInstList().erase(I);
1559 MadeChanges = true;
1560 ++IPNumInstRemoved;
1561 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001562
Chris Lattnerbae4b642004-12-10 22:29:08 +00001563 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1564 BasicBlock *Succ = TI->getSuccessor(i);
1565 if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1566 TI->getSuccessor(i)->removePredecessor(BB);
1567 }
Chris Lattner99e12952004-12-11 02:53:57 +00001568 if (!TI->use_empty())
1569 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnerbae4b642004-12-10 22:29:08 +00001570 BB->getInstList().erase(TI);
1571
Chris Lattner8525ebe2004-12-11 05:32:19 +00001572 if (&*BB != &F->front())
1573 BlocksToErase.push_back(BB);
1574 else
1575 new UnreachableInst(BB);
1576
Chris Lattnerb4394642004-12-10 08:02:06 +00001577 } else {
1578 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1579 Instruction *Inst = BI++;
1580 if (Inst->getType() != Type::VoidTy) {
1581 LatticeVal &IV = Values[Inst];
1582 if (IV.isConstant() || IV.isUndefined() &&
1583 !isa<TerminatorInst>(Inst)) {
1584 Constant *Const = IV.isConstant()
1585 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001586 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001587
Chris Lattnerb4394642004-12-10 08:02:06 +00001588 // Replaces all of the uses of a variable with uses of the
1589 // constant.
1590 Inst->replaceAllUsesWith(Const);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001591
Chris Lattnerb4394642004-12-10 08:02:06 +00001592 // Delete the instruction.
1593 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1594 BB->getInstList().erase(Inst);
1595
1596 // Hey, we just changed something!
1597 MadeChanges = true;
1598 ++IPNumInstRemoved;
1599 }
1600 }
1601 }
1602 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001603
1604 // Now that all instructions in the function are constant folded, erase dead
1605 // blocks, because we can now use ConstantFoldTerminator to get rid of
1606 // in-edges.
1607 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1608 // If there are any PHI nodes in this successor, drop entries for BB now.
1609 BasicBlock *DeadBB = BlocksToErase[i];
1610 while (!DeadBB->use_empty()) {
1611 Instruction *I = cast<Instruction>(DeadBB->use_back());
1612 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001613 if (!Folded) {
1614 // The constant folder may not have been able to fold the termiantor
1615 // if this is a branch or switch on undef. Fold it manually as a
1616 // branch to the first successor.
1617 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1618 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1619 "Branch should be foldable!");
1620 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1621 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1622 } else {
1623 assert(0 && "Didn't fold away reference to block!");
1624 }
1625
1626 // Make this an uncond branch to the first successor.
1627 TerminatorInst *TI = I->getParent()->getTerminator();
1628 new BranchInst(TI->getSuccessor(0), TI);
1629
1630 // Remove entries in successor phi nodes to remove edges.
1631 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1632 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1633
1634 // Remove the old terminator.
1635 TI->eraseFromParent();
1636 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001637 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001638
Chris Lattnerbae4b642004-12-10 22:29:08 +00001639 // Finally, delete the basic block.
1640 F->getBasicBlockList().erase(DeadBB);
1641 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001642 }
Chris Lattner99e12952004-12-11 02:53:57 +00001643
1644 // If we inferred constant or undef return values for a function, we replaced
1645 // all call uses with the inferred value. This means we don't need to bother
1646 // actually returning anything from the function. Replace all return
1647 // instructions with return undef.
1648 const hash_map<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals();
1649 for (hash_map<Function*, LatticeVal>::const_iterator I = RV.begin(),
1650 E = RV.end(); I != E; ++I)
1651 if (!I->second.isOverdefined() &&
1652 I->first->getReturnType() != Type::VoidTy) {
1653 Function *F = I->first;
1654 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1655 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1656 if (!isa<UndefValue>(RI->getOperand(0)))
1657 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1658 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001659
1660 // If we infered constant or undef values for globals variables, we can delete
1661 // the global and any stores that remain to it.
1662 const hash_map<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1663 for (hash_map<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1664 E = TG.end(); I != E; ++I) {
1665 GlobalVariable *GV = I->first;
1666 assert(!I->second.isOverdefined() &&
1667 "Overdefined values should have been taken out of the map!");
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001668 DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
Chris Lattner91dbae62004-12-11 05:15:59 +00001669 while (!GV->use_empty()) {
1670 StoreInst *SI = cast<StoreInst>(GV->use_back());
1671 SI->eraseFromParent();
1672 }
1673 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00001674 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00001675 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001676
Chris Lattnerb4394642004-12-10 08:02:06 +00001677 return MadeChanges;
1678}