blob: e55e313686da9bae51e06b4bc607d704ccfcb9db [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;
91 ConstantVal = V;
92 } else {
93 assert(LatticeValue == forcedconstant &&
94 "Cannot move from overdefined to constant!");
95 // Stay at forcedconstant if the constant is the same.
96 if (V == ConstantVal) return false;
97
98 // Otherwise, we go to overdefined. Assumptions made based on the
99 // forced value are possibly wrong. Assuming this is another constant
100 // could expose a contradiction.
101 LatticeValue = overdefined;
102 }
Chris Lattner347389d2001-06-27 23:38:11 +0000103 return true;
104 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +0000105 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +0000106 }
107 return false;
108 }
109
Chris Lattner1847f6d2006-12-20 06:21:33 +0000110 inline void markForcedConstant(Constant *V) {
111 assert(LatticeValue == undefined && "Can't force a defined value!");
112 LatticeValue = forcedconstant;
113 ConstantVal = V;
114 }
115
116 inline bool isUndefined() const { return LatticeValue == undefined; }
117 inline bool isConstant() const {
118 return LatticeValue == constant || LatticeValue == forcedconstant;
119 }
Chris Lattner3462ae32001-12-03 22:26:30 +0000120 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +0000121
Chris Lattner05fe6842004-01-12 03:57:30 +0000122 inline Constant *getConstant() const {
123 assert(isConstant() && "Cannot get the constant of a non-constant!");
124 return ConstantVal;
125 }
Chris Lattner347389d2001-06-27 23:38:11 +0000126};
127
Chris Lattner7d325382002-04-29 21:26:08 +0000128} // end anonymous namespace
Chris Lattner347389d2001-06-27 23:38:11 +0000129
130
131//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000132//
Chris Lattner074be1f2004-11-15 04:44:20 +0000133/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
134/// Constant Propagation.
135///
136class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner7f74a562002-01-20 22:54:45 +0000137 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattner4f031622004-11-15 05:03:30 +0000138 hash_map<Value*, LatticeVal> ValueState; // The state each value is in...
Chris Lattner347389d2001-06-27 23:38:11 +0000139
Chris Lattner91dbae62004-12-11 05:15:59 +0000140 /// GlobalValue - If we are tracking any values for the contents of a global
141 /// variable, we keep a mapping from the constant accessor to the element of
142 /// the global, to the currently known value. If the value becomes
143 /// overdefined, it's entry is simply removed from this map.
144 hash_map<GlobalVariable*, LatticeVal> TrackedGlobals;
145
Chris Lattnerb4394642004-12-10 08:02:06 +0000146 /// TrackedFunctionRetVals - If we are tracking arguments into and the return
147 /// value out of a function, it will have an entry in this map, indicating
148 /// what the known return value for the function is.
149 hash_map<Function*, LatticeVal> TrackedFunctionRetVals;
150
Chris Lattnerd79334d2004-07-15 23:36:43 +0000151 // The reason for two worklists is that overdefined is the lowest state
152 // on the lattice, and moving things to overdefined as fast as possible
153 // makes SCCP converge much faster.
154 // By having a separate worklist, we accomplish this because everything
155 // possibly overdefined will become overdefined at the soonest possible
156 // point.
Chris Lattnerb4394642004-12-10 08:02:06 +0000157 std::vector<Value*> OverdefinedInstWorkList;
158 std::vector<Value*> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000159
160
Chris Lattner7f74a562002-01-20 22:54:45 +0000161 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000162
Chris Lattner05fe6842004-01-12 03:57:30 +0000163 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
164 /// overdefined, despite the fact that the PHI node is overdefined.
165 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
166
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000167 /// KnownFeasibleEdges - Entries in this set are edges which have already had
168 /// PHI nodes retriggered.
169 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
170 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000171public:
172
Chris Lattner074be1f2004-11-15 04:44:20 +0000173 /// MarkBlockExecutable - This method can be used by clients to mark all of
174 /// the blocks that are known to be intrinsically live in the processed unit.
175 void MarkBlockExecutable(BasicBlock *BB) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000176 DOUT << "Marking Block Executable: " << BB->getName() << "\n";
Chris Lattner074be1f2004-11-15 04:44:20 +0000177 BBExecutable.insert(BB); // Basic block is executable!
178 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner7d325382002-04-29 21:26:08 +0000179 }
180
Chris Lattner91dbae62004-12-11 05:15:59 +0000181 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000182 /// inform the SCCPSolver that it should track loads and stores to the
183 /// specified global variable if it can. This is only legal to call if
184 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000185 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
186 const Type *ElTy = GV->getType()->getElementType();
187 if (ElTy->isFirstClassType()) {
188 LatticeVal &IV = TrackedGlobals[GV];
189 if (!isa<UndefValue>(GV->getInitializer()))
190 IV.markConstant(GV->getInitializer());
191 }
192 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000193
194 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
195 /// and out of the specified function (which cannot have its address taken),
196 /// this method must be called.
197 void AddTrackedFunction(Function *F) {
198 assert(F->hasInternalLinkage() && "Can only track internal functions!");
199 // Add an entry, F -> undef.
200 TrackedFunctionRetVals[F];
201 }
202
Chris Lattner074be1f2004-11-15 04:44:20 +0000203 /// Solve - Solve for constants and executable blocks.
204 ///
205 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000206
Chris Lattner1847f6d2006-12-20 06:21:33 +0000207 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000208 /// that branches on undef values cannot reach any of their successors.
209 /// However, this is not a safe assumption. After we solve dataflow, this
210 /// method should be use to handle this. If this returns true, the solver
211 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000212 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000213
Chris Lattner074be1f2004-11-15 04:44:20 +0000214 /// getExecutableBlocks - Once we have solved for constants, return the set of
215 /// blocks that is known to be executable.
216 std::set<BasicBlock*> &getExecutableBlocks() {
217 return BBExecutable;
218 }
219
220 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattner4f031622004-11-15 05:03:30 +0000221 /// LLVM values to LatticeVals.
222 hash_map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000223 return ValueState;
224 }
225
Chris Lattner99e12952004-12-11 02:53:57 +0000226 /// getTrackedFunctionRetVals - Get the inferred return value map.
227 ///
228 const hash_map<Function*, LatticeVal> &getTrackedFunctionRetVals() {
229 return TrackedFunctionRetVals;
230 }
231
Chris Lattner91dbae62004-12-11 05:15:59 +0000232 /// getTrackedGlobals - Get and return the set of inferred initializers for
233 /// global variables.
234 const hash_map<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
235 return TrackedGlobals;
236 }
237
Chris Lattner99e12952004-12-11 02:53:57 +0000238
Chris Lattner347389d2001-06-27 23:38:11 +0000239private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000240 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000241 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000242 // the users of the instruction are updated later.
243 //
Chris Lattnerb4394642004-12-10 08:02:06 +0000244 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000245 if (IV.markConstant(C)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000246 DOUT << "markConstant: " << *C << ": " << *V;
Chris Lattnerb4394642004-12-10 08:02:06 +0000247 InstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000248 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000249 }
Chris Lattner1847f6d2006-12-20 06:21:33 +0000250
251 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
252 IV.markForcedConstant(C);
253 DOUT << "markForcedConstant: " << *C << ": " << *V;
254 InstWorkList.push_back(V);
255 }
256
Chris Lattnerb4394642004-12-10 08:02:06 +0000257 inline void markConstant(Value *V, Constant *C) {
258 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000259 }
260
Chris Lattnerd79334d2004-07-15 23:36:43 +0000261 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000262 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000263 // work list so that the users of the instruction are updated later.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000264
Chris Lattnerb4394642004-12-10 08:02:06 +0000265 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000266 if (IV.markOverdefined()) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000267 DEBUG(DOUT << "markOverdefined: ";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000268 if (Function *F = dyn_cast<Function>(V))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000269 DOUT << "Function '" << F->getName() << "'\n";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000270 else
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000271 DOUT << *V);
Chris Lattner074be1f2004-11-15 04:44:20 +0000272 // Only instructions go on the work list
Chris Lattnerb4394642004-12-10 08:02:06 +0000273 OverdefinedInstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000274 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000275 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000276 inline void markOverdefined(Value *V) {
277 markOverdefined(ValueState[V], V);
278 }
279
280 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
281 if (IV.isOverdefined() || MergeWithV.isUndefined())
282 return; // Noop.
283 if (MergeWithV.isOverdefined())
284 markOverdefined(IV, V);
285 else if (IV.isUndefined())
286 markConstant(IV, V, MergeWithV.getConstant());
287 else if (IV.getConstant() != MergeWithV.getConstant())
288 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000289 }
Chris Lattner06a0ed12006-02-08 02:38:11 +0000290
291 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
292 return mergeInValue(ValueState[V], V, MergeWithV);
293 }
294
Chris Lattner347389d2001-06-27 23:38:11 +0000295
Chris Lattner4f031622004-11-15 05:03:30 +0000296 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000297 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000298 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000299 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000300 // Instruction object, then use this accessor to get its value from the map.
301 //
Chris Lattner4f031622004-11-15 05:03:30 +0000302 inline LatticeVal &getValueState(Value *V) {
303 hash_map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000304 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner646354b2004-10-16 18:09:41 +0000305
Chris Lattner1847f6d2006-12-20 06:21:33 +0000306 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000307 if (isa<UndefValue>(V)) {
308 // Nothing to do, remain undefined.
309 } else {
Chris Lattner1847f6d2006-12-20 06:21:33 +0000310 ValueState[C].markConstant(C); // Constants are constant
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000311 }
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000312 }
Chris Lattner347389d2001-06-27 23:38:11 +0000313 // All others are underdefined by default...
314 return ValueState[V];
315 }
316
Misha Brukmanb1c93172005-04-21 23:48:37 +0000317 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000318 // work list if it is not already executable...
Misha Brukmanb1c93172005-04-21 23:48:37 +0000319 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000320 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
321 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
322 return; // This edge is already known to be executable!
323
324 if (BBExecutable.count(Dest)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000325 DOUT << "Marking Edge Executable: " << Source->getName()
326 << " -> " << Dest->getName() << "\n";
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000327
328 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000329 // feasible that wasn't before. Revisit the PHI nodes in the block
330 // because they have potentially new operands.
Chris Lattnerb4394642004-12-10 08:02:06 +0000331 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
332 visitPHINode(*cast<PHINode>(I));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000333
334 } else {
Chris Lattner074be1f2004-11-15 04:44:20 +0000335 MarkBlockExecutable(Dest);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000336 }
Chris Lattner347389d2001-06-27 23:38:11 +0000337 }
338
Chris Lattner074be1f2004-11-15 04:44:20 +0000339 // getFeasibleSuccessors - Return a vector of booleans to indicate which
340 // successors are reachable from a given terminator instruction.
341 //
342 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
343
344 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
345 // block to the 'To' basic block is currently feasible...
346 //
347 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
348
349 // OperandChangedState - This method is invoked on all of the users of an
350 // instruction that was just changed state somehow.... Based on this
351 // information, we need to update the specified user of this instruction.
352 //
353 void OperandChangedState(User *U) {
354 // Only instructions use other variable values!
355 Instruction &I = cast<Instruction>(*U);
356 if (BBExecutable.count(I.getParent())) // Inst is executable?
357 visit(I);
358 }
359
360private:
361 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000362
Misha Brukmanb1c93172005-04-21 23:48:37 +0000363 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000364 // operand made a transition, or the instruction is newly executable. Change
365 // the value type of I to reflect these changes if appropriate.
366 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000367 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000368
369 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000370 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000371 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000372
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000373 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000374 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000375 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000376 void visitCmpInst(CmpInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000377 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Robert Bocchinobd518d12006-01-10 19:05:05 +0000378 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino6dce2502006-01-17 20:06:55 +0000379 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner17bd6052006-04-08 01:19:12 +0000380 void visitShuffleVectorInst(ShuffleVectorInst &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000381
382 // Instructions that cannot be folded away...
Chris Lattner91dbae62004-12-11 05:15:59 +0000383 void visitStoreInst (Instruction &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000384 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000385 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerb4394642004-12-10 08:02:06 +0000386 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
387 void visitInvokeInst (InvokeInst &II) {
388 visitCallSite(CallSite::get(&II));
389 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000390 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000391 void visitCallSite (CallSite CS);
Chris Lattner9c58cf62003-09-08 18:54:55 +0000392 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000393 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000394 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000395 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
396 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000397 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000398
Chris Lattner113f4f42002-06-25 16:13:24 +0000399 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000400 // If a new instruction is added to LLVM that we don't handle...
Bill Wendlingf3baad32006-12-07 01:30:32 +0000401 cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000402 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000403 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000404};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000405
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000406// getFeasibleSuccessors - Return a vector of booleans to indicate which
407// successors are reachable from a given terminator instruction.
408//
Chris Lattner074be1f2004-11-15 04:44:20 +0000409void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
410 std::vector<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000411 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000412 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000413 if (BI->isUnconditional()) {
414 Succs[0] = true;
415 } else {
Chris Lattner4f031622004-11-15 05:03:30 +0000416 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000417 if (BCValue.isOverdefined() ||
418 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
419 // Overdefined condition variables, and branches on unfoldable constant
420 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000421 Succs[0] = Succs[1] = true;
422 } else if (BCValue.isConstant()) {
423 // Constant condition variables mean the branch can only go a single way
Chris Lattner6ab03f62006-09-28 23:35:22 +0000424 Succs[BCValue.getConstant() == ConstantBool::getFalse()] = true;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000425 }
426 }
Reid Spencerde46e482006-11-02 20:25:50 +0000427 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000428 // Invoke instructions successors are always executable.
429 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000430 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000431 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000432 if (SCValue.isOverdefined() || // Overdefined condition?
433 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000434 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000435 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000436 } else if (SCValue.isConstant()) {
437 Constant *CPV = SCValue.getConstant();
438 // Make sure to skip the "default value" which isn't a value
439 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
440 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
441 Succs[i] = true;
442 return;
443 }
444 }
445
446 // Constant value not equal to any of the branches... must execute
447 // default branch then...
448 Succs[0] = true;
449 }
450 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000451 cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner113f4f42002-06-25 16:13:24 +0000452 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000453 }
454}
455
456
Chris Lattner13b52e72002-05-02 21:18:01 +0000457// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
458// block to the 'To' basic block is currently feasible...
459//
Chris Lattner074be1f2004-11-15 04:44:20 +0000460bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000461 assert(BBExecutable.count(To) && "Dest should always be alive!");
462
463 // Make sure the source basic block is executable!!
464 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000465
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000466 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000467 TerminatorInst *TI = From->getTerminator();
468 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
469 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000470 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000471 else {
Chris Lattner4f031622004-11-15 05:03:30 +0000472 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000473 if (BCValue.isOverdefined()) {
474 // Overdefined condition variables mean the branch could go either way.
475 return true;
476 } else if (BCValue.isConstant()) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000477 // Not branching on an evaluatable constant?
478 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
479
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000480 // Constant condition variables mean the branch can only go a single way
Misha Brukmanb1c93172005-04-21 23:48:37 +0000481 return BI->getSuccessor(BCValue.getConstant() ==
Chris Lattner6ab03f62006-09-28 23:35:22 +0000482 ConstantBool::getFalse()) == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000483 }
484 return false;
485 }
Reid Spencerde46e482006-11-02 20:25:50 +0000486 } else if (isa<InvokeInst>(TI)) {
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000487 // Invoke instructions successors are always executable.
488 return true;
489 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000490 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000491 if (SCValue.isOverdefined()) { // Overdefined condition?
492 // All destinations are executable!
493 return true;
494 } else if (SCValue.isConstant()) {
495 Constant *CPV = SCValue.getConstant();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000496 if (!isa<ConstantInt>(CPV))
497 return true; // not a foldable constant?
498
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000499 // Make sure to skip the "default value" which isn't a value
500 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
501 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
502 return SI->getSuccessor(i) == To;
503
504 // Constant value not equal to any of the branches... must execute
505 // default branch then...
506 return SI->getDefaultDest() == To;
507 }
508 return false;
509 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000510 cerr << "Unknown terminator instruction: " << *TI;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000511 abort();
512 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000513}
Chris Lattner347389d2001-06-27 23:38:11 +0000514
Chris Lattner6e560792002-04-18 15:13:15 +0000515// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000516// operand made a transition, or the instruction is newly executable. Change
517// the value type of I to reflect these changes if appropriate. This method
518// makes sure to do the following actions:
519//
520// 1. If a phi node merges two constants in, and has conflicting value coming
521// from different branches, or if the PHI node merges in an overdefined
522// value, then the PHI node becomes overdefined.
523// 2. If a phi node merges only constants in, and they all agree on value, the
524// PHI node becomes a constant value equal to that.
525// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
526// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
527// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
528// 6. If a conditional branch has a value that is constant, make the selected
529// destination executable
530// 7. If a conditional branch has a value that is overdefined, make all
531// successors executable.
532//
Chris Lattner074be1f2004-11-15 04:44:20 +0000533void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner4f031622004-11-15 05:03:30 +0000534 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000535 if (PNIV.isOverdefined()) {
536 // There may be instructions using this PHI node that are not overdefined
537 // themselves. If so, make sure that they know that the PHI node operand
538 // changed.
539 std::multimap<PHINode*, Instruction*>::iterator I, E;
540 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
541 if (I != E) {
542 std::vector<Instruction*> Users;
543 Users.reserve(std::distance(I, E));
544 for (; I != E; ++I) Users.push_back(I->second);
545 while (!Users.empty()) {
546 visit(Users.back());
547 Users.pop_back();
548 }
549 }
550 return; // Quick exit
551 }
Chris Lattner347389d2001-06-27 23:38:11 +0000552
Chris Lattner7a7b1142004-03-16 19:49:59 +0000553 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
554 // and slow us down a lot. Just mark them overdefined.
555 if (PN.getNumIncomingValues() > 64) {
556 markOverdefined(PNIV, &PN);
557 return;
558 }
559
Chris Lattner6e560792002-04-18 15:13:15 +0000560 // Look at all of the executable operands of the PHI node. If any of them
561 // are overdefined, the PHI becomes overdefined as well. If they are all
562 // constant, and they agree with each other, the PHI becomes the identical
563 // constant. If they are constant and don't agree, the PHI is overdefined.
564 // If there are no executable operands, the PHI remains undefined.
565 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000566 Constant *OperandVal = 0;
567 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000568 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000569 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000570
Chris Lattner113f4f42002-06-25 16:13:24 +0000571 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000572 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000573 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000574 return;
575 }
576
Chris Lattnercccc5c72003-04-25 02:50:03 +0000577 if (OperandVal == 0) { // Grab the first value...
578 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000579 } else { // Another value is being merged in!
580 // There is already a reachable operand. If we conflict with it,
581 // then the PHI node becomes overdefined. If we agree with it, we
582 // can continue on.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000583
Chris Lattner6e560792002-04-18 15:13:15 +0000584 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000585 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000586 // Yes there is. This means the PHI node is not constant.
587 // You must be overdefined poor PHI.
588 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000589 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000590 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000591 }
Chris Lattner347389d2001-06-27 23:38:11 +0000592 }
593 }
Chris Lattner347389d2001-06-27 23:38:11 +0000594 }
595
Chris Lattner6e560792002-04-18 15:13:15 +0000596 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000597 // arguments that agree with each other(and OperandVal is the constant) or
598 // OperandVal is null because there are no defined incoming arguments. If
599 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000600 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000601 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000602 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000603}
604
Chris Lattnerb4394642004-12-10 08:02:06 +0000605void SCCPSolver::visitReturnInst(ReturnInst &I) {
606 if (I.getNumOperands() == 0) return; // Ret void
607
608 // If we are tracking the return value of this function, merge it in.
609 Function *F = I.getParent()->getParent();
610 if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
611 hash_map<Function*, LatticeVal>::iterator TFRVI =
612 TrackedFunctionRetVals.find(F);
613 if (TFRVI != TrackedFunctionRetVals.end() &&
614 !TFRVI->second.isOverdefined()) {
615 LatticeVal &IV = getValueState(I.getOperand(0));
616 mergeInValue(TFRVI->second, F, IV);
617 }
618 }
619}
620
621
Chris Lattner074be1f2004-11-15 04:44:20 +0000622void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000623 std::vector<bool> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000624 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000625
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000626 BasicBlock *BB = TI.getParent();
627
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000628 // Mark all feasible successors executable...
629 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000630 if (SuccFeasible[i])
631 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000632}
633
Chris Lattner074be1f2004-11-15 04:44:20 +0000634void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000635 Value *V = I.getOperand(0);
Chris Lattner4f031622004-11-15 05:03:30 +0000636 LatticeVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000637 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000638 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000639 else if (VState.isConstant()) // Propagate constant value
Reid Spencerb341b082006-12-12 05:05:00 +0000640 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
641 VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000642}
643
Chris Lattner074be1f2004-11-15 04:44:20 +0000644void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000645 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000646 if (CondValue.isUndefined())
647 return;
648 if (CondValue.isConstant()) {
Chris Lattner6ab03f62006-09-28 23:35:22 +0000649 if (ConstantBool *CondCB = dyn_cast<ConstantBool>(CondValue.getConstant())){
650 mergeInValue(&I, getValueState(CondCB->getValue() ? I.getTrueValue()
651 : I.getFalseValue()));
Chris Lattner06a0ed12006-02-08 02:38:11 +0000652 return;
653 }
654 }
655
656 // Otherwise, the condition is overdefined or a constant we can't evaluate.
657 // See if we can produce something better than overdefined based on the T/F
658 // value.
659 LatticeVal &TVal = getValueState(I.getTrueValue());
660 LatticeVal &FVal = getValueState(I.getFalseValue());
661
662 // select ?, C, C -> C.
663 if (TVal.isConstant() && FVal.isConstant() &&
664 TVal.getConstant() == FVal.getConstant()) {
665 markConstant(&I, FVal.getConstant());
666 return;
667 }
668
669 if (TVal.isUndefined()) { // select ?, undef, X -> X.
670 mergeInValue(&I, FVal);
671 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
672 mergeInValue(&I, TVal);
673 } else {
674 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000675 }
676}
677
Chris Lattner6e560792002-04-18 15:13:15 +0000678// Handle BinaryOperators and Shift Instructions...
Chris Lattner074be1f2004-11-15 04:44:20 +0000679void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000680 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000681 if (IV.isOverdefined()) return;
682
Chris Lattner4f031622004-11-15 05:03:30 +0000683 LatticeVal &V1State = getValueState(I.getOperand(0));
684 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000685
Chris Lattner6e560792002-04-18 15:13:15 +0000686 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnercbc01612004-12-11 23:15:19 +0000687 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
688 // operand is overdefined.
689 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
690 LatticeVal *NonOverdefVal = 0;
691 if (!V1State.isOverdefined()) {
692 NonOverdefVal = &V1State;
693 } else if (!V2State.isOverdefined()) {
694 NonOverdefVal = &V2State;
695 }
696
697 if (NonOverdefVal) {
698 if (NonOverdefVal->isUndefined()) {
699 // Could annihilate value.
700 if (I.getOpcode() == Instruction::And)
701 markConstant(IV, &I, Constant::getNullValue(I.getType()));
702 else
703 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
704 return;
705 } else {
706 if (I.getOpcode() == Instruction::And) {
707 if (NonOverdefVal->getConstant()->isNullValue()) {
708 markConstant(IV, &I, NonOverdefVal->getConstant());
709 return; // X or 0 = -1
710 }
711 } else {
712 if (ConstantIntegral *CI =
713 dyn_cast<ConstantIntegral>(NonOverdefVal->getConstant()))
714 if (CI->isAllOnesValue()) {
715 markConstant(IV, &I, NonOverdefVal->getConstant());
716 return; // X or -1 = -1
717 }
718 }
719 }
720 }
721 }
722
723
Chris Lattner05fe6842004-01-12 03:57:30 +0000724 // If both operands are PHI nodes, it is possible that this instruction has
725 // a constant value, despite the fact that the PHI node doesn't. Check for
726 // this condition now.
727 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
728 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
729 if (PN1->getParent() == PN2->getParent()) {
730 // Since the two PHI nodes are in the same basic block, they must have
731 // entries for the same predecessors. Walk the predecessor list, and
732 // if all of the incoming values are constants, and the result of
733 // evaluating this expression with all incoming value pairs is the
734 // same, then this expression is a constant even though the PHI node
735 // is not a constant!
Chris Lattner4f031622004-11-15 05:03:30 +0000736 LatticeVal Result;
Chris Lattner05fe6842004-01-12 03:57:30 +0000737 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000738 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner05fe6842004-01-12 03:57:30 +0000739 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattner4f031622004-11-15 05:03:30 +0000740 LatticeVal &In2 =
741 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner05fe6842004-01-12 03:57:30 +0000742
743 if (In1.isOverdefined() || In2.isOverdefined()) {
744 Result.markOverdefined();
745 break; // Cannot fold this operation over the PHI nodes!
746 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000747 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
748 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000749 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000750 Result.markConstant(V);
751 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000752 Result.markOverdefined();
753 break;
754 }
755 }
756 }
757
758 // If we found a constant value here, then we know the instruction is
759 // constant despite the fact that the PHI nodes are overdefined.
760 if (Result.isConstant()) {
761 markConstant(IV, &I, Result.getConstant());
762 // Remember that this instruction is virtually using the PHI node
763 // operands.
764 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
765 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
766 return;
767 } else if (Result.isUndefined()) {
768 return;
769 }
770
771 // Okay, this really is overdefined now. Since we might have
772 // speculatively thought that this was not overdefined before, and
773 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
774 // make sure to clean out any entries that we put there, for
775 // efficiency.
776 std::multimap<PHINode*, Instruction*>::iterator It, E;
777 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
778 while (It != E) {
779 if (It->second == &I) {
780 UsersOfOverdefinedPHIs.erase(It++);
781 } else
782 ++It;
783 }
784 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
785 while (It != E) {
786 if (It->second == &I) {
787 UsersOfOverdefinedPHIs.erase(It++);
788 } else
789 ++It;
790 }
791 }
792
793 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000794 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000795 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
796 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000797 }
798}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000799
Reid Spencer266e42b2006-12-23 06:05:41 +0000800// Handle ICmpInst instruction...
801void SCCPSolver::visitCmpInst(CmpInst &I) {
802 LatticeVal &IV = ValueState[&I];
803 if (IV.isOverdefined()) return;
804
805 LatticeVal &V1State = getValueState(I.getOperand(0));
806 LatticeVal &V2State = getValueState(I.getOperand(1));
807
808 if (V1State.isOverdefined() || V2State.isOverdefined()) {
809 // If both operands are PHI nodes, it is possible that this instruction has
810 // a constant value, despite the fact that the PHI node doesn't. Check for
811 // this condition now.
812 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
813 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
814 if (PN1->getParent() == PN2->getParent()) {
815 // Since the two PHI nodes are in the same basic block, they must have
816 // entries for the same predecessors. Walk the predecessor list, and
817 // if all of the incoming values are constants, and the result of
818 // evaluating this expression with all incoming value pairs is the
819 // same, then this expression is a constant even though the PHI node
820 // is not a constant!
821 LatticeVal Result;
822 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
823 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
824 BasicBlock *InBlock = PN1->getIncomingBlock(i);
825 LatticeVal &In2 =
826 getValueState(PN2->getIncomingValueForBlock(InBlock));
827
828 if (In1.isOverdefined() || In2.isOverdefined()) {
829 Result.markOverdefined();
830 break; // Cannot fold this operation over the PHI nodes!
831 } else if (In1.isConstant() && In2.isConstant()) {
832 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
833 In1.getConstant(),
834 In2.getConstant());
835 if (Result.isUndefined())
836 Result.markConstant(V);
837 else if (Result.isConstant() && Result.getConstant() != V) {
838 Result.markOverdefined();
839 break;
840 }
841 }
842 }
843
844 // If we found a constant value here, then we know the instruction is
845 // constant despite the fact that the PHI nodes are overdefined.
846 if (Result.isConstant()) {
847 markConstant(IV, &I, Result.getConstant());
848 // Remember that this instruction is virtually using the PHI node
849 // operands.
850 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
851 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
852 return;
853 } else if (Result.isUndefined()) {
854 return;
855 }
856
857 // Okay, this really is overdefined now. Since we might have
858 // speculatively thought that this was not overdefined before, and
859 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
860 // make sure to clean out any entries that we put there, for
861 // efficiency.
862 std::multimap<PHINode*, Instruction*>::iterator It, E;
863 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
864 while (It != E) {
865 if (It->second == &I) {
866 UsersOfOverdefinedPHIs.erase(It++);
867 } else
868 ++It;
869 }
870 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
871 while (It != E) {
872 if (It->second == &I) {
873 UsersOfOverdefinedPHIs.erase(It++);
874 } else
875 ++It;
876 }
877 }
878
879 markOverdefined(IV, &I);
880 } else if (V1State.isConstant() && V2State.isConstant()) {
881 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
882 V1State.getConstant(),
883 V2State.getConstant()));
884 }
885}
886
Robert Bocchinobd518d12006-01-10 19:05:05 +0000887void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000888 // FIXME : SCCP does not handle vectors properly.
889 markOverdefined(&I);
890 return;
891
892#if 0
Robert Bocchinobd518d12006-01-10 19:05:05 +0000893 LatticeVal &ValState = getValueState(I.getOperand(0));
894 LatticeVal &IdxState = getValueState(I.getOperand(1));
895
896 if (ValState.isOverdefined() || IdxState.isOverdefined())
897 markOverdefined(&I);
898 else if(ValState.isConstant() && IdxState.isConstant())
899 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
900 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000901#endif
Robert Bocchinobd518d12006-01-10 19:05:05 +0000902}
903
Robert Bocchino6dce2502006-01-17 20:06:55 +0000904void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000905 // FIXME : SCCP does not handle vectors properly.
906 markOverdefined(&I);
907 return;
908#if 0
Robert Bocchino6dce2502006-01-17 20:06:55 +0000909 LatticeVal &ValState = getValueState(I.getOperand(0));
910 LatticeVal &EltState = getValueState(I.getOperand(1));
911 LatticeVal &IdxState = getValueState(I.getOperand(2));
912
913 if (ValState.isOverdefined() || EltState.isOverdefined() ||
914 IdxState.isOverdefined())
915 markOverdefined(&I);
916 else if(ValState.isConstant() && EltState.isConstant() &&
917 IdxState.isConstant())
918 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
919 EltState.getConstant(),
920 IdxState.getConstant()));
921 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel21efc732006-12-04 23:54:59 +0000922 IdxState.isConstant())
Robert Bocchino6dce2502006-01-17 20:06:55 +0000923 markConstant(&I, ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
924 EltState.getConstant(),
925 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000926#endif
Robert Bocchino6dce2502006-01-17 20:06:55 +0000927}
928
Chris Lattner17bd6052006-04-08 01:19:12 +0000929void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000930 // FIXME : SCCP does not handle vectors properly.
931 markOverdefined(&I);
932 return;
933#if 0
Chris Lattner17bd6052006-04-08 01:19:12 +0000934 LatticeVal &V1State = getValueState(I.getOperand(0));
935 LatticeVal &V2State = getValueState(I.getOperand(1));
936 LatticeVal &MaskState = getValueState(I.getOperand(2));
937
938 if (MaskState.isUndefined() ||
939 (V1State.isUndefined() && V2State.isUndefined()))
940 return; // Undefined output if mask or both inputs undefined.
941
942 if (V1State.isOverdefined() || V2State.isOverdefined() ||
943 MaskState.isOverdefined()) {
944 markOverdefined(&I);
945 } else {
946 // A mix of constant/undef inputs.
947 Constant *V1 = V1State.isConstant() ?
948 V1State.getConstant() : UndefValue::get(I.getType());
949 Constant *V2 = V2State.isConstant() ?
950 V2State.getConstant() : UndefValue::get(I.getType());
951 Constant *Mask = MaskState.isConstant() ?
952 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
953 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
954 }
Devang Patel21efc732006-12-04 23:54:59 +0000955#endif
Chris Lattner17bd6052006-04-08 01:19:12 +0000956}
957
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000958// Handle getelementptr instructions... if all operands are constants then we
959// can turn this into a getelementptr ConstantExpr.
960//
Chris Lattner074be1f2004-11-15 04:44:20 +0000961void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000962 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000963 if (IV.isOverdefined()) return;
964
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000965 std::vector<Constant*> Operands;
966 Operands.reserve(I.getNumOperands());
967
968 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000969 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000970 if (State.isUndefined())
971 return; // Operands are not resolved yet...
972 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +0000973 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000974 return;
975 }
976 assert(State.isConstant() && "Unknown state!");
977 Operands.push_back(State.getConstant());
978 }
979
980 Constant *Ptr = Operands[0];
981 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
982
Misha Brukmanb1c93172005-04-21 23:48:37 +0000983 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000984}
Brian Gaeke960707c2003-11-11 22:41:34 +0000985
Chris Lattner91dbae62004-12-11 05:15:59 +0000986void SCCPSolver::visitStoreInst(Instruction &SI) {
987 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
988 return;
989 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
990 hash_map<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
991 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
992
993 // Get the value we are storing into the global.
994 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
995
996 mergeInValue(I->second, GV, PtrVal);
997 if (I->second.isOverdefined())
998 TrackedGlobals.erase(I); // No need to keep tracking this!
999}
1000
1001
Chris Lattner49f74522004-01-12 04:29:41 +00001002// Handle load instructions. If the operand is a constant pointer to a constant
1003// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001004void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +00001005 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001006 if (IV.isOverdefined()) return;
1007
Chris Lattner4f031622004-11-15 05:03:30 +00001008 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattner49f74522004-01-12 04:29:41 +00001009 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1010 if (PtrVal.isConstant() && !I.isVolatile()) {
1011 Value *Ptr = PtrVal.getConstant();
Chris Lattner538fee72004-03-07 22:16:24 +00001012 if (isa<ConstantPointerNull>(Ptr)) {
1013 // load null -> null
1014 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1015 return;
1016 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001017
Chris Lattner49f74522004-01-12 04:29:41 +00001018 // Transform load (constant global) into the value loaded.
Chris Lattner91dbae62004-12-11 05:15:59 +00001019 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1020 if (GV->isConstant()) {
1021 if (!GV->isExternal()) {
1022 markConstant(IV, &I, GV->getInitializer());
1023 return;
1024 }
1025 } else if (!TrackedGlobals.empty()) {
1026 // If we are tracking this global, merge in the known value for it.
1027 hash_map<GlobalVariable*, LatticeVal>::iterator It =
1028 TrackedGlobals.find(GV);
1029 if (It != TrackedGlobals.end()) {
1030 mergeInValue(IV, &I, It->second);
1031 return;
1032 }
Chris Lattner49f74522004-01-12 04:29:41 +00001033 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001034 }
Chris Lattner49f74522004-01-12 04:29:41 +00001035
1036 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1037 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1038 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen82639852005-04-23 21:38:35 +00001039 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
1040 if (GV->isConstant() && !GV->isExternal())
1041 if (Constant *V =
Chris Lattner02ae21e2005-09-26 05:28:52 +00001042 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen82639852005-04-23 21:38:35 +00001043 markConstant(IV, &I, V);
1044 return;
1045 }
Chris Lattner49f74522004-01-12 04:29:41 +00001046 }
1047
1048 // Otherwise we cannot say for certain what value this load will produce.
1049 // Bail out.
1050 markOverdefined(IV, &I);
1051}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001052
Chris Lattnerb4394642004-12-10 08:02:06 +00001053void SCCPSolver::visitCallSite(CallSite CS) {
1054 Function *F = CS.getCalledFunction();
1055
1056 // If we are tracking this function, we must make sure to bind arguments as
1057 // appropriate.
1058 hash_map<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
1059 if (F && F->hasInternalLinkage())
1060 TFRVI = TrackedFunctionRetVals.find(F);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001061
Chris Lattnerb4394642004-12-10 08:02:06 +00001062 if (TFRVI != TrackedFunctionRetVals.end()) {
1063 // If this is the first call to the function hit, mark its entry block
1064 // executable.
1065 if (!BBExecutable.count(F->begin()))
1066 MarkBlockExecutable(F->begin());
1067
1068 CallSite::arg_iterator CAI = CS.arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +00001069 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
Chris Lattnerb4394642004-12-10 08:02:06 +00001070 AI != E; ++AI, ++CAI) {
1071 LatticeVal &IV = ValueState[AI];
1072 if (!IV.isOverdefined())
1073 mergeInValue(IV, AI, getValueState(*CAI));
1074 }
1075 }
1076 Instruction *I = CS.getInstruction();
1077 if (I->getType() == Type::VoidTy) return;
1078
1079 LatticeVal &IV = ValueState[I];
Chris Lattnerff9362a2004-04-13 19:43:54 +00001080 if (IV.isOverdefined()) return;
1081
Chris Lattnerb4394642004-12-10 08:02:06 +00001082 // Propagate the return value of the function to the value of the instruction.
1083 if (TFRVI != TrackedFunctionRetVals.end()) {
1084 mergeInValue(IV, I, TFRVI->second);
1085 return;
1086 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001087
Chris Lattnerb4394642004-12-10 08:02:06 +00001088 if (F == 0 || !F->isExternal() || !canConstantFoldCallTo(F)) {
1089 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001090 return;
1091 }
1092
1093 std::vector<Constant*> Operands;
Chris Lattnerb4394642004-12-10 08:02:06 +00001094 Operands.reserve(I->getNumOperands()-1);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001095
Chris Lattnerb4394642004-12-10 08:02:06 +00001096 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1097 AI != E; ++AI) {
1098 LatticeVal &State = getValueState(*AI);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001099 if (State.isUndefined())
1100 return; // Operands are not resolved yet...
1101 else if (State.isOverdefined()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001102 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001103 return;
1104 }
1105 assert(State.isConstant() && "Unknown state!");
1106 Operands.push_back(State.getConstant());
1107 }
1108
1109 if (Constant *C = ConstantFoldCall(F, Operands))
Chris Lattnerb4394642004-12-10 08:02:06 +00001110 markConstant(IV, I, C);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001111 else
Chris Lattnerb4394642004-12-10 08:02:06 +00001112 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001113}
Chris Lattner074be1f2004-11-15 04:44:20 +00001114
1115
1116void SCCPSolver::Solve() {
1117 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001118 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001119 !OverdefinedInstWorkList.empty()) {
Chris Lattner074be1f2004-11-15 04:44:20 +00001120 // Process the instruction work list...
1121 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001122 Value *I = OverdefinedInstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001123 OverdefinedInstWorkList.pop_back();
1124
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001125 DOUT << "\nPopped off OI-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001126
Chris Lattner074be1f2004-11-15 04:44:20 +00001127 // "I" got into the work list because it either made the transition from
1128 // bottom to constant
1129 //
1130 // Anything on this worklist that is overdefined need not be visited
1131 // since all of its users will have already been marked as overdefined
1132 // Update all of the users of this instruction's value...
1133 //
1134 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1135 UI != E; ++UI)
1136 OperandChangedState(*UI);
1137 }
1138 // Process the instruction work list...
1139 while (!InstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001140 Value *I = InstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001141 InstWorkList.pop_back();
1142
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001143 DOUT << "\nPopped off I-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001144
Chris Lattner074be1f2004-11-15 04:44:20 +00001145 // "I" got into the work list because it either made the transition from
1146 // bottom to constant
1147 //
1148 // Anything on this worklist that is overdefined need not be visited
1149 // since all of its users will have already been marked as overdefined.
1150 // Update all of the users of this instruction's value...
1151 //
1152 if (!getValueState(I).isOverdefined())
1153 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1154 UI != E; ++UI)
1155 OperandChangedState(*UI);
1156 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001157
Chris Lattner074be1f2004-11-15 04:44:20 +00001158 // Process the basic block work list...
1159 while (!BBWorkList.empty()) {
1160 BasicBlock *BB = BBWorkList.back();
1161 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001162
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001163 DOUT << "\nPopped off BBWL: " << *BB;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001164
Chris Lattner074be1f2004-11-15 04:44:20 +00001165 // Notify all instructions in this basic block that they are newly
1166 // executable.
1167 visit(BB);
1168 }
1169 }
1170}
1171
Chris Lattner1847f6d2006-12-20 06:21:33 +00001172/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001173/// that branches on undef values cannot reach any of their successors.
1174/// However, this is not a safe assumption. After we solve dataflow, this
1175/// method should be use to handle this. If this returns true, the solver
1176/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001177///
1178/// This method handles this by finding an unresolved branch and marking it one
1179/// of the edges from the block as being feasible, even though the condition
1180/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1181/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001182/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001183/// constraints on the condition of the branch, as that would impact other users
1184/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001185///
1186/// This scan also checks for values that use undefs, whose results are actually
1187/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1188/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1189/// even if X isn't defined.
1190bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattneraf170962006-10-22 05:59:17 +00001191 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1192 if (!BBExecutable.count(BB))
1193 continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001194
1195 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1196 // Look for instructions which produce undef values.
1197 if (I->getType() == Type::VoidTy) continue;
1198
1199 LatticeVal &LV = getValueState(I);
1200 if (!LV.isUndefined()) continue;
1201
1202 // Get the lattice values of the first two operands for use below.
1203 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1204 LatticeVal Op1LV;
1205 if (I->getNumOperands() == 2) {
1206 // If this is a two-operand instruction, and if both operands are
1207 // undefs, the result stays undef.
1208 Op1LV = getValueState(I->getOperand(1));
1209 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1210 continue;
1211 }
1212
1213 // If this is an instructions whose result is defined even if the input is
1214 // not fully defined, propagate the information.
1215 const Type *ITy = I->getType();
1216 switch (I->getOpcode()) {
1217 default: break; // Leave the instruction as an undef.
1218 case Instruction::ZExt:
1219 // After a zero extend, we know the top part is zero. SExt doesn't have
1220 // to be handled here, because we don't know whether the top part is 1's
1221 // or 0's.
1222 assert(Op0LV.isUndefined());
1223 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1224 return true;
1225 case Instruction::Mul:
1226 case Instruction::And:
1227 // undef * X -> 0. X could be zero.
1228 // undef & X -> 0. X could be zero.
1229 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1230 return true;
1231
1232 case Instruction::Or:
1233 // undef | X -> -1. X could be -1.
1234 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1235 return true;
1236
1237 case Instruction::SDiv:
1238 case Instruction::UDiv:
1239 case Instruction::SRem:
1240 case Instruction::URem:
1241 // X / undef -> undef. No change.
1242 // X % undef -> undef. No change.
1243 if (Op1LV.isUndefined()) break;
1244
1245 // undef / X -> 0. X could be maxint.
1246 // undef % X -> 0. X could be 1.
1247 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1248 return true;
1249
1250 case Instruction::AShr:
1251 // undef >>s X -> undef. No change.
1252 if (Op0LV.isUndefined()) break;
1253
1254 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1255 if (Op0LV.isConstant())
1256 markForcedConstant(LV, I, Op0LV.getConstant());
1257 else
1258 markOverdefined(LV, I);
1259 return true;
1260 case Instruction::LShr:
1261 case Instruction::Shl:
1262 // undef >> X -> undef. No change.
1263 // undef << X -> undef. No change.
1264 if (Op0LV.isUndefined()) break;
1265
1266 // X >> undef -> 0. X could be 0.
1267 // X << undef -> 0. X could be 0.
1268 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1269 return true;
1270 case Instruction::Select:
1271 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1272 if (Op0LV.isUndefined()) {
1273 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1274 Op1LV = getValueState(I->getOperand(2));
1275 } else if (Op1LV.isUndefined()) {
1276 // c ? undef : undef -> undef. No change.
1277 Op1LV = getValueState(I->getOperand(2));
1278 if (Op1LV.isUndefined())
1279 break;
1280 // Otherwise, c ? undef : x -> x.
1281 } else {
1282 // Leave Op1LV as Operand(1)'s LatticeValue.
1283 }
1284
1285 if (Op1LV.isConstant())
1286 markForcedConstant(LV, I, Op1LV.getConstant());
1287 else
1288 markOverdefined(LV, I);
1289 return true;
1290 }
1291 }
Chris Lattneraf170962006-10-22 05:59:17 +00001292
1293 TerminatorInst *TI = BB->getTerminator();
1294 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1295 if (!BI->isConditional()) continue;
1296 if (!getValueState(BI->getCondition()).isUndefined())
1297 continue;
1298 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1299 if (!getValueState(SI->getCondition()).isUndefined())
1300 continue;
1301 } else {
1302 continue;
Chris Lattner7285f432004-12-10 20:41:50 +00001303 }
Chris Lattneraf170962006-10-22 05:59:17 +00001304
1305 // If the edge to the first successor isn't thought to be feasible yet, mark
1306 // it so now.
1307 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(0))))
1308 continue;
1309
1310 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1311 // and return. This will make other blocks reachable, which will allow new
1312 // values to be discovered and existing ones to be moved in the lattice.
1313 markEdgeExecutable(BB, TI->getSuccessor(0));
1314 return true;
1315 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001316
Chris Lattneraf170962006-10-22 05:59:17 +00001317 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001318}
1319
Chris Lattner074be1f2004-11-15 04:44:20 +00001320
1321namespace {
Chris Lattner1890f942004-11-15 07:15:04 +00001322 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +00001323 //
Chris Lattner1890f942004-11-15 07:15:04 +00001324 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spencere8a74ee2006-12-31 22:26:06 +00001325 /// Sparse Conditional Constant Propagator.
Chris Lattner1890f942004-11-15 07:15:04 +00001326 ///
1327 struct SCCP : public FunctionPass {
1328 // runOnFunction - Run the Sparse Conditional Constant Propagation
1329 // algorithm, and return true if the function was modified.
1330 //
1331 bool runOnFunction(Function &F);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001332
Chris Lattner1890f942004-11-15 07:15:04 +00001333 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1334 AU.setPreservesCFG();
1335 }
1336 };
Chris Lattner074be1f2004-11-15 04:44:20 +00001337
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001338 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner074be1f2004-11-15 04:44:20 +00001339} // end anonymous namespace
1340
1341
1342// createSCCPPass - This is the public interface to this file...
1343FunctionPass *llvm::createSCCPPass() {
1344 return new SCCP();
1345}
1346
1347
Chris Lattner074be1f2004-11-15 04:44:20 +00001348// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1349// and return true if the function was modified.
1350//
1351bool SCCP::runOnFunction(Function &F) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001352 DOUT << "SCCP on function '" << F.getName() << "'\n";
Chris Lattner074be1f2004-11-15 04:44:20 +00001353 SCCPSolver Solver;
1354
1355 // Mark the first block of the function as being executable.
1356 Solver.MarkBlockExecutable(F.begin());
1357
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001358 // Mark all arguments to the function as being overdefined.
1359 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner531f9e92005-03-15 04:54:21 +00001360 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; ++AI)
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001361 Values[AI].markOverdefined();
1362
Chris Lattner074be1f2004-11-15 04:44:20 +00001363 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001364 bool ResolvedUndefs = true;
1365 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001366 Solver.Solve();
Chris Lattner1847f6d2006-12-20 06:21:33 +00001367 DOUT << "RESOLVING UNDEFs\n";
1368 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001369 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001370
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001371 bool MadeChanges = false;
1372
1373 // If we decided that there are basic blocks that are dead in this function,
1374 // delete their contents now. Note that we cannot actually delete the blocks,
1375 // as we cannot modify the CFG of the function.
1376 //
1377 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1378 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1379 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001380 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattner9a038a32004-11-15 07:02:42 +00001381 ++NumDeadBlocks;
1382
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001383 // Delete the instructions backwards, as it has a reduced likelihood of
1384 // having to update as many def-use and use-def chains.
1385 std::vector<Instruction*> Insts;
1386 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1387 I != E; ++I)
1388 Insts.push_back(I);
1389 while (!Insts.empty()) {
1390 Instruction *I = Insts.back();
1391 Insts.pop_back();
1392 if (!I->use_empty())
1393 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1394 BB->getInstList().erase(I);
1395 MadeChanges = true;
Chris Lattner9a038a32004-11-15 07:02:42 +00001396 ++NumInstRemoved;
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001397 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001398 } else {
1399 // Iterate over all of the instructions in a function, replacing them with
1400 // constants if we have found them to be of constant values.
1401 //
1402 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1403 Instruction *Inst = BI++;
1404 if (Inst->getType() != Type::VoidTy) {
1405 LatticeVal &IV = Values[Inst];
1406 if (IV.isConstant() || IV.isUndefined() &&
1407 !isa<TerminatorInst>(Inst)) {
1408 Constant *Const = IV.isConstant()
1409 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001410 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001411
Chris Lattnerb4394642004-12-10 08:02:06 +00001412 // Replaces all of the uses of a variable with uses of the constant.
1413 Inst->replaceAllUsesWith(Const);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001414
Chris Lattnerb4394642004-12-10 08:02:06 +00001415 // Delete the instruction.
1416 BB->getInstList().erase(Inst);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001417
Chris Lattnerb4394642004-12-10 08:02:06 +00001418 // Hey, we just changed something!
1419 MadeChanges = true;
1420 ++NumInstRemoved;
Chris Lattner074be1f2004-11-15 04:44:20 +00001421 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001422 }
1423 }
1424 }
1425
1426 return MadeChanges;
1427}
Chris Lattnerb4394642004-12-10 08:02:06 +00001428
1429namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +00001430 //===--------------------------------------------------------------------===//
1431 //
1432 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1433 /// Constant Propagation.
1434 ///
1435 struct IPSCCP : public ModulePass {
1436 bool runOnModule(Module &M);
1437 };
1438
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001439 RegisterPass<IPSCCP>
Chris Lattnerb4394642004-12-10 08:02:06 +00001440 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1441} // end anonymous namespace
1442
1443// createIPSCCPPass - This is the public interface to this file...
1444ModulePass *llvm::createIPSCCPPass() {
1445 return new IPSCCP();
1446}
1447
1448
1449static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001450 // Delete any dead constantexpr klingons.
1451 GV->removeDeadConstantUsers();
1452
Chris Lattnerb4394642004-12-10 08:02:06 +00001453 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1454 UI != E; ++UI)
1455 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001456 if (SI->getOperand(0) == GV || SI->isVolatile())
1457 return true; // Storing addr of GV.
Chris Lattnerb4394642004-12-10 08:02:06 +00001458 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1459 // Make sure we are calling the function, not passing the address.
1460 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1461 for (CallSite::arg_iterator AI = CS.arg_begin(),
1462 E = CS.arg_end(); AI != E; ++AI)
1463 if (*AI == GV)
1464 return true;
Chris Lattner91dbae62004-12-11 05:15:59 +00001465 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1466 if (LI->isVolatile())
1467 return true;
1468 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001469 return true;
1470 }
1471 return false;
1472}
1473
1474bool IPSCCP::runOnModule(Module &M) {
1475 SCCPSolver Solver;
1476
1477 // Loop over all functions, marking arguments to those with their addresses
1478 // taken or that are external as overdefined.
1479 //
1480 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1481 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1482 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1483 if (!F->isExternal())
1484 Solver.MarkBlockExecutable(F->begin());
Chris Lattner8cb10a12005-04-19 19:16:19 +00001485 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1486 AI != E; ++AI)
Chris Lattnerb4394642004-12-10 08:02:06 +00001487 Values[AI].markOverdefined();
1488 } else {
1489 Solver.AddTrackedFunction(F);
1490 }
1491
Chris Lattner91dbae62004-12-11 05:15:59 +00001492 // Loop over global variables. We inform the solver about any internal global
1493 // variables that do not have their 'addresses taken'. If they don't have
1494 // their addresses taken, we can propagate constants through them.
Chris Lattner8cb10a12005-04-19 19:16:19 +00001495 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1496 G != E; ++G)
Chris Lattner91dbae62004-12-11 05:15:59 +00001497 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1498 Solver.TrackValueOfGlobalVariable(G);
1499
Chris Lattnerb4394642004-12-10 08:02:06 +00001500 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001501 bool ResolvedUndefs = true;
1502 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001503 Solver.Solve();
1504
Chris Lattner1847f6d2006-12-20 06:21:33 +00001505 DOUT << "RESOLVING UNDEFS\n";
1506 ResolvedUndefs = false;
Chris Lattner7285f432004-12-10 20:41:50 +00001507 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner1847f6d2006-12-20 06:21:33 +00001508 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattner7285f432004-12-10 20:41:50 +00001509 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001510
1511 bool MadeChanges = false;
1512
1513 // Iterate over all of the instructions in the module, replacing them with
1514 // constants if we have found them to be of constant values.
1515 //
1516 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1517 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001518 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1519 AI != E; ++AI)
Chris Lattnerb4394642004-12-10 08:02:06 +00001520 if (!AI->use_empty()) {
1521 LatticeVal &IV = Values[AI];
1522 if (IV.isConstant() || IV.isUndefined()) {
1523 Constant *CST = IV.isConstant() ?
1524 IV.getConstant() : UndefValue::get(AI->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001525 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
Misha Brukmanb1c93172005-04-21 23:48:37 +00001526
Chris Lattnerb4394642004-12-10 08:02:06 +00001527 // Replaces all of the uses of a variable with uses of the
1528 // constant.
1529 AI->replaceAllUsesWith(CST);
1530 ++IPNumArgsElimed;
1531 }
1532 }
1533
Chris Lattnerbae4b642004-12-10 22:29:08 +00001534 std::vector<BasicBlock*> BlocksToErase;
Chris Lattnerb4394642004-12-10 08:02:06 +00001535 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1536 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001537 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattnerb4394642004-12-10 08:02:06 +00001538 ++IPNumDeadBlocks;
Chris Lattner7285f432004-12-10 20:41:50 +00001539
Chris Lattnerb4394642004-12-10 08:02:06 +00001540 // Delete the instructions backwards, as it has a reduced likelihood of
1541 // having to update as many def-use and use-def chains.
1542 std::vector<Instruction*> Insts;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001543 TerminatorInst *TI = BB->getTerminator();
1544 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattnerb4394642004-12-10 08:02:06 +00001545 Insts.push_back(I);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001546
Chris Lattnerb4394642004-12-10 08:02:06 +00001547 while (!Insts.empty()) {
1548 Instruction *I = Insts.back();
1549 Insts.pop_back();
1550 if (!I->use_empty())
1551 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1552 BB->getInstList().erase(I);
1553 MadeChanges = true;
1554 ++IPNumInstRemoved;
1555 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001556
Chris Lattnerbae4b642004-12-10 22:29:08 +00001557 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1558 BasicBlock *Succ = TI->getSuccessor(i);
1559 if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1560 TI->getSuccessor(i)->removePredecessor(BB);
1561 }
Chris Lattner99e12952004-12-11 02:53:57 +00001562 if (!TI->use_empty())
1563 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnerbae4b642004-12-10 22:29:08 +00001564 BB->getInstList().erase(TI);
1565
Chris Lattner8525ebe2004-12-11 05:32:19 +00001566 if (&*BB != &F->front())
1567 BlocksToErase.push_back(BB);
1568 else
1569 new UnreachableInst(BB);
1570
Chris Lattnerb4394642004-12-10 08:02:06 +00001571 } else {
1572 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1573 Instruction *Inst = BI++;
1574 if (Inst->getType() != Type::VoidTy) {
1575 LatticeVal &IV = Values[Inst];
1576 if (IV.isConstant() || IV.isUndefined() &&
1577 !isa<TerminatorInst>(Inst)) {
1578 Constant *Const = IV.isConstant()
1579 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001580 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001581
Chris Lattnerb4394642004-12-10 08:02:06 +00001582 // Replaces all of the uses of a variable with uses of the
1583 // constant.
1584 Inst->replaceAllUsesWith(Const);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001585
Chris Lattnerb4394642004-12-10 08:02:06 +00001586 // Delete the instruction.
1587 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1588 BB->getInstList().erase(Inst);
1589
1590 // Hey, we just changed something!
1591 MadeChanges = true;
1592 ++IPNumInstRemoved;
1593 }
1594 }
1595 }
1596 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001597
1598 // Now that all instructions in the function are constant folded, erase dead
1599 // blocks, because we can now use ConstantFoldTerminator to get rid of
1600 // in-edges.
1601 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1602 // If there are any PHI nodes in this successor, drop entries for BB now.
1603 BasicBlock *DeadBB = BlocksToErase[i];
1604 while (!DeadBB->use_empty()) {
1605 Instruction *I = cast<Instruction>(DeadBB->use_back());
1606 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001607 if (!Folded) {
1608 // The constant folder may not have been able to fold the termiantor
1609 // if this is a branch or switch on undef. Fold it manually as a
1610 // branch to the first successor.
1611 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1612 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1613 "Branch should be foldable!");
1614 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1615 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1616 } else {
1617 assert(0 && "Didn't fold away reference to block!");
1618 }
1619
1620 // Make this an uncond branch to the first successor.
1621 TerminatorInst *TI = I->getParent()->getTerminator();
1622 new BranchInst(TI->getSuccessor(0), TI);
1623
1624 // Remove entries in successor phi nodes to remove edges.
1625 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1626 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1627
1628 // Remove the old terminator.
1629 TI->eraseFromParent();
1630 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001631 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001632
Chris Lattnerbae4b642004-12-10 22:29:08 +00001633 // Finally, delete the basic block.
1634 F->getBasicBlockList().erase(DeadBB);
1635 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001636 }
Chris Lattner99e12952004-12-11 02:53:57 +00001637
1638 // If we inferred constant or undef return values for a function, we replaced
1639 // all call uses with the inferred value. This means we don't need to bother
1640 // actually returning anything from the function. Replace all return
1641 // instructions with return undef.
1642 const hash_map<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals();
1643 for (hash_map<Function*, LatticeVal>::const_iterator I = RV.begin(),
1644 E = RV.end(); I != E; ++I)
1645 if (!I->second.isOverdefined() &&
1646 I->first->getReturnType() != Type::VoidTy) {
1647 Function *F = I->first;
1648 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1649 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1650 if (!isa<UndefValue>(RI->getOperand(0)))
1651 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1652 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001653
1654 // If we infered constant or undef values for globals variables, we can delete
1655 // the global and any stores that remain to it.
1656 const hash_map<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1657 for (hash_map<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1658 E = TG.end(); I != E; ++I) {
1659 GlobalVariable *GV = I->first;
1660 assert(!I->second.isOverdefined() &&
1661 "Overdefined values should have been taken out of the map!");
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001662 DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
Chris Lattner91dbae62004-12-11 05:15:59 +00001663 while (!GV->use_empty()) {
1664 StoreInst *SI = cast<StoreInst>(GV->use_back());
1665 SI->eraseFromParent();
1666 }
1667 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00001668 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00001669 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001670
Chris Lattnerb4394642004-12-10 08:02:06 +00001671 return MadeChanges;
1672}