blob: 8c64d8ff7c98f7ad887a9e9a62b92b62bbe8d778 [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"
Dan Gohman041f9d02008-06-20 01:15:44 +000032#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerff9362a2004-04-13 19:43:54 +000033#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerb4394642004-12-10 08:02:06 +000034#include "llvm/Support/CallSite.h"
Reid Spencer557ab152007-02-05 23:32:05 +000035#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000036#include "llvm/Support/Debug.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000037#include "llvm/Support/InstVisitor.h"
Chris Lattner067d6072007-02-02 20:38:30 +000038#include "llvm/ADT/DenseMap.h"
Chris Lattner3e667f32007-02-02 20:57:39 +000039#include "llvm/ADT/SmallSet.h"
Chris Lattner0d74d3c2007-01-30 23:15:19 +000040#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000041#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/STLExtras.h"
Chris Lattner347389d2001-06-27 23:38:11 +000043#include <algorithm>
Dan Gohman99885692008-03-21 23:51:57 +000044#include <map>
Chris Lattner49525f82004-01-09 06:02:20 +000045using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000046
Chris Lattner79a42ac2006-12-19 21:40:18 +000047STATISTIC(NumInstRemoved, "Number of instructions removed");
48STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49
Nick Lewycky35e92c72008-03-08 07:48:41 +000050STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner79a42ac2006-12-19 21:40:18 +000051STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
52STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
53STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
54
Chris Lattner7d325382002-04-29 21:26:08 +000055namespace {
Chris Lattner1847f6d2006-12-20 06:21:33 +000056/// LatticeVal class - This class represents the different lattice values that
57/// an LLVM value may occupy. It is a simple class with value semantics.
58///
Reid Spencer557ab152007-02-05 23:32:05 +000059class VISIBILITY_HIDDEN LatticeVal {
Misha Brukmanb1c93172005-04-21 23:48:37 +000060 enum {
Chris Lattner1847f6d2006-12-20 06:21:33 +000061 /// undefined - This LLVM Value has no known value yet.
62 undefined,
63
64 /// constant - This LLVM Value has a specific constant value.
65 constant,
66
67 /// forcedconstant - This LLVM Value was thought to be undef until
68 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
69 /// with another (different) constant, it goes to overdefined, instead of
70 /// asserting.
71 forcedconstant,
72
73 /// overdefined - This instruction is not known to be constant, and we know
74 /// it has a value.
75 overdefined
76 } LatticeValue; // The current lattice position
77
Chris Lattner3462ae32001-12-03 22:26:30 +000078 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000079public:
Chris Lattner4f031622004-11-15 05:03:30 +000080 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner1847f6d2006-12-20 06:21:33 +000081
Chris Lattner347389d2001-06-27 23:38:11 +000082 // markOverdefined - Return true if this is a new status to be in...
83 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000084 if (LatticeValue != overdefined) {
85 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000086 return true;
87 }
88 return false;
89 }
90
Chris Lattner1847f6d2006-12-20 06:21:33 +000091 // markConstant - Return true if this is a new status for us.
Chris Lattner3462ae32001-12-03 22:26:30 +000092 inline bool markConstant(Constant *V) {
93 if (LatticeValue != constant) {
Chris Lattner1847f6d2006-12-20 06:21:33 +000094 if (LatticeValue == undefined) {
95 LatticeValue = constant;
Jim Laskeyc4ba9c12007-01-03 00:11:03 +000096 assert(V && "Marking constant with NULL");
Chris Lattner1847f6d2006-12-20 06:21:33 +000097 ConstantVal = V;
98 } else {
99 assert(LatticeValue == forcedconstant &&
100 "Cannot move from overdefined to constant!");
101 // Stay at forcedconstant if the constant is the same.
102 if (V == ConstantVal) return false;
103
104 // Otherwise, we go to overdefined. Assumptions made based on the
105 // forced value are possibly wrong. Assuming this is another constant
106 // could expose a contradiction.
107 LatticeValue = overdefined;
108 }
Chris Lattner347389d2001-06-27 23:38:11 +0000109 return true;
110 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +0000111 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +0000112 }
113 return false;
114 }
115
Chris Lattner1847f6d2006-12-20 06:21:33 +0000116 inline void markForcedConstant(Constant *V) {
117 assert(LatticeValue == undefined && "Can't force a defined value!");
118 LatticeValue = forcedconstant;
119 ConstantVal = V;
120 }
121
122 inline bool isUndefined() const { return LatticeValue == undefined; }
123 inline bool isConstant() const {
124 return LatticeValue == constant || LatticeValue == forcedconstant;
125 }
Chris Lattner3462ae32001-12-03 22:26:30 +0000126 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +0000127
Chris Lattner05fe6842004-01-12 03:57:30 +0000128 inline Constant *getConstant() const {
129 assert(isConstant() && "Cannot get the constant of a non-constant!");
130 return ConstantVal;
131 }
Chris Lattner347389d2001-06-27 23:38:11 +0000132};
133
Chris Lattner347389d2001-06-27 23:38:11 +0000134//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000135//
Chris Lattner074be1f2004-11-15 04:44:20 +0000136/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
137/// Constant Propagation.
138///
139class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner3e667f32007-02-02 20:57:39 +0000140 SmallSet<BasicBlock*, 16> BBExecutable;// The basic blocks that are executable
Bill Wendling861bec72008-08-14 23:05:24 +0000141 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner347389d2001-06-27 23:38:11 +0000142
Chris Lattner91dbae62004-12-11 05:15:59 +0000143 /// GlobalValue - If we are tracking any values for the contents of a global
144 /// variable, we keep a mapping from the constant accessor to the element of
145 /// the global, to the currently known value. If the value becomes
146 /// overdefined, it's entry is simply removed from this map.
Chris Lattner067d6072007-02-02 20:38:30 +0000147 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattner91dbae62004-12-11 05:15:59 +0000148
Devang Patela7a20752008-03-11 05:46:42 +0000149 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattnerb4394642004-12-10 08:02:06 +0000150 /// value out of a function, it will have an entry in this map, indicating
151 /// what the known return value for the function is.
Devang Patela7a20752008-03-11 05:46:42 +0000152 DenseMap<Function*, LatticeVal> TrackedRetVals;
153
154 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
155 /// that return multiple values.
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000156 std::map<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattnerb4394642004-12-10 08:02:06 +0000157
Chris Lattnerd79334d2004-07-15 23:36:43 +0000158 // The reason for two worklists is that overdefined is the lowest state
159 // on the lattice, and moving things to overdefined as fast as possible
160 // makes SCCP converge much faster.
161 // By having a separate worklist, we accomplish this because everything
162 // possibly overdefined will become overdefined at the soonest possible
163 // point.
Chris Lattnerb4394642004-12-10 08:02:06 +0000164 std::vector<Value*> OverdefinedInstWorkList;
165 std::vector<Value*> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000166
167
Chris Lattner7f74a562002-01-20 22:54:45 +0000168 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000169
Chris Lattner05fe6842004-01-12 03:57:30 +0000170 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
171 /// overdefined, despite the fact that the PHI node is overdefined.
172 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
173
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000174 /// KnownFeasibleEdges - Entries in this set are edges which have already had
175 /// PHI nodes retriggered.
176 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
177 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000178public:
179
Chris Lattner074be1f2004-11-15 04:44:20 +0000180 /// MarkBlockExecutable - This method can be used by clients to mark all of
181 /// the blocks that are known to be intrinsically live in the processed unit.
182 void MarkBlockExecutable(BasicBlock *BB) {
Chris Lattner47fed6152008-05-11 01:55:59 +0000183 DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n";
Chris Lattner074be1f2004-11-15 04:44:20 +0000184 BBExecutable.insert(BB); // Basic block is executable!
185 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner7d325382002-04-29 21:26:08 +0000186 }
187
Chris Lattner91dbae62004-12-11 05:15:59 +0000188 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000189 /// inform the SCCPSolver that it should track loads and stores to the
190 /// specified global variable if it can. This is only legal to call if
191 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000192 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
193 const Type *ElTy = GV->getType()->getElementType();
194 if (ElTy->isFirstClassType()) {
195 LatticeVal &IV = TrackedGlobals[GV];
196 if (!isa<UndefValue>(GV->getInitializer()))
197 IV.markConstant(GV->getInitializer());
198 }
199 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000200
201 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
202 /// and out of the specified function (which cannot have its address taken),
203 /// this method must be called.
204 void AddTrackedFunction(Function *F) {
205 assert(F->hasInternalLinkage() && "Can only track internal functions!");
206 // Add an entry, F -> undef.
Devang Patela7a20752008-03-11 05:46:42 +0000207 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
208 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000209 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
210 LatticeVal()));
211 } else
212 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattnerb4394642004-12-10 08:02:06 +0000213 }
214
Chris Lattner074be1f2004-11-15 04:44:20 +0000215 /// Solve - Solve for constants and executable blocks.
216 ///
217 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000218
Chris Lattner1847f6d2006-12-20 06:21:33 +0000219 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000220 /// that branches on undef values cannot reach any of their successors.
221 /// However, this is not a safe assumption. After we solve dataflow, this
222 /// method should be use to handle this. If this returns true, the solver
223 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000224 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000225
Chris Lattner074be1f2004-11-15 04:44:20 +0000226 /// getExecutableBlocks - Once we have solved for constants, return the set of
227 /// blocks that is known to be executable.
Chris Lattner3e667f32007-02-02 20:57:39 +0000228 SmallSet<BasicBlock*, 16> &getExecutableBlocks() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000229 return BBExecutable;
230 }
231
232 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattner4f031622004-11-15 05:03:30 +0000233 /// LLVM values to LatticeVals.
Bill Wendling861bec72008-08-14 23:05:24 +0000234 std::map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000235 return ValueState;
236 }
237
Devang Patela7a20752008-03-11 05:46:42 +0000238 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner99e12952004-12-11 02:53:57 +0000239 ///
Devang Patela7a20752008-03-11 05:46:42 +0000240 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
241 return TrackedRetVals;
Chris Lattner99e12952004-12-11 02:53:57 +0000242 }
243
Chris Lattner91dbae62004-12-11 05:15:59 +0000244 /// getTrackedGlobals - Get and return the set of inferred initializers for
245 /// global variables.
Chris Lattner067d6072007-02-02 20:38:30 +0000246 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattner91dbae62004-12-11 05:15:59 +0000247 return TrackedGlobals;
248 }
249
Chris Lattnerc33fd462007-03-04 04:50:21 +0000250 inline void markOverdefined(Value *V) {
251 markOverdefined(ValueState[V], V);
252 }
Chris Lattner99e12952004-12-11 02:53:57 +0000253
Chris Lattner347389d2001-06-27 23:38:11 +0000254private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000255 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000256 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000257 // the users of the instruction are updated later.
258 //
Chris Lattnerb4394642004-12-10 08:02:06 +0000259 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000260 if (IV.markConstant(C)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000261 DOUT << "markConstant: " << *C << ": " << *V;
Chris Lattnerb4394642004-12-10 08:02:06 +0000262 InstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000263 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000264 }
Chris Lattner1847f6d2006-12-20 06:21:33 +0000265
266 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
267 IV.markForcedConstant(C);
268 DOUT << "markForcedConstant: " << *C << ": " << *V;
269 InstWorkList.push_back(V);
270 }
271
Chris Lattnerb4394642004-12-10 08:02:06 +0000272 inline void markConstant(Value *V, Constant *C) {
273 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000274 }
275
Chris Lattnerd79334d2004-07-15 23:36:43 +0000276 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000277 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000278 // work list so that the users of the instruction are updated later.
Chris Lattnerb4394642004-12-10 08:02:06 +0000279 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000280 if (IV.markOverdefined()) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000281 DEBUG(DOUT << "markOverdefined: ";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000282 if (Function *F = dyn_cast<Function>(V))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000283 DOUT << "Function '" << F->getName() << "'\n";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000284 else
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000285 DOUT << *V);
Chris Lattner074be1f2004-11-15 04:44:20 +0000286 // Only instructions go on the work list
Chris Lattnerb4394642004-12-10 08:02:06 +0000287 OverdefinedInstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000288 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000289 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000290
291 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
292 if (IV.isOverdefined() || MergeWithV.isUndefined())
293 return; // Noop.
294 if (MergeWithV.isOverdefined())
295 markOverdefined(IV, V);
296 else if (IV.isUndefined())
297 markConstant(IV, V, MergeWithV.getConstant());
298 else if (IV.getConstant() != MergeWithV.getConstant())
299 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000300 }
Chris Lattner06a0ed12006-02-08 02:38:11 +0000301
302 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
303 return mergeInValue(ValueState[V], V, MergeWithV);
304 }
305
Chris Lattner347389d2001-06-27 23:38:11 +0000306
Chris Lattner4f031622004-11-15 05:03:30 +0000307 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000308 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000309 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000310 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000311 // Instruction object, then use this accessor to get its value from the map.
312 //
Chris Lattner4f031622004-11-15 05:03:30 +0000313 inline LatticeVal &getValueState(Value *V) {
Bill Wendling861bec72008-08-14 23:05:24 +0000314 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000315 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner646354b2004-10-16 18:09:41 +0000316
Chris Lattner1847f6d2006-12-20 06:21:33 +0000317 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000318 if (isa<UndefValue>(V)) {
319 // Nothing to do, remain undefined.
320 } else {
Chris Lattner067d6072007-02-02 20:38:30 +0000321 LatticeVal &LV = ValueState[C];
322 LV.markConstant(C); // Constants are constant
323 return LV;
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000324 }
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000325 }
Chris Lattner347389d2001-06-27 23:38:11 +0000326 // All others are underdefined by default...
327 return ValueState[V];
328 }
329
Misha Brukmanb1c93172005-04-21 23:48:37 +0000330 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000331 // work list if it is not already executable...
Misha Brukmanb1c93172005-04-21 23:48:37 +0000332 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000333 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
334 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
335 return; // This edge is already known to be executable!
336
337 if (BBExecutable.count(Dest)) {
Chris Lattner47fed6152008-05-11 01:55:59 +0000338 DOUT << "Marking Edge Executable: " << Source->getNameStart()
339 << " -> " << Dest->getNameStart() << "\n";
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000340
341 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000342 // feasible that wasn't before. Revisit the PHI nodes in the block
343 // because they have potentially new operands.
Chris Lattnerb4394642004-12-10 08:02:06 +0000344 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
345 visitPHINode(*cast<PHINode>(I));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000346
347 } else {
Chris Lattner074be1f2004-11-15 04:44:20 +0000348 MarkBlockExecutable(Dest);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000349 }
Chris Lattner347389d2001-06-27 23:38:11 +0000350 }
351
Chris Lattner074be1f2004-11-15 04:44:20 +0000352 // getFeasibleSuccessors - Return a vector of booleans to indicate which
353 // successors are reachable from a given terminator instruction.
354 //
Chris Lattner37d400a2007-02-02 21:15:06 +0000355 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner074be1f2004-11-15 04:44:20 +0000356
357 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
358 // block to the 'To' basic block is currently feasible...
359 //
360 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
361
362 // OperandChangedState - This method is invoked on all of the users of an
363 // instruction that was just changed state somehow.... Based on this
364 // information, we need to update the specified user of this instruction.
365 //
366 void OperandChangedState(User *U) {
367 // Only instructions use other variable values!
368 Instruction &I = cast<Instruction>(*U);
369 if (BBExecutable.count(I.getParent())) // Inst is executable?
370 visit(I);
371 }
372
373private:
374 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000375
Misha Brukmanb1c93172005-04-21 23:48:37 +0000376 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000377 // operand made a transition, or the instruction is newly executable. Change
378 // the value type of I to reflect these changes if appropriate.
379 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000380 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000381
382 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000383 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000384 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000385
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000386 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000387 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000388 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000389 void visitCmpInst(CmpInst &I);
Robert Bocchinobd518d12006-01-10 19:05:05 +0000390 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino6dce2502006-01-17 20:06:55 +0000391 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner17bd6052006-04-08 01:19:12 +0000392 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman041f9d02008-06-20 01:15:44 +0000393 void visitExtractValueInst(ExtractValueInst &EVI);
394 void visitInsertValueInst(InsertValueInst &IVI);
Chris Lattner6e560792002-04-18 15:13:15 +0000395
396 // Instructions that cannot be folded away...
Chris Lattner91dbae62004-12-11 05:15:59 +0000397 void visitStoreInst (Instruction &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000398 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000399 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerb4394642004-12-10 08:02:06 +0000400 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
401 void visitInvokeInst (InvokeInst &II) {
402 visitCallSite(CallSite::get(&II));
403 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000404 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000405 void visitCallSite (CallSite CS);
Chris Lattner9c58cf62003-09-08 18:54:55 +0000406 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000407 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000408 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000409 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
410 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000411 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000412
Chris Lattner113f4f42002-06-25 16:13:24 +0000413 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000414 // If a new instruction is added to LLVM that we don't handle...
Bill Wendlingf3baad32006-12-07 01:30:32 +0000415 cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000416 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000417 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000418};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000419
Duncan Sands2be91fc2007-07-20 08:56:21 +0000420} // end anonymous namespace
421
422
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000423// getFeasibleSuccessors - Return a vector of booleans to indicate which
424// successors are reachable from a given terminator instruction.
425//
Chris Lattner074be1f2004-11-15 04:44:20 +0000426void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner37d400a2007-02-02 21:15:06 +0000427 SmallVector<bool, 16> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000428 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000429 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000430 if (BI->isUnconditional()) {
431 Succs[0] = true;
432 } else {
Chris Lattner4f031622004-11-15 05:03:30 +0000433 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000434 if (BCValue.isOverdefined() ||
Reid Spencercddc9df2007-01-12 04:24:46 +0000435 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000436 // Overdefined condition variables, and branches on unfoldable constant
437 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000438 Succs[0] = Succs[1] = true;
439 } else if (BCValue.isConstant()) {
440 // Constant condition variables mean the branch can only go a single way
Zhou Sheng75b871f2007-01-11 12:24:14 +0000441 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000442 }
443 }
Reid Spencerde46e482006-11-02 20:25:50 +0000444 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000445 // Invoke instructions successors are always executable.
446 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000447 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000448 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000449 if (SCValue.isOverdefined() || // Overdefined condition?
450 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000451 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000452 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner82146fa2008-05-10 23:56:54 +0000453 } else if (SCValue.isConstant())
454 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000455 } else {
Chris Lattner37d400a2007-02-02 21:15:06 +0000456 assert(0 && "SCCP: Don't know how to handle this terminator!");
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000457 }
458}
459
460
Chris Lattner13b52e72002-05-02 21:18:01 +0000461// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
462// block to the 'To' basic block is currently feasible...
463//
Chris Lattner074be1f2004-11-15 04:44:20 +0000464bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000465 assert(BBExecutable.count(To) && "Dest should always be alive!");
466
467 // Make sure the source basic block is executable!!
468 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000469
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000470 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000471 TerminatorInst *TI = From->getTerminator();
472 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
473 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000474 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000475 else {
Chris Lattner4f031622004-11-15 05:03:30 +0000476 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000477 if (BCValue.isOverdefined()) {
478 // Overdefined condition variables mean the branch could go either way.
479 return true;
480 } else if (BCValue.isConstant()) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000481 // Not branching on an evaluatable constant?
Chris Lattnerff7434a2007-01-13 00:42:58 +0000482 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
Chris Lattnerfe992d42004-01-12 17:40:36 +0000483
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000484 // Constant condition variables mean the branch can only go a single way
Misha Brukmanb1c93172005-04-21 23:48:37 +0000485 return BI->getSuccessor(BCValue.getConstant() ==
Zhou Sheng75b871f2007-01-11 12:24:14 +0000486 ConstantInt::getFalse()) == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000487 }
488 return false;
489 }
Reid Spencerde46e482006-11-02 20:25:50 +0000490 } else if (isa<InvokeInst>(TI)) {
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000491 // Invoke instructions successors are always executable.
492 return true;
493 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000494 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000495 if (SCValue.isOverdefined()) { // Overdefined condition?
496 // All destinations are executable!
497 return true;
498 } else if (SCValue.isConstant()) {
499 Constant *CPV = SCValue.getConstant();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000500 if (!isa<ConstantInt>(CPV))
501 return true; // not a foldable constant?
502
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000503 // Make sure to skip the "default value" which isn't a value
504 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
505 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
506 return SI->getSuccessor(i) == To;
507
508 // Constant value not equal to any of the branches... must execute
509 // default branch then...
510 return SI->getDefaultDest() == To;
511 }
512 return false;
513 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000514 cerr << "Unknown terminator instruction: " << *TI;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000515 abort();
516 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000517}
Chris Lattner347389d2001-06-27 23:38:11 +0000518
Chris Lattner6e560792002-04-18 15:13:15 +0000519// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000520// operand made a transition, or the instruction is newly executable. Change
521// the value type of I to reflect these changes if appropriate. This method
522// makes sure to do the following actions:
523//
524// 1. If a phi node merges two constants in, and has conflicting value coming
525// from different branches, or if the PHI node merges in an overdefined
526// value, then the PHI node becomes overdefined.
527// 2. If a phi node merges only constants in, and they all agree on value, the
528// PHI node becomes a constant value equal to that.
529// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
530// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
531// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
532// 6. If a conditional branch has a value that is constant, make the selected
533// destination executable
534// 7. If a conditional branch has a value that is overdefined, make all
535// successors executable.
536//
Chris Lattner074be1f2004-11-15 04:44:20 +0000537void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner4f031622004-11-15 05:03:30 +0000538 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000539 if (PNIV.isOverdefined()) {
540 // There may be instructions using this PHI node that are not overdefined
541 // themselves. If so, make sure that they know that the PHI node operand
542 // changed.
543 std::multimap<PHINode*, Instruction*>::iterator I, E;
544 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
545 if (I != E) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000546 SmallVector<Instruction*, 16> Users;
Chris Lattner05fe6842004-01-12 03:57:30 +0000547 for (; I != E; ++I) Users.push_back(I->second);
548 while (!Users.empty()) {
549 visit(Users.back());
550 Users.pop_back();
551 }
552 }
553 return; // Quick exit
554 }
Chris Lattner347389d2001-06-27 23:38:11 +0000555
Chris Lattner7a7b1142004-03-16 19:49:59 +0000556 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
557 // and slow us down a lot. Just mark them overdefined.
558 if (PN.getNumIncomingValues() > 64) {
559 markOverdefined(PNIV, &PN);
560 return;
561 }
562
Chris Lattner6e560792002-04-18 15:13:15 +0000563 // Look at all of the executable operands of the PHI node. If any of them
564 // are overdefined, the PHI becomes overdefined as well. If they are all
565 // constant, and they agree with each other, the PHI becomes the identical
566 // constant. If they are constant and don't agree, the PHI is overdefined.
567 // If there are no executable operands, the PHI remains undefined.
568 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000569 Constant *OperandVal = 0;
570 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000571 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000572 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000573
Chris Lattner113f4f42002-06-25 16:13:24 +0000574 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000575 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000576 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000577 return;
578 }
579
Chris Lattnercccc5c72003-04-25 02:50:03 +0000580 if (OperandVal == 0) { // Grab the first value...
581 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000582 } else { // Another value is being merged in!
583 // There is already a reachable operand. If we conflict with it,
584 // then the PHI node becomes overdefined. If we agree with it, we
585 // can continue on.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000586
Chris Lattner6e560792002-04-18 15:13:15 +0000587 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000588 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000589 // Yes there is. This means the PHI node is not constant.
590 // You must be overdefined poor PHI.
591 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000592 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000593 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000594 }
Chris Lattner347389d2001-06-27 23:38:11 +0000595 }
596 }
Chris Lattner347389d2001-06-27 23:38:11 +0000597 }
598
Chris Lattner6e560792002-04-18 15:13:15 +0000599 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000600 // arguments that agree with each other(and OperandVal is the constant) or
601 // OperandVal is null because there are no defined incoming arguments. If
602 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000603 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000604 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000605 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000606}
607
Chris Lattnerb4394642004-12-10 08:02:06 +0000608void SCCPSolver::visitReturnInst(ReturnInst &I) {
609 if (I.getNumOperands() == 0) return; // Ret void
610
Chris Lattnerb4394642004-12-10 08:02:06 +0000611 Function *F = I.getParent()->getParent();
Devang Patela7a20752008-03-11 05:46:42 +0000612 // If we are tracking the return value of this function, merge it in.
613 if (!F->hasInternalLinkage())
614 return;
615
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000616 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Chris Lattner067d6072007-02-02 20:38:30 +0000617 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patela7a20752008-03-11 05:46:42 +0000618 TrackedRetVals.find(F);
619 if (TFRVI != TrackedRetVals.end() &&
Chris Lattnerb4394642004-12-10 08:02:06 +0000620 !TFRVI->second.isOverdefined()) {
621 LatticeVal &IV = getValueState(I.getOperand(0));
622 mergeInValue(TFRVI->second, F, IV);
Devang Patela7a20752008-03-11 05:46:42 +0000623 return;
624 }
625 }
626
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000627 // Handle functions that return multiple values.
628 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
629 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
630 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
631 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
632 if (It == TrackedMultipleRetVals.end()) break;
633 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Chris Lattnerb4394642004-12-10 08:02:06 +0000634 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000635 } else if (!TrackedMultipleRetVals.empty() &&
636 I.getNumOperands() == 1 &&
637 isa<StructType>(I.getOperand(0)->getType())) {
638 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
639 i != e; ++i) {
640 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
641 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
642 if (It == TrackedMultipleRetVals.end()) break;
643 Value *Val = FindInsertedValue(I.getOperand(0), i);
644 mergeInValue(It->second, F, getValueState(Val));
645 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000646 }
647}
648
Chris Lattner074be1f2004-11-15 04:44:20 +0000649void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000650 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000651 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000652
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000653 BasicBlock *BB = TI.getParent();
654
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000655 // Mark all feasible successors executable...
656 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000657 if (SuccFeasible[i])
658 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000659}
660
Chris Lattner074be1f2004-11-15 04:44:20 +0000661void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000662 Value *V = I.getOperand(0);
Chris Lattner4f031622004-11-15 05:03:30 +0000663 LatticeVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000664 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000665 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000666 else if (VState.isConstant()) // Propagate constant value
Reid Spencerb341b082006-12-12 05:05:00 +0000667 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
668 VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000669}
670
Dan Gohman041f9d02008-06-20 01:15:44 +0000671void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohmana5dd67f2008-06-20 16:41:17 +0000672 Value *Aggr = EVI.getAggregateOperand();
Dan Gohman041f9d02008-06-20 01:15:44 +0000673
Dan Gohmana5dd67f2008-06-20 16:41:17 +0000674 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohman041f9d02008-06-20 01:15:44 +0000675 if (isa<UndefValue>(Aggr))
676 return;
677
678 // Currently only handle single-index extractvalues.
679 if (EVI.getNumIndices() != 1) {
680 markOverdefined(&EVI);
681 return;
682 }
683
684 Function *F = 0;
685 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
686 F = CI->getCalledFunction();
687 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
688 F = II->getCalledFunction();
689
690 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
691 // result back!
692 if (F == 0 || TrackedMultipleRetVals.empty()) {
693 markOverdefined(&EVI);
694 return;
695 }
696
697 // See if we are tracking the result of the callee.
698 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
699 It = TrackedMultipleRetVals.find(std::make_pair(F, *EVI.idx_begin()));
700
701 // If not tracking this function (for example, it is a declaration) just move
702 // to overdefined.
703 if (It == TrackedMultipleRetVals.end()) {
704 markOverdefined(&EVI);
705 return;
706 }
707
708 // Otherwise, the value will be merged in here as a result of CallSite
709 // handling.
710}
711
712void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohmana5dd67f2008-06-20 16:41:17 +0000713 Value *Aggr = IVI.getAggregateOperand();
714 Value *Val = IVI.getInsertedValueOperand();
Dan Gohman041f9d02008-06-20 01:15:44 +0000715
Dan Gohmana5dd67f2008-06-20 16:41:17 +0000716 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohmanb5210ef2008-06-20 16:39:44 +0000717 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohman041f9d02008-06-20 01:15:44 +0000718 return;
719
720 // Currently only handle single-index insertvalues.
721 if (IVI.getNumIndices() != 1) {
722 markOverdefined(&IVI);
723 return;
724 }
Dan Gohmanb5210ef2008-06-20 16:39:44 +0000725
726 // Currently only handle insertvalue instructions that are in a single-use
727 // chain that builds up a return value.
728 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
729 if (!TmpIVI->hasOneUse()) {
730 markOverdefined(&IVI);
731 return;
732 }
733 const Value *V = *TmpIVI->use_begin();
734 if (isa<ReturnInst>(V))
735 break;
736 TmpIVI = dyn_cast<InsertValueInst>(V);
737 if (!TmpIVI) {
738 markOverdefined(&IVI);
739 return;
740 }
741 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000742
743 // See if we are tracking the result of the callee.
744 Function *F = IVI.getParent()->getParent();
745 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
746 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
747
748 // Merge in the inserted member value.
749 if (It != TrackedMultipleRetVals.end())
750 mergeInValue(It->second, F, getValueState(Val));
751
Dan Gohmana5dd67f2008-06-20 16:41:17 +0000752 // Mark the aggregate result of the IVI overdefined; any tracking that we do
753 // will be done on the individual member values.
Dan Gohman041f9d02008-06-20 01:15:44 +0000754 markOverdefined(&IVI);
755}
756
Chris Lattner074be1f2004-11-15 04:44:20 +0000757void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000758 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000759 if (CondValue.isUndefined())
760 return;
Reid Spencercddc9df2007-01-12 04:24:46 +0000761 if (CondValue.isConstant()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000762 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencercddc9df2007-01-12 04:24:46 +0000763 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng75b871f2007-01-11 12:24:14 +0000764 : I.getFalseValue()));
Chris Lattner06a0ed12006-02-08 02:38:11 +0000765 return;
766 }
767 }
768
769 // Otherwise, the condition is overdefined or a constant we can't evaluate.
770 // See if we can produce something better than overdefined based on the T/F
771 // value.
772 LatticeVal &TVal = getValueState(I.getTrueValue());
773 LatticeVal &FVal = getValueState(I.getFalseValue());
774
775 // select ?, C, C -> C.
776 if (TVal.isConstant() && FVal.isConstant() &&
777 TVal.getConstant() == FVal.getConstant()) {
778 markConstant(&I, FVal.getConstant());
779 return;
780 }
781
782 if (TVal.isUndefined()) { // select ?, undef, X -> X.
783 mergeInValue(&I, FVal);
784 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
785 mergeInValue(&I, TVal);
786 } else {
787 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000788 }
789}
790
Chris Lattner6e560792002-04-18 15:13:15 +0000791// Handle BinaryOperators and Shift Instructions...
Chris Lattner074be1f2004-11-15 04:44:20 +0000792void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000793 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000794 if (IV.isOverdefined()) return;
795
Chris Lattner4f031622004-11-15 05:03:30 +0000796 LatticeVal &V1State = getValueState(I.getOperand(0));
797 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000798
Chris Lattner6e560792002-04-18 15:13:15 +0000799 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnercbc01612004-12-11 23:15:19 +0000800 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
801 // operand is overdefined.
802 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
803 LatticeVal *NonOverdefVal = 0;
804 if (!V1State.isOverdefined()) {
805 NonOverdefVal = &V1State;
806 } else if (!V2State.isOverdefined()) {
807 NonOverdefVal = &V2State;
808 }
809
810 if (NonOverdefVal) {
811 if (NonOverdefVal->isUndefined()) {
812 // Could annihilate value.
813 if (I.getOpcode() == Instruction::And)
814 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +0000815 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
816 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
Chris Lattner806adaf2007-01-04 02:12:40 +0000817 else
818 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnercbc01612004-12-11 23:15:19 +0000819 return;
820 } else {
821 if (I.getOpcode() == Instruction::And) {
822 if (NonOverdefVal->getConstant()->isNullValue()) {
823 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskeyc4ba9c12007-01-03 00:11:03 +0000824 return; // X and 0 = 0
Chris Lattnercbc01612004-12-11 23:15:19 +0000825 }
826 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000827 if (ConstantInt *CI =
828 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnercbc01612004-12-11 23:15:19 +0000829 if (CI->isAllOnesValue()) {
830 markConstant(IV, &I, NonOverdefVal->getConstant());
831 return; // X or -1 = -1
832 }
833 }
834 }
835 }
836 }
837
838
Chris Lattner05fe6842004-01-12 03:57:30 +0000839 // If both operands are PHI nodes, it is possible that this instruction has
840 // a constant value, despite the fact that the PHI node doesn't. Check for
841 // this condition now.
842 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
843 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
844 if (PN1->getParent() == PN2->getParent()) {
845 // Since the two PHI nodes are in the same basic block, they must have
846 // entries for the same predecessors. Walk the predecessor list, and
847 // if all of the incoming values are constants, and the result of
848 // evaluating this expression with all incoming value pairs is the
849 // same, then this expression is a constant even though the PHI node
850 // is not a constant!
Chris Lattner4f031622004-11-15 05:03:30 +0000851 LatticeVal Result;
Chris Lattner05fe6842004-01-12 03:57:30 +0000852 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000853 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner05fe6842004-01-12 03:57:30 +0000854 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattner4f031622004-11-15 05:03:30 +0000855 LatticeVal &In2 =
856 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner05fe6842004-01-12 03:57:30 +0000857
858 if (In1.isOverdefined() || In2.isOverdefined()) {
859 Result.markOverdefined();
860 break; // Cannot fold this operation over the PHI nodes!
861 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000862 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
863 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000864 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000865 Result.markConstant(V);
866 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000867 Result.markOverdefined();
868 break;
869 }
870 }
871 }
872
873 // If we found a constant value here, then we know the instruction is
874 // constant despite the fact that the PHI nodes are overdefined.
875 if (Result.isConstant()) {
876 markConstant(IV, &I, Result.getConstant());
877 // Remember that this instruction is virtually using the PHI node
878 // operands.
879 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
880 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
881 return;
882 } else if (Result.isUndefined()) {
883 return;
884 }
885
886 // Okay, this really is overdefined now. Since we might have
887 // speculatively thought that this was not overdefined before, and
888 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
889 // make sure to clean out any entries that we put there, for
890 // efficiency.
891 std::multimap<PHINode*, Instruction*>::iterator It, E;
892 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
893 while (It != E) {
894 if (It->second == &I) {
895 UsersOfOverdefinedPHIs.erase(It++);
896 } else
897 ++It;
898 }
899 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
900 while (It != E) {
901 if (It->second == &I) {
902 UsersOfOverdefinedPHIs.erase(It++);
903 } else
904 ++It;
905 }
906 }
907
908 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000909 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000910 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
911 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000912 }
913}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000914
Reid Spencer266e42b2006-12-23 06:05:41 +0000915// Handle ICmpInst instruction...
916void SCCPSolver::visitCmpInst(CmpInst &I) {
917 LatticeVal &IV = ValueState[&I];
918 if (IV.isOverdefined()) return;
919
920 LatticeVal &V1State = getValueState(I.getOperand(0));
921 LatticeVal &V2State = getValueState(I.getOperand(1));
922
923 if (V1State.isOverdefined() || V2State.isOverdefined()) {
924 // If both operands are PHI nodes, it is possible that this instruction has
925 // a constant value, despite the fact that the PHI node doesn't. Check for
926 // this condition now.
927 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
928 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
929 if (PN1->getParent() == PN2->getParent()) {
930 // Since the two PHI nodes are in the same basic block, they must have
931 // entries for the same predecessors. Walk the predecessor list, and
932 // if all of the incoming values are constants, and the result of
933 // evaluating this expression with all incoming value pairs is the
934 // same, then this expression is a constant even though the PHI node
935 // is not a constant!
936 LatticeVal Result;
937 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
938 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
939 BasicBlock *InBlock = PN1->getIncomingBlock(i);
940 LatticeVal &In2 =
941 getValueState(PN2->getIncomingValueForBlock(InBlock));
942
943 if (In1.isOverdefined() || In2.isOverdefined()) {
944 Result.markOverdefined();
945 break; // Cannot fold this operation over the PHI nodes!
946 } else if (In1.isConstant() && In2.isConstant()) {
947 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
948 In1.getConstant(),
949 In2.getConstant());
950 if (Result.isUndefined())
951 Result.markConstant(V);
952 else if (Result.isConstant() && Result.getConstant() != V) {
953 Result.markOverdefined();
954 break;
955 }
956 }
957 }
958
959 // If we found a constant value here, then we know the instruction is
960 // constant despite the fact that the PHI nodes are overdefined.
961 if (Result.isConstant()) {
962 markConstant(IV, &I, Result.getConstant());
963 // Remember that this instruction is virtually using the PHI node
964 // operands.
965 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
966 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
967 return;
968 } else if (Result.isUndefined()) {
969 return;
970 }
971
972 // Okay, this really is overdefined now. Since we might have
973 // speculatively thought that this was not overdefined before, and
974 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
975 // make sure to clean out any entries that we put there, for
976 // efficiency.
977 std::multimap<PHINode*, Instruction*>::iterator It, E;
978 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
979 while (It != E) {
980 if (It->second == &I) {
981 UsersOfOverdefinedPHIs.erase(It++);
982 } else
983 ++It;
984 }
985 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
986 while (It != E) {
987 if (It->second == &I) {
988 UsersOfOverdefinedPHIs.erase(It++);
989 } else
990 ++It;
991 }
992 }
993
994 markOverdefined(IV, &I);
995 } else if (V1State.isConstant() && V2State.isConstant()) {
996 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
997 V1State.getConstant(),
998 V2State.getConstant()));
999 }
1000}
1001
Robert Bocchinobd518d12006-01-10 19:05:05 +00001002void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +00001003 // FIXME : SCCP does not handle vectors properly.
1004 markOverdefined(&I);
1005 return;
1006
1007#if 0
Robert Bocchinobd518d12006-01-10 19:05:05 +00001008 LatticeVal &ValState = getValueState(I.getOperand(0));
1009 LatticeVal &IdxState = getValueState(I.getOperand(1));
1010
1011 if (ValState.isOverdefined() || IdxState.isOverdefined())
1012 markOverdefined(&I);
1013 else if(ValState.isConstant() && IdxState.isConstant())
1014 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1015 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +00001016#endif
Robert Bocchinobd518d12006-01-10 19:05:05 +00001017}
1018
Robert Bocchino6dce2502006-01-17 20:06:55 +00001019void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +00001020 // FIXME : SCCP does not handle vectors properly.
1021 markOverdefined(&I);
1022 return;
1023#if 0
Robert Bocchino6dce2502006-01-17 20:06:55 +00001024 LatticeVal &ValState = getValueState(I.getOperand(0));
1025 LatticeVal &EltState = getValueState(I.getOperand(1));
1026 LatticeVal &IdxState = getValueState(I.getOperand(2));
1027
1028 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1029 IdxState.isOverdefined())
1030 markOverdefined(&I);
1031 else if(ValState.isConstant() && EltState.isConstant() &&
1032 IdxState.isConstant())
1033 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1034 EltState.getConstant(),
1035 IdxState.getConstant()));
1036 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel21efc732006-12-04 23:54:59 +00001037 IdxState.isConstant())
Chris Lattner28d921d2007-04-14 23:32:02 +00001038 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1039 EltState.getConstant(),
1040 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +00001041#endif
Robert Bocchino6dce2502006-01-17 20:06:55 +00001042}
1043
Chris Lattner17bd6052006-04-08 01:19:12 +00001044void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +00001045 // FIXME : SCCP does not handle vectors properly.
1046 markOverdefined(&I);
1047 return;
1048#if 0
Chris Lattner17bd6052006-04-08 01:19:12 +00001049 LatticeVal &V1State = getValueState(I.getOperand(0));
1050 LatticeVal &V2State = getValueState(I.getOperand(1));
1051 LatticeVal &MaskState = getValueState(I.getOperand(2));
1052
1053 if (MaskState.isUndefined() ||
1054 (V1State.isUndefined() && V2State.isUndefined()))
1055 return; // Undefined output if mask or both inputs undefined.
1056
1057 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1058 MaskState.isOverdefined()) {
1059 markOverdefined(&I);
1060 } else {
1061 // A mix of constant/undef inputs.
1062 Constant *V1 = V1State.isConstant() ?
1063 V1State.getConstant() : UndefValue::get(I.getType());
1064 Constant *V2 = V2State.isConstant() ?
1065 V2State.getConstant() : UndefValue::get(I.getType());
1066 Constant *Mask = MaskState.isConstant() ?
1067 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1068 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1069 }
Devang Patel21efc732006-12-04 23:54:59 +00001070#endif
Chris Lattner17bd6052006-04-08 01:19:12 +00001071}
1072
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001073// Handle getelementptr instructions... if all operands are constants then we
1074// can turn this into a getelementptr ConstantExpr.
1075//
Chris Lattner074be1f2004-11-15 04:44:20 +00001076void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +00001077 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001078 if (IV.isOverdefined()) return;
1079
Chris Lattner0e7ec672007-02-02 20:51:48 +00001080 SmallVector<Constant*, 8> Operands;
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001081 Operands.reserve(I.getNumOperands());
1082
1083 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +00001084 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001085 if (State.isUndefined())
1086 return; // Operands are not resolved yet...
1087 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +00001088 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001089 return;
1090 }
1091 assert(State.isConstant() && "Unknown state!");
1092 Operands.push_back(State.getConstant());
1093 }
1094
1095 Constant *Ptr = Operands[0];
1096 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1097
Chris Lattner0e7ec672007-02-02 20:51:48 +00001098 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1099 Operands.size()));
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001100}
Brian Gaeke960707c2003-11-11 22:41:34 +00001101
Chris Lattner91dbae62004-12-11 05:15:59 +00001102void SCCPSolver::visitStoreInst(Instruction &SI) {
1103 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1104 return;
1105 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattner067d6072007-02-02 20:38:30 +00001106 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-12-11 05:15:59 +00001107 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1108
1109 // Get the value we are storing into the global.
1110 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1111
1112 mergeInValue(I->second, GV, PtrVal);
1113 if (I->second.isOverdefined())
1114 TrackedGlobals.erase(I); // No need to keep tracking this!
1115}
1116
1117
Chris Lattner49f74522004-01-12 04:29:41 +00001118// Handle load instructions. If the operand is a constant pointer to a constant
1119// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001120void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +00001121 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001122 if (IV.isOverdefined()) return;
1123
Chris Lattner4f031622004-11-15 05:03:30 +00001124 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattner49f74522004-01-12 04:29:41 +00001125 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1126 if (PtrVal.isConstant() && !I.isVolatile()) {
1127 Value *Ptr = PtrVal.getConstant();
Christopher Lambb053b802007-12-29 07:56:53 +00001128 // TODO: Consider a target hook for valid address spaces for this xform.
1129 if (isa<ConstantPointerNull>(Ptr) &&
1130 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner538fee72004-03-07 22:16:24 +00001131 // load null -> null
1132 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1133 return;
1134 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001135
Chris Lattner49f74522004-01-12 04:29:41 +00001136 // Transform load (constant global) into the value loaded.
Chris Lattner91dbae62004-12-11 05:15:59 +00001137 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1138 if (GV->isConstant()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00001139 if (!GV->isDeclaration()) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001140 markConstant(IV, &I, GV->getInitializer());
1141 return;
1142 }
1143 } else if (!TrackedGlobals.empty()) {
1144 // If we are tracking this global, merge in the known value for it.
Chris Lattner067d6072007-02-02 20:38:30 +00001145 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
Chris Lattner91dbae62004-12-11 05:15:59 +00001146 TrackedGlobals.find(GV);
1147 if (It != TrackedGlobals.end()) {
1148 mergeInValue(IV, &I, It->second);
1149 return;
1150 }
Chris Lattner49f74522004-01-12 04:29:41 +00001151 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001152 }
Chris Lattner49f74522004-01-12 04:29:41 +00001153
1154 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1155 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1156 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen82639852005-04-23 21:38:35 +00001157 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00001158 if (GV->isConstant() && !GV->isDeclaration())
Jeff Cohen82639852005-04-23 21:38:35 +00001159 if (Constant *V =
Chris Lattner02ae21e2005-09-26 05:28:52 +00001160 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen82639852005-04-23 21:38:35 +00001161 markConstant(IV, &I, V);
1162 return;
1163 }
Chris Lattner49f74522004-01-12 04:29:41 +00001164 }
1165
1166 // Otherwise we cannot say for certain what value this load will produce.
1167 // Bail out.
1168 markOverdefined(IV, &I);
1169}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001170
Chris Lattnerb4394642004-12-10 08:02:06 +00001171void SCCPSolver::visitCallSite(CallSite CS) {
1172 Function *F = CS.getCalledFunction();
Chris Lattnerb4394642004-12-10 08:02:06 +00001173 Instruction *I = CS.getInstruction();
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001174
1175 // The common case is that we aren't tracking the callee, either because we
1176 // are not doing interprocedural analysis or the callee is indirect, or is
1177 // external. Handle these cases first.
1178 if (F == 0 || !F->hasInternalLinkage()) {
1179CallOverdefined:
1180 // Void return and not tracking callee, just bail.
1181 if (I->getType() == Type::VoidTy) return;
1182
1183 // Otherwise, if we have a single return value case, and if the function is
1184 // a declaration, maybe we can constant fold it.
1185 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1186 canConstantFoldCallTo(F)) {
1187
1188 SmallVector<Constant*, 8> Operands;
1189 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1190 AI != E; ++AI) {
1191 LatticeVal &State = getValueState(*AI);
1192 if (State.isUndefined())
1193 return; // Operands are not resolved yet.
1194 else if (State.isOverdefined()) {
1195 markOverdefined(I);
1196 return;
1197 }
1198 assert(State.isConstant() && "Unknown state!");
1199 Operands.push_back(State.getConstant());
1200 }
1201
1202 // If we can constant fold this, mark the result of the call as a
1203 // constant.
1204 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size())) {
1205 markConstant(I, C);
1206 return;
1207 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001208 }
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001209
1210 // Otherwise, we don't know anything about this call, mark it overdefined.
1211 markOverdefined(I);
1212 return;
Chris Lattnerff9362a2004-04-13 19:43:54 +00001213 }
1214
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001215 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohman041f9d02008-06-20 01:15:44 +00001216 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1217 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001218 // If so, propagate the return value of the callee into this call result.
1219 mergeInValue(I, TFRVI->second);
Dan Gohman041f9d02008-06-20 01:15:44 +00001220 } else if (isa<StructType>(I->getType())) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001221 // Check to see if we're tracking this callee, if not, handle it in the
1222 // common path above.
1223 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
1224 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
1225 if (TMRVI == TrackedMultipleRetVals.end())
1226 goto CallOverdefined;
1227
1228 // If we are tracking this callee, propagate the return values of the call
Dan Gohman041f9d02008-06-20 01:15:44 +00001229 // into this call site. We do this by walking all the uses. Single-index
1230 // ExtractValueInst uses can be tracked; anything more complicated is
1231 // currently handled conservatively.
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001232 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1233 UI != E; ++UI) {
Dan Gohman041f9d02008-06-20 01:15:44 +00001234 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1235 if (EVI->getNumIndices() == 1) {
1236 mergeInValue(EVI,
Dan Gohmana5dd67f2008-06-20 16:41:17 +00001237 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohman041f9d02008-06-20 01:15:44 +00001238 continue;
1239 }
1240 }
1241 // The aggregate value is used in a way not handled here. Assume nothing.
1242 markOverdefined(*UI);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001243 }
Dan Gohman041f9d02008-06-20 01:15:44 +00001244 } else {
1245 // Otherwise we're not tracking this callee, so handle it in the
1246 // common path above.
1247 goto CallOverdefined;
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001248 }
1249
1250 // Finally, if this is the first call to the function hit, mark its entry
1251 // block executable.
1252 if (!BBExecutable.count(F->begin()))
1253 MarkBlockExecutable(F->begin());
1254
1255 // Propagate information from this call site into the callee.
1256 CallSite::arg_iterator CAI = CS.arg_begin();
1257 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1258 AI != E; ++AI, ++CAI) {
1259 LatticeVal &IV = ValueState[AI];
1260 if (!IV.isOverdefined())
1261 mergeInValue(IV, AI, getValueState(*CAI));
1262 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001263}
Chris Lattner074be1f2004-11-15 04:44:20 +00001264
1265
1266void SCCPSolver::Solve() {
1267 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001268 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001269 !OverdefinedInstWorkList.empty()) {
Chris Lattner074be1f2004-11-15 04:44:20 +00001270 // Process the instruction work list...
1271 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001272 Value *I = OverdefinedInstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001273 OverdefinedInstWorkList.pop_back();
1274
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001275 DOUT << "\nPopped off OI-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001276
Chris Lattner074be1f2004-11-15 04:44:20 +00001277 // "I" got into the work list because it either made the transition from
1278 // bottom to constant
1279 //
1280 // Anything on this worklist that is overdefined need not be visited
1281 // since all of its users will have already been marked as overdefined
1282 // Update all of the users of this instruction's value...
1283 //
1284 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1285 UI != E; ++UI)
1286 OperandChangedState(*UI);
1287 }
1288 // Process the instruction work list...
1289 while (!InstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001290 Value *I = InstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001291 InstWorkList.pop_back();
1292
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001293 DOUT << "\nPopped off I-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001294
Chris Lattner074be1f2004-11-15 04:44:20 +00001295 // "I" got into the work list because it either made the transition from
1296 // bottom to constant
1297 //
1298 // Anything on this worklist that is overdefined need not be visited
1299 // since all of its users will have already been marked as overdefined.
1300 // Update all of the users of this instruction's value...
1301 //
1302 if (!getValueState(I).isOverdefined())
1303 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1304 UI != E; ++UI)
1305 OperandChangedState(*UI);
1306 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001307
Chris Lattner074be1f2004-11-15 04:44:20 +00001308 // Process the basic block work list...
1309 while (!BBWorkList.empty()) {
1310 BasicBlock *BB = BBWorkList.back();
1311 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001312
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001313 DOUT << "\nPopped off BBWL: " << *BB;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001314
Chris Lattner074be1f2004-11-15 04:44:20 +00001315 // Notify all instructions in this basic block that they are newly
1316 // executable.
1317 visit(BB);
1318 }
1319 }
1320}
1321
Chris Lattner1847f6d2006-12-20 06:21:33 +00001322/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001323/// that branches on undef values cannot reach any of their successors.
1324/// However, this is not a safe assumption. After we solve dataflow, this
1325/// method should be use to handle this. If this returns true, the solver
1326/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001327///
1328/// This method handles this by finding an unresolved branch and marking it one
1329/// of the edges from the block as being feasible, even though the condition
1330/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1331/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001332/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001333/// constraints on the condition of the branch, as that would impact other users
1334/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001335///
1336/// This scan also checks for values that use undefs, whose results are actually
1337/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1338/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1339/// even if X isn't defined.
1340bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattneraf170962006-10-22 05:59:17 +00001341 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1342 if (!BBExecutable.count(BB))
1343 continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001344
1345 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1346 // Look for instructions which produce undef values.
1347 if (I->getType() == Type::VoidTy) continue;
1348
1349 LatticeVal &LV = getValueState(I);
1350 if (!LV.isUndefined()) continue;
1351
1352 // Get the lattice values of the first two operands for use below.
1353 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1354 LatticeVal Op1LV;
1355 if (I->getNumOperands() == 2) {
1356 // If this is a two-operand instruction, and if both operands are
1357 // undefs, the result stays undef.
1358 Op1LV = getValueState(I->getOperand(1));
1359 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1360 continue;
1361 }
1362
1363 // If this is an instructions whose result is defined even if the input is
1364 // not fully defined, propagate the information.
1365 const Type *ITy = I->getType();
1366 switch (I->getOpcode()) {
1367 default: break; // Leave the instruction as an undef.
1368 case Instruction::ZExt:
1369 // After a zero extend, we know the top part is zero. SExt doesn't have
1370 // to be handled here, because we don't know whether the top part is 1's
1371 // or 0's.
1372 assert(Op0LV.isUndefined());
1373 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1374 return true;
1375 case Instruction::Mul:
1376 case Instruction::And:
1377 // undef * X -> 0. X could be zero.
1378 // undef & X -> 0. X could be zero.
1379 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1380 return true;
1381
1382 case Instruction::Or:
1383 // undef | X -> -1. X could be -1.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001384 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1385 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
Chris Lattner806adaf2007-01-04 02:12:40 +00001386 else
1387 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1388 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001389
1390 case Instruction::SDiv:
1391 case Instruction::UDiv:
1392 case Instruction::SRem:
1393 case Instruction::URem:
1394 // X / undef -> undef. No change.
1395 // X % undef -> undef. No change.
1396 if (Op1LV.isUndefined()) break;
1397
1398 // undef / X -> 0. X could be maxint.
1399 // undef % X -> 0. X could be 1.
1400 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1401 return true;
1402
1403 case Instruction::AShr:
1404 // undef >>s X -> undef. No change.
1405 if (Op0LV.isUndefined()) break;
1406
1407 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1408 if (Op0LV.isConstant())
1409 markForcedConstant(LV, I, Op0LV.getConstant());
1410 else
1411 markOverdefined(LV, I);
1412 return true;
1413 case Instruction::LShr:
1414 case Instruction::Shl:
1415 // undef >> X -> undef. No change.
1416 // undef << X -> undef. No change.
1417 if (Op0LV.isUndefined()) break;
1418
1419 // X >> undef -> 0. X could be 0.
1420 // X << undef -> 0. X could be 0.
1421 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1422 return true;
1423 case Instruction::Select:
1424 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1425 if (Op0LV.isUndefined()) {
1426 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1427 Op1LV = getValueState(I->getOperand(2));
1428 } else if (Op1LV.isUndefined()) {
1429 // c ? undef : undef -> undef. No change.
1430 Op1LV = getValueState(I->getOperand(2));
1431 if (Op1LV.isUndefined())
1432 break;
1433 // Otherwise, c ? undef : x -> x.
1434 } else {
1435 // Leave Op1LV as Operand(1)'s LatticeValue.
1436 }
1437
1438 if (Op1LV.isConstant())
1439 markForcedConstant(LV, I, Op1LV.getConstant());
1440 else
1441 markOverdefined(LV, I);
1442 return true;
Chris Lattner5c207c82008-05-24 03:59:33 +00001443 case Instruction::Call:
1444 // If a call has an undef result, it is because it is constant foldable
1445 // but one of the inputs was undef. Just force the result to
1446 // overdefined.
1447 markOverdefined(LV, I);
1448 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001449 }
1450 }
Chris Lattneraf170962006-10-22 05:59:17 +00001451
1452 TerminatorInst *TI = BB->getTerminator();
1453 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1454 if (!BI->isConditional()) continue;
1455 if (!getValueState(BI->getCondition()).isUndefined())
1456 continue;
1457 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Dale Johannesenfecb8822008-05-23 01:01:31 +00001458 if (SI->getNumSuccessors()<2) // no cases
1459 continue;
Chris Lattneraf170962006-10-22 05:59:17 +00001460 if (!getValueState(SI->getCondition()).isUndefined())
1461 continue;
1462 } else {
1463 continue;
Chris Lattner7285f432004-12-10 20:41:50 +00001464 }
Chris Lattneraf170962006-10-22 05:59:17 +00001465
Chris Lattner1b706dd2008-01-28 00:32:30 +00001466 // If the edge to the second successor isn't thought to be feasible yet,
1467 // mark it so now. We pick the second one so that this goes to some
1468 // enumerated value in a switch instead of going to the default destination.
1469 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattneraf170962006-10-22 05:59:17 +00001470 continue;
1471
1472 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1473 // and return. This will make other blocks reachable, which will allow new
1474 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner1b706dd2008-01-28 00:32:30 +00001475 markEdgeExecutable(BB, TI->getSuccessor(1));
1476
1477 // This must be a conditional branch of switch on undef. At this point,
1478 // force the old terminator to branch to the first successor. This is
1479 // required because we are now influencing the dataflow of the function with
1480 // the assumption that this edge is taken. If we leave the branch condition
1481 // as undef, then further analysis could think the undef went another way
1482 // leading to an inconsistent set of conclusions.
1483 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1484 BI->setCondition(ConstantInt::getFalse());
1485 } else {
1486 SwitchInst *SI = cast<SwitchInst>(TI);
1487 SI->setCondition(SI->getCaseValue(1));
1488 }
1489
Chris Lattneraf170962006-10-22 05:59:17 +00001490 return true;
1491 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001492
Chris Lattneraf170962006-10-22 05:59:17 +00001493 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001494}
1495
Chris Lattner074be1f2004-11-15 04:44:20 +00001496
1497namespace {
Chris Lattner1890f942004-11-15 07:15:04 +00001498 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +00001499 //
Chris Lattner1890f942004-11-15 07:15:04 +00001500 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spencere8a74ee2006-12-31 22:26:06 +00001501 /// Sparse Conditional Constant Propagator.
Chris Lattner1890f942004-11-15 07:15:04 +00001502 ///
Reid Spencer557ab152007-02-05 23:32:05 +00001503 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +00001504 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +00001505 SCCP() : FunctionPass((intptr_t)&ID) {}
1506
Chris Lattner1890f942004-11-15 07:15:04 +00001507 // runOnFunction - Run the Sparse Conditional Constant Propagation
1508 // algorithm, and return true if the function was modified.
1509 //
1510 bool runOnFunction(Function &F);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001511
Chris Lattner1890f942004-11-15 07:15:04 +00001512 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1513 AU.setPreservesCFG();
1514 }
1515 };
Chris Lattner074be1f2004-11-15 04:44:20 +00001516} // end anonymous namespace
1517
Dan Gohmand78c4002008-05-13 00:00:25 +00001518char SCCP::ID = 0;
1519static RegisterPass<SCCP>
1520X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner074be1f2004-11-15 04:44:20 +00001521
1522// createSCCPPass - This is the public interface to this file...
1523FunctionPass *llvm::createSCCPPass() {
1524 return new SCCP();
1525}
1526
1527
Chris Lattner074be1f2004-11-15 04:44:20 +00001528// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1529// and return true if the function was modified.
1530//
1531bool SCCP::runOnFunction(Function &F) {
Chris Lattner47fed6152008-05-11 01:55:59 +00001532 DOUT << "SCCP on function '" << F.getNameStart() << "'\n";
Chris Lattner074be1f2004-11-15 04:44:20 +00001533 SCCPSolver Solver;
1534
1535 // Mark the first block of the function as being executable.
1536 Solver.MarkBlockExecutable(F.begin());
1537
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001538 // Mark all arguments to the function as being overdefined.
Chris Lattner28d921d2007-04-14 23:32:02 +00001539 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattnerc33fd462007-03-04 04:50:21 +00001540 Solver.markOverdefined(AI);
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001541
Chris Lattner074be1f2004-11-15 04:44:20 +00001542 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001543 bool ResolvedUndefs = true;
1544 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001545 Solver.Solve();
Chris Lattner1847f6d2006-12-20 06:21:33 +00001546 DOUT << "RESOLVING UNDEFs\n";
1547 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001548 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001549
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001550 bool MadeChanges = false;
1551
1552 // If we decided that there are basic blocks that are dead in this function,
1553 // delete their contents now. Note that we cannot actually delete the blocks,
1554 // as we cannot modify the CFG of the function.
1555 //
Chris Lattner3e667f32007-02-02 20:57:39 +00001556 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
Chris Lattner37d400a2007-02-02 21:15:06 +00001557 SmallVector<Instruction*, 32> Insts;
Bill Wendling861bec72008-08-14 23:05:24 +00001558 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattnerc33fd462007-03-04 04:50:21 +00001559
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001560 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1561 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001562 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattner9a038a32004-11-15 07:02:42 +00001563 ++NumDeadBlocks;
1564
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001565 // Delete the instructions backwards, as it has a reduced likelihood of
1566 // having to update as many def-use and use-def chains.
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001567 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1568 I != E; ++I)
1569 Insts.push_back(I);
1570 while (!Insts.empty()) {
1571 Instruction *I = Insts.back();
1572 Insts.pop_back();
1573 if (!I->use_empty())
1574 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1575 BB->getInstList().erase(I);
1576 MadeChanges = true;
Chris Lattner9a038a32004-11-15 07:02:42 +00001577 ++NumInstRemoved;
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001578 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001579 } else {
1580 // Iterate over all of the instructions in a function, replacing them with
1581 // constants if we have found them to be of constant values.
1582 //
1583 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1584 Instruction *Inst = BI++;
Chris Lattner12f1e002008-04-24 00:19:54 +00001585 if (Inst->getType() == Type::VoidTy ||
Chris Lattner769203c2008-04-24 00:16:28 +00001586 isa<TerminatorInst>(Inst))
1587 continue;
1588
1589 LatticeVal &IV = Values[Inst];
1590 if (!IV.isConstant() && !IV.isUndefined())
1591 continue;
1592
1593 Constant *Const = IV.isConstant()
1594 ? IV.getConstant() : UndefValue::get(Inst->getType());
1595 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001596
Chris Lattner769203c2008-04-24 00:16:28 +00001597 // Replaces all of the uses of a variable with uses of the constant.
1598 Inst->replaceAllUsesWith(Const);
1599
1600 // Delete the instruction.
1601 Inst->eraseFromParent();
1602
1603 // Hey, we just changed something!
1604 MadeChanges = true;
1605 ++NumInstRemoved;
Chris Lattner074be1f2004-11-15 04:44:20 +00001606 }
1607 }
1608
1609 return MadeChanges;
1610}
Chris Lattnerb4394642004-12-10 08:02:06 +00001611
1612namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +00001613 //===--------------------------------------------------------------------===//
1614 //
1615 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1616 /// Constant Propagation.
1617 ///
Reid Spencer557ab152007-02-05 23:32:05 +00001618 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
Devang Patel8c78a0b2007-05-03 01:11:54 +00001619 static char ID;
Devang Patel09f162c2007-05-01 21:15:47 +00001620 IPSCCP() : ModulePass((intptr_t)&ID) {}
Chris Lattnerb4394642004-12-10 08:02:06 +00001621 bool runOnModule(Module &M);
1622 };
Chris Lattnerb4394642004-12-10 08:02:06 +00001623} // end anonymous namespace
1624
Dan Gohmand78c4002008-05-13 00:00:25 +00001625char IPSCCP::ID = 0;
1626static RegisterPass<IPSCCP>
1627Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1628
Chris Lattnerb4394642004-12-10 08:02:06 +00001629// createIPSCCPPass - This is the public interface to this file...
1630ModulePass *llvm::createIPSCCPPass() {
1631 return new IPSCCP();
1632}
1633
1634
1635static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001636 // Delete any dead constantexpr klingons.
1637 GV->removeDeadConstantUsers();
1638
Chris Lattnerb4394642004-12-10 08:02:06 +00001639 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1640 UI != E; ++UI)
1641 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001642 if (SI->getOperand(0) == GV || SI->isVolatile())
1643 return true; // Storing addr of GV.
Chris Lattnerb4394642004-12-10 08:02:06 +00001644 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1645 // Make sure we are calling the function, not passing the address.
1646 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1647 for (CallSite::arg_iterator AI = CS.arg_begin(),
1648 E = CS.arg_end(); AI != E; ++AI)
1649 if (*AI == GV)
1650 return true;
Chris Lattner91dbae62004-12-11 05:15:59 +00001651 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1652 if (LI->isVolatile())
1653 return true;
1654 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001655 return true;
1656 }
1657 return false;
1658}
1659
1660bool IPSCCP::runOnModule(Module &M) {
1661 SCCPSolver Solver;
1662
1663 // Loop over all functions, marking arguments to those with their addresses
1664 // taken or that are external as overdefined.
1665 //
Chris Lattnerb4394642004-12-10 08:02:06 +00001666 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1667 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00001668 if (!F->isDeclaration())
Chris Lattnerb4394642004-12-10 08:02:06 +00001669 Solver.MarkBlockExecutable(F->begin());
Chris Lattner8cb10a12005-04-19 19:16:19 +00001670 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1671 AI != E; ++AI)
Chris Lattnerc33fd462007-03-04 04:50:21 +00001672 Solver.markOverdefined(AI);
Chris Lattnerb4394642004-12-10 08:02:06 +00001673 } else {
1674 Solver.AddTrackedFunction(F);
1675 }
1676
Chris Lattner91dbae62004-12-11 05:15:59 +00001677 // Loop over global variables. We inform the solver about any internal global
1678 // variables that do not have their 'addresses taken'. If they don't have
1679 // their addresses taken, we can propagate constants through them.
Chris Lattner8cb10a12005-04-19 19:16:19 +00001680 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1681 G != E; ++G)
Chris Lattner91dbae62004-12-11 05:15:59 +00001682 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1683 Solver.TrackValueOfGlobalVariable(G);
1684
Chris Lattnerb4394642004-12-10 08:02:06 +00001685 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001686 bool ResolvedUndefs = true;
1687 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001688 Solver.Solve();
1689
Chris Lattner1847f6d2006-12-20 06:21:33 +00001690 DOUT << "RESOLVING UNDEFS\n";
1691 ResolvedUndefs = false;
Chris Lattner7285f432004-12-10 20:41:50 +00001692 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner1847f6d2006-12-20 06:21:33 +00001693 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattner7285f432004-12-10 20:41:50 +00001694 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001695
1696 bool MadeChanges = false;
1697
1698 // Iterate over all of the instructions in the module, replacing them with
1699 // constants if we have found them to be of constant values.
1700 //
Chris Lattner3e667f32007-02-02 20:57:39 +00001701 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
Chris Lattner37d400a2007-02-02 21:15:06 +00001702 SmallVector<Instruction*, 32> Insts;
1703 SmallVector<BasicBlock*, 32> BlocksToErase;
Bill Wendling861bec72008-08-14 23:05:24 +00001704 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner37d400a2007-02-02 21:15:06 +00001705
Chris Lattnerb4394642004-12-10 08:02:06 +00001706 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001707 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1708 AI != E; ++AI)
Chris Lattnerb4394642004-12-10 08:02:06 +00001709 if (!AI->use_empty()) {
1710 LatticeVal &IV = Values[AI];
1711 if (IV.isConstant() || IV.isUndefined()) {
1712 Constant *CST = IV.isConstant() ?
1713 IV.getConstant() : UndefValue::get(AI->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001714 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
Misha Brukmanb1c93172005-04-21 23:48:37 +00001715
Chris Lattnerb4394642004-12-10 08:02:06 +00001716 // Replaces all of the uses of a variable with uses of the
1717 // constant.
1718 AI->replaceAllUsesWith(CST);
1719 ++IPNumArgsElimed;
1720 }
1721 }
1722
1723 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1724 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001725 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattnerb4394642004-12-10 08:02:06 +00001726 ++IPNumDeadBlocks;
Chris Lattner7285f432004-12-10 20:41:50 +00001727
Chris Lattnerb4394642004-12-10 08:02:06 +00001728 // Delete the instructions backwards, as it has a reduced likelihood of
1729 // having to update as many def-use and use-def chains.
Chris Lattnerbae4b642004-12-10 22:29:08 +00001730 TerminatorInst *TI = BB->getTerminator();
1731 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattnerb4394642004-12-10 08:02:06 +00001732 Insts.push_back(I);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001733
Chris Lattnerb4394642004-12-10 08:02:06 +00001734 while (!Insts.empty()) {
1735 Instruction *I = Insts.back();
1736 Insts.pop_back();
1737 if (!I->use_empty())
1738 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1739 BB->getInstList().erase(I);
1740 MadeChanges = true;
1741 ++IPNumInstRemoved;
1742 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001743
Chris Lattnerbae4b642004-12-10 22:29:08 +00001744 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1745 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmanc731c972007-10-03 19:26:29 +00001746 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattnerbae4b642004-12-10 22:29:08 +00001747 TI->getSuccessor(i)->removePredecessor(BB);
1748 }
Chris Lattner99e12952004-12-11 02:53:57 +00001749 if (!TI->use_empty())
1750 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnerbae4b642004-12-10 22:29:08 +00001751 BB->getInstList().erase(TI);
1752
Chris Lattner8525ebe2004-12-11 05:32:19 +00001753 if (&*BB != &F->front())
1754 BlocksToErase.push_back(BB);
1755 else
1756 new UnreachableInst(BB);
1757
Chris Lattnerb4394642004-12-10 08:02:06 +00001758 } else {
1759 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1760 Instruction *Inst = BI++;
Chris Lattner97951ac2008-04-24 00:21:50 +00001761 if (Inst->getType() == Type::VoidTy ||
Chris Lattner97951ac2008-04-24 00:21:50 +00001762 isa<TerminatorInst>(Inst))
1763 continue;
1764
1765 LatticeVal &IV = Values[Inst];
1766 if (!IV.isConstant() && !IV.isUndefined())
1767 continue;
1768
1769 Constant *Const = IV.isConstant()
1770 ? IV.getConstant() : UndefValue::get(Inst->getType());
1771 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001772
Chris Lattner97951ac2008-04-24 00:21:50 +00001773 // Replaces all of the uses of a variable with uses of the
1774 // constant.
1775 Inst->replaceAllUsesWith(Const);
1776
1777 // Delete the instruction.
1778 if (!isa<CallInst>(Inst))
1779 Inst->eraseFromParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001780
Chris Lattner97951ac2008-04-24 00:21:50 +00001781 // Hey, we just changed something!
1782 MadeChanges = true;
1783 ++IPNumInstRemoved;
Chris Lattnerb4394642004-12-10 08:02:06 +00001784 }
1785 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001786
1787 // Now that all instructions in the function are constant folded, erase dead
1788 // blocks, because we can now use ConstantFoldTerminator to get rid of
1789 // in-edges.
1790 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1791 // If there are any PHI nodes in this successor, drop entries for BB now.
1792 BasicBlock *DeadBB = BlocksToErase[i];
1793 while (!DeadBB->use_empty()) {
1794 Instruction *I = cast<Instruction>(DeadBB->use_back());
1795 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001796 if (!Folded) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001797 // The constant folder may not have been able to fold the terminator
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001798 // if this is a branch or switch on undef. Fold it manually as a
1799 // branch to the first successor.
1800 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1801 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1802 "Branch should be foldable!");
1803 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1804 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1805 } else {
1806 assert(0 && "Didn't fold away reference to block!");
1807 }
1808
1809 // Make this an uncond branch to the first successor.
1810 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greife9ecc682008-04-06 20:25:17 +00001811 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001812
1813 // Remove entries in successor phi nodes to remove edges.
1814 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1815 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1816
1817 // Remove the old terminator.
1818 TI->eraseFromParent();
1819 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001820 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001821
Chris Lattnerbae4b642004-12-10 22:29:08 +00001822 // Finally, delete the basic block.
1823 F->getBasicBlockList().erase(DeadBB);
1824 }
Chris Lattner37d400a2007-02-02 21:15:06 +00001825 BlocksToErase.clear();
Chris Lattnerb4394642004-12-10 08:02:06 +00001826 }
Chris Lattner99e12952004-12-11 02:53:57 +00001827
1828 // If we inferred constant or undef return values for a function, we replaced
1829 // all call uses with the inferred value. This means we don't need to bother
1830 // actually returning anything from the function. Replace all return
1831 // instructions with return undef.
Devang Patele418de32008-03-11 17:32:05 +00001832 // TODO: Process multiple value ret instructions also.
Devang Patela7a20752008-03-11 05:46:42 +00001833 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattner067d6072007-02-02 20:38:30 +00001834 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner99e12952004-12-11 02:53:57 +00001835 E = RV.end(); I != E; ++I)
1836 if (!I->second.isOverdefined() &&
1837 I->first->getReturnType() != Type::VoidTy) {
1838 Function *F = I->first;
1839 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1840 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1841 if (!isa<UndefValue>(RI->getOperand(0)))
1842 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1843 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001844
1845 // If we infered constant or undef values for globals variables, we can delete
1846 // the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00001847 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1848 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00001849 E = TG.end(); I != E; ++I) {
1850 GlobalVariable *GV = I->first;
1851 assert(!I->second.isOverdefined() &&
1852 "Overdefined values should have been taken out of the map!");
Chris Lattner47fed6152008-05-11 01:55:59 +00001853 DOUT << "Found that GV '" << GV->getNameStart() << "' is constant!\n";
Chris Lattner91dbae62004-12-11 05:15:59 +00001854 while (!GV->use_empty()) {
1855 StoreInst *SI = cast<StoreInst>(GV->use_back());
1856 SI->eraseFromParent();
1857 }
1858 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00001859 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00001860 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001861
Chris Lattnerb4394642004-12-10 08:02:06 +00001862 return MadeChanges;
1863}