blob: 59d96bee1c9dd278536da78abde4cf158c698ea9 [file] [log] [blame]
Misha Brukman82c89b92003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +00009//
Misha Brukman82c89b92003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner138a1242001-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 Lattner2a88bb72002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner138a1242001-06-27 23:38:11 +000017//
Chris Lattner138a1242001-06-27 23:38:11 +000018//===----------------------------------------------------------------------===//
19
Chris Lattneref36dfd2004-11-15 05:03:30 +000020#define DEBUG_TYPE "sccp"
Chris Lattner022103b2002-05-07 20:03:00 +000021#include "llvm/Transforms/Scalar.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000022#include "llvm/Transforms/IPO.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000023#include "llvm/Constants.h"
Chris Lattnerdd336d12004-12-11 05:15:59 +000024#include "llvm/DerivedTypes.h"
Chris Lattner9de28282003-04-25 02:50:03 +000025#include "llvm/Instructions.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000026#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000027#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanc4b65ea2008-06-20 01:15:44 +000028#include "llvm/Analysis/ValueTracking.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000029#include "llvm/Transforms/Utils/Local.h"
Chris Lattner5638dc62009-11-02 06:06:14 +000030#include "llvm/Target/TargetData.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000031#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000034#include "llvm/Support/InstVisitor.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattnercf712de2008-08-23 23:36:38 +000037#include "llvm/ADT/DenseSet.h"
Chris Lattner79272202009-11-02 02:20:32 +000038#include "llvm/ADT/PointerIntPair.h"
Chris Lattner09275292009-11-02 06:11:23 +000039#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000040#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000041#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000043#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000044#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Chris Lattner0e5f4992006-12-19 21:40:18 +000047STATISTIC(NumInstRemoved, "Number of instructions removed");
48STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000050STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000051STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
53
Chris Lattner0dbfc052002-04-29 21:26:08 +000054namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000055/// LatticeVal class - This class represents the different lattice values that
56/// an LLVM value may occupy. It is a simple class with value semantics.
57///
Chris Lattner3e8b6632009-09-02 06:11:42 +000058class LatticeVal {
Chris Lattner79272202009-11-02 02:20:32 +000059 enum LatticeValueTy {
Chris Lattner3bad2532006-12-20 06:21:33 +000060 /// undefined - This LLVM Value has no known value yet.
61 undefined,
62
63 /// constant - This LLVM Value has a specific constant value.
64 constant,
65
66 /// forcedconstant - This LLVM Value was thought to be undef until
67 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
68 /// with another (different) constant, it goes to overdefined, instead of
69 /// asserting.
70 forcedconstant,
71
72 /// overdefined - This instruction is not known to be constant, and we know
73 /// it has a value.
74 overdefined
Chris Lattner79272202009-11-02 02:20:32 +000075 };
76
77 /// Val: This stores the current lattice value along with the Constant* for
78 /// the constant if this is a 'constant' or 'forcedconstant' value.
79 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Chris Lattner3bad2532006-12-20 06:21:33 +000080
Chris Lattner79272202009-11-02 02:20:32 +000081 LatticeValueTy getLatticeValue() const {
82 return Val.getInt();
83 }
84
Chris Lattner138a1242001-06-27 23:38:11 +000085public:
Chris Lattner38871e42009-11-02 03:03:42 +000086 LatticeVal() : Val(0, undefined) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000087
Chris Lattner38871e42009-11-02 03:03:42 +000088 bool isUndefined() const { return getLatticeValue() == undefined; }
89 bool isConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000090 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
91 }
Chris Lattner38871e42009-11-02 03:03:42 +000092 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Chris Lattner79272202009-11-02 02:20:32 +000093
Chris Lattner38871e42009-11-02 03:03:42 +000094 Constant *getConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000095 assert(isConstant() && "Cannot get the constant of a non-constant!");
96 return Val.getPointer();
97 }
98
99 /// markOverdefined - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000100 bool markOverdefined() {
Chris Lattner79272202009-11-02 02:20:32 +0000101 if (isOverdefined())
102 return false;
103
104 Val.setInt(overdefined);
105 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000106 }
107
Chris Lattner79272202009-11-02 02:20:32 +0000108 /// markConstant - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000109 bool markConstant(Constant *V) {
Chris Lattnerc175e5d2009-11-03 16:50:11 +0000110 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattner79272202009-11-02 02:20:32 +0000111 assert(getConstant() == V && "Marking constant with different value");
112 return false;
Chris Lattner138a1242001-06-27 23:38:11 +0000113 }
Chris Lattner79272202009-11-02 02:20:32 +0000114
115 if (isUndefined()) {
116 Val.setInt(constant);
117 assert(V && "Marking constant with NULL");
118 Val.setPointer(V);
119 } else {
120 assert(getLatticeValue() == forcedconstant &&
121 "Cannot move from overdefined to constant!");
122 // Stay at forcedconstant if the constant is the same.
123 if (V == getConstant()) return false;
124
125 // Otherwise, we go to overdefined. Assumptions made based on the
126 // forced value are possibly wrong. Assuming this is another constant
127 // could expose a contradiction.
128 Val.setInt(overdefined);
129 }
130 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000131 }
132
Chris Lattner36c99522009-11-02 03:21:36 +0000133 /// getConstantInt - If this is a constant with a ConstantInt value, return it
134 /// otherwise return null.
135 ConstantInt *getConstantInt() const {
136 if (isConstant())
137 return dyn_cast<ConstantInt>(getConstant());
138 return 0;
139 }
140
Chris Lattner38871e42009-11-02 03:03:42 +0000141 void markForcedConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000142 assert(isUndefined() && "Can't force a defined value!");
143 Val.setInt(forcedconstant);
144 Val.setPointer(V);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000145 }
Chris Lattner138a1242001-06-27 23:38:11 +0000146};
Chris Lattnercc4f60b2009-11-02 02:47:51 +0000147} // end anonymous namespace.
148
149
150namespace {
Chris Lattner138a1242001-06-27 23:38:11 +0000151
Chris Lattner138a1242001-06-27 23:38:11 +0000152//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000153//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000154/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
155/// Constant Propagation.
156///
157class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner5638dc62009-11-02 06:06:14 +0000158 const TargetData *TD;
Nick Lewyckyfd47a592011-07-25 21:16:04 +0000159 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000160 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000161
Chris Lattnerfc36a562009-11-03 23:40:48 +0000162 /// StructValueState - This maintains ValueState for values that have
163 /// StructType, for example for formal arguments, calls, insertelement, etc.
164 ///
165 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
166
Chris Lattnerdd336d12004-12-11 05:15:59 +0000167 /// GlobalValue - If we are tracking any values for the contents of a global
168 /// variable, we keep a mapping from the constant accessor to the element of
169 /// the global, to the currently known value. If the value becomes
170 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000171 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000172
Devang Patel7c490d42008-03-11 05:46:42 +0000173 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000174 /// value out of a function, it will have an entry in this map, indicating
175 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000176 DenseMap<Function*, LatticeVal> TrackedRetVals;
177
178 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
179 /// that return multiple values.
Chris Lattnercf712de2008-08-23 23:36:38 +0000180 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattnerfc36a562009-11-03 23:40:48 +0000181
182 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
183 /// represented here for efficient lookup.
184 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000185
Chris Lattnerabf67ef2009-11-03 20:52:57 +0000186 /// TrackingIncomingArguments - This is the set of functions for whose
187 /// arguments we make optimistic assumptions about and try to prove as
188 /// constants.
Chris Lattner2396cc32009-11-03 19:24:51 +0000189 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
190
Chris Lattner38871e42009-11-02 03:03:42 +0000191 /// The reason for two worklists is that overdefined is the lowest state
192 /// on the lattice, and moving things to overdefined as fast as possible
193 /// makes SCCP converge much faster.
194 ///
195 /// By having a separate worklist, we accomplish this because everything
196 /// possibly overdefined will become overdefined at the soonest possible
197 /// point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000198 SmallVector<Value*, 64> OverdefinedInstWorkList;
199 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000200
201
Chris Lattnercf712de2008-08-23 23:36:38 +0000202 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000203
Chris Lattner1daee8b2004-01-12 03:57:30 +0000204 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
205 /// overdefined, despite the fact that the PHI node is overdefined.
206 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
207
Chris Lattner16b18fd2003-10-08 16:55:34 +0000208 /// KnownFeasibleEdges - Entries in this set are edges which have already had
209 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000210 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
211 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000212public:
Chris Lattner5638dc62009-11-02 06:06:14 +0000213 SCCPSolver(const TargetData *td) : TD(td) {}
Chris Lattner138a1242001-06-27 23:38:11 +0000214
Chris Lattner82bec2c2004-11-15 04:44:20 +0000215 /// MarkBlockExecutable - This method can be used by clients to mark all of
216 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner09275292009-11-02 06:11:23 +0000217 ///
218 /// This returns true if the block was not considered live before.
219 bool MarkBlockExecutable(BasicBlock *BB) {
220 if (!BBExecutable.insert(BB)) return false;
David Greene971cc7e2010-01-05 01:27:15 +0000221 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +0000222 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner09275292009-11-02 06:11:23 +0000223 return true;
Chris Lattner0dbfc052002-04-29 21:26:08 +0000224 }
225
Chris Lattnerdd336d12004-12-11 05:15:59 +0000226 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000227 /// inform the SCCPSolver that it should track loads and stores to the
228 /// specified global variable if it can. This is only legal to call if
229 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000230 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000231 // We only track the contents of scalar globals.
232 if (GV->getType()->getElementType()->isSingleValueType()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000233 LatticeVal &IV = TrackedGlobals[GV];
234 if (!isa<UndefValue>(GV->getInitializer()))
235 IV.markConstant(GV->getInitializer());
236 }
237 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000238
239 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
240 /// and out of the specified function (which cannot have its address taken),
241 /// this method must be called.
242 void AddTrackedFunction(Function *F) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000243 // Add an entry, F -> undef.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000244 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000245 MRVFunctionsTracked.insert(F);
Devang Patel7c490d42008-03-11 05:46:42 +0000246 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000247 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
248 LatticeVal()));
249 } else
250 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000251 }
252
Chris Lattner2396cc32009-11-03 19:24:51 +0000253 void AddArgumentTrackedFunction(Function *F) {
254 TrackingIncomingArguments.insert(F);
255 }
256
Chris Lattner82bec2c2004-11-15 04:44:20 +0000257 /// Solve - Solve for constants and executable blocks.
258 ///
259 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000260
Chris Lattner3bad2532006-12-20 06:21:33 +0000261 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000262 /// that branches on undef values cannot reach any of their successors.
263 /// However, this is not a safe assumption. After we solve dataflow, this
264 /// method should be use to handle this. If this returns true, the solver
265 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000266 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000267
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000268 bool isBlockExecutable(BasicBlock *BB) const {
269 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000270 }
271
Chris Lattner8db50122009-11-02 02:54:24 +0000272 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000273 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattner8db50122009-11-02 02:54:24 +0000274 assert(I != ValueState.end() && "V is not in valuemap!");
275 return I->second;
Chris Lattner82bec2c2004-11-15 04:44:20 +0000276 }
Chris Lattnerfc36a562009-11-03 23:40:48 +0000277
Chris Lattner473fc962010-08-18 02:41:56 +0000278 /*LatticeVal getStructLatticeValueFor(Value *V, unsigned i) const {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000279 DenseMap<std::pair<Value*, unsigned>, LatticeVal>::const_iterator I =
280 StructValueState.find(std::make_pair(V, i));
281 assert(I != StructValueState.end() && "V is not in valuemap!");
282 return I->second;
Chris Lattner473fc962010-08-18 02:41:56 +0000283 }*/
Chris Lattner82bec2c2004-11-15 04:44:20 +0000284
Devang Patel7c490d42008-03-11 05:46:42 +0000285 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000286 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000287 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
288 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000289 }
290
Chris Lattnerdd336d12004-12-11 05:15:59 +0000291 /// getTrackedGlobals - Get and return the set of inferred initializers for
292 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000293 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000294 return TrackedGlobals;
295 }
296
Chris Lattner36c99522009-11-02 03:21:36 +0000297 void markOverdefined(Value *V) {
Duncan Sands1df98592010-02-16 11:11:14 +0000298 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner57939df2007-03-04 04:50:21 +0000299 markOverdefined(ValueState[V], V);
300 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000301
Chris Lattnerfc36a562009-11-03 23:40:48 +0000302 /// markAnythingOverdefined - Mark the specified value overdefined. This
303 /// works with both scalars and structs.
304 void markAnythingOverdefined(Value *V) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000305 if (StructType *STy = dyn_cast<StructType>(V->getType()))
Chris Lattnerfc36a562009-11-03 23:40:48 +0000306 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
307 markOverdefined(getStructValueState(V, i), V);
308 else
309 markOverdefined(V);
310 }
311
Chris Lattner138a1242001-06-27 23:38:11 +0000312private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000313 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000314 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000315 // the users of the instruction are updated later.
316 //
Chris Lattner38871e42009-11-02 03:03:42 +0000317 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
318 if (!IV.markConstant(C)) return;
David Greene971cc7e2010-01-05 01:27:15 +0000319 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Chris Lattner8829cec2010-04-09 01:14:31 +0000320 if (IV.isOverdefined())
321 OverdefinedInstWorkList.push_back(V);
322 else
323 InstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000324 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000325
Chris Lattner38871e42009-11-02 03:03:42 +0000326 void markConstant(Value *V, Constant *C) {
Duncan Sands1df98592010-02-16 11:11:14 +0000327 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner59acc7d2004-12-10 08:02:06 +0000328 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000329 }
330
Chris Lattner2a0433b2009-11-02 05:55:40 +0000331 void markForcedConstant(Value *V, Constant *C) {
Duncan Sands1df98592010-02-16 11:11:14 +0000332 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner8829cec2010-04-09 01:14:31 +0000333 LatticeVal &IV = ValueState[V];
334 IV.markForcedConstant(C);
David Greene971cc7e2010-01-05 01:27:15 +0000335 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Chris Lattner8829cec2010-04-09 01:14:31 +0000336 if (IV.isOverdefined())
337 OverdefinedInstWorkList.push_back(V);
338 else
339 InstWorkList.push_back(V);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000340 }
341
342
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000343 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000344 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000345 // work list so that the users of the instruction are updated later.
Chris Lattner38871e42009-11-02 03:03:42 +0000346 void markOverdefined(LatticeVal &IV, Value *V) {
347 if (!IV.markOverdefined()) return;
348
David Greene971cc7e2010-01-05 01:27:15 +0000349 DEBUG(dbgs() << "markOverdefined: ";
Chris Lattner38871e42009-11-02 03:03:42 +0000350 if (Function *F = dyn_cast<Function>(V))
David Greene971cc7e2010-01-05 01:27:15 +0000351 dbgs() << "Function '" << F->getName() << "'\n";
Chris Lattner38871e42009-11-02 03:03:42 +0000352 else
David Greene971cc7e2010-01-05 01:27:15 +0000353 dbgs() << *V << '\n');
Chris Lattner38871e42009-11-02 03:03:42 +0000354 // Only instructions go on the work list
355 OverdefinedInstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000356 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000357
Chris Lattner2a0433b2009-11-02 05:55:40 +0000358 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000359 if (IV.isOverdefined() || MergeWithV.isUndefined())
360 return; // Noop.
361 if (MergeWithV.isOverdefined())
362 markOverdefined(IV, V);
363 else if (IV.isUndefined())
364 markConstant(IV, V, MergeWithV.getConstant());
365 else if (IV.getConstant() != MergeWithV.getConstant())
366 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000367 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000368
Chris Lattner2a0433b2009-11-02 05:55:40 +0000369 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Duncan Sands1df98592010-02-16 11:11:14 +0000370 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner36c99522009-11-02 03:21:36 +0000371 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000372 }
373
Chris Lattner138a1242001-06-27 23:38:11 +0000374
Chris Lattner2a0433b2009-11-02 05:55:40 +0000375 /// getValueState - Return the LatticeVal object that corresponds to the
376 /// value. This function handles the case when the value hasn't been seen yet
377 /// by properly seeding constants etc.
Chris Lattner38871e42009-11-02 03:03:42 +0000378 LatticeVal &getValueState(Value *V) {
Duncan Sands1df98592010-02-16 11:11:14 +0000379 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Chris Lattner5d356a72004-10-16 18:09:41 +0000380
Benjamin Kramerbcaa2152009-11-05 14:33:27 +0000381 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
382 ValueState.insert(std::make_pair(V, LatticeVal()));
383 LatticeVal &LV = I.first->second;
384
385 if (!I.second)
386 return LV; // Common case, already in the map.
Chris Lattner36c99522009-11-02 03:21:36 +0000387
Chris Lattner3bad2532006-12-20 06:21:33 +0000388 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner36c99522009-11-02 03:21:36 +0000389 // Undef values remain undefined.
390 if (!isa<UndefValue>(V))
Chris Lattnerb59673e2007-02-02 20:38:30 +0000391 LV.markConstant(C); // Constants are constant
Chris Lattner2a88bb72002-08-30 23:39:00 +0000392 }
Chris Lattner36c99522009-11-02 03:21:36 +0000393
Chris Lattner2f096252009-11-02 02:33:50 +0000394 // All others are underdefined by default.
Chris Lattner36c99522009-11-02 03:21:36 +0000395 return LV;
Chris Lattner138a1242001-06-27 23:38:11 +0000396 }
397
Chris Lattnerfc36a562009-11-03 23:40:48 +0000398 /// getStructValueState - Return the LatticeVal object that corresponds to the
399 /// value/field pair. This function handles the case when the value hasn't
400 /// been seen yet by properly seeding constants etc.
401 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands1df98592010-02-16 11:11:14 +0000402 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattnerfc36a562009-11-03 23:40:48 +0000403 assert(i < cast<StructType>(V->getType())->getNumElements() &&
404 "Invalid element #");
Benjamin Kramerbcaa2152009-11-05 14:33:27 +0000405
406 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
407 bool> I = StructValueState.insert(
408 std::make_pair(std::make_pair(V, i), LatticeVal()));
409 LatticeVal &LV = I.first->second;
410
411 if (!I.second)
412 return LV; // Common case, already in the map.
413
Chris Lattnerfc36a562009-11-03 23:40:48 +0000414 if (Constant *C = dyn_cast<Constant>(V)) {
415 if (isa<UndefValue>(C))
416 ; // Undef values remain undefined.
417 else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C))
418 LV.markConstant(CS->getOperand(i)); // Constants are constant.
419 else if (isa<ConstantAggregateZero>(C)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000420 Type *FieldTy = cast<StructType>(V->getType())->getElementType(i);
Chris Lattnerfc36a562009-11-03 23:40:48 +0000421 LV.markConstant(Constant::getNullValue(FieldTy));
422 } else
423 LV.markOverdefined(); // Unknown sort of constant.
424 }
425
426 // All others are underdefined by default.
427 return LV;
428 }
429
430
Chris Lattner2a0433b2009-11-02 05:55:40 +0000431 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
432 /// work list if it is not already executable.
Chris Lattner16b18fd2003-10-08 16:55:34 +0000433 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
434 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
435 return; // This edge is already known to be executable!
436
Chris Lattner09275292009-11-02 06:11:23 +0000437 if (!MarkBlockExecutable(Dest)) {
438 // If the destination is already executable, we just made an *edge*
439 // feasible that wasn't before. Revisit the PHI nodes in the block
440 // because they have potentially new operands.
David Greene971cc7e2010-01-05 01:27:15 +0000441 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000442 << " -> " << Dest->getName() << "\n");
Chris Lattner16b18fd2003-10-08 16:55:34 +0000443
Chris Lattner09275292009-11-02 06:11:23 +0000444 PHINode *PN;
445 for (BasicBlock::iterator I = Dest->begin();
446 (PN = dyn_cast<PHINode>(I)); ++I)
447 visitPHINode(*PN);
Chris Lattner9de28282003-04-25 02:50:03 +0000448 }
Chris Lattner138a1242001-06-27 23:38:11 +0000449 }
450
Chris Lattner82bec2c2004-11-15 04:44:20 +0000451 // getFeasibleSuccessors - Return a vector of booleans to indicate which
452 // successors are reachable from a given terminator instruction.
453 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000454 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000455
456 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000457 // block to the 'To' basic block is currently feasible.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000458 //
459 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
460
461 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattner2f096252009-11-02 02:33:50 +0000462 // instruction that was just changed state somehow. Based on this
Chris Lattner82bec2c2004-11-15 04:44:20 +0000463 // information, we need to update the specified user of this instruction.
464 //
Chris Lattner14532d02009-11-03 03:42:51 +0000465 void OperandChangedState(Instruction *I) {
466 if (BBExecutable.count(I->getParent())) // Inst is executable?
467 visit(*I);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000468 }
Chris Lattnere01985c2009-11-02 06:28:16 +0000469
470 /// RemoveFromOverdefinedPHIs - If I has any entries in the
471 /// UsersOfOverdefinedPHIs map for PN, remove them now.
472 void RemoveFromOverdefinedPHIs(Instruction *I, PHINode *PN) {
473 if (UsersOfOverdefinedPHIs.empty()) return;
Chris Lattnerc30a38f2011-07-21 06:21:31 +0000474 typedef std::multimap<PHINode*, Instruction*>::iterator ItTy;
475 std::pair<ItTy, ItTy> Range = UsersOfOverdefinedPHIs.equal_range(PN);
476 for (ItTy It = Range.first, E = Range.second; It != E;) {
Chris Lattnere01985c2009-11-02 06:28:16 +0000477 if (It->second == I)
478 UsersOfOverdefinedPHIs.erase(It++);
479 else
480 ++It;
481 }
482 }
Chris Lattner82bec2c2004-11-15 04:44:20 +0000483
Dale Johannesenf619b5a2010-11-30 20:23:21 +0000484 /// InsertInOverdefinedPHIs - Insert an entry in the UsersOfOverdefinedPHIS
485 /// map for I and PN, but if one is there already, do not create another.
486 /// (Duplicate entries do not break anything directly, but can lead to
487 /// exponential growth of the table in rare cases.)
488 void InsertInOverdefinedPHIs(Instruction *I, PHINode *PN) {
Chris Lattnerc30a38f2011-07-21 06:21:31 +0000489 typedef std::multimap<PHINode*, Instruction*>::iterator ItTy;
490 std::pair<ItTy, ItTy> Range = UsersOfOverdefinedPHIs.equal_range(PN);
491 for (ItTy J = Range.first, E = Range.second; J != E; ++J)
Chris Lattner54cfe7e2011-01-16 07:11:21 +0000492 if (J->second == I)
493 return;
494 UsersOfOverdefinedPHIs.insert(std::make_pair(PN, I));
Dale Johannesenf619b5a2010-11-30 20:23:21 +0000495 }
496
Chris Lattner82bec2c2004-11-15 04:44:20 +0000497private:
498 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000499
Chris Lattner2f096252009-11-02 02:33:50 +0000500 // visit implementations - Something changed in this instruction. Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000501 // operand made a transition, or the instruction is newly executable. Change
502 // the value type of I to reflect these changes if appropriate.
Chris Lattner7e708292002-06-25 16:13:24 +0000503 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000504
505 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000506 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000507 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000508
Chris Lattnerb8047602002-08-14 17:53:45 +0000509 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000510 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000511 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000512 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000513 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000514 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000515 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000516 void visitExtractValueInst(ExtractValueInst &EVI);
517 void visitInsertValueInst(InsertValueInst &IVI);
Bill Wendlinge6e88262011-08-12 20:24:12 +0000518 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000519
Chris Lattner2f096252009-11-02 02:33:50 +0000520 // Instructions that cannot be folded away.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000521 void visitStoreInst (StoreInst &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000522 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000523 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez66284e02009-10-24 04:23:03 +0000524 void visitCallInst (CallInst &I) {
Gabor Greif7d3056b2010-07-28 22:50:26 +0000525 visitCallSite(&I);
Victor Hernandez83d63912009-09-18 22:35:49 +0000526 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000527 void visitInvokeInst (InvokeInst &II) {
Gabor Greif7d3056b2010-07-28 22:50:26 +0000528 visitCallSite(&II);
Chris Lattner59acc7d2004-12-10 08:02:06 +0000529 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000530 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000531 void visitCallSite (CallSite CS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +0000532 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner36143fc2003-09-08 18:54:55 +0000533 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000534 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Eli Friedman8a552bb2011-07-27 01:08:30 +0000535 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Eli Friedmanfe1926e2011-08-02 21:35:16 +0000536 void visitAtomicCmpXchgInst (AtomicCmpXchgInst &I) { markOverdefined(&I); }
537 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
Victor Hernandez7b929da2009-10-23 21:09:37 +0000538 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnerfc36a562009-11-03 23:40:48 +0000539 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000540
Chris Lattner7e708292002-06-25 16:13:24 +0000541 void visitInstruction(Instruction &I) {
Chris Lattner2f096252009-11-02 02:33:50 +0000542 // If a new instruction is added to LLVM that we don't handle.
David Greene971cc7e2010-01-05 01:27:15 +0000543 dbgs() << "SCCP: Don't know how to handle: " << I;
Chris Lattnerfc36a562009-11-03 23:40:48 +0000544 markAnythingOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000545 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000546};
Chris Lattnerf6293092002-07-23 18:06:35 +0000547
Duncan Sandse2abf122007-07-20 08:56:21 +0000548} // end anonymous namespace
549
550
Chris Lattnerb9a66342002-05-02 21:44:00 +0000551// getFeasibleSuccessors - Return a vector of booleans to indicate which
552// successors are reachable from a given terminator instruction.
553//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000554void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000555 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000556 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000557 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000558 if (BI->isUnconditional()) {
559 Succs[0] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000560 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000561 }
Chris Lattnerea0db072009-11-02 02:30:06 +0000562
Chris Lattner2a0433b2009-11-02 05:55:40 +0000563 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000564 ConstantInt *CI = BCValue.getConstantInt();
565 if (CI == 0) {
Chris Lattnerea0db072009-11-02 02:30:06 +0000566 // Overdefined condition variables, and branches on unfoldable constant
567 // conditions, mean the branch could go either way.
Chris Lattner36c99522009-11-02 03:21:36 +0000568 if (!BCValue.isUndefined())
569 Succs[0] = Succs[1] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000570 return;
571 }
572
573 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000574 Succs[CI->isZero()] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000575 return;
576 }
577
Chris Lattner36c99522009-11-02 03:21:36 +0000578 if (isa<InvokeInst>(TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000579 // Invoke instructions successors are always executable.
580 Succs[0] = Succs[1] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000581 return;
582 }
583
584 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000585 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000586 ConstantInt *CI = SCValue.getConstantInt();
587
588 if (CI == 0) { // Overdefined or undefined condition?
Chris Lattnerb9a66342002-05-02 21:44:00 +0000589 // All destinations are executable!
Chris Lattner36c99522009-11-02 03:21:36 +0000590 if (!SCValue.isUndefined())
591 Succs.assign(TI.getNumSuccessors(), true);
592 return;
593 }
594
595 Succs[SI->findCaseValue(CI)] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000596 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000597 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000598
599 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
600 if (isa<IndirectBrInst>(&TI)) {
601 // Just mark all destinations executable!
602 Succs.assign(TI.getNumSuccessors(), true);
603 return;
604 }
605
606#ifndef NDEBUG
David Greene971cc7e2010-01-05 01:27:15 +0000607 dbgs() << "Unknown terminator instruction: " << TI << '\n';
Chris Lattner4c0236f2009-10-29 01:21:20 +0000608#endif
609 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000610}
611
612
Chris Lattner59f0ce22002-05-02 21:18:01 +0000613// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000614// block to the 'To' basic block is currently feasible.
Chris Lattner59f0ce22002-05-02 21:18:01 +0000615//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000616bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000617 assert(BBExecutable.count(To) && "Dest should always be alive!");
618
619 // Make sure the source basic block is executable!!
620 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000621
Chris Lattner2f096252009-11-02 02:33:50 +0000622 // Check to make sure this edge itself is actually feasible now.
Chris Lattner7d275f42003-10-08 15:47:41 +0000623 TerminatorInst *TI = From->getTerminator();
624 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
625 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000626 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000627
Chris Lattner2a0433b2009-11-02 05:55:40 +0000628 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000629
Chris Lattnerea0db072009-11-02 02:30:06 +0000630 // Overdefined condition variables mean the branch could go either way,
631 // undef conditions mean that neither edge is feasible yet.
Chris Lattner36c99522009-11-02 03:21:36 +0000632 ConstantInt *CI = BCValue.getConstantInt();
633 if (CI == 0)
634 return !BCValue.isUndefined();
Chris Lattnerea0db072009-11-02 02:30:06 +0000635
Chris Lattnerea0db072009-11-02 02:30:06 +0000636 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000637 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000638 }
639
640 // Invoke instructions successors are always executable.
641 if (isa<InvokeInst>(TI))
Chris Lattner7d275f42003-10-08 15:47:41 +0000642 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000643
644 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000645 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000646 ConstantInt *CI = SCValue.getConstantInt();
647
648 if (CI == 0)
649 return !SCValue.isUndefined();
Chris Lattner84831642004-01-12 17:40:36 +0000650
Chris Lattner36c99522009-11-02 03:21:36 +0000651 // Make sure to skip the "default value" which isn't a value
652 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
653 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
654 return SI->getSuccessor(i) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000655
Chris Lattner36c99522009-11-02 03:21:36 +0000656 // If the constant value is not equal to any of the branches, we must
657 // execute default branch.
658 return SI->getDefaultDest() == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000659 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000660
661 // Just mark all destinations executable!
662 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
Eli Friedman21c60902011-05-21 19:13:10 +0000663 if (isa<IndirectBrInst>(TI))
Chris Lattner4c0236f2009-10-29 01:21:20 +0000664 return true;
665
666#ifndef NDEBUG
David Greene971cc7e2010-01-05 01:27:15 +0000667 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
Chris Lattner4c0236f2009-10-29 01:21:20 +0000668#endif
669 llvm_unreachable(0);
Chris Lattner59f0ce22002-05-02 21:18:01 +0000670}
Chris Lattner138a1242001-06-27 23:38:11 +0000671
Chris Lattner2f096252009-11-02 02:33:50 +0000672// visit Implementations - Something changed in this instruction, either an
Chris Lattner138a1242001-06-27 23:38:11 +0000673// operand made a transition, or the instruction is newly executable. Change
674// the value type of I to reflect these changes if appropriate. This method
675// makes sure to do the following actions:
676//
677// 1. If a phi node merges two constants in, and has conflicting value coming
678// from different branches, or if the PHI node merges in an overdefined
679// value, then the PHI node becomes overdefined.
680// 2. If a phi node merges only constants in, and they all agree on value, the
681// PHI node becomes a constant value equal to that.
682// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
683// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
684// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
685// 6. If a conditional branch has a value that is constant, make the selected
686// destination executable
687// 7. If a conditional branch has a value that is overdefined, make all
688// successors executable.
689//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000690void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000691 // If this PN returns a struct, just mark the result overdefined.
692 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands1df98592010-02-16 11:11:14 +0000693 if (PN.getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +0000694 return markAnythingOverdefined(&PN);
695
Chris Lattner2a0433b2009-11-02 05:55:40 +0000696 if (getValueState(&PN).isOverdefined()) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000697 // There may be instructions using this PHI node that are not overdefined
698 // themselves. If so, make sure that they know that the PHI node operand
699 // changed.
Chris Lattnerc30a38f2011-07-21 06:21:31 +0000700 typedef std::multimap<PHINode*, Instruction*>::iterator ItTy;
701 std::pair<ItTy, ItTy> Range = UsersOfOverdefinedPHIs.equal_range(&PN);
702
703 if (Range.first == Range.second)
Chris Lattner2a0433b2009-11-02 05:55:40 +0000704 return;
705
706 SmallVector<Instruction*, 16> Users;
Chris Lattnerc30a38f2011-07-21 06:21:31 +0000707 for (ItTy I = Range.first, E = Range.second; I != E; ++I)
Chris Lattner2a0433b2009-11-02 05:55:40 +0000708 Users.push_back(I->second);
709 while (!Users.empty())
710 visit(Users.pop_back_val());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000711 return; // Quick exit
712 }
Chris Lattner138a1242001-06-27 23:38:11 +0000713
Chris Lattnera2f652d2004-03-16 19:49:59 +0000714 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
715 // and slow us down a lot. Just mark them overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +0000716 if (PN.getNumIncomingValues() > 64)
Chris Lattner2a0433b2009-11-02 05:55:40 +0000717 return markOverdefined(&PN);
Chris Lattnerfc36a562009-11-03 23:40:48 +0000718
Chris Lattner2a632552002-04-18 15:13:15 +0000719 // Look at all of the executable operands of the PHI node. If any of them
720 // are overdefined, the PHI becomes overdefined as well. If they are all
721 // constant, and they agree with each other, the PHI becomes the identical
722 // constant. If they are constant and don't agree, the PHI is overdefined.
723 // If there are no executable operands, the PHI remains undefined.
724 //
Chris Lattner9de28282003-04-25 02:50:03 +0000725 Constant *OperandVal = 0;
726 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000727 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000728 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000729
Chris Lattner38871e42009-11-02 03:03:42 +0000730 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
731 continue;
732
733 if (IV.isOverdefined()) // PHI node becomes overdefined!
734 return markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000735
Chris Lattner38871e42009-11-02 03:03:42 +0000736 if (OperandVal == 0) { // Grab the first value.
737 OperandVal = IV.getConstant();
738 continue;
Chris Lattner138a1242001-06-27 23:38:11 +0000739 }
Chris Lattner38871e42009-11-02 03:03:42 +0000740
741 // There is already a reachable operand. If we conflict with it,
742 // then the PHI node becomes overdefined. If we agree with it, we
743 // can continue on.
744
745 // Check to see if there are two different constants merging, if so, the PHI
746 // node is overdefined.
747 if (IV.getConstant() != OperandVal)
748 return markOverdefined(&PN);
Chris Lattner138a1242001-06-27 23:38:11 +0000749 }
750
Chris Lattner2a632552002-04-18 15:13:15 +0000751 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000752 // arguments that agree with each other(and OperandVal is the constant) or
753 // OperandVal is null because there are no defined incoming arguments. If
754 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000755 //
Chris Lattner9de28282003-04-25 02:50:03 +0000756 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000757 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000758}
759
Chris Lattner14532d02009-11-03 03:42:51 +0000760
761
762
Chris Lattner59acc7d2004-12-10 08:02:06 +0000763void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000764 if (I.getNumOperands() == 0) return; // ret void
Chris Lattner59acc7d2004-12-10 08:02:06 +0000765
Chris Lattner59acc7d2004-12-10 08:02:06 +0000766 Function *F = I.getParent()->getParent();
Chris Lattnerfc36a562009-11-03 23:40:48 +0000767 Value *ResultOp = I.getOperand(0);
Chris Lattner14532d02009-11-03 03:42:51 +0000768
Devang Patel7c490d42008-03-11 05:46:42 +0000769 // If we are tracking the return value of this function, merge it in.
Duncan Sands1df98592010-02-16 11:11:14 +0000770 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000771 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000772 TrackedRetVals.find(F);
Chris Lattner14532d02009-11-03 03:42:51 +0000773 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000774 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patel7c490d42008-03-11 05:46:42 +0000775 return;
776 }
777 }
778
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000779 // Handle functions that return multiple values.
Chris Lattnerfc36a562009-11-03 23:40:48 +0000780 if (!TrackedMultipleRetVals.empty()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000781 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattnerfc36a562009-11-03 23:40:48 +0000782 if (MRVFunctionsTracked.count(F))
783 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
784 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
785 getStructValueState(ResultOp, i));
786
Chris Lattner59acc7d2004-12-10 08:02:06 +0000787 }
788}
789
Chris Lattner82bec2c2004-11-15 04:44:20 +0000790void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000791 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000792 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000793
Chris Lattner16b18fd2003-10-08 16:55:34 +0000794 BasicBlock *BB = TI.getParent();
795
Chris Lattner2f096252009-11-02 02:33:50 +0000796 // Mark all feasible successors executable.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000797 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000798 if (SuccFeasible[i])
799 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000800}
801
Chris Lattner82bec2c2004-11-15 04:44:20 +0000802void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000803 LatticeVal OpSt = getValueState(I.getOperand(0));
804 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000805 markOverdefined(&I);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000806 else if (OpSt.isConstant()) // Propagate constant value
Owen Andersonbaf3c402009-07-29 18:55:55 +0000807 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattner2a0433b2009-11-02 05:55:40 +0000808 OpSt.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000809}
810
Chris Lattnerfc36a562009-11-03 23:40:48 +0000811
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000812void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000813 // If this returns a struct, mark all elements over defined, we don't track
814 // structs in structs.
Duncan Sands1df98592010-02-16 11:11:14 +0000815 if (EVI.getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +0000816 return markAnythingOverdefined(&EVI);
817
818 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner38871e42009-11-02 03:03:42 +0000819 if (EVI.getNumIndices() != 1)
820 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000821
Chris Lattnerfc36a562009-11-03 23:40:48 +0000822 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands1df98592010-02-16 11:11:14 +0000823 if (AggVal->getType()->isStructTy()) {
Chris Lattner103f2432009-11-10 22:02:09 +0000824 unsigned i = *EVI.idx_begin();
825 LatticeVal EltVal = getStructValueState(AggVal, i);
826 mergeInValue(getValueState(&EVI), &EVI, EltVal);
827 } else {
828 // Otherwise, must be extracting from an array.
829 return markOverdefined(&EVI);
830 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000831}
832
833void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000834 StructType *STy = dyn_cast<StructType>(IVI.getType());
Chris Lattnerfc36a562009-11-03 23:40:48 +0000835 if (STy == 0)
Chris Lattner38871e42009-11-02 03:03:42 +0000836 return markOverdefined(&IVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000837
Chris Lattnerfc36a562009-11-03 23:40:48 +0000838 // If this has more than one index, we can't handle it, drive all results to
839 // undef.
840 if (IVI.getNumIndices() != 1)
841 return markAnythingOverdefined(&IVI);
842
843 Value *Aggr = IVI.getAggregateOperand();
844 unsigned Idx = *IVI.idx_begin();
845
846 // Compute the result based on what we're inserting.
847 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
848 // This passes through all values that aren't the inserted element.
849 if (i != Idx) {
850 LatticeVal EltVal = getStructValueState(Aggr, i);
851 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
852 continue;
853 }
854
855 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands1df98592010-02-16 11:11:14 +0000856 if (Val->getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +0000857 // We don't track structs in structs.
858 markOverdefined(getStructValueState(&IVI, i), &IVI);
859 else {
860 LatticeVal InVal = getValueState(Val);
861 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
862 }
863 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000864}
865
Chris Lattner82bec2c2004-11-15 04:44:20 +0000866void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000867 // If this select returns a struct, just mark the result overdefined.
868 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands1df98592010-02-16 11:11:14 +0000869 if (I.getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +0000870 return markAnythingOverdefined(&I);
871
Chris Lattner2a0433b2009-11-02 05:55:40 +0000872 LatticeVal CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000873 if (CondValue.isUndefined())
874 return;
Chris Lattner36c99522009-11-02 03:21:36 +0000875
876 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000877 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
878 mergeInValue(&I, getValueState(OpVal));
Chris Lattner36c99522009-11-02 03:21:36 +0000879 return;
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000880 }
881
882 // Otherwise, the condition is overdefined or a constant we can't evaluate.
883 // See if we can produce something better than overdefined based on the T/F
884 // value.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000885 LatticeVal TVal = getValueState(I.getTrueValue());
886 LatticeVal FVal = getValueState(I.getFalseValue());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000887
888 // select ?, C, C -> C.
889 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner38871e42009-11-02 03:03:42 +0000890 TVal.getConstant() == FVal.getConstant())
891 return markConstant(&I, FVal.getConstant());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000892
Chris Lattner2a0433b2009-11-02 05:55:40 +0000893 if (TVal.isUndefined()) // select ?, undef, X -> X.
894 return mergeInValue(&I, FVal);
895 if (FVal.isUndefined()) // select ?, X, undef -> X.
896 return mergeInValue(&I, TVal);
897 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000898}
899
Chris Lattner2a0433b2009-11-02 05:55:40 +0000900// Handle Binary Operators.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000901void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000902 LatticeVal V1State = getValueState(I.getOperand(0));
903 LatticeVal V2State = getValueState(I.getOperand(1));
904
Chris Lattneref36dfd2004-11-15 05:03:30 +0000905 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000906 if (IV.isOverdefined()) return;
907
Chris Lattner2a0433b2009-11-02 05:55:40 +0000908 if (V1State.isConstant() && V2State.isConstant())
909 return markConstant(IV, &I,
910 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
911 V2State.getConstant()));
912
913 // If something is undef, wait for it to resolve.
914 if (!V1State.isOverdefined() && !V2State.isOverdefined())
915 return;
916
917 // Otherwise, one of our operands is overdefined. Try to produce something
918 // better than overdefined with some tricks.
919
920 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
921 // operand is overdefined.
922 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
923 LatticeVal *NonOverdefVal = 0;
924 if (!V1State.isOverdefined())
925 NonOverdefVal = &V1State;
926 else if (!V2State.isOverdefined())
927 NonOverdefVal = &V2State;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000928
Chris Lattner2a0433b2009-11-02 05:55:40 +0000929 if (NonOverdefVal) {
930 if (NonOverdefVal->isUndefined()) {
931 // Could annihilate value.
932 if (I.getOpcode() == Instruction::And)
933 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000934 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
Chris Lattner2a0433b2009-11-02 05:55:40 +0000935 markConstant(IV, &I, Constant::getAllOnesValue(PT));
936 else
937 markConstant(IV, &I,
938 Constant::getAllOnesValue(I.getType()));
939 return;
Chris Lattnera177c672004-12-11 23:15:19 +0000940 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000941
942 if (I.getOpcode() == Instruction::And) {
943 // X and 0 = 0
944 if (NonOverdefVal->getConstant()->isNullValue())
945 return markConstant(IV, &I, NonOverdefVal->getConstant());
946 } else {
947 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
948 if (CI->isAllOnesValue()) // X or -1 = -1
949 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnera177c672004-12-11 23:15:19 +0000950 }
951 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000952 }
Chris Lattnera177c672004-12-11 23:15:19 +0000953
954
Chris Lattner2a0433b2009-11-02 05:55:40 +0000955 // If both operands are PHI nodes, it is possible that this instruction has
956 // a constant value, despite the fact that the PHI node doesn't. Check for
957 // this condition now.
958 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
959 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
960 if (PN1->getParent() == PN2->getParent()) {
961 // Since the two PHI nodes are in the same basic block, they must have
962 // entries for the same predecessors. Walk the predecessor list, and
963 // if all of the incoming values are constants, and the result of
964 // evaluating this expression with all incoming value pairs is the
965 // same, then this expression is a constant even though the PHI node
966 // is not a constant!
967 LatticeVal Result;
968 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
969 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
970 BasicBlock *InBlock = PN1->getIncomingBlock(i);
971 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000972
Chris Lattner2a0433b2009-11-02 05:55:40 +0000973 if (In1.isOverdefined() || In2.isOverdefined()) {
974 Result.markOverdefined();
975 break; // Cannot fold this operation over the PHI nodes!
976 }
977
978 if (In1.isConstant() && In2.isConstant()) {
979 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
980 In2.getConstant());
981 if (Result.isUndefined())
982 Result.markConstant(V);
983 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000984 Result.markOverdefined();
Chris Lattner2a0433b2009-11-02 05:55:40 +0000985 break;
Chris Lattner38871e42009-11-02 03:03:42 +0000986 }
Chris Lattner1daee8b2004-01-12 03:57:30 +0000987 }
988 }
989
Chris Lattner2a0433b2009-11-02 05:55:40 +0000990 // If we found a constant value here, then we know the instruction is
991 // constant despite the fact that the PHI nodes are overdefined.
992 if (Result.isConstant()) {
993 markConstant(IV, &I, Result.getConstant());
994 // Remember that this instruction is virtually using the PHI node
Dale Johannesenf619b5a2010-11-30 20:23:21 +0000995 // operands.
996 InsertInOverdefinedPHIs(&I, PN1);
997 InsertInOverdefinedPHIs(&I, PN2);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000998 return;
999 }
1000
1001 if (Result.isUndefined())
1002 return;
1003
1004 // Okay, this really is overdefined now. Since we might have
1005 // speculatively thought that this was not overdefined before, and
1006 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1007 // make sure to clean out any entries that we put there, for
1008 // efficiency.
Chris Lattnere01985c2009-11-02 06:28:16 +00001009 RemoveFromOverdefinedPHIs(&I, PN1);
1010 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001011 }
1012
1013 markOverdefined(&I);
Chris Lattner2a632552002-04-18 15:13:15 +00001014}
Chris Lattner2a88bb72002-08-30 23:39:00 +00001015
Chris Lattner2f096252009-11-02 02:33:50 +00001016// Handle ICmpInst instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001017void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001018 LatticeVal V1State = getValueState(I.getOperand(0));
1019 LatticeVal V2State = getValueState(I.getOperand(1));
1020
Reid Spencere4d87aa2006-12-23 06:05:41 +00001021 LatticeVal &IV = ValueState[&I];
1022 if (IV.isOverdefined()) return;
1023
Chris Lattner2a0433b2009-11-02 05:55:40 +00001024 if (V1State.isConstant() && V2State.isConstant())
1025 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
1026 V1State.getConstant(),
1027 V2State.getConstant()));
1028
1029 // If operands are still undefined, wait for it to resolve.
1030 if (!V1State.isOverdefined() && !V2State.isOverdefined())
1031 return;
1032
1033 // If something is overdefined, use some tricks to avoid ending up and over
1034 // defined if we can.
1035
1036 // If both operands are PHI nodes, it is possible that this instruction has
1037 // a constant value, despite the fact that the PHI node doesn't. Check for
1038 // this condition now.
1039 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
1040 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
1041 if (PN1->getParent() == PN2->getParent()) {
1042 // Since the two PHI nodes are in the same basic block, they must have
1043 // entries for the same predecessors. Walk the predecessor list, and
1044 // if all of the incoming values are constants, and the result of
1045 // evaluating this expression with all incoming value pairs is the
1046 // same, then this expression is a constant even though the PHI node
1047 // is not a constant!
1048 LatticeVal Result;
1049 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
1050 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
1051 BasicBlock *InBlock = PN1->getIncomingBlock(i);
1052 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001053
Chris Lattner2a0433b2009-11-02 05:55:40 +00001054 if (In1.isOverdefined() || In2.isOverdefined()) {
1055 Result.markOverdefined();
1056 break; // Cannot fold this operation over the PHI nodes!
1057 }
1058
1059 if (In1.isConstant() && In2.isConstant()) {
1060 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
1061 In1.getConstant(),
1062 In2.getConstant());
1063 if (Result.isUndefined())
1064 Result.markConstant(V);
1065 else if (Result.isConstant() && Result.getConstant() != V) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001066 Result.markOverdefined();
Chris Lattner2a0433b2009-11-02 05:55:40 +00001067 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001068 }
1069 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001070 }
1071
Chris Lattner2a0433b2009-11-02 05:55:40 +00001072 // If we found a constant value here, then we know the instruction is
1073 // constant despite the fact that the PHI nodes are overdefined.
1074 if (Result.isConstant()) {
1075 markConstant(&I, Result.getConstant());
1076 // Remember that this instruction is virtually using the PHI node
1077 // operands.
Dale Johannesenf619b5a2010-11-30 20:23:21 +00001078 InsertInOverdefinedPHIs(&I, PN1);
1079 InsertInOverdefinedPHIs(&I, PN2);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001080 return;
1081 }
1082
1083 if (Result.isUndefined())
1084 return;
1085
1086 // Okay, this really is overdefined now. Since we might have
1087 // speculatively thought that this was not overdefined before, and
1088 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1089 // make sure to clean out any entries that we put there, for
1090 // efficiency.
Chris Lattnere01985c2009-11-02 06:28:16 +00001091 RemoveFromOverdefinedPHIs(&I, PN1);
1092 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001093 }
1094
1095 markOverdefined(&I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001096}
1097
Robert Bocchino56107e22006-01-10 19:05:05 +00001098void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001099 // TODO : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001100 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001101
1102#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +00001103 LatticeVal &ValState = getValueState(I.getOperand(0));
1104 LatticeVal &IdxState = getValueState(I.getOperand(1));
1105
1106 if (ValState.isOverdefined() || IdxState.isOverdefined())
1107 markOverdefined(&I);
1108 else if(ValState.isConstant() && IdxState.isConstant())
1109 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1110 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001111#endif
Robert Bocchino56107e22006-01-10 19:05:05 +00001112}
1113
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001114void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001115 // TODO : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001116 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001117#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001118 LatticeVal &ValState = getValueState(I.getOperand(0));
1119 LatticeVal &EltState = getValueState(I.getOperand(1));
1120 LatticeVal &IdxState = getValueState(I.getOperand(2));
1121
1122 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1123 IdxState.isOverdefined())
1124 markOverdefined(&I);
1125 else if(ValState.isConstant() && EltState.isConstant() &&
1126 IdxState.isConstant())
1127 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1128 EltState.getConstant(),
1129 IdxState.getConstant()));
1130 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +00001131 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +00001132 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1133 EltState.getConstant(),
1134 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001135#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001136}
1137
Chris Lattner543abdf2006-04-08 01:19:12 +00001138void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001139 // TODO : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001140 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001141#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +00001142 LatticeVal &V1State = getValueState(I.getOperand(0));
1143 LatticeVal &V2State = getValueState(I.getOperand(1));
1144 LatticeVal &MaskState = getValueState(I.getOperand(2));
1145
1146 if (MaskState.isUndefined() ||
1147 (V1State.isUndefined() && V2State.isUndefined()))
1148 return; // Undefined output if mask or both inputs undefined.
1149
1150 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1151 MaskState.isOverdefined()) {
1152 markOverdefined(&I);
1153 } else {
1154 // A mix of constant/undef inputs.
1155 Constant *V1 = V1State.isConstant() ?
1156 V1State.getConstant() : UndefValue::get(I.getType());
1157 Constant *V2 = V2State.isConstant() ?
1158 V2State.getConstant() : UndefValue::get(I.getType());
1159 Constant *Mask = MaskState.isConstant() ?
1160 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1161 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1162 }
Devang Patel67a821d2006-12-04 23:54:59 +00001163#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001164}
1165
Chris Lattner2f096252009-11-02 02:33:50 +00001166// Handle getelementptr instructions. If all operands are constants then we
Chris Lattner2a88bb72002-08-30 23:39:00 +00001167// can turn this into a getelementptr ConstantExpr.
1168//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001169void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner5cc66d92009-11-02 23:25:39 +00001170 if (ValueState[&I].isOverdefined()) return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001171
Chris Lattnere777ff22007-02-02 20:51:48 +00001172 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001173 Operands.reserve(I.getNumOperands());
1174
1175 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001176 LatticeVal State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001177 if (State.isUndefined())
Chris Lattner2f096252009-11-02 02:33:50 +00001178 return; // Operands are not resolved yet.
1179
Chris Lattner38871e42009-11-02 03:03:42 +00001180 if (State.isOverdefined())
Chris Lattner5cc66d92009-11-02 23:25:39 +00001181 return markOverdefined(&I);
Chris Lattner38871e42009-11-02 03:03:42 +00001182
Chris Lattner2a88bb72002-08-30 23:39:00 +00001183 assert(State.isConstant() && "Unknown state!");
1184 Operands.push_back(State.getConstant());
1185 }
1186
1187 Constant *Ptr = Operands[0];
Jay Foaddab3d292011-07-21 14:31:17 +00001188 ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
1189 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001190}
Brian Gaeked0fde302003-11-11 22:41:34 +00001191
Chris Lattner2a0433b2009-11-02 05:55:40 +00001192void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001193 // If this store is of a struct, ignore it.
Duncan Sands1df98592010-02-16 11:11:14 +00001194 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +00001195 return;
1196
Chris Lattnerdd336d12004-12-11 05:15:59 +00001197 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1198 return;
Chris Lattner2a0433b2009-11-02 05:55:40 +00001199
Chris Lattnerdd336d12004-12-11 05:15:59 +00001200 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001201 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001202 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1203
Chris Lattner2a0433b2009-11-02 05:55:40 +00001204 // Get the value we are storing into the global, then merge it.
1205 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattnerdd336d12004-12-11 05:15:59 +00001206 if (I->second.isOverdefined())
1207 TrackedGlobals.erase(I); // No need to keep tracking this!
1208}
1209
1210
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001211// Handle load instructions. If the operand is a constant pointer to a constant
1212// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001213void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001214 // If this load is of a struct, just mark the result overdefined.
Duncan Sands1df98592010-02-16 11:11:14 +00001215 if (I.getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +00001216 return markAnythingOverdefined(&I);
1217
Chris Lattner2a0433b2009-11-02 05:55:40 +00001218 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattner5638dc62009-11-02 06:06:14 +00001219 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Chris Lattner2a0433b2009-11-02 05:55:40 +00001220
Chris Lattneref36dfd2004-11-15 05:03:30 +00001221 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001222 if (IV.isOverdefined()) return;
1223
Chris Lattner2a0433b2009-11-02 05:55:40 +00001224 if (!PtrVal.isConstant() || I.isVolatile())
1225 return markOverdefined(IV, &I);
1226
Chris Lattner5638dc62009-11-02 06:06:14 +00001227 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanfd939082005-04-21 23:48:37 +00001228
Chris Lattner2a0433b2009-11-02 05:55:40 +00001229 // load null -> null
1230 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1231 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1232
1233 // Transform load (constant global) into the value loaded.
1234 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001235 if (!TrackedGlobals.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001236 // If we are tracking this global, merge in the known value for it.
1237 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1238 TrackedGlobals.find(GV);
1239 if (It != TrackedGlobals.end()) {
1240 mergeInValue(IV, &I, It->second);
1241 return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001242 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001243 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001244 }
1245
Chris Lattner5638dc62009-11-02 06:06:14 +00001246 // Transform load from a constant into a constant if possible.
1247 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1248 return markConstant(IV, &I, C);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001249
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001250 // Otherwise we cannot say for certain what value this load will produce.
1251 // Bail out.
1252 markOverdefined(IV, &I);
1253}
Chris Lattner58b7b082004-04-13 19:43:54 +00001254
Chris Lattner59acc7d2004-12-10 08:02:06 +00001255void SCCPSolver::visitCallSite(CallSite CS) {
1256 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001257 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001258
1259 // The common case is that we aren't tracking the callee, either because we
1260 // are not doing interprocedural analysis or the callee is indirect, or is
1261 // external. Handle these cases first.
Chris Lattner14532d02009-11-03 03:42:51 +00001262 if (F == 0 || F->isDeclaration()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001263CallOverdefined:
1264 // Void return and not tracking callee, just bail.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001265 if (I->getType()->isVoidTy()) return;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001266
1267 // Otherwise, if we have a single return value case, and if the function is
1268 // a declaration, maybe we can constant fold it.
Duncan Sands1df98592010-02-16 11:11:14 +00001269 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001270 canConstantFoldCallTo(F)) {
1271
1272 SmallVector<Constant*, 8> Operands;
1273 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1274 AI != E; ++AI) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001275 LatticeVal State = getValueState(*AI);
Chris Lattner38871e42009-11-02 03:03:42 +00001276
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001277 if (State.isUndefined())
1278 return; // Operands are not resolved yet.
Chris Lattner38871e42009-11-02 03:03:42 +00001279 if (State.isOverdefined())
1280 return markOverdefined(I);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001281 assert(State.isConstant() && "Unknown state!");
1282 Operands.push_back(State.getConstant());
1283 }
1284
1285 // If we can constant fold this, mark the result of the call as a
1286 // constant.
Jay Foad1d2f5692011-07-19 13:32:40 +00001287 if (Constant *C = ConstantFoldCall(F, Operands))
Chris Lattner38871e42009-11-02 03:03:42 +00001288 return markConstant(I, C);
Chris Lattner58b7b082004-04-13 19:43:54 +00001289 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001290
1291 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattnerfc36a562009-11-03 23:40:48 +00001292 return markAnythingOverdefined(I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001293 }
1294
Chris Lattner2396cc32009-11-03 19:24:51 +00001295 // If this is a local function that doesn't have its address taken, mark its
1296 // entry block executable and merge in the actual arguments to the call into
1297 // the formal arguments of the function.
1298 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1299 MarkBlockExecutable(F->begin());
1300
1301 // Propagate information from this call site into the callee.
1302 CallSite::arg_iterator CAI = CS.arg_begin();
1303 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1304 AI != E; ++AI, ++CAI) {
1305 // If this argument is byval, and if the function is not readonly, there
1306 // will be an implicit copy formed of the input aggregate.
1307 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1308 markOverdefined(AI);
1309 continue;
1310 }
1311
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001312 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner0fb7e182009-11-04 18:57:42 +00001313 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1314 LatticeVal CallArg = getStructValueState(*CAI, i);
1315 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1316 }
Chris Lattnerfc36a562009-11-03 23:40:48 +00001317 } else {
1318 mergeInValue(AI, getValueState(*CAI));
1319 }
Chris Lattner2396cc32009-11-03 19:24:51 +00001320 }
1321 }
1322
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001323 // If this is a single/zero retval case, see if we're tracking the function.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001324 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001325 if (!MRVFunctionsTracked.count(F))
1326 goto CallOverdefined; // Not tracking this callee.
1327
1328 // If we are tracking this callee, propagate the result of the function
1329 // into this call site.
1330 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1331 mergeInValue(getStructValueState(I, i), I,
1332 TrackedMultipleRetVals[std::make_pair(F, i)]);
1333 } else {
1334 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1335 if (TFRVI == TrackedRetVals.end())
1336 goto CallOverdefined; // Not tracking this callee.
1337
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001338 // If so, propagate the return value of the callee into this call result.
1339 mergeInValue(I, TFRVI->second);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001340 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001341}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001342
Chris Lattner82bec2c2004-11-15 04:44:20 +00001343void SCCPSolver::Solve() {
1344 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001345 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001346 !OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001347 // Process the overdefined instruction's work list first, which drives other
1348 // things to overdefined more quickly.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001349 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001350 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001351
David Greene971cc7e2010-01-05 01:27:15 +00001352 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001353
Chris Lattner82bec2c2004-11-15 04:44:20 +00001354 // "I" got into the work list because it either made the transition from
1355 // bottom to constant
1356 //
1357 // Anything on this worklist that is overdefined need not be visited
1358 // since all of its users will have already been marked as overdefined
Chris Lattner2f096252009-11-02 02:33:50 +00001359 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001360 //
1361 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1362 UI != E; ++UI)
Chris Lattner14532d02009-11-03 03:42:51 +00001363 if (Instruction *I = dyn_cast<Instruction>(*UI))
1364 OperandChangedState(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001365 }
Chris Lattner2f096252009-11-02 02:33:50 +00001366
1367 // Process the instruction work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001368 while (!InstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001369 Value *I = InstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001370
David Greene971cc7e2010-01-05 01:27:15 +00001371 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001372
Chris Lattner2a0433b2009-11-02 05:55:40 +00001373 // "I" got into the work list because it made the transition from undef to
1374 // constant.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001375 //
1376 // Anything on this worklist that is overdefined need not be visited
1377 // since all of its users will have already been marked as overdefined.
Chris Lattner2f096252009-11-02 02:33:50 +00001378 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001379 //
Duncan Sands1df98592010-02-16 11:11:14 +00001380 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Chris Lattner82bec2c2004-11-15 04:44:20 +00001381 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1382 UI != E; ++UI)
Chris Lattner14532d02009-11-03 03:42:51 +00001383 if (Instruction *I = dyn_cast<Instruction>(*UI))
1384 OperandChangedState(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001385 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001386
Chris Lattner2f096252009-11-02 02:33:50 +00001387 // Process the basic block work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001388 while (!BBWorkList.empty()) {
1389 BasicBlock *BB = BBWorkList.back();
1390 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001391
David Greene971cc7e2010-01-05 01:27:15 +00001392 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001393
Chris Lattner82bec2c2004-11-15 04:44:20 +00001394 // Notify all instructions in this basic block that they are newly
1395 // executable.
1396 visit(BB);
1397 }
1398 }
1399}
1400
Chris Lattner3bad2532006-12-20 06:21:33 +00001401/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001402/// that branches on undef values cannot reach any of their successors.
1403/// However, this is not a safe assumption. After we solve dataflow, this
1404/// method should be use to handle this. If this returns true, the solver
1405/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001406///
1407/// This method handles this by finding an unresolved branch and marking it one
1408/// of the edges from the block as being feasible, even though the condition
1409/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1410/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001411/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001412/// constraints on the condition of the branch, as that would impact other users
1413/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001414///
1415/// This scan also checks for values that use undefs, whose results are actually
1416/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1417/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1418/// even if X isn't defined.
1419bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001420 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1421 if (!BBExecutable.count(BB))
1422 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001423
1424 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1425 // Look for instructions which produce undef values.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001426 if (I->getType()->isVoidTy()) continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001427
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001428 if (StructType *STy = dyn_cast<StructType>(I->getType())) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001429 // Only a few things that can be structs matter for undef. Just send
1430 // all their results to overdefined. We could be more precise than this
1431 // but it isn't worth bothering.
1432 if (isa<CallInst>(I) || isa<SelectInst>(I)) {
1433 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1434 LatticeVal &LV = getStructValueState(I, i);
1435 if (LV.isUndefined())
1436 markOverdefined(LV, I);
1437 }
1438 }
1439 continue;
1440 }
1441
Chris Lattner3bad2532006-12-20 06:21:33 +00001442 LatticeVal &LV = getValueState(I);
1443 if (!LV.isUndefined()) continue;
1444
Chris Lattnerfc36a562009-11-03 23:40:48 +00001445 // No instructions using structs need disambiguation.
Duncan Sands1df98592010-02-16 11:11:14 +00001446 if (I->getOperand(0)->getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +00001447 continue;
1448
Chris Lattner3bad2532006-12-20 06:21:33 +00001449 // Get the lattice values of the first two operands for use below.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001450 LatticeVal Op0LV = getValueState(I->getOperand(0));
Chris Lattner3bad2532006-12-20 06:21:33 +00001451 LatticeVal Op1LV;
1452 if (I->getNumOperands() == 2) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001453 // No instructions using structs need disambiguation.
Duncan Sands1df98592010-02-16 11:11:14 +00001454 if (I->getOperand(1)->getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +00001455 continue;
1456
Chris Lattner3bad2532006-12-20 06:21:33 +00001457 // If this is a two-operand instruction, and if both operands are
1458 // undefs, the result stays undef.
1459 Op1LV = getValueState(I->getOperand(1));
1460 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1461 continue;
1462 }
1463
1464 // If this is an instructions whose result is defined even if the input is
1465 // not fully defined, propagate the information.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001466 Type *ITy = I->getType();
Chris Lattner3bad2532006-12-20 06:21:33 +00001467 switch (I->getOpcode()) {
1468 default: break; // Leave the instruction as an undef.
1469 case Instruction::ZExt:
1470 // After a zero extend, we know the top part is zero. SExt doesn't have
1471 // to be handled here, because we don't know whether the top part is 1's
1472 // or 0's.
Chris Lattner8581c262010-04-26 18:21:23 +00001473 case Instruction::SIToFP: // some FP values are not possible, just use 0.
1474 case Instruction::UIToFP: // some FP values are not possible, just use 0.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001475 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001476 return true;
1477 case Instruction::Mul:
1478 case Instruction::And:
1479 // undef * X -> 0. X could be zero.
1480 // undef & X -> 0. X could be zero.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001481 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001482 return true;
1483
1484 case Instruction::Or:
1485 // undef | X -> -1. X could be -1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001486 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001487 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001488
1489 case Instruction::SDiv:
1490 case Instruction::UDiv:
1491 case Instruction::SRem:
1492 case Instruction::URem:
1493 // X / undef -> undef. No change.
1494 // X % undef -> undef. No change.
1495 if (Op1LV.isUndefined()) break;
1496
1497 // undef / X -> 0. X could be maxint.
1498 // undef % X -> 0. X could be 1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001499 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001500 return true;
1501
1502 case Instruction::AShr:
1503 // undef >>s X -> undef. No change.
1504 if (Op0LV.isUndefined()) break;
1505
1506 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1507 if (Op0LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001508 markForcedConstant(I, Op0LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001509 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001510 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001511 return true;
1512 case Instruction::LShr:
1513 case Instruction::Shl:
1514 // undef >> X -> undef. No change.
1515 // undef << X -> undef. No change.
1516 if (Op0LV.isUndefined()) break;
1517
1518 // X >> undef -> 0. X could be 0.
1519 // X << undef -> 0. X could be 0.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001520 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001521 return true;
1522 case Instruction::Select:
1523 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1524 if (Op0LV.isUndefined()) {
1525 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1526 Op1LV = getValueState(I->getOperand(2));
1527 } else if (Op1LV.isUndefined()) {
1528 // c ? undef : undef -> undef. No change.
1529 Op1LV = getValueState(I->getOperand(2));
1530 if (Op1LV.isUndefined())
1531 break;
1532 // Otherwise, c ? undef : x -> x.
1533 } else {
1534 // Leave Op1LV as Operand(1)'s LatticeValue.
1535 }
1536
1537 if (Op1LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001538 markForcedConstant(I, Op1LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001539 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001540 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001541 return true;
Chris Lattner60301602008-05-24 03:59:33 +00001542 case Instruction::Call:
1543 // If a call has an undef result, it is because it is constant foldable
1544 // but one of the inputs was undef. Just force the result to
1545 // overdefined.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001546 markOverdefined(I);
Chris Lattner60301602008-05-24 03:59:33 +00001547 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001548 }
1549 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001550
Chris Lattnere597f002010-04-05 22:14:48 +00001551 // Check to see if we have a branch or switch on an undefined value. If so
1552 // we force the branch to go one way or the other to make the successor
1553 // values live. It doesn't really matter which way we force it.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001554 TerminatorInst *TI = BB->getTerminator();
1555 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1556 if (!BI->isConditional()) continue;
1557 if (!getValueState(BI->getCondition()).isUndefined())
1558 continue;
Chris Lattnere597f002010-04-05 22:14:48 +00001559
1560 // If the input to SCCP is actually branch on undef, fix the undef to
1561 // false.
1562 if (isa<UndefValue>(BI->getCondition())) {
1563 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1564 markEdgeExecutable(BB, TI->getSuccessor(1));
1565 return true;
1566 }
1567
1568 // Otherwise, it is a branch on a symbolic value which is currently
1569 // considered to be undef. Handle this by forcing the input value to the
1570 // branch to false.
1571 markForcedConstant(BI->getCondition(),
1572 ConstantInt::getFalse(TI->getContext()));
1573 return true;
1574 }
1575
1576 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001577 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesen9bca5832008-05-23 01:01:31 +00001578 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001579 if (!getValueState(SI->getCondition()).isUndefined())
1580 continue;
Chris Lattnere597f002010-04-05 22:14:48 +00001581
1582 // If the input to SCCP is actually switch on undef, fix the undef to
1583 // the first constant.
1584 if (isa<UndefValue>(SI->getCondition())) {
1585 SI->setCondition(SI->getCaseValue(1));
1586 markEdgeExecutable(BB, TI->getSuccessor(1));
1587 return true;
1588 }
1589
1590 markForcedConstant(SI->getCondition(), SI->getCaseValue(1));
1591 return true;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001592 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001593 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001594
Chris Lattnerd2d86702006-10-22 05:59:17 +00001595 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001596}
1597
Chris Lattner82bec2c2004-11-15 04:44:20 +00001598
1599namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001600 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001601 //
Chris Lattner14051812004-11-15 07:15:04 +00001602 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001603 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001604 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001605 struct SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001606 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +00001607 SCCP() : FunctionPass(ID) {
1608 initializeSCCPPass(*PassRegistry::getPassRegistry());
1609 }
Devang Patel794fd752007-05-01 21:15:47 +00001610
Chris Lattner14051812004-11-15 07:15:04 +00001611 // runOnFunction - Run the Sparse Conditional Constant Propagation
1612 // algorithm, and return true if the function was modified.
1613 //
1614 bool runOnFunction(Function &F);
Chris Lattner14051812004-11-15 07:15:04 +00001615 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001616} // end anonymous namespace
1617
Dan Gohman844731a2008-05-13 00:00:25 +00001618char SCCP::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +00001619INITIALIZE_PASS(SCCP, "sccp",
Owen Andersonce665bd2010-10-07 22:25:06 +00001620 "Sparse Conditional Constant Propagation", false, false)
Chris Lattner82bec2c2004-11-15 04:44:20 +00001621
Chris Lattner2f096252009-11-02 02:33:50 +00001622// createSCCPPass - This is the public interface to this file.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001623FunctionPass *llvm::createSCCPPass() {
1624 return new SCCP();
1625}
1626
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001627static void DeleteInstructionInBlock(BasicBlock *BB) {
David Greene971cc7e2010-01-05 01:27:15 +00001628 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001629 ++NumDeadBlocks;
1630
1631 // Delete the instructions backwards, as it has a reduced likelihood of
1632 // having to update as many def-use and use-def chains.
1633 while (!isa<TerminatorInst>(BB->begin())) {
1634 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1635
1636 if (!I->use_empty())
1637 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1638 BB->getInstList().erase(I);
1639 ++NumInstRemoved;
1640 }
1641}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001642
Chris Lattner82bec2c2004-11-15 04:44:20 +00001643// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1644// and return true if the function was modified.
1645//
1646bool SCCP::runOnFunction(Function &F) {
David Greene971cc7e2010-01-05 01:27:15 +00001647 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner5638dc62009-11-02 06:06:14 +00001648 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner82bec2c2004-11-15 04:44:20 +00001649
1650 // Mark the first block of the function as being executable.
1651 Solver.MarkBlockExecutable(F.begin());
1652
Chris Lattner7e529e42004-11-15 05:45:33 +00001653 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001654 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattnerfc36a562009-11-03 23:40:48 +00001655 Solver.markAnythingOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001656
Chris Lattner82bec2c2004-11-15 04:44:20 +00001657 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001658 bool ResolvedUndefs = true;
1659 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001660 Solver.Solve();
David Greene971cc7e2010-01-05 01:27:15 +00001661 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001662 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001663 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001664
Chris Lattner7e529e42004-11-15 05:45:33 +00001665 bool MadeChanges = false;
1666
1667 // If we decided that there are basic blocks that are dead in this function,
1668 // delete their contents now. Note that we cannot actually delete the blocks,
1669 // as we cannot modify the CFG of the function.
Chris Lattner57939df2007-03-04 04:50:21 +00001670
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001671 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001672 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001673 DeleteInstructionInBlock(BB);
1674 MadeChanges = true;
1675 continue;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001676 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001677
1678 // Iterate over all of the instructions in a function, replacing them with
1679 // constants if we have found them to be of constant values.
1680 //
1681 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1682 Instruction *Inst = BI++;
1683 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1684 continue;
1685
Chris Lattnerfc36a562009-11-03 23:40:48 +00001686 // TODO: Reconstruct structs from their elements.
Duncan Sands1df98592010-02-16 11:11:14 +00001687 if (Inst->getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +00001688 continue;
1689
Chris Lattner8db50122009-11-02 02:54:24 +00001690 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1691 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001692 continue;
1693
1694 Constant *Const = IV.isConstant()
1695 ? IV.getConstant() : UndefValue::get(Inst->getType());
David Greene971cc7e2010-01-05 01:27:15 +00001696 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001697
1698 // Replaces all of the uses of a variable with uses of the constant.
1699 Inst->replaceAllUsesWith(Const);
1700
1701 // Delete the instruction.
1702 Inst->eraseFromParent();
1703
1704 // Hey, we just changed something!
1705 MadeChanges = true;
1706 ++NumInstRemoved;
1707 }
1708 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001709
1710 return MadeChanges;
1711}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001712
1713namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001714 //===--------------------------------------------------------------------===//
1715 //
1716 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1717 /// Constant Propagation.
1718 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001719 struct IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001720 static char ID;
Owen Anderson081c34b2010-10-19 17:21:58 +00001721 IPSCCP() : ModulePass(ID) {
1722 initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1723 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001724 bool runOnModule(Module &M);
1725 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001726} // end anonymous namespace
1727
Dan Gohman844731a2008-05-13 00:00:25 +00001728char IPSCCP::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +00001729INITIALIZE_PASS(IPSCCP, "ipsccp",
1730 "Interprocedural Sparse Conditional Constant Propagation",
Owen Andersonce665bd2010-10-07 22:25:06 +00001731 false, false)
Dan Gohman844731a2008-05-13 00:00:25 +00001732
Chris Lattner2f096252009-11-02 02:33:50 +00001733// createIPSCCPPass - This is the public interface to this file.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001734ModulePass *llvm::createIPSCCPPass() {
1735 return new IPSCCP();
1736}
1737
1738
Gabor Greifbd1f9932010-03-24 10:29:52 +00001739static bool AddressIsTaken(const GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001740 // Delete any dead constantexpr klingons.
1741 GV->removeDeadConstantUsers();
1742
Gabor Greif60ad7812010-03-25 23:06:16 +00001743 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifbd1f9932010-03-24 10:29:52 +00001744 UI != E; ++UI) {
1745 const User *U = *UI;
1746 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001747 if (SI->getOperand(0) == GV || SI->isVolatile())
1748 return true; // Storing addr of GV.
Gabor Greifbd1f9932010-03-24 10:29:52 +00001749 } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001750 // Make sure we are calling the function, not passing the address.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001751 ImmutableCallSite CS(cast<Instruction>(U));
Gabor Greifc9f75002010-03-24 13:21:49 +00001752 if (!CS.isCallee(UI))
Nick Lewyckyaf386132008-11-03 03:49:14 +00001753 return true;
Gabor Greifbd1f9932010-03-24 10:29:52 +00001754 } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001755 if (LI->isVolatile())
1756 return true;
Gabor Greifbd1f9932010-03-24 10:29:52 +00001757 } else if (isa<BlockAddress>(U)) {
Chris Lattnerb2710042009-11-01 06:11:53 +00001758 // blockaddress doesn't take the address of the function, it takes addr
1759 // of label.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001760 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001761 return true;
1762 }
Gabor Greifbd1f9932010-03-24 10:29:52 +00001763 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001764 return false;
1765}
1766
1767bool IPSCCP::runOnModule(Module &M) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001768 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner59acc7d2004-12-10 08:02:06 +00001769
Chris Lattner1522ce92010-08-12 22:25:23 +00001770 // AddressTakenFunctions - This set keeps track of the address-taken functions
1771 // that are in the input. As IPSCCP runs through and simplifies code,
1772 // functions that were address taken can end up losing their
1773 // address-taken-ness. Because of this, we keep track of their addresses from
1774 // the first pass so we can use them for the later simplification pass.
1775 SmallPtrSet<Function*, 32> AddressTakenFunctions;
1776
Chris Lattner59acc7d2004-12-10 08:02:06 +00001777 // Loop over all functions, marking arguments to those with their addresses
1778 // taken or that are external as overdefined.
1779 //
Chris Lattnerff3ca152009-11-02 06:34:04 +00001780 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1781 if (F->isDeclaration())
1782 continue;
1783
Chris Lattner14532d02009-11-03 03:42:51 +00001784 // If this is a strong or ODR definition of this function, then we can
1785 // propagate information about its result into callsites of it.
Chris Lattnerfc36a562009-11-03 23:40:48 +00001786 if (!F->mayBeOverridden())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001787 Solver.AddTrackedFunction(F);
Chris Lattner14532d02009-11-03 03:42:51 +00001788
1789 // If this function only has direct calls that we can see, we can track its
1790 // arguments and return value aggressively, and can assume it is not called
1791 // unless we see evidence to the contrary.
Chris Lattner1522ce92010-08-12 22:25:23 +00001792 if (F->hasLocalLinkage()) {
1793 if (AddressIsTaken(F))
1794 AddressTakenFunctions.insert(F);
1795 else {
1796 Solver.AddArgumentTrackedFunction(F);
1797 continue;
1798 }
Chris Lattner2396cc32009-11-03 19:24:51 +00001799 }
Chris Lattner14532d02009-11-03 03:42:51 +00001800
1801 // Assume the function is called.
1802 Solver.MarkBlockExecutable(F->begin());
1803
1804 // Assume nothing about the incoming arguments.
1805 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1806 AI != E; ++AI)
Chris Lattnerfc36a562009-11-03 23:40:48 +00001807 Solver.markAnythingOverdefined(AI);
Chris Lattnerff3ca152009-11-02 06:34:04 +00001808 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001809
Chris Lattnerdd336d12004-12-11 05:15:59 +00001810 // Loop over global variables. We inform the solver about any internal global
1811 // variables that do not have their 'addresses taken'. If they don't have
1812 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001813 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1814 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001815 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001816 Solver.TrackValueOfGlobalVariable(G);
1817
Chris Lattner59acc7d2004-12-10 08:02:06 +00001818 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001819 bool ResolvedUndefs = true;
1820 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001821 Solver.Solve();
1822
David Greene971cc7e2010-01-05 01:27:15 +00001823 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001824 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001825 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001826 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001827 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001828
1829 bool MadeChanges = false;
1830
1831 // Iterate over all of the instructions in the module, replacing them with
1832 // constants if we have found them to be of constant values.
1833 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001834 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner1c1f1122007-02-02 21:15:06 +00001835
Chris Lattner59acc7d2004-12-10 08:02:06 +00001836 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner89112b62009-11-02 03:25:55 +00001837 if (Solver.isBlockExecutable(F->begin())) {
1838 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1839 AI != E; ++AI) {
Duncan Sands1df98592010-02-16 11:11:14 +00001840 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
Chris Lattner89112b62009-11-02 03:25:55 +00001841
Chris Lattnerfc36a562009-11-03 23:40:48 +00001842 // TODO: Could use getStructLatticeValueFor to find out if the entire
1843 // result is a constant and replace it entirely if so.
1844
Chris Lattner89112b62009-11-02 03:25:55 +00001845 LatticeVal IV = Solver.getLatticeValueFor(AI);
1846 if (IV.isOverdefined()) continue;
1847
1848 Constant *CST = IV.isConstant() ?
1849 IV.getConstant() : UndefValue::get(AI->getType());
David Greene971cc7e2010-01-05 01:27:15 +00001850 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Chris Lattner89112b62009-11-02 03:25:55 +00001851
1852 // Replaces all of the uses of a variable with uses of the
1853 // constant.
1854 AI->replaceAllUsesWith(CST);
1855 ++IPNumArgsElimed;
1856 }
Chris Lattner8db50122009-11-02 02:54:24 +00001857 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001858
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001859 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001860 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001861 DeleteInstructionInBlock(BB);
1862 MadeChanges = true;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001863
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001864 TerminatorInst *TI = BB->getTerminator();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001865 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1866 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001867 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001868 TI->getSuccessor(i)->removePredecessor(BB);
1869 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001870 if (!TI->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001871 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001872 TI->eraseFromParent();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001873
Chris Lattner864737b2004-12-11 05:32:19 +00001874 if (&*BB != &F->front())
1875 BlocksToErase.push_back(BB);
1876 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001877 new UnreachableInst(M.getContext(), BB);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001878 continue;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001879 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001880
1881 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1882 Instruction *Inst = BI++;
Duncan Sands1df98592010-02-16 11:11:14 +00001883 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001884 continue;
1885
Chris Lattnerfc36a562009-11-03 23:40:48 +00001886 // TODO: Could use getStructLatticeValueFor to find out if the entire
1887 // result is a constant and replace it entirely if so.
1888
Chris Lattner8db50122009-11-02 02:54:24 +00001889 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1890 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001891 continue;
1892
1893 Constant *Const = IV.isConstant()
1894 ? IV.getConstant() : UndefValue::get(Inst->getType());
David Greene971cc7e2010-01-05 01:27:15 +00001895 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001896
1897 // Replaces all of the uses of a variable with uses of the
1898 // constant.
1899 Inst->replaceAllUsesWith(Const);
1900
1901 // Delete the instruction.
1902 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1903 Inst->eraseFromParent();
1904
1905 // Hey, we just changed something!
1906 MadeChanges = true;
1907 ++IPNumInstRemoved;
1908 }
1909 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001910
1911 // Now that all instructions in the function are constant folded, erase dead
1912 // blocks, because we can now use ConstantFoldTerminator to get rid of
1913 // in-edges.
1914 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1915 // If there are any PHI nodes in this successor, drop entries for BB now.
1916 BasicBlock *DeadBB = BlocksToErase[i];
Dan Gohman6a239212009-11-20 20:19:14 +00001917 for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1918 UI != UE; ) {
Dan Gohman8f3817f2009-11-23 16:13:39 +00001919 // Grab the user and then increment the iterator early, as the user
1920 // will be deleted. Step past all adjacent uses from the same user.
1921 Instruction *I = dyn_cast<Instruction>(*UI);
1922 do { ++UI; } while (UI != UE && *UI == I);
1923
Dan Gohman6a239212009-11-20 20:19:14 +00001924 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohman6a239212009-11-20 20:19:14 +00001925 if (!I) continue;
1926
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001927 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001928 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001929 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001930 // if this is a branch or switch on undef. Fold it manually as a
1931 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001932#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001933 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1934 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1935 "Branch should be foldable!");
1936 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1937 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1938 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001939 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerddaaa372006-10-23 18:57:02 +00001940 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001941#endif
Chris Lattnerddaaa372006-10-23 18:57:02 +00001942
1943 // Make this an uncond branch to the first successor.
1944 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001945 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001946
1947 // Remove entries in successor phi nodes to remove edges.
1948 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1949 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1950
1951 // Remove the old terminator.
1952 TI->eraseFromParent();
1953 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001954 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001955
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001956 // Finally, delete the basic block.
1957 F->getBasicBlockList().erase(DeadBB);
1958 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001959 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001960 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001961
1962 // If we inferred constant or undef return values for a function, we replaced
1963 // all call uses with the inferred value. This means we don't need to bother
1964 // actually returning anything from the function. Replace all return
1965 // instructions with return undef.
Chris Lattnerd38cdb02010-02-27 00:07:42 +00001966 //
1967 // Do this in two stages: first identify the functions we should process, then
1968 // actually zap their returns. This is important because we can only do this
Chris Lattner9fcd72b2010-02-27 07:50:40 +00001969 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd38cdb02010-02-27 00:07:42 +00001970 // last use of a function, the order of processing functions would affect
Chris Lattner9fcd72b2010-02-27 07:50:40 +00001971 // whether other functions are optimizable.
Chris Lattnerd38cdb02010-02-27 00:07:42 +00001972 SmallVector<ReturnInst*, 8> ReturnsToZap;
1973
Devang Patel9af014f2008-03-11 17:32:05 +00001974 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001975 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001976 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner14532d02009-11-03 03:42:51 +00001977 E = RV.end(); I != E; ++I) {
1978 Function *F = I->first;
1979 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1980 continue;
1981
1982 // We can only do this if we know that nothing else can call the function.
Chris Lattner1522ce92010-08-12 22:25:23 +00001983 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
Chris Lattner14532d02009-11-03 03:42:51 +00001984 continue;
1985
1986 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1987 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1988 if (!isa<UndefValue>(RI->getOperand(0)))
Chris Lattnerd38cdb02010-02-27 00:07:42 +00001989 ReturnsToZap.push_back(RI);
1990 }
1991
1992 // Zap all returns which we've identified as zap to change.
1993 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1994 Function *F = ReturnsToZap[i]->getParent()->getParent();
1995 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattner14532d02009-11-03 03:42:51 +00001996 }
1997
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001998 // If we inferred constant or undef values for globals variables, we can delete
Chris Lattnerdd336d12004-12-11 05:15:59 +00001999 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00002000 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
2001 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00002002 E = TG.end(); I != E; ++I) {
2003 GlobalVariable *GV = I->first;
2004 assert(!I->second.isOverdefined() &&
2005 "Overdefined values should have been taken out of the map!");
David Greene971cc7e2010-01-05 01:27:15 +00002006 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattnerdd336d12004-12-11 05:15:59 +00002007 while (!GV->use_empty()) {
2008 StoreInst *SI = cast<StoreInst>(GV->use_back());
2009 SI->eraseFromParent();
2010 }
2011 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00002012 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00002013 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002014
Chris Lattner59acc7d2004-12-10 08:02:06 +00002015 return MadeChanges;
2016}