blob: 479588ef3cebbe3b75b6ecfb81107f1f3f9a43cb [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//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +00009//
Misha Brukman373086d2003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner347389d2001-06-27 23:38:11 +000011//
12// Specifically, this:
13// * Assumes values are constant unless proven otherwise
14// * Assumes BasicBlocks are dead unless proven otherwise
15// * Proves values to be constant, and replaces them with constants
Chris Lattnerdd6522e2002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner347389d2001-06-27 23:38:11 +000017//
18// Notice that:
19// * This pass has a habit of making definitions be dead. It is a good idea
20// to to run a DCE pass sometime after running this pass.
21//
22//===----------------------------------------------------------------------===//
23
Chris Lattner4f031622004-11-15 05:03:30 +000024#define DEBUG_TYPE "sccp"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000025#include "llvm/Transforms/Scalar.h"
Chris Lattnerb4394642004-12-10 08:02:06 +000026#include "llvm/Transforms/IPO.h"
Chris Lattner0fe5b322004-01-12 17:43:40 +000027#include "llvm/Constants.h"
Chris Lattner91dbae62004-12-11 05:15:59 +000028#include "llvm/DerivedTypes.h"
Chris Lattnercccc5c72003-04-25 02:50:03 +000029#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000030#include "llvm/Pass.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000031#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerff9362a2004-04-13 19:43:54 +000032#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerb4394642004-12-10 08:02:06 +000033#include "llvm/Support/CallSite.h"
Reid Spencer557ab152007-02-05 23:32:05 +000034#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000035#include "llvm/Support/Debug.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000036#include "llvm/Support/InstVisitor.h"
Chris Lattner067d6072007-02-02 20:38:30 +000037#include "llvm/ADT/DenseMap.h"
Chris Lattner3e667f32007-02-02 20:57:39 +000038#include "llvm/ADT/SmallSet.h"
Chris Lattner0d74d3c2007-01-30 23:15:19 +000039#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000040#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/STLExtras.h"
Chris Lattner347389d2001-06-27 23:38:11 +000042#include <algorithm>
Chris Lattner49525f82004-01-09 06:02:20 +000043using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000044
Chris Lattner79a42ac2006-12-19 21:40:18 +000045STATISTIC(NumInstRemoved, "Number of instructions removed");
46STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
47
Nick Lewycky35e92c72008-03-08 07:48:41 +000048STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner79a42ac2006-12-19 21:40:18 +000049STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
50STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
51STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
52
Chris Lattner7d325382002-04-29 21:26:08 +000053namespace {
Chris Lattner1847f6d2006-12-20 06:21:33 +000054/// LatticeVal class - This class represents the different lattice values that
55/// an LLVM value may occupy. It is a simple class with value semantics.
56///
Reid Spencer557ab152007-02-05 23:32:05 +000057class VISIBILITY_HIDDEN LatticeVal {
Misha Brukmanb1c93172005-04-21 23:48:37 +000058 enum {
Chris Lattner1847f6d2006-12-20 06:21:33 +000059 /// undefined - This LLVM Value has no known value yet.
60 undefined,
61
62 /// constant - This LLVM Value has a specific constant value.
63 constant,
64
65 /// forcedconstant - This LLVM Value was thought to be undef until
66 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
67 /// with another (different) constant, it goes to overdefined, instead of
68 /// asserting.
69 forcedconstant,
70
71 /// overdefined - This instruction is not known to be constant, and we know
72 /// it has a value.
73 overdefined
74 } LatticeValue; // The current lattice position
75
Chris Lattner3462ae32001-12-03 22:26:30 +000076 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000077public:
Chris Lattner4f031622004-11-15 05:03:30 +000078 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner1847f6d2006-12-20 06:21:33 +000079
Chris Lattner347389d2001-06-27 23:38:11 +000080 // markOverdefined - Return true if this is a new status to be in...
81 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000082 if (LatticeValue != overdefined) {
83 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000084 return true;
85 }
86 return false;
87 }
88
Chris Lattner1847f6d2006-12-20 06:21:33 +000089 // markConstant - Return true if this is a new status for us.
Chris Lattner3462ae32001-12-03 22:26:30 +000090 inline bool markConstant(Constant *V) {
91 if (LatticeValue != constant) {
Chris Lattner1847f6d2006-12-20 06:21:33 +000092 if (LatticeValue == undefined) {
93 LatticeValue = constant;
Jim Laskeyc4ba9c12007-01-03 00:11:03 +000094 assert(V && "Marking constant with NULL");
Chris Lattner1847f6d2006-12-20 06:21:33 +000095 ConstantVal = V;
96 } else {
97 assert(LatticeValue == forcedconstant &&
98 "Cannot move from overdefined to constant!");
99 // Stay at forcedconstant if the constant is the same.
100 if (V == ConstantVal) return false;
101
102 // Otherwise, we go to overdefined. Assumptions made based on the
103 // forced value are possibly wrong. Assuming this is another constant
104 // could expose a contradiction.
105 LatticeValue = overdefined;
106 }
Chris Lattner347389d2001-06-27 23:38:11 +0000107 return true;
108 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +0000109 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +0000110 }
111 return false;
112 }
113
Chris Lattner1847f6d2006-12-20 06:21:33 +0000114 inline void markForcedConstant(Constant *V) {
115 assert(LatticeValue == undefined && "Can't force a defined value!");
116 LatticeValue = forcedconstant;
117 ConstantVal = V;
118 }
119
120 inline bool isUndefined() const { return LatticeValue == undefined; }
121 inline bool isConstant() const {
122 return LatticeValue == constant || LatticeValue == forcedconstant;
123 }
Chris Lattner3462ae32001-12-03 22:26:30 +0000124 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +0000125
Chris Lattner05fe6842004-01-12 03:57:30 +0000126 inline Constant *getConstant() const {
127 assert(isConstant() && "Cannot get the constant of a non-constant!");
128 return ConstantVal;
129 }
Chris Lattner347389d2001-06-27 23:38:11 +0000130};
131
Devang Patela7a20752008-03-11 05:46:42 +0000132/// LatticeValIndex - LatticeVal and associated Index. This is used
133/// to track individual operand Lattice values for multi value ret instructions.
134class VISIBILITY_HIDDEN LatticeValIndexed {
135 public:
136 LatticeValIndexed(unsigned I = 0) { Index = I; }
137 LatticeVal &getLatticeVal() { return LV; }
138 unsigned getIndex() const { return Index; }
139
140 void setLatticeVal(LatticeVal &L) { LV = L; }
141 void setIndex(unsigned I) { Index = I; }
142
143 private:
144 LatticeVal LV;
145 unsigned Index;
146};
Chris Lattner347389d2001-06-27 23:38:11 +0000147//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000148//
Chris Lattner074be1f2004-11-15 04:44:20 +0000149/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
150/// Constant Propagation.
151///
152class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner3e667f32007-02-02 20:57:39 +0000153 SmallSet<BasicBlock*, 16> BBExecutable;// The basic blocks that are executable
Chris Lattnerfc8190d2007-02-02 22:36:16 +0000154 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner347389d2001-06-27 23:38:11 +0000155
Chris Lattner91dbae62004-12-11 05:15:59 +0000156 /// GlobalValue - If we are tracking any values for the contents of a global
157 /// variable, we keep a mapping from the constant accessor to the element of
158 /// the global, to the currently known value. If the value becomes
159 /// overdefined, it's entry is simply removed from this map.
Chris Lattner067d6072007-02-02 20:38:30 +0000160 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattner91dbae62004-12-11 05:15:59 +0000161
Devang Patela7a20752008-03-11 05:46:42 +0000162 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattnerb4394642004-12-10 08:02:06 +0000163 /// value out of a function, it will have an entry in this map, indicating
164 /// what the known return value for the function is.
Devang Patela7a20752008-03-11 05:46:42 +0000165 DenseMap<Function*, LatticeVal> TrackedRetVals;
166
167 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
168 /// that return multiple values.
169 std::multimap<Function*, LatticeValIndexed> TrackedMultipleRetVals;
Chris Lattnerb4394642004-12-10 08:02:06 +0000170
Chris Lattnerd79334d2004-07-15 23:36:43 +0000171 // The reason for two worklists is that overdefined is the lowest state
172 // on the lattice, and moving things to overdefined as fast as possible
173 // makes SCCP converge much faster.
174 // By having a separate worklist, we accomplish this because everything
175 // possibly overdefined will become overdefined at the soonest possible
176 // point.
Chris Lattnerb4394642004-12-10 08:02:06 +0000177 std::vector<Value*> OverdefinedInstWorkList;
178 std::vector<Value*> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000179
180
Chris Lattner7f74a562002-01-20 22:54:45 +0000181 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000182
Chris Lattner05fe6842004-01-12 03:57:30 +0000183 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
184 /// overdefined, despite the fact that the PHI node is overdefined.
185 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
186
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000187 /// KnownFeasibleEdges - Entries in this set are edges which have already had
188 /// PHI nodes retriggered.
189 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
190 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000191public:
192
Chris Lattner074be1f2004-11-15 04:44:20 +0000193 /// MarkBlockExecutable - This method can be used by clients to mark all of
194 /// the blocks that are known to be intrinsically live in the processed unit.
195 void MarkBlockExecutable(BasicBlock *BB) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000196 DOUT << "Marking Block Executable: " << BB->getName() << "\n";
Chris Lattner074be1f2004-11-15 04:44:20 +0000197 BBExecutable.insert(BB); // Basic block is executable!
198 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner7d325382002-04-29 21:26:08 +0000199 }
200
Chris Lattner91dbae62004-12-11 05:15:59 +0000201 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000202 /// inform the SCCPSolver that it should track loads and stores to the
203 /// specified global variable if it can. This is only legal to call if
204 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000205 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
206 const Type *ElTy = GV->getType()->getElementType();
207 if (ElTy->isFirstClassType()) {
208 LatticeVal &IV = TrackedGlobals[GV];
209 if (!isa<UndefValue>(GV->getInitializer()))
210 IV.markConstant(GV->getInitializer());
211 }
212 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000213
214 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
215 /// and out of the specified function (which cannot have its address taken),
216 /// this method must be called.
217 void AddTrackedFunction(Function *F) {
218 assert(F->hasInternalLinkage() && "Can only track internal functions!");
219 // Add an entry, F -> undef.
Devang Patela7a20752008-03-11 05:46:42 +0000220 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
221 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
222 TrackedMultipleRetVals.insert(std::pair<Function *, LatticeValIndexed>
223 (F, LatticeValIndexed(i)));
224 }
225 else
226 TrackedRetVals[F];
Chris Lattnerb4394642004-12-10 08:02:06 +0000227 }
228
Chris Lattner074be1f2004-11-15 04:44:20 +0000229 /// Solve - Solve for constants and executable blocks.
230 ///
231 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000232
Chris Lattner1847f6d2006-12-20 06:21:33 +0000233 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000234 /// that branches on undef values cannot reach any of their successors.
235 /// However, this is not a safe assumption. After we solve dataflow, this
236 /// method should be use to handle this. If this returns true, the solver
237 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000238 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000239
Chris Lattner074be1f2004-11-15 04:44:20 +0000240 /// getExecutableBlocks - Once we have solved for constants, return the set of
241 /// blocks that is known to be executable.
Chris Lattner3e667f32007-02-02 20:57:39 +0000242 SmallSet<BasicBlock*, 16> &getExecutableBlocks() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000243 return BBExecutable;
244 }
245
246 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattner4f031622004-11-15 05:03:30 +0000247 /// LLVM values to LatticeVals.
Chris Lattnerfc8190d2007-02-02 22:36:16 +0000248 std::map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000249 return ValueState;
250 }
251
Devang Patela7a20752008-03-11 05:46:42 +0000252 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner99e12952004-12-11 02:53:57 +0000253 ///
Devang Patela7a20752008-03-11 05:46:42 +0000254 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
255 return TrackedRetVals;
Chris Lattner99e12952004-12-11 02:53:57 +0000256 }
257
Chris Lattner91dbae62004-12-11 05:15:59 +0000258 /// getTrackedGlobals - Get and return the set of inferred initializers for
259 /// global variables.
Chris Lattner067d6072007-02-02 20:38:30 +0000260 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattner91dbae62004-12-11 05:15:59 +0000261 return TrackedGlobals;
262 }
263
Chris Lattnerc33fd462007-03-04 04:50:21 +0000264 inline void markOverdefined(Value *V) {
265 markOverdefined(ValueState[V], V);
266 }
Chris Lattner99e12952004-12-11 02:53:57 +0000267
Chris Lattner347389d2001-06-27 23:38:11 +0000268private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000269 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000270 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000271 // the users of the instruction are updated later.
272 //
Chris Lattnerb4394642004-12-10 08:02:06 +0000273 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000274 if (IV.markConstant(C)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000275 DOUT << "markConstant: " << *C << ": " << *V;
Chris Lattnerb4394642004-12-10 08:02:06 +0000276 InstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000277 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000278 }
Chris Lattner1847f6d2006-12-20 06:21:33 +0000279
280 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
281 IV.markForcedConstant(C);
282 DOUT << "markForcedConstant: " << *C << ": " << *V;
283 InstWorkList.push_back(V);
284 }
285
Chris Lattnerb4394642004-12-10 08:02:06 +0000286 inline void markConstant(Value *V, Constant *C) {
287 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000288 }
289
Chris Lattnerd79334d2004-07-15 23:36:43 +0000290 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000291 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000292 // work list so that the users of the instruction are updated later.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000293
Chris Lattnerb4394642004-12-10 08:02:06 +0000294 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000295 if (IV.markOverdefined()) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000296 DEBUG(DOUT << "markOverdefined: ";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000297 if (Function *F = dyn_cast<Function>(V))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000298 DOUT << "Function '" << F->getName() << "'\n";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000299 else
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000300 DOUT << *V);
Chris Lattner074be1f2004-11-15 04:44:20 +0000301 // Only instructions go on the work list
Chris Lattnerb4394642004-12-10 08:02:06 +0000302 OverdefinedInstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000303 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000304 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000305
306 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
307 if (IV.isOverdefined() || MergeWithV.isUndefined())
308 return; // Noop.
309 if (MergeWithV.isOverdefined())
310 markOverdefined(IV, V);
311 else if (IV.isUndefined())
312 markConstant(IV, V, MergeWithV.getConstant());
313 else if (IV.getConstant() != MergeWithV.getConstant())
314 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000315 }
Chris Lattner06a0ed12006-02-08 02:38:11 +0000316
317 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
318 return mergeInValue(ValueState[V], V, MergeWithV);
319 }
320
Chris Lattner347389d2001-06-27 23:38:11 +0000321
Chris Lattner4f031622004-11-15 05:03:30 +0000322 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000323 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000324 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000325 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000326 // Instruction object, then use this accessor to get its value from the map.
327 //
Chris Lattner4f031622004-11-15 05:03:30 +0000328 inline LatticeVal &getValueState(Value *V) {
Chris Lattnerfc8190d2007-02-02 22:36:16 +0000329 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000330 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner646354b2004-10-16 18:09:41 +0000331
Chris Lattner1847f6d2006-12-20 06:21:33 +0000332 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000333 if (isa<UndefValue>(V)) {
334 // Nothing to do, remain undefined.
335 } else {
Chris Lattner067d6072007-02-02 20:38:30 +0000336 LatticeVal &LV = ValueState[C];
337 LV.markConstant(C); // Constants are constant
338 return LV;
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000339 }
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000340 }
Chris Lattner347389d2001-06-27 23:38:11 +0000341 // All others are underdefined by default...
342 return ValueState[V];
343 }
344
Misha Brukmanb1c93172005-04-21 23:48:37 +0000345 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000346 // work list if it is not already executable...
Misha Brukmanb1c93172005-04-21 23:48:37 +0000347 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000348 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
349 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
350 return; // This edge is already known to be executable!
351
352 if (BBExecutable.count(Dest)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000353 DOUT << "Marking Edge Executable: " << Source->getName()
354 << " -> " << Dest->getName() << "\n";
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000355
356 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000357 // feasible that wasn't before. Revisit the PHI nodes in the block
358 // because they have potentially new operands.
Chris Lattnerb4394642004-12-10 08:02:06 +0000359 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
360 visitPHINode(*cast<PHINode>(I));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000361
362 } else {
Chris Lattner074be1f2004-11-15 04:44:20 +0000363 MarkBlockExecutable(Dest);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000364 }
Chris Lattner347389d2001-06-27 23:38:11 +0000365 }
366
Chris Lattner074be1f2004-11-15 04:44:20 +0000367 // getFeasibleSuccessors - Return a vector of booleans to indicate which
368 // successors are reachable from a given terminator instruction.
369 //
Chris Lattner37d400a2007-02-02 21:15:06 +0000370 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner074be1f2004-11-15 04:44:20 +0000371
372 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
373 // block to the 'To' basic block is currently feasible...
374 //
375 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
376
377 // OperandChangedState - This method is invoked on all of the users of an
378 // instruction that was just changed state somehow.... Based on this
379 // information, we need to update the specified user of this instruction.
380 //
381 void OperandChangedState(User *U) {
382 // Only instructions use other variable values!
383 Instruction &I = cast<Instruction>(*U);
384 if (BBExecutable.count(I.getParent())) // Inst is executable?
385 visit(I);
386 }
387
388private:
389 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000390
Misha Brukmanb1c93172005-04-21 23:48:37 +0000391 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000392 // operand made a transition, or the instruction is newly executable. Change
393 // the value type of I to reflect these changes if appropriate.
394 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000395 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000396
397 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000398 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000399 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000400
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000401 void visitCastInst(CastInst &I);
Devang Patela7a20752008-03-11 05:46:42 +0000402 void visitGetResultInst(GetResultInst &GRI);
Chris Lattner59db22d2004-03-12 05:52:44 +0000403 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000404 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000405 void visitCmpInst(CmpInst &I);
Robert Bocchinobd518d12006-01-10 19:05:05 +0000406 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino6dce2502006-01-17 20:06:55 +0000407 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner17bd6052006-04-08 01:19:12 +0000408 void visitShuffleVectorInst(ShuffleVectorInst &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000409
410 // Instructions that cannot be folded away...
Chris Lattner91dbae62004-12-11 05:15:59 +0000411 void visitStoreInst (Instruction &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000412 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000413 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerb4394642004-12-10 08:02:06 +0000414 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
415 void visitInvokeInst (InvokeInst &II) {
416 visitCallSite(CallSite::get(&II));
417 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000418 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000419 void visitCallSite (CallSite CS);
Chris Lattner9c58cf62003-09-08 18:54:55 +0000420 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000421 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000422 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000423 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
424 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000425 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000426
Chris Lattner113f4f42002-06-25 16:13:24 +0000427 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000428 // If a new instruction is added to LLVM that we don't handle...
Bill Wendlingf3baad32006-12-07 01:30:32 +0000429 cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000430 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000431 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000432};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000433
Duncan Sands2be91fc2007-07-20 08:56:21 +0000434} // end anonymous namespace
435
436
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000437// getFeasibleSuccessors - Return a vector of booleans to indicate which
438// successors are reachable from a given terminator instruction.
439//
Chris Lattner074be1f2004-11-15 04:44:20 +0000440void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner37d400a2007-02-02 21:15:06 +0000441 SmallVector<bool, 16> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000442 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000443 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000444 if (BI->isUnconditional()) {
445 Succs[0] = true;
446 } else {
Chris Lattner4f031622004-11-15 05:03:30 +0000447 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000448 if (BCValue.isOverdefined() ||
Reid Spencercddc9df2007-01-12 04:24:46 +0000449 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000450 // Overdefined condition variables, and branches on unfoldable constant
451 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000452 Succs[0] = Succs[1] = true;
453 } else if (BCValue.isConstant()) {
454 // Constant condition variables mean the branch can only go a single way
Zhou Sheng75b871f2007-01-11 12:24:14 +0000455 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000456 }
457 }
Reid Spencerde46e482006-11-02 20:25:50 +0000458 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000459 // Invoke instructions successors are always executable.
460 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000461 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000462 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000463 if (SCValue.isOverdefined() || // Overdefined condition?
464 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000465 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000466 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000467 } else if (SCValue.isConstant()) {
468 Constant *CPV = SCValue.getConstant();
469 // Make sure to skip the "default value" which isn't a value
470 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
471 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
472 Succs[i] = true;
473 return;
474 }
475 }
476
477 // Constant value not equal to any of the branches... must execute
478 // default branch then...
479 Succs[0] = true;
480 }
481 } else {
Chris Lattner37d400a2007-02-02 21:15:06 +0000482 assert(0 && "SCCP: Don't know how to handle this terminator!");
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000483 }
484}
485
486
Chris Lattner13b52e72002-05-02 21:18:01 +0000487// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
488// block to the 'To' basic block is currently feasible...
489//
Chris Lattner074be1f2004-11-15 04:44:20 +0000490bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000491 assert(BBExecutable.count(To) && "Dest should always be alive!");
492
493 // Make sure the source basic block is executable!!
494 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000495
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000496 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000497 TerminatorInst *TI = From->getTerminator();
498 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
499 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000500 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000501 else {
Chris Lattner4f031622004-11-15 05:03:30 +0000502 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000503 if (BCValue.isOverdefined()) {
504 // Overdefined condition variables mean the branch could go either way.
505 return true;
506 } else if (BCValue.isConstant()) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000507 // Not branching on an evaluatable constant?
Chris Lattnerff7434a2007-01-13 00:42:58 +0000508 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
Chris Lattnerfe992d42004-01-12 17:40:36 +0000509
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000510 // Constant condition variables mean the branch can only go a single way
Misha Brukmanb1c93172005-04-21 23:48:37 +0000511 return BI->getSuccessor(BCValue.getConstant() ==
Zhou Sheng75b871f2007-01-11 12:24:14 +0000512 ConstantInt::getFalse()) == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000513 }
514 return false;
515 }
Reid Spencerde46e482006-11-02 20:25:50 +0000516 } else if (isa<InvokeInst>(TI)) {
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000517 // Invoke instructions successors are always executable.
518 return true;
519 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000520 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000521 if (SCValue.isOverdefined()) { // Overdefined condition?
522 // All destinations are executable!
523 return true;
524 } else if (SCValue.isConstant()) {
525 Constant *CPV = SCValue.getConstant();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000526 if (!isa<ConstantInt>(CPV))
527 return true; // not a foldable constant?
528
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000529 // Make sure to skip the "default value" which isn't a value
530 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
531 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
532 return SI->getSuccessor(i) == To;
533
534 // Constant value not equal to any of the branches... must execute
535 // default branch then...
536 return SI->getDefaultDest() == To;
537 }
538 return false;
539 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000540 cerr << "Unknown terminator instruction: " << *TI;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000541 abort();
542 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000543}
Chris Lattner347389d2001-06-27 23:38:11 +0000544
Chris Lattner6e560792002-04-18 15:13:15 +0000545// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000546// operand made a transition, or the instruction is newly executable. Change
547// the value type of I to reflect these changes if appropriate. This method
548// makes sure to do the following actions:
549//
550// 1. If a phi node merges two constants in, and has conflicting value coming
551// from different branches, or if the PHI node merges in an overdefined
552// value, then the PHI node becomes overdefined.
553// 2. If a phi node merges only constants in, and they all agree on value, the
554// PHI node becomes a constant value equal to that.
555// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
556// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
557// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
558// 6. If a conditional branch has a value that is constant, make the selected
559// destination executable
560// 7. If a conditional branch has a value that is overdefined, make all
561// successors executable.
562//
Chris Lattner074be1f2004-11-15 04:44:20 +0000563void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner4f031622004-11-15 05:03:30 +0000564 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000565 if (PNIV.isOverdefined()) {
566 // There may be instructions using this PHI node that are not overdefined
567 // themselves. If so, make sure that they know that the PHI node operand
568 // changed.
569 std::multimap<PHINode*, Instruction*>::iterator I, E;
570 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
571 if (I != E) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000572 SmallVector<Instruction*, 16> Users;
Chris Lattner05fe6842004-01-12 03:57:30 +0000573 for (; I != E; ++I) Users.push_back(I->second);
574 while (!Users.empty()) {
575 visit(Users.back());
576 Users.pop_back();
577 }
578 }
579 return; // Quick exit
580 }
Chris Lattner347389d2001-06-27 23:38:11 +0000581
Chris Lattner7a7b1142004-03-16 19:49:59 +0000582 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
583 // and slow us down a lot. Just mark them overdefined.
584 if (PN.getNumIncomingValues() > 64) {
585 markOverdefined(PNIV, &PN);
586 return;
587 }
588
Chris Lattner6e560792002-04-18 15:13:15 +0000589 // Look at all of the executable operands of the PHI node. If any of them
590 // are overdefined, the PHI becomes overdefined as well. If they are all
591 // constant, and they agree with each other, the PHI becomes the identical
592 // constant. If they are constant and don't agree, the PHI is overdefined.
593 // If there are no executable operands, the PHI remains undefined.
594 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000595 Constant *OperandVal = 0;
596 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000597 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000598 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000599
Chris Lattner113f4f42002-06-25 16:13:24 +0000600 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000601 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000602 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000603 return;
604 }
605
Chris Lattnercccc5c72003-04-25 02:50:03 +0000606 if (OperandVal == 0) { // Grab the first value...
607 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000608 } else { // Another value is being merged in!
609 // There is already a reachable operand. If we conflict with it,
610 // then the PHI node becomes overdefined. If we agree with it, we
611 // can continue on.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000612
Chris Lattner6e560792002-04-18 15:13:15 +0000613 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000614 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000615 // Yes there is. This means the PHI node is not constant.
616 // You must be overdefined poor PHI.
617 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000618 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000619 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000620 }
Chris Lattner347389d2001-06-27 23:38:11 +0000621 }
622 }
Chris Lattner347389d2001-06-27 23:38:11 +0000623 }
624
Chris Lattner6e560792002-04-18 15:13:15 +0000625 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000626 // arguments that agree with each other(and OperandVal is the constant) or
627 // OperandVal is null because there are no defined incoming arguments. If
628 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000629 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000630 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000631 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000632}
633
Chris Lattnerb4394642004-12-10 08:02:06 +0000634void SCCPSolver::visitReturnInst(ReturnInst &I) {
635 if (I.getNumOperands() == 0) return; // Ret void
636
Chris Lattnerb4394642004-12-10 08:02:06 +0000637 Function *F = I.getParent()->getParent();
Devang Patela7a20752008-03-11 05:46:42 +0000638 // If we are tracking the return value of this function, merge it in.
639 if (!F->hasInternalLinkage())
640 return;
641
642 if (!TrackedRetVals.empty()) {
Chris Lattner067d6072007-02-02 20:38:30 +0000643 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patela7a20752008-03-11 05:46:42 +0000644 TrackedRetVals.find(F);
645 if (TFRVI != TrackedRetVals.end() &&
Chris Lattnerb4394642004-12-10 08:02:06 +0000646 !TFRVI->second.isOverdefined()) {
647 LatticeVal &IV = getValueState(I.getOperand(0));
648 mergeInValue(TFRVI->second, F, IV);
Devang Patela7a20752008-03-11 05:46:42 +0000649 return;
650 }
651 }
652
653 // Handle function that returns multiple values.
654 std::multimap<Function*, LatticeValIndexed>::iterator It, E;
655 tie(It, E) = TrackedMultipleRetVals.equal_range(F);
656 if (It != E) {
657 for (; It != E; ++It) {
658 LatticeValIndexed &LV = It->second;
659 unsigned Idx = LV.getIndex();
660 Value *V = I.getOperand(Idx);
661 mergeInValue(LV.getLatticeVal(), V, getValueState(V));
Chris Lattnerb4394642004-12-10 08:02:06 +0000662 }
663 }
664}
665
Chris Lattner074be1f2004-11-15 04:44:20 +0000666void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000667 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000668 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000669
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000670 BasicBlock *BB = TI.getParent();
671
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000672 // Mark all feasible successors executable...
673 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000674 if (SuccFeasible[i])
675 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000676}
677
Chris Lattner074be1f2004-11-15 04:44:20 +0000678void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000679 Value *V = I.getOperand(0);
Chris Lattner4f031622004-11-15 05:03:30 +0000680 LatticeVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000681 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000682 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000683 else if (VState.isConstant()) // Propagate constant value
Reid Spencerb341b082006-12-12 05:05:00 +0000684 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
685 VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000686}
687
Devang Patela7a20752008-03-11 05:46:42 +0000688void SCCPSolver::visitGetResultInst(GetResultInst &GRI) {
689 unsigned Idx = GRI.getIndex();
690 Value *Aggr = GRI.getOperand(0);
691 Function *F = NULL;
692 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
693 F = CI->getCalledFunction();
694 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
695 F = II->getCalledFunction();
696
697 assert (F && "Invalid GetResultInst operands!");
698
699 std::multimap<Function*, LatticeValIndexed>::iterator It, E;
700 tie(It, E) = TrackedMultipleRetVals.equal_range(F);
701 if (It == E)
702 return;
703
704 for (; It != E; ++It) {
705 LatticeValIndexed &LIV = It->second;
706 if (LIV.getIndex() == Idx) {
707 mergeInValue(&GRI, LIV.getLatticeVal());
708 }
709 }
710}
711
Chris Lattner074be1f2004-11-15 04:44:20 +0000712void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000713 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000714 if (CondValue.isUndefined())
715 return;
Reid Spencercddc9df2007-01-12 04:24:46 +0000716 if (CondValue.isConstant()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000717 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencercddc9df2007-01-12 04:24:46 +0000718 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng75b871f2007-01-11 12:24:14 +0000719 : I.getFalseValue()));
Chris Lattner06a0ed12006-02-08 02:38:11 +0000720 return;
721 }
722 }
723
724 // Otherwise, the condition is overdefined or a constant we can't evaluate.
725 // See if we can produce something better than overdefined based on the T/F
726 // value.
727 LatticeVal &TVal = getValueState(I.getTrueValue());
728 LatticeVal &FVal = getValueState(I.getFalseValue());
729
730 // select ?, C, C -> C.
731 if (TVal.isConstant() && FVal.isConstant() &&
732 TVal.getConstant() == FVal.getConstant()) {
733 markConstant(&I, FVal.getConstant());
734 return;
735 }
736
737 if (TVal.isUndefined()) { // select ?, undef, X -> X.
738 mergeInValue(&I, FVal);
739 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
740 mergeInValue(&I, TVal);
741 } else {
742 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000743 }
744}
745
Chris Lattner6e560792002-04-18 15:13:15 +0000746// Handle BinaryOperators and Shift Instructions...
Chris Lattner074be1f2004-11-15 04:44:20 +0000747void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000748 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000749 if (IV.isOverdefined()) return;
750
Chris Lattner4f031622004-11-15 05:03:30 +0000751 LatticeVal &V1State = getValueState(I.getOperand(0));
752 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000753
Chris Lattner6e560792002-04-18 15:13:15 +0000754 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnercbc01612004-12-11 23:15:19 +0000755 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
756 // operand is overdefined.
757 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
758 LatticeVal *NonOverdefVal = 0;
759 if (!V1State.isOverdefined()) {
760 NonOverdefVal = &V1State;
761 } else if (!V2State.isOverdefined()) {
762 NonOverdefVal = &V2State;
763 }
764
765 if (NonOverdefVal) {
766 if (NonOverdefVal->isUndefined()) {
767 // Could annihilate value.
768 if (I.getOpcode() == Instruction::And)
769 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +0000770 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
771 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
Chris Lattner806adaf2007-01-04 02:12:40 +0000772 else
773 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnercbc01612004-12-11 23:15:19 +0000774 return;
775 } else {
776 if (I.getOpcode() == Instruction::And) {
777 if (NonOverdefVal->getConstant()->isNullValue()) {
778 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskeyc4ba9c12007-01-03 00:11:03 +0000779 return; // X and 0 = 0
Chris Lattnercbc01612004-12-11 23:15:19 +0000780 }
781 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000782 if (ConstantInt *CI =
783 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnercbc01612004-12-11 23:15:19 +0000784 if (CI->isAllOnesValue()) {
785 markConstant(IV, &I, NonOverdefVal->getConstant());
786 return; // X or -1 = -1
787 }
788 }
789 }
790 }
791 }
792
793
Chris Lattner05fe6842004-01-12 03:57:30 +0000794 // If both operands are PHI nodes, it is possible that this instruction has
795 // a constant value, despite the fact that the PHI node doesn't. Check for
796 // this condition now.
797 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
798 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
799 if (PN1->getParent() == PN2->getParent()) {
800 // Since the two PHI nodes are in the same basic block, they must have
801 // entries for the same predecessors. Walk the predecessor list, and
802 // if all of the incoming values are constants, and the result of
803 // evaluating this expression with all incoming value pairs is the
804 // same, then this expression is a constant even though the PHI node
805 // is not a constant!
Chris Lattner4f031622004-11-15 05:03:30 +0000806 LatticeVal Result;
Chris Lattner05fe6842004-01-12 03:57:30 +0000807 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000808 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner05fe6842004-01-12 03:57:30 +0000809 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattner4f031622004-11-15 05:03:30 +0000810 LatticeVal &In2 =
811 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner05fe6842004-01-12 03:57:30 +0000812
813 if (In1.isOverdefined() || In2.isOverdefined()) {
814 Result.markOverdefined();
815 break; // Cannot fold this operation over the PHI nodes!
816 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000817 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
818 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000819 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000820 Result.markConstant(V);
821 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000822 Result.markOverdefined();
823 break;
824 }
825 }
826 }
827
828 // If we found a constant value here, then we know the instruction is
829 // constant despite the fact that the PHI nodes are overdefined.
830 if (Result.isConstant()) {
831 markConstant(IV, &I, Result.getConstant());
832 // Remember that this instruction is virtually using the PHI node
833 // operands.
834 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
835 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
836 return;
837 } else if (Result.isUndefined()) {
838 return;
839 }
840
841 // Okay, this really is overdefined now. Since we might have
842 // speculatively thought that this was not overdefined before, and
843 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
844 // make sure to clean out any entries that we put there, for
845 // efficiency.
846 std::multimap<PHINode*, Instruction*>::iterator It, E;
847 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
848 while (It != E) {
849 if (It->second == &I) {
850 UsersOfOverdefinedPHIs.erase(It++);
851 } else
852 ++It;
853 }
854 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
855 while (It != E) {
856 if (It->second == &I) {
857 UsersOfOverdefinedPHIs.erase(It++);
858 } else
859 ++It;
860 }
861 }
862
863 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000864 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000865 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
866 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000867 }
868}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000869
Reid Spencer266e42b2006-12-23 06:05:41 +0000870// Handle ICmpInst instruction...
871void SCCPSolver::visitCmpInst(CmpInst &I) {
872 LatticeVal &IV = ValueState[&I];
873 if (IV.isOverdefined()) return;
874
875 LatticeVal &V1State = getValueState(I.getOperand(0));
876 LatticeVal &V2State = getValueState(I.getOperand(1));
877
878 if (V1State.isOverdefined() || V2State.isOverdefined()) {
879 // If both operands are PHI nodes, it is possible that this instruction has
880 // a constant value, despite the fact that the PHI node doesn't. Check for
881 // this condition now.
882 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
883 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
884 if (PN1->getParent() == PN2->getParent()) {
885 // Since the two PHI nodes are in the same basic block, they must have
886 // entries for the same predecessors. Walk the predecessor list, and
887 // if all of the incoming values are constants, and the result of
888 // evaluating this expression with all incoming value pairs is the
889 // same, then this expression is a constant even though the PHI node
890 // is not a constant!
891 LatticeVal Result;
892 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
893 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
894 BasicBlock *InBlock = PN1->getIncomingBlock(i);
895 LatticeVal &In2 =
896 getValueState(PN2->getIncomingValueForBlock(InBlock));
897
898 if (In1.isOverdefined() || In2.isOverdefined()) {
899 Result.markOverdefined();
900 break; // Cannot fold this operation over the PHI nodes!
901 } else if (In1.isConstant() && In2.isConstant()) {
902 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
903 In1.getConstant(),
904 In2.getConstant());
905 if (Result.isUndefined())
906 Result.markConstant(V);
907 else if (Result.isConstant() && Result.getConstant() != V) {
908 Result.markOverdefined();
909 break;
910 }
911 }
912 }
913
914 // If we found a constant value here, then we know the instruction is
915 // constant despite the fact that the PHI nodes are overdefined.
916 if (Result.isConstant()) {
917 markConstant(IV, &I, Result.getConstant());
918 // Remember that this instruction is virtually using the PHI node
919 // operands.
920 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
921 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
922 return;
923 } else if (Result.isUndefined()) {
924 return;
925 }
926
927 // Okay, this really is overdefined now. Since we might have
928 // speculatively thought that this was not overdefined before, and
929 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
930 // make sure to clean out any entries that we put there, for
931 // efficiency.
932 std::multimap<PHINode*, Instruction*>::iterator It, E;
933 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
934 while (It != E) {
935 if (It->second == &I) {
936 UsersOfOverdefinedPHIs.erase(It++);
937 } else
938 ++It;
939 }
940 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
941 while (It != E) {
942 if (It->second == &I) {
943 UsersOfOverdefinedPHIs.erase(It++);
944 } else
945 ++It;
946 }
947 }
948
949 markOverdefined(IV, &I);
950 } else if (V1State.isConstant() && V2State.isConstant()) {
951 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
952 V1State.getConstant(),
953 V2State.getConstant()));
954 }
955}
956
Robert Bocchinobd518d12006-01-10 19:05:05 +0000957void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000958 // FIXME : SCCP does not handle vectors properly.
959 markOverdefined(&I);
960 return;
961
962#if 0
Robert Bocchinobd518d12006-01-10 19:05:05 +0000963 LatticeVal &ValState = getValueState(I.getOperand(0));
964 LatticeVal &IdxState = getValueState(I.getOperand(1));
965
966 if (ValState.isOverdefined() || IdxState.isOverdefined())
967 markOverdefined(&I);
968 else if(ValState.isConstant() && IdxState.isConstant())
969 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
970 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000971#endif
Robert Bocchinobd518d12006-01-10 19:05:05 +0000972}
973
Robert Bocchino6dce2502006-01-17 20:06:55 +0000974void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000975 // FIXME : SCCP does not handle vectors properly.
976 markOverdefined(&I);
977 return;
978#if 0
Robert Bocchino6dce2502006-01-17 20:06:55 +0000979 LatticeVal &ValState = getValueState(I.getOperand(0));
980 LatticeVal &EltState = getValueState(I.getOperand(1));
981 LatticeVal &IdxState = getValueState(I.getOperand(2));
982
983 if (ValState.isOverdefined() || EltState.isOverdefined() ||
984 IdxState.isOverdefined())
985 markOverdefined(&I);
986 else if(ValState.isConstant() && EltState.isConstant() &&
987 IdxState.isConstant())
988 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
989 EltState.getConstant(),
990 IdxState.getConstant()));
991 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel21efc732006-12-04 23:54:59 +0000992 IdxState.isConstant())
Chris Lattner28d921d2007-04-14 23:32:02 +0000993 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
994 EltState.getConstant(),
995 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000996#endif
Robert Bocchino6dce2502006-01-17 20:06:55 +0000997}
998
Chris Lattner17bd6052006-04-08 01:19:12 +0000999void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +00001000 // FIXME : SCCP does not handle vectors properly.
1001 markOverdefined(&I);
1002 return;
1003#if 0
Chris Lattner17bd6052006-04-08 01:19:12 +00001004 LatticeVal &V1State = getValueState(I.getOperand(0));
1005 LatticeVal &V2State = getValueState(I.getOperand(1));
1006 LatticeVal &MaskState = getValueState(I.getOperand(2));
1007
1008 if (MaskState.isUndefined() ||
1009 (V1State.isUndefined() && V2State.isUndefined()))
1010 return; // Undefined output if mask or both inputs undefined.
1011
1012 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1013 MaskState.isOverdefined()) {
1014 markOverdefined(&I);
1015 } else {
1016 // A mix of constant/undef inputs.
1017 Constant *V1 = V1State.isConstant() ?
1018 V1State.getConstant() : UndefValue::get(I.getType());
1019 Constant *V2 = V2State.isConstant() ?
1020 V2State.getConstant() : UndefValue::get(I.getType());
1021 Constant *Mask = MaskState.isConstant() ?
1022 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1023 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1024 }
Devang Patel21efc732006-12-04 23:54:59 +00001025#endif
Chris Lattner17bd6052006-04-08 01:19:12 +00001026}
1027
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001028// Handle getelementptr instructions... if all operands are constants then we
1029// can turn this into a getelementptr ConstantExpr.
1030//
Chris Lattner074be1f2004-11-15 04:44:20 +00001031void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +00001032 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001033 if (IV.isOverdefined()) return;
1034
Chris Lattner0e7ec672007-02-02 20:51:48 +00001035 SmallVector<Constant*, 8> Operands;
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001036 Operands.reserve(I.getNumOperands());
1037
1038 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +00001039 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001040 if (State.isUndefined())
1041 return; // Operands are not resolved yet...
1042 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +00001043 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001044 return;
1045 }
1046 assert(State.isConstant() && "Unknown state!");
1047 Operands.push_back(State.getConstant());
1048 }
1049
1050 Constant *Ptr = Operands[0];
1051 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1052
Chris Lattner0e7ec672007-02-02 20:51:48 +00001053 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1054 Operands.size()));
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001055}
Brian Gaeke960707c2003-11-11 22:41:34 +00001056
Chris Lattner91dbae62004-12-11 05:15:59 +00001057void SCCPSolver::visitStoreInst(Instruction &SI) {
1058 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1059 return;
1060 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattner067d6072007-02-02 20:38:30 +00001061 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-12-11 05:15:59 +00001062 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1063
1064 // Get the value we are storing into the global.
1065 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1066
1067 mergeInValue(I->second, GV, PtrVal);
1068 if (I->second.isOverdefined())
1069 TrackedGlobals.erase(I); // No need to keep tracking this!
1070}
1071
1072
Chris Lattner49f74522004-01-12 04:29:41 +00001073// Handle load instructions. If the operand is a constant pointer to a constant
1074// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001075void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +00001076 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001077 if (IV.isOverdefined()) return;
1078
Chris Lattner4f031622004-11-15 05:03:30 +00001079 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattner49f74522004-01-12 04:29:41 +00001080 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1081 if (PtrVal.isConstant() && !I.isVolatile()) {
1082 Value *Ptr = PtrVal.getConstant();
Christopher Lambb053b802007-12-29 07:56:53 +00001083 // TODO: Consider a target hook for valid address spaces for this xform.
1084 if (isa<ConstantPointerNull>(Ptr) &&
1085 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner538fee72004-03-07 22:16:24 +00001086 // load null -> null
1087 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1088 return;
1089 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001090
Chris Lattner49f74522004-01-12 04:29:41 +00001091 // Transform load (constant global) into the value loaded.
Chris Lattner91dbae62004-12-11 05:15:59 +00001092 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1093 if (GV->isConstant()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00001094 if (!GV->isDeclaration()) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001095 markConstant(IV, &I, GV->getInitializer());
1096 return;
1097 }
1098 } else if (!TrackedGlobals.empty()) {
1099 // If we are tracking this global, merge in the known value for it.
Chris Lattner067d6072007-02-02 20:38:30 +00001100 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
Chris Lattner91dbae62004-12-11 05:15:59 +00001101 TrackedGlobals.find(GV);
1102 if (It != TrackedGlobals.end()) {
1103 mergeInValue(IV, &I, It->second);
1104 return;
1105 }
Chris Lattner49f74522004-01-12 04:29:41 +00001106 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001107 }
Chris Lattner49f74522004-01-12 04:29:41 +00001108
1109 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1110 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1111 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen82639852005-04-23 21:38:35 +00001112 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00001113 if (GV->isConstant() && !GV->isDeclaration())
Jeff Cohen82639852005-04-23 21:38:35 +00001114 if (Constant *V =
Chris Lattner02ae21e2005-09-26 05:28:52 +00001115 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen82639852005-04-23 21:38:35 +00001116 markConstant(IV, &I, V);
1117 return;
1118 }
Chris Lattner49f74522004-01-12 04:29:41 +00001119 }
1120
1121 // Otherwise we cannot say for certain what value this load will produce.
1122 // Bail out.
1123 markOverdefined(IV, &I);
1124}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001125
Chris Lattnerb4394642004-12-10 08:02:06 +00001126void SCCPSolver::visitCallSite(CallSite CS) {
1127 Function *F = CS.getCalledFunction();
1128
Devang Patela7a20752008-03-11 05:46:42 +00001129 DenseMap<Function*, LatticeVal>::iterator TFRVI =TrackedRetVals.end();
Chris Lattnerb4394642004-12-10 08:02:06 +00001130 // If we are tracking this function, we must make sure to bind arguments as
1131 // appropriate.
Devang Patela7a20752008-03-11 05:46:42 +00001132 bool FirstCall = false;
1133 if (F && F->hasInternalLinkage()) {
1134 TFRVI = TrackedRetVals.find(F);
1135 if (TFRVI != TrackedRetVals.end())
1136 FirstCall = true;
1137 else {
1138 std::multimap<Function*, LatticeValIndexed>::iterator It, E;
1139 tie(It, E) = TrackedMultipleRetVals.equal_range(F);
1140 if (It != E)
1141 FirstCall = true;
1142 }
1143 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001144
Devang Patela7a20752008-03-11 05:46:42 +00001145 if (FirstCall) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001146 // If this is the first call to the function hit, mark its entry block
1147 // executable.
1148 if (!BBExecutable.count(F->begin()))
1149 MarkBlockExecutable(F->begin());
Devang Patela7a20752008-03-11 05:46:42 +00001150
Chris Lattnerb4394642004-12-10 08:02:06 +00001151 CallSite::arg_iterator CAI = CS.arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +00001152 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
Chris Lattnerb4394642004-12-10 08:02:06 +00001153 AI != E; ++AI, ++CAI) {
1154 LatticeVal &IV = ValueState[AI];
1155 if (!IV.isOverdefined())
1156 mergeInValue(IV, AI, getValueState(*CAI));
1157 }
1158 }
1159 Instruction *I = CS.getInstruction();
Nick Lewycky83750d92008-03-09 09:44:38 +00001160
1161 if (!CS.doesNotThrow() && I->getParent()->getUnwindDest())
1162 markEdgeExecutable(I->getParent(), I->getParent()->getUnwindDest());
1163
Chris Lattnerb4394642004-12-10 08:02:06 +00001164 if (I->getType() == Type::VoidTy) return;
1165
1166 LatticeVal &IV = ValueState[I];
Chris Lattnerff9362a2004-04-13 19:43:54 +00001167 if (IV.isOverdefined()) return;
1168
Devang Patela7a20752008-03-11 05:46:42 +00001169 // Propagate the single return value of the function to the value of the
1170 // instruction.
1171 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001172 mergeInValue(IV, I, TFRVI->second);
1173 return;
1174 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001175
Reid Spencer5301e7c2007-01-30 20:08:39 +00001176 if (F == 0 || !F->isDeclaration() || !canConstantFoldCallTo(F)) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001177 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001178 return;
1179 }
1180
Chris Lattner0d74d3c2007-01-30 23:15:19 +00001181 SmallVector<Constant*, 8> Operands;
Chris Lattnerb4394642004-12-10 08:02:06 +00001182 Operands.reserve(I->getNumOperands()-1);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001183
Chris Lattnerb4394642004-12-10 08:02:06 +00001184 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1185 AI != E; ++AI) {
1186 LatticeVal &State = getValueState(*AI);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001187 if (State.isUndefined())
1188 return; // Operands are not resolved yet...
1189 else if (State.isOverdefined()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001190 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001191 return;
1192 }
1193 assert(State.isConstant() && "Unknown state!");
1194 Operands.push_back(State.getConstant());
1195 }
1196
Chris Lattner0d74d3c2007-01-30 23:15:19 +00001197 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size()))
Chris Lattnerb4394642004-12-10 08:02:06 +00001198 markConstant(IV, I, C);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001199 else
Chris Lattnerb4394642004-12-10 08:02:06 +00001200 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001201}
Chris Lattner074be1f2004-11-15 04:44:20 +00001202
1203
1204void SCCPSolver::Solve() {
1205 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001206 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001207 !OverdefinedInstWorkList.empty()) {
Chris Lattner074be1f2004-11-15 04:44:20 +00001208 // Process the instruction work list...
1209 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001210 Value *I = OverdefinedInstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001211 OverdefinedInstWorkList.pop_back();
1212
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001213 DOUT << "\nPopped off OI-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001214
Chris Lattner074be1f2004-11-15 04:44:20 +00001215 // "I" got into the work list because it either made the transition from
1216 // bottom to constant
1217 //
1218 // Anything on this worklist that is overdefined need not be visited
1219 // since all of its users will have already been marked as overdefined
1220 // Update all of the users of this instruction's value...
1221 //
1222 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1223 UI != E; ++UI)
1224 OperandChangedState(*UI);
1225 }
1226 // Process the instruction work list...
1227 while (!InstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001228 Value *I = InstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001229 InstWorkList.pop_back();
1230
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001231 DOUT << "\nPopped off I-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001232
Chris Lattner074be1f2004-11-15 04:44:20 +00001233 // "I" got into the work list because it either made the transition from
1234 // bottom to constant
1235 //
1236 // Anything on this worklist that is overdefined need not be visited
1237 // since all of its users will have already been marked as overdefined.
1238 // Update all of the users of this instruction's value...
1239 //
1240 if (!getValueState(I).isOverdefined())
1241 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1242 UI != E; ++UI)
1243 OperandChangedState(*UI);
1244 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001245
Chris Lattner074be1f2004-11-15 04:44:20 +00001246 // Process the basic block work list...
1247 while (!BBWorkList.empty()) {
1248 BasicBlock *BB = BBWorkList.back();
1249 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001250
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001251 DOUT << "\nPopped off BBWL: " << *BB;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001252
Chris Lattner074be1f2004-11-15 04:44:20 +00001253 // Notify all instructions in this basic block that they are newly
1254 // executable.
1255 visit(BB);
1256 }
1257 }
1258}
1259
Chris Lattner1847f6d2006-12-20 06:21:33 +00001260/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001261/// that branches on undef values cannot reach any of their successors.
1262/// However, this is not a safe assumption. After we solve dataflow, this
1263/// method should be use to handle this. If this returns true, the solver
1264/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001265///
1266/// This method handles this by finding an unresolved branch and marking it one
1267/// of the edges from the block as being feasible, even though the condition
1268/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1269/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001270/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001271/// constraints on the condition of the branch, as that would impact other users
1272/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001273///
1274/// This scan also checks for values that use undefs, whose results are actually
1275/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1276/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1277/// even if X isn't defined.
1278bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattneraf170962006-10-22 05:59:17 +00001279 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1280 if (!BBExecutable.count(BB))
1281 continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001282
1283 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1284 // Look for instructions which produce undef values.
1285 if (I->getType() == Type::VoidTy) continue;
1286
1287 LatticeVal &LV = getValueState(I);
1288 if (!LV.isUndefined()) continue;
1289
1290 // Get the lattice values of the first two operands for use below.
1291 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1292 LatticeVal Op1LV;
1293 if (I->getNumOperands() == 2) {
1294 // If this is a two-operand instruction, and if both operands are
1295 // undefs, the result stays undef.
1296 Op1LV = getValueState(I->getOperand(1));
1297 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1298 continue;
1299 }
1300
1301 // If this is an instructions whose result is defined even if the input is
1302 // not fully defined, propagate the information.
1303 const Type *ITy = I->getType();
1304 switch (I->getOpcode()) {
1305 default: break; // Leave the instruction as an undef.
1306 case Instruction::ZExt:
1307 // After a zero extend, we know the top part is zero. SExt doesn't have
1308 // to be handled here, because we don't know whether the top part is 1's
1309 // or 0's.
1310 assert(Op0LV.isUndefined());
1311 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1312 return true;
1313 case Instruction::Mul:
1314 case Instruction::And:
1315 // undef * X -> 0. X could be zero.
1316 // undef & X -> 0. X could be zero.
1317 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1318 return true;
1319
1320 case Instruction::Or:
1321 // undef | X -> -1. X could be -1.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001322 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1323 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
Chris Lattner806adaf2007-01-04 02:12:40 +00001324 else
1325 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1326 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001327
1328 case Instruction::SDiv:
1329 case Instruction::UDiv:
1330 case Instruction::SRem:
1331 case Instruction::URem:
1332 // X / undef -> undef. No change.
1333 // X % undef -> undef. No change.
1334 if (Op1LV.isUndefined()) break;
1335
1336 // undef / X -> 0. X could be maxint.
1337 // undef % X -> 0. X could be 1.
1338 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1339 return true;
1340
1341 case Instruction::AShr:
1342 // undef >>s X -> undef. No change.
1343 if (Op0LV.isUndefined()) break;
1344
1345 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1346 if (Op0LV.isConstant())
1347 markForcedConstant(LV, I, Op0LV.getConstant());
1348 else
1349 markOverdefined(LV, I);
1350 return true;
1351 case Instruction::LShr:
1352 case Instruction::Shl:
1353 // undef >> X -> undef. No change.
1354 // undef << X -> undef. No change.
1355 if (Op0LV.isUndefined()) break;
1356
1357 // X >> undef -> 0. X could be 0.
1358 // X << undef -> 0. X could be 0.
1359 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1360 return true;
1361 case Instruction::Select:
1362 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1363 if (Op0LV.isUndefined()) {
1364 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1365 Op1LV = getValueState(I->getOperand(2));
1366 } else if (Op1LV.isUndefined()) {
1367 // c ? undef : undef -> undef. No change.
1368 Op1LV = getValueState(I->getOperand(2));
1369 if (Op1LV.isUndefined())
1370 break;
1371 // Otherwise, c ? undef : x -> x.
1372 } else {
1373 // Leave Op1LV as Operand(1)'s LatticeValue.
1374 }
1375
1376 if (Op1LV.isConstant())
1377 markForcedConstant(LV, I, Op1LV.getConstant());
1378 else
1379 markOverdefined(LV, I);
1380 return true;
1381 }
1382 }
Chris Lattneraf170962006-10-22 05:59:17 +00001383
1384 TerminatorInst *TI = BB->getTerminator();
1385 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1386 if (!BI->isConditional()) continue;
1387 if (!getValueState(BI->getCondition()).isUndefined())
1388 continue;
1389 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1390 if (!getValueState(SI->getCondition()).isUndefined())
1391 continue;
1392 } else {
1393 continue;
Chris Lattner7285f432004-12-10 20:41:50 +00001394 }
Chris Lattneraf170962006-10-22 05:59:17 +00001395
Chris Lattner1b706dd2008-01-28 00:32:30 +00001396 // If the edge to the second successor isn't thought to be feasible yet,
1397 // mark it so now. We pick the second one so that this goes to some
1398 // enumerated value in a switch instead of going to the default destination.
1399 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattneraf170962006-10-22 05:59:17 +00001400 continue;
1401
1402 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1403 // and return. This will make other blocks reachable, which will allow new
1404 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner1b706dd2008-01-28 00:32:30 +00001405 markEdgeExecutable(BB, TI->getSuccessor(1));
1406
1407 // This must be a conditional branch of switch on undef. At this point,
1408 // force the old terminator to branch to the first successor. This is
1409 // required because we are now influencing the dataflow of the function with
1410 // the assumption that this edge is taken. If we leave the branch condition
1411 // as undef, then further analysis could think the undef went another way
1412 // leading to an inconsistent set of conclusions.
1413 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1414 BI->setCondition(ConstantInt::getFalse());
1415 } else {
1416 SwitchInst *SI = cast<SwitchInst>(TI);
1417 SI->setCondition(SI->getCaseValue(1));
1418 }
1419
Chris Lattneraf170962006-10-22 05:59:17 +00001420 return true;
1421 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001422
Chris Lattneraf170962006-10-22 05:59:17 +00001423 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001424}
1425
Chris Lattner074be1f2004-11-15 04:44:20 +00001426
1427namespace {
Chris Lattner1890f942004-11-15 07:15:04 +00001428 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +00001429 //
Chris Lattner1890f942004-11-15 07:15:04 +00001430 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spencere8a74ee2006-12-31 22:26:06 +00001431 /// Sparse Conditional Constant Propagator.
Chris Lattner1890f942004-11-15 07:15:04 +00001432 ///
Reid Spencer557ab152007-02-05 23:32:05 +00001433 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +00001434 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +00001435 SCCP() : FunctionPass((intptr_t)&ID) {}
1436
Chris Lattner1890f942004-11-15 07:15:04 +00001437 // runOnFunction - Run the Sparse Conditional Constant Propagation
1438 // algorithm, and return true if the function was modified.
1439 //
1440 bool runOnFunction(Function &F);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001441
Chris Lattner1890f942004-11-15 07:15:04 +00001442 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1443 AU.setPreservesCFG();
1444 }
1445 };
Chris Lattner074be1f2004-11-15 04:44:20 +00001446
Devang Patel8c78a0b2007-05-03 01:11:54 +00001447 char SCCP::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001448 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner074be1f2004-11-15 04:44:20 +00001449} // end anonymous namespace
1450
1451
1452// createSCCPPass - This is the public interface to this file...
1453FunctionPass *llvm::createSCCPPass() {
1454 return new SCCP();
1455}
1456
1457
Chris Lattner074be1f2004-11-15 04:44:20 +00001458// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1459// and return true if the function was modified.
1460//
1461bool SCCP::runOnFunction(Function &F) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001462 DOUT << "SCCP on function '" << F.getName() << "'\n";
Chris Lattner074be1f2004-11-15 04:44:20 +00001463 SCCPSolver Solver;
1464
1465 // Mark the first block of the function as being executable.
1466 Solver.MarkBlockExecutable(F.begin());
1467
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001468 // Mark all arguments to the function as being overdefined.
Chris Lattner28d921d2007-04-14 23:32:02 +00001469 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattnerc33fd462007-03-04 04:50:21 +00001470 Solver.markOverdefined(AI);
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001471
Chris Lattner074be1f2004-11-15 04:44:20 +00001472 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001473 bool ResolvedUndefs = true;
1474 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001475 Solver.Solve();
Chris Lattner1847f6d2006-12-20 06:21:33 +00001476 DOUT << "RESOLVING UNDEFs\n";
1477 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001478 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001479
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001480 bool MadeChanges = false;
1481
1482 // If we decided that there are basic blocks that are dead in this function,
1483 // delete their contents now. Note that we cannot actually delete the blocks,
1484 // as we cannot modify the CFG of the function.
1485 //
Chris Lattner3e667f32007-02-02 20:57:39 +00001486 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
Chris Lattner37d400a2007-02-02 21:15:06 +00001487 SmallVector<Instruction*, 32> Insts;
Chris Lattnerc33fd462007-03-04 04:50:21 +00001488 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1489
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001490 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1491 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001492 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattner9a038a32004-11-15 07:02:42 +00001493 ++NumDeadBlocks;
1494
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001495 // Delete the instructions backwards, as it has a reduced likelihood of
1496 // having to update as many def-use and use-def chains.
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001497 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1498 I != E; ++I)
1499 Insts.push_back(I);
1500 while (!Insts.empty()) {
1501 Instruction *I = Insts.back();
1502 Insts.pop_back();
1503 if (!I->use_empty())
1504 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1505 BB->getInstList().erase(I);
1506 MadeChanges = true;
Chris Lattner9a038a32004-11-15 07:02:42 +00001507 ++NumInstRemoved;
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001508 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001509 } else {
1510 // Iterate over all of the instructions in a function, replacing them with
1511 // constants if we have found them to be of constant values.
1512 //
1513 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1514 Instruction *Inst = BI++;
1515 if (Inst->getType() != Type::VoidTy) {
1516 LatticeVal &IV = Values[Inst];
Devang Patel2c30a372007-05-17 22:10:15 +00001517 if ((IV.isConstant() || IV.isUndefined()) &&
Chris Lattnerb4394642004-12-10 08:02:06 +00001518 !isa<TerminatorInst>(Inst)) {
1519 Constant *Const = IV.isConstant()
1520 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001521 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001522
Chris Lattnerb4394642004-12-10 08:02:06 +00001523 // Replaces all of the uses of a variable with uses of the constant.
1524 Inst->replaceAllUsesWith(Const);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001525
Chris Lattnerb4394642004-12-10 08:02:06 +00001526 // Delete the instruction.
1527 BB->getInstList().erase(Inst);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001528
Chris Lattnerb4394642004-12-10 08:02:06 +00001529 // Hey, we just changed something!
1530 MadeChanges = true;
1531 ++NumInstRemoved;
Chris Lattner074be1f2004-11-15 04:44:20 +00001532 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001533 }
1534 }
1535 }
1536
1537 return MadeChanges;
1538}
Chris Lattnerb4394642004-12-10 08:02:06 +00001539
1540namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +00001541 //===--------------------------------------------------------------------===//
1542 //
1543 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1544 /// Constant Propagation.
1545 ///
Reid Spencer557ab152007-02-05 23:32:05 +00001546 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
Devang Patel8c78a0b2007-05-03 01:11:54 +00001547 static char ID;
Devang Patel09f162c2007-05-01 21:15:47 +00001548 IPSCCP() : ModulePass((intptr_t)&ID) {}
Chris Lattnerb4394642004-12-10 08:02:06 +00001549 bool runOnModule(Module &M);
1550 };
1551
Devang Patel8c78a0b2007-05-03 01:11:54 +00001552 char IPSCCP::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001553 RegisterPass<IPSCCP>
Chris Lattnerb4394642004-12-10 08:02:06 +00001554 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1555} // end anonymous namespace
1556
1557// createIPSCCPPass - This is the public interface to this file...
1558ModulePass *llvm::createIPSCCPPass() {
1559 return new IPSCCP();
1560}
1561
1562
1563static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001564 // Delete any dead constantexpr klingons.
1565 GV->removeDeadConstantUsers();
1566
Chris Lattnerb4394642004-12-10 08:02:06 +00001567 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1568 UI != E; ++UI)
1569 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001570 if (SI->getOperand(0) == GV || SI->isVolatile())
1571 return true; // Storing addr of GV.
Chris Lattnerb4394642004-12-10 08:02:06 +00001572 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1573 // Make sure we are calling the function, not passing the address.
1574 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1575 for (CallSite::arg_iterator AI = CS.arg_begin(),
1576 E = CS.arg_end(); AI != E; ++AI)
1577 if (*AI == GV)
1578 return true;
Chris Lattner91dbae62004-12-11 05:15:59 +00001579 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1580 if (LI->isVolatile())
1581 return true;
1582 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001583 return true;
1584 }
1585 return false;
1586}
1587
1588bool IPSCCP::runOnModule(Module &M) {
1589 SCCPSolver Solver;
1590
1591 // Loop over all functions, marking arguments to those with their addresses
1592 // taken or that are external as overdefined.
1593 //
Chris Lattnerb4394642004-12-10 08:02:06 +00001594 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1595 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00001596 if (!F->isDeclaration())
Chris Lattnerb4394642004-12-10 08:02:06 +00001597 Solver.MarkBlockExecutable(F->begin());
Chris Lattner8cb10a12005-04-19 19:16:19 +00001598 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1599 AI != E; ++AI)
Chris Lattnerc33fd462007-03-04 04:50:21 +00001600 Solver.markOverdefined(AI);
Chris Lattnerb4394642004-12-10 08:02:06 +00001601 } else {
1602 Solver.AddTrackedFunction(F);
1603 }
1604
Chris Lattner91dbae62004-12-11 05:15:59 +00001605 // Loop over global variables. We inform the solver about any internal global
1606 // variables that do not have their 'addresses taken'. If they don't have
1607 // their addresses taken, we can propagate constants through them.
Chris Lattner8cb10a12005-04-19 19:16:19 +00001608 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1609 G != E; ++G)
Chris Lattner91dbae62004-12-11 05:15:59 +00001610 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1611 Solver.TrackValueOfGlobalVariable(G);
1612
Chris Lattnerb4394642004-12-10 08:02:06 +00001613 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001614 bool ResolvedUndefs = true;
1615 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001616 Solver.Solve();
1617
Chris Lattner1847f6d2006-12-20 06:21:33 +00001618 DOUT << "RESOLVING UNDEFS\n";
1619 ResolvedUndefs = false;
Chris Lattner7285f432004-12-10 20:41:50 +00001620 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner1847f6d2006-12-20 06:21:33 +00001621 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattner7285f432004-12-10 20:41:50 +00001622 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001623
1624 bool MadeChanges = false;
1625
1626 // Iterate over all of the instructions in the module, replacing them with
1627 // constants if we have found them to be of constant values.
1628 //
Chris Lattner3e667f32007-02-02 20:57:39 +00001629 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
Chris Lattner37d400a2007-02-02 21:15:06 +00001630 SmallVector<Instruction*, 32> Insts;
1631 SmallVector<BasicBlock*, 32> BlocksToErase;
Chris Lattnerc33fd462007-03-04 04:50:21 +00001632 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner37d400a2007-02-02 21:15:06 +00001633
Chris Lattnerb4394642004-12-10 08:02:06 +00001634 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001635 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1636 AI != E; ++AI)
Chris Lattnerb4394642004-12-10 08:02:06 +00001637 if (!AI->use_empty()) {
1638 LatticeVal &IV = Values[AI];
1639 if (IV.isConstant() || IV.isUndefined()) {
1640 Constant *CST = IV.isConstant() ?
1641 IV.getConstant() : UndefValue::get(AI->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001642 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
Misha Brukmanb1c93172005-04-21 23:48:37 +00001643
Chris Lattnerb4394642004-12-10 08:02:06 +00001644 // Replaces all of the uses of a variable with uses of the
1645 // constant.
1646 AI->replaceAllUsesWith(CST);
1647 ++IPNumArgsElimed;
1648 }
1649 }
1650
1651 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1652 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001653 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattnerb4394642004-12-10 08:02:06 +00001654 ++IPNumDeadBlocks;
Chris Lattner7285f432004-12-10 20:41:50 +00001655
Chris Lattnerb4394642004-12-10 08:02:06 +00001656 // Delete the instructions backwards, as it has a reduced likelihood of
1657 // having to update as many def-use and use-def chains.
Chris Lattnerbae4b642004-12-10 22:29:08 +00001658 TerminatorInst *TI = BB->getTerminator();
1659 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattnerb4394642004-12-10 08:02:06 +00001660 Insts.push_back(I);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001661
Chris Lattnerb4394642004-12-10 08:02:06 +00001662 while (!Insts.empty()) {
1663 Instruction *I = Insts.back();
1664 Insts.pop_back();
1665 if (!I->use_empty())
1666 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1667 BB->getInstList().erase(I);
1668 MadeChanges = true;
1669 ++IPNumInstRemoved;
1670 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001671
Chris Lattnerbae4b642004-12-10 22:29:08 +00001672 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1673 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmanc731c972007-10-03 19:26:29 +00001674 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattnerbae4b642004-12-10 22:29:08 +00001675 TI->getSuccessor(i)->removePredecessor(BB);
1676 }
Chris Lattner99e12952004-12-11 02:53:57 +00001677 if (!TI->use_empty())
1678 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnerbae4b642004-12-10 22:29:08 +00001679 BB->getInstList().erase(TI);
1680
Chris Lattner8525ebe2004-12-11 05:32:19 +00001681 if (&*BB != &F->front())
1682 BlocksToErase.push_back(BB);
1683 else
1684 new UnreachableInst(BB);
1685
Chris Lattnerb4394642004-12-10 08:02:06 +00001686 } else {
1687 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1688 Instruction *Inst = BI++;
1689 if (Inst->getType() != Type::VoidTy) {
1690 LatticeVal &IV = Values[Inst];
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00001691 if (IV.isConstant() ||
1692 (IV.isUndefined() && !isa<TerminatorInst>(Inst))) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001693 Constant *Const = IV.isConstant()
1694 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001695 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001696
Chris Lattnerb4394642004-12-10 08:02:06 +00001697 // Replaces all of the uses of a variable with uses of the
1698 // constant.
1699 Inst->replaceAllUsesWith(Const);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001700
Chris Lattnerb4394642004-12-10 08:02:06 +00001701 // Delete the instruction.
1702 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1703 BB->getInstList().erase(Inst);
1704
1705 // Hey, we just changed something!
1706 MadeChanges = true;
1707 ++IPNumInstRemoved;
1708 }
1709 }
1710 }
1711 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001712
1713 // Now that all instructions in the function are constant folded, erase dead
1714 // blocks, because we can now use ConstantFoldTerminator to get rid of
1715 // in-edges.
1716 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1717 // If there are any PHI nodes in this successor, drop entries for BB now.
1718 BasicBlock *DeadBB = BlocksToErase[i];
1719 while (!DeadBB->use_empty()) {
Nick Lewycky35e92c72008-03-08 07:48:41 +00001720 if (BasicBlock *PredBB = dyn_cast<BasicBlock>(DeadBB->use_back())) {
1721 PredBB->setUnwindDest(NULL);
1722 continue;
1723 }
1724
Chris Lattnerbae4b642004-12-10 22:29:08 +00001725 Instruction *I = cast<Instruction>(DeadBB->use_back());
1726 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001727 if (!Folded) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001728 // The constant folder may not have been able to fold the terminator
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001729 // if this is a branch or switch on undef. Fold it manually as a
1730 // branch to the first successor.
1731 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1732 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1733 "Branch should be foldable!");
1734 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1735 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1736 } else {
1737 assert(0 && "Didn't fold away reference to block!");
1738 }
1739
1740 // Make this an uncond branch to the first successor.
1741 TerminatorInst *TI = I->getParent()->getTerminator();
1742 new BranchInst(TI->getSuccessor(0), TI);
1743
1744 // Remove entries in successor phi nodes to remove edges.
1745 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1746 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1747
1748 // Remove the old terminator.
1749 TI->eraseFromParent();
1750 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001751 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001752
Chris Lattnerbae4b642004-12-10 22:29:08 +00001753 // Finally, delete the basic block.
1754 F->getBasicBlockList().erase(DeadBB);
1755 }
Chris Lattner37d400a2007-02-02 21:15:06 +00001756 BlocksToErase.clear();
Chris Lattnerb4394642004-12-10 08:02:06 +00001757 }
Chris Lattner99e12952004-12-11 02:53:57 +00001758
1759 // If we inferred constant or undef return values for a function, we replaced
1760 // all call uses with the inferred value. This means we don't need to bother
1761 // actually returning anything from the function. Replace all return
1762 // instructions with return undef.
Devang Patele418de32008-03-11 17:32:05 +00001763 // TODO: Process multiple value ret instructions also.
Devang Patela7a20752008-03-11 05:46:42 +00001764 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattner067d6072007-02-02 20:38:30 +00001765 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner99e12952004-12-11 02:53:57 +00001766 E = RV.end(); I != E; ++I)
1767 if (!I->second.isOverdefined() &&
1768 I->first->getReturnType() != Type::VoidTy) {
1769 Function *F = I->first;
1770 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1771 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1772 if (!isa<UndefValue>(RI->getOperand(0)))
1773 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1774 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001775
1776 // If we infered constant or undef values for globals variables, we can delete
1777 // the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00001778 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1779 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00001780 E = TG.end(); I != E; ++I) {
1781 GlobalVariable *GV = I->first;
1782 assert(!I->second.isOverdefined() &&
1783 "Overdefined values should have been taken out of the map!");
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001784 DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
Chris Lattner91dbae62004-12-11 05:15:59 +00001785 while (!GV->use_empty()) {
1786 StoreInst *SI = cast<StoreInst>(GV->use_back());
1787 SI->eraseFromParent();
1788 }
1789 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00001790 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00001791 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001792
Chris Lattnerb4394642004-12-10 08:02:06 +00001793 return MadeChanges;
1794}