blob: c4fc38ae083bffca9e27a65af81b66889475d4fc [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"
Chris Lattner58b7b082004-04-13 19:43:54 +000028#include "llvm/Transforms/Utils/Local.h"
Chris Lattner5638dc62009-11-02 06:06:14 +000029#include "llvm/Target/TargetData.h"
Chad Rosier00737bd2011-12-01 21:29:16 +000030#include "llvm/Target/TargetLibraryInfo.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"
Chris Lattner138a1242001-06-27 23:38:11 +000042#include <algorithm>
Chris Lattnerd7456022004-01-09 06:02:20 +000043using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000044
Chris Lattner0e5f4992006-12-19 21:40:18 +000045STATISTIC(NumInstRemoved, "Number of instructions removed");
46STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
47
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000048STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000049STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
50STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
51
Chris Lattner0dbfc052002-04-29 21:26:08 +000052namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000053/// LatticeVal class - This class represents the different lattice values that
54/// an LLVM value may occupy. It is a simple class with value semantics.
55///
Chris Lattner3e8b6632009-09-02 06:11:42 +000056class LatticeVal {
Chris Lattner79272202009-11-02 02:20:32 +000057 enum LatticeValueTy {
Chris Lattner3bad2532006-12-20 06:21:33 +000058 /// undefined - This LLVM Value has no known value yet.
59 undefined,
Jakub Staszak785a7a92012-01-18 21:16:33 +000060
Chris Lattner3bad2532006-12-20 06:21:33 +000061 /// constant - This LLVM Value has a specific constant value.
62 constant,
63
64 /// forcedconstant - This LLVM Value was thought to be undef until
65 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
66 /// with another (different) constant, it goes to overdefined, instead of
67 /// asserting.
68 forcedconstant,
Jakub Staszak785a7a92012-01-18 21:16:33 +000069
Chris Lattner3bad2532006-12-20 06:21:33 +000070 /// overdefined - This instruction is not known to be constant, and we know
71 /// it has a value.
72 overdefined
Chris Lattner79272202009-11-02 02:20:32 +000073 };
74
75 /// Val: This stores the current lattice value along with the Constant* for
76 /// the constant if this is a 'constant' or 'forcedconstant' value.
77 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Jakub Staszak785a7a92012-01-18 21:16:33 +000078
Chris Lattner79272202009-11-02 02:20:32 +000079 LatticeValueTy getLatticeValue() const {
80 return Val.getInt();
81 }
Jakub Staszak785a7a92012-01-18 21:16:33 +000082
Chris Lattner138a1242001-06-27 23:38:11 +000083public:
Chris Lattner38871e42009-11-02 03:03:42 +000084 LatticeVal() : Val(0, undefined) {}
Jakub Staszak785a7a92012-01-18 21:16:33 +000085
Chris Lattner38871e42009-11-02 03:03:42 +000086 bool isUndefined() const { return getLatticeValue() == undefined; }
87 bool isConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000088 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
89 }
Chris Lattner38871e42009-11-02 03:03:42 +000090 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Jakub Staszak785a7a92012-01-18 21:16:33 +000091
Chris Lattner38871e42009-11-02 03:03:42 +000092 Constant *getConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000093 assert(isConstant() && "Cannot get the constant of a non-constant!");
94 return Val.getPointer();
95 }
Jakub Staszak785a7a92012-01-18 21:16:33 +000096
Chris Lattner79272202009-11-02 02:20:32 +000097 /// markOverdefined - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +000098 bool markOverdefined() {
Chris Lattner79272202009-11-02 02:20:32 +000099 if (isOverdefined())
100 return false;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000101
Chris Lattner79272202009-11-02 02:20:32 +0000102 Val.setInt(overdefined);
103 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000104 }
105
Chris Lattner79272202009-11-02 02:20:32 +0000106 /// markConstant - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000107 bool markConstant(Constant *V) {
Chris Lattnerc175e5d2009-11-03 16:50:11 +0000108 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattner79272202009-11-02 02:20:32 +0000109 assert(getConstant() == V && "Marking constant with different value");
110 return false;
Chris Lattner138a1242001-06-27 23:38:11 +0000111 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000112
Chris Lattner79272202009-11-02 02:20:32 +0000113 if (isUndefined()) {
114 Val.setInt(constant);
115 assert(V && "Marking constant with NULL");
116 Val.setPointer(V);
117 } else {
Jakub Staszak785a7a92012-01-18 21:16:33 +0000118 assert(getLatticeValue() == forcedconstant &&
Chris Lattner79272202009-11-02 02:20:32 +0000119 "Cannot move from overdefined to constant!");
120 // Stay at forcedconstant if the constant is the same.
121 if (V == getConstant()) return false;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000122
Chris Lattner79272202009-11-02 02:20:32 +0000123 // Otherwise, we go to overdefined. Assumptions made based on the
124 // forced value are possibly wrong. Assuming this is another constant
125 // could expose a contradiction.
126 Val.setInt(overdefined);
127 }
128 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000129 }
130
Chris Lattner36c99522009-11-02 03:21:36 +0000131 /// getConstantInt - If this is a constant with a ConstantInt value, return it
132 /// otherwise return null.
133 ConstantInt *getConstantInt() const {
134 if (isConstant())
135 return dyn_cast<ConstantInt>(getConstant());
136 return 0;
137 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000138
Chris Lattner38871e42009-11-02 03:03:42 +0000139 void markForcedConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000140 assert(isUndefined() && "Can't force a defined value!");
141 Val.setInt(forcedconstant);
142 Val.setPointer(V);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000143 }
Chris Lattner138a1242001-06-27 23:38:11 +0000144};
Chris Lattnercc4f60b2009-11-02 02:47:51 +0000145} // end anonymous namespace.
146
147
148namespace {
Chris Lattner138a1242001-06-27 23:38:11 +0000149
Chris Lattner138a1242001-06-27 23:38:11 +0000150//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000151//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000152/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
153/// Constant Propagation.
154///
155class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner5638dc62009-11-02 06:06:14 +0000156 const TargetData *TD;
Chad Rosier00737bd2011-12-01 21:29:16 +0000157 const TargetLibraryInfo *TLI;
Nick Lewyckyfd47a592011-07-25 21:16:04 +0000158 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000159 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000160
Chris Lattnerfc36a562009-11-03 23:40:48 +0000161 /// StructValueState - This maintains ValueState for values that have
162 /// StructType, for example for formal arguments, calls, insertelement, etc.
163 ///
164 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000165
Chris Lattnerdd336d12004-12-11 05:15:59 +0000166 /// GlobalValue - If we are tracking any values for the contents of a global
167 /// variable, we keep a mapping from the constant accessor to the element of
168 /// the global, to the currently known value. If the value becomes
169 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000170 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000171
Devang Patel7c490d42008-03-11 05:46:42 +0000172 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000173 /// value out of a function, it will have an entry in this map, indicating
174 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000175 DenseMap<Function*, LatticeVal> TrackedRetVals;
176
177 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
178 /// that return multiple values.
Chris Lattnercf712de2008-08-23 23:36:38 +0000179 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000180
Chris Lattnerfc36a562009-11-03 23:40:48 +0000181 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
182 /// represented here for efficient lookup.
183 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000184
Chris Lattnerabf67ef2009-11-03 20:52:57 +0000185 /// TrackingIncomingArguments - This is the set of functions for whose
186 /// arguments we make optimistic assumptions about and try to prove as
187 /// constants.
Chris Lattner2396cc32009-11-03 19:24:51 +0000188 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000189
Chris Lattner38871e42009-11-02 03:03:42 +0000190 /// The reason for two worklists is that overdefined is the lowest state
191 /// on the lattice, and moving things to overdefined as fast as possible
192 /// makes SCCP converge much faster.
193 ///
194 /// By having a separate worklist, we accomplish this because everything
195 /// possibly overdefined will become overdefined at the soonest possible
196 /// point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000197 SmallVector<Value*, 64> OverdefinedInstWorkList;
198 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000199
200
Chris Lattnercf712de2008-08-23 23:36:38 +0000201 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000202
203 /// KnownFeasibleEdges - Entries in this set are edges which have already had
204 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000205 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
206 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000207public:
Chad Rosier00737bd2011-12-01 21:29:16 +0000208 SCCPSolver(const TargetData *td, const TargetLibraryInfo *tli)
209 : TD(td), TLI(tli) {}
Chris Lattner138a1242001-06-27 23:38:11 +0000210
Chris Lattner82bec2c2004-11-15 04:44:20 +0000211 /// MarkBlockExecutable - This method can be used by clients to mark all of
212 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner09275292009-11-02 06:11:23 +0000213 ///
214 /// This returns true if the block was not considered live before.
215 bool MarkBlockExecutable(BasicBlock *BB) {
216 if (!BBExecutable.insert(BB)) return false;
David Greene971cc7e2010-01-05 01:27:15 +0000217 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +0000218 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner09275292009-11-02 06:11:23 +0000219 return true;
Chris Lattner0dbfc052002-04-29 21:26:08 +0000220 }
221
Chris Lattnerdd336d12004-12-11 05:15:59 +0000222 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000223 /// inform the SCCPSolver that it should track loads and stores to the
224 /// specified global variable if it can. This is only legal to call if
225 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000226 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000227 // We only track the contents of scalar globals.
228 if (GV->getType()->getElementType()->isSingleValueType()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000229 LatticeVal &IV = TrackedGlobals[GV];
230 if (!isa<UndefValue>(GV->getInitializer()))
231 IV.markConstant(GV->getInitializer());
232 }
233 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000234
235 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
236 /// and out of the specified function (which cannot have its address taken),
237 /// this method must be called.
238 void AddTrackedFunction(Function *F) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000239 // Add an entry, F -> undef.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000240 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000241 MRVFunctionsTracked.insert(F);
Devang Patel7c490d42008-03-11 05:46:42 +0000242 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000243 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
244 LatticeVal()));
245 } else
246 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000247 }
248
Chris Lattner2396cc32009-11-03 19:24:51 +0000249 void AddArgumentTrackedFunction(Function *F) {
250 TrackingIncomingArguments.insert(F);
251 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000252
Chris Lattner82bec2c2004-11-15 04:44:20 +0000253 /// Solve - Solve for constants and executable blocks.
254 ///
255 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000256
Chris Lattner3bad2532006-12-20 06:21:33 +0000257 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000258 /// that branches on undef values cannot reach any of their successors.
259 /// However, this is not a safe assumption. After we solve dataflow, this
260 /// method should be use to handle this. If this returns true, the solver
261 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000262 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000263
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000264 bool isBlockExecutable(BasicBlock *BB) const {
265 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000266 }
267
Chris Lattner8db50122009-11-02 02:54:24 +0000268 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000269 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattner8db50122009-11-02 02:54:24 +0000270 assert(I != ValueState.end() && "V is not in valuemap!");
271 return I->second;
Chris Lattner82bec2c2004-11-15 04:44:20 +0000272 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000273
Chris Lattner473fc962010-08-18 02:41:56 +0000274 /*LatticeVal getStructLatticeValueFor(Value *V, unsigned i) const {
Jakub Staszak785a7a92012-01-18 21:16:33 +0000275 DenseMap<std::pair<Value*, unsigned>, LatticeVal>::const_iterator I =
Chris Lattnerfc36a562009-11-03 23:40:48 +0000276 StructValueState.find(std::make_pair(V, i));
277 assert(I != StructValueState.end() && "V is not in valuemap!");
278 return I->second;
Chris Lattner473fc962010-08-18 02:41:56 +0000279 }*/
Chris Lattner82bec2c2004-11-15 04:44:20 +0000280
Devang Patel7c490d42008-03-11 05:46:42 +0000281 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000282 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000283 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
284 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000285 }
286
Chris Lattnerdd336d12004-12-11 05:15:59 +0000287 /// getTrackedGlobals - Get and return the set of inferred initializers for
288 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000289 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000290 return TrackedGlobals;
291 }
292
Chris Lattner36c99522009-11-02 03:21:36 +0000293 void markOverdefined(Value *V) {
Duncan Sands1df98592010-02-16 11:11:14 +0000294 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner57939df2007-03-04 04:50:21 +0000295 markOverdefined(ValueState[V], V);
296 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000297
Chris Lattnerfc36a562009-11-03 23:40:48 +0000298 /// markAnythingOverdefined - Mark the specified value overdefined. This
299 /// works with both scalars and structs.
300 void markAnythingOverdefined(Value *V) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000301 if (StructType *STy = dyn_cast<StructType>(V->getType()))
Chris Lattnerfc36a562009-11-03 23:40:48 +0000302 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
303 markOverdefined(getStructValueState(V, i), V);
304 else
305 markOverdefined(V);
306 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000307
Chris Lattner138a1242001-06-27 23:38:11 +0000308private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000309 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000310 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000311 // the users of the instruction are updated later.
312 //
Chris Lattner38871e42009-11-02 03:03:42 +0000313 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
314 if (!IV.markConstant(C)) return;
David Greene971cc7e2010-01-05 01:27:15 +0000315 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Chris Lattner8829cec2010-04-09 01:14:31 +0000316 if (IV.isOverdefined())
317 OverdefinedInstWorkList.push_back(V);
318 else
319 InstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000320 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000321
Chris Lattner38871e42009-11-02 03:03:42 +0000322 void markConstant(Value *V, Constant *C) {
Duncan Sands1df98592010-02-16 11:11:14 +0000323 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner59acc7d2004-12-10 08:02:06 +0000324 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000325 }
326
Chris Lattner2a0433b2009-11-02 05:55:40 +0000327 void markForcedConstant(Value *V, Constant *C) {
Duncan Sands1df98592010-02-16 11:11:14 +0000328 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner8829cec2010-04-09 01:14:31 +0000329 LatticeVal &IV = ValueState[V];
330 IV.markForcedConstant(C);
David Greene971cc7e2010-01-05 01:27:15 +0000331 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Chris Lattner8829cec2010-04-09 01:14:31 +0000332 if (IV.isOverdefined())
333 OverdefinedInstWorkList.push_back(V);
334 else
335 InstWorkList.push_back(V);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000336 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000337
338
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000339 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000340 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000341 // work list so that the users of the instruction are updated later.
Chris Lattner38871e42009-11-02 03:03:42 +0000342 void markOverdefined(LatticeVal &IV, Value *V) {
343 if (!IV.markOverdefined()) return;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000344
David Greene971cc7e2010-01-05 01:27:15 +0000345 DEBUG(dbgs() << "markOverdefined: ";
Chris Lattner38871e42009-11-02 03:03:42 +0000346 if (Function *F = dyn_cast<Function>(V))
David Greene971cc7e2010-01-05 01:27:15 +0000347 dbgs() << "Function '" << F->getName() << "'\n";
Chris Lattner38871e42009-11-02 03:03:42 +0000348 else
David Greene971cc7e2010-01-05 01:27:15 +0000349 dbgs() << *V << '\n');
Chris Lattner38871e42009-11-02 03:03:42 +0000350 // Only instructions go on the work list
351 OverdefinedInstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000352 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000353
Chris Lattner2a0433b2009-11-02 05:55:40 +0000354 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000355 if (IV.isOverdefined() || MergeWithV.isUndefined())
356 return; // Noop.
357 if (MergeWithV.isOverdefined())
358 markOverdefined(IV, V);
359 else if (IV.isUndefined())
360 markConstant(IV, V, MergeWithV.getConstant());
361 else if (IV.getConstant() != MergeWithV.getConstant())
362 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000363 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000364
Chris Lattner2a0433b2009-11-02 05:55:40 +0000365 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Duncan Sands1df98592010-02-16 11:11:14 +0000366 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner36c99522009-11-02 03:21:36 +0000367 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000368 }
369
Chris Lattner138a1242001-06-27 23:38:11 +0000370
Chris Lattner2a0433b2009-11-02 05:55:40 +0000371 /// getValueState - Return the LatticeVal object that corresponds to the
372 /// value. This function handles the case when the value hasn't been seen yet
373 /// by properly seeding constants etc.
Chris Lattner38871e42009-11-02 03:03:42 +0000374 LatticeVal &getValueState(Value *V) {
Duncan Sands1df98592010-02-16 11:11:14 +0000375 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Chris Lattner5d356a72004-10-16 18:09:41 +0000376
Benjamin Kramerbcaa2152009-11-05 14:33:27 +0000377 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
378 ValueState.insert(std::make_pair(V, LatticeVal()));
379 LatticeVal &LV = I.first->second;
380
381 if (!I.second)
382 return LV; // Common case, already in the map.
Chris Lattner36c99522009-11-02 03:21:36 +0000383
Chris Lattner3bad2532006-12-20 06:21:33 +0000384 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner36c99522009-11-02 03:21:36 +0000385 // Undef values remain undefined.
386 if (!isa<UndefValue>(V))
Chris Lattnerb59673e2007-02-02 20:38:30 +0000387 LV.markConstant(C); // Constants are constant
Chris Lattner2a88bb72002-08-30 23:39:00 +0000388 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000389
Chris Lattner2f096252009-11-02 02:33:50 +0000390 // All others are underdefined by default.
Chris Lattner36c99522009-11-02 03:21:36 +0000391 return LV;
Chris Lattner138a1242001-06-27 23:38:11 +0000392 }
393
Chris Lattnerfc36a562009-11-03 23:40:48 +0000394 /// getStructValueState - Return the LatticeVal object that corresponds to the
395 /// value/field pair. This function handles the case when the value hasn't
396 /// been seen yet by properly seeding constants etc.
397 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands1df98592010-02-16 11:11:14 +0000398 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattnerfc36a562009-11-03 23:40:48 +0000399 assert(i < cast<StructType>(V->getType())->getNumElements() &&
400 "Invalid element #");
Benjamin Kramerbcaa2152009-11-05 14:33:27 +0000401
402 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
403 bool> I = StructValueState.insert(
404 std::make_pair(std::make_pair(V, i), LatticeVal()));
405 LatticeVal &LV = I.first->second;
406
407 if (!I.second)
408 return LV; // Common case, already in the map.
409
Chris Lattnerfc36a562009-11-03 23:40:48 +0000410 if (Constant *C = dyn_cast<Constant>(V)) {
411 if (isa<UndefValue>(C))
412 ; // Undef values remain undefined.
413 else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C))
414 LV.markConstant(CS->getOperand(i)); // Constants are constant.
415 else if (isa<ConstantAggregateZero>(C)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000416 Type *FieldTy = cast<StructType>(V->getType())->getElementType(i);
Chris Lattnerfc36a562009-11-03 23:40:48 +0000417 LV.markConstant(Constant::getNullValue(FieldTy));
418 } else
419 LV.markOverdefined(); // Unknown sort of constant.
420 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000421
Chris Lattnerfc36a562009-11-03 23:40:48 +0000422 // All others are underdefined by default.
423 return LV;
424 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000425
Chris Lattnerfc36a562009-11-03 23:40:48 +0000426
Chris Lattner2a0433b2009-11-02 05:55:40 +0000427 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
428 /// work list if it is not already executable.
Chris Lattner16b18fd2003-10-08 16:55:34 +0000429 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
430 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
431 return; // This edge is already known to be executable!
432
Chris Lattner09275292009-11-02 06:11:23 +0000433 if (!MarkBlockExecutable(Dest)) {
434 // If the destination is already executable, we just made an *edge*
435 // feasible that wasn't before. Revisit the PHI nodes in the block
436 // because they have potentially new operands.
David Greene971cc7e2010-01-05 01:27:15 +0000437 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000438 << " -> " << Dest->getName() << "\n");
Chris Lattner16b18fd2003-10-08 16:55:34 +0000439
Chris Lattner09275292009-11-02 06:11:23 +0000440 PHINode *PN;
441 for (BasicBlock::iterator I = Dest->begin();
442 (PN = dyn_cast<PHINode>(I)); ++I)
443 visitPHINode(*PN);
Chris Lattner9de28282003-04-25 02:50:03 +0000444 }
Chris Lattner138a1242001-06-27 23:38:11 +0000445 }
446
Chris Lattner82bec2c2004-11-15 04:44:20 +0000447 // getFeasibleSuccessors - Return a vector of booleans to indicate which
448 // successors are reachable from a given terminator instruction.
449 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000450 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000451
452 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000453 // block to the 'To' basic block is currently feasible.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000454 //
455 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
456
457 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattner2f096252009-11-02 02:33:50 +0000458 // instruction that was just changed state somehow. Based on this
Chris Lattner82bec2c2004-11-15 04:44:20 +0000459 // information, we need to update the specified user of this instruction.
460 //
Chris Lattner14532d02009-11-03 03:42:51 +0000461 void OperandChangedState(Instruction *I) {
462 if (BBExecutable.count(I->getParent())) // Inst is executable?
463 visit(*I);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000464 }
Dale Johannesenf619b5a2010-11-30 20:23:21 +0000465
Chris Lattner82bec2c2004-11-15 04:44:20 +0000466private:
467 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000468
Chris Lattner2f096252009-11-02 02:33:50 +0000469 // visit implementations - Something changed in this instruction. Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000470 // operand made a transition, or the instruction is newly executable. Change
471 // the value type of I to reflect these changes if appropriate.
Chris Lattner7e708292002-06-25 16:13:24 +0000472 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000473
474 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000475 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000476 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000477
Chris Lattnerb8047602002-08-14 17:53:45 +0000478 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000479 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000480 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000481 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000482 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000483 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000484 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000485 void visitExtractValueInst(ExtractValueInst &EVI);
486 void visitInsertValueInst(InsertValueInst &IVI);
Bill Wendlinge6e88262011-08-12 20:24:12 +0000487 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000488
Chris Lattner2f096252009-11-02 02:33:50 +0000489 // Instructions that cannot be folded away.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000490 void visitStoreInst (StoreInst &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000491 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000492 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez66284e02009-10-24 04:23:03 +0000493 void visitCallInst (CallInst &I) {
Gabor Greif7d3056b2010-07-28 22:50:26 +0000494 visitCallSite(&I);
Victor Hernandez83d63912009-09-18 22:35:49 +0000495 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000496 void visitInvokeInst (InvokeInst &II) {
Gabor Greif7d3056b2010-07-28 22:50:26 +0000497 visitCallSite(&II);
Chris Lattner59acc7d2004-12-10 08:02:06 +0000498 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000499 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000500 void visitCallSite (CallSite CS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +0000501 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner36143fc2003-09-08 18:54:55 +0000502 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000503 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Eli Friedman8a552bb2011-07-27 01:08:30 +0000504 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Eli Friedmanfe1926e2011-08-02 21:35:16 +0000505 void visitAtomicCmpXchgInst (AtomicCmpXchgInst &I) { markOverdefined(&I); }
506 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
Victor Hernandez7b929da2009-10-23 21:09:37 +0000507 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnerfc36a562009-11-03 23:40:48 +0000508 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000509
Chris Lattner7e708292002-06-25 16:13:24 +0000510 void visitInstruction(Instruction &I) {
Chris Lattner2f096252009-11-02 02:33:50 +0000511 // If a new instruction is added to LLVM that we don't handle.
David Greene971cc7e2010-01-05 01:27:15 +0000512 dbgs() << "SCCP: Don't know how to handle: " << I;
Chris Lattnerfc36a562009-11-03 23:40:48 +0000513 markAnythingOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000514 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000515};
Chris Lattnerf6293092002-07-23 18:06:35 +0000516
Duncan Sandse2abf122007-07-20 08:56:21 +0000517} // end anonymous namespace
518
519
Chris Lattnerb9a66342002-05-02 21:44:00 +0000520// getFeasibleSuccessors - Return a vector of booleans to indicate which
521// successors are reachable from a given terminator instruction.
522//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000523void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000524 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000525 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000526 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000527 if (BI->isUnconditional()) {
528 Succs[0] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000529 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000530 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000531
Chris Lattner2a0433b2009-11-02 05:55:40 +0000532 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000533 ConstantInt *CI = BCValue.getConstantInt();
534 if (CI == 0) {
Chris Lattnerea0db072009-11-02 02:30:06 +0000535 // Overdefined condition variables, and branches on unfoldable constant
536 // conditions, mean the branch could go either way.
Chris Lattner36c99522009-11-02 03:21:36 +0000537 if (!BCValue.isUndefined())
538 Succs[0] = Succs[1] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000539 return;
540 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000541
Chris Lattnerea0db072009-11-02 02:30:06 +0000542 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000543 Succs[CI->isZero()] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000544 return;
545 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000546
Chris Lattner36c99522009-11-02 03:21:36 +0000547 if (isa<InvokeInst>(TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000548 // Invoke instructions successors are always executable.
549 Succs[0] = Succs[1] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000550 return;
551 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000552
Chris Lattner4c0236f2009-10-29 01:21:20 +0000553 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Eli Friedman1fc291f2011-08-16 21:12:35 +0000554 if (TI.getNumSuccessors() < 2) {
555 Succs[0] = true;
556 return;
557 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000558 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000559 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak785a7a92012-01-18 21:16:33 +0000560
Chris Lattner36c99522009-11-02 03:21:36 +0000561 if (CI == 0) { // Overdefined or undefined condition?
Chris Lattnerb9a66342002-05-02 21:44:00 +0000562 // All destinations are executable!
Chris Lattner36c99522009-11-02 03:21:36 +0000563 if (!SCValue.isUndefined())
564 Succs.assign(TI.getNumSuccessors(), true);
565 return;
566 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000567
Chris Lattner36c99522009-11-02 03:21:36 +0000568 Succs[SI->findCaseValue(CI)] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000569 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000570 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000571
Chris Lattner4c0236f2009-10-29 01:21:20 +0000572 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
573 if (isa<IndirectBrInst>(&TI)) {
574 // Just mark all destinations executable!
575 Succs.assign(TI.getNumSuccessors(), true);
576 return;
577 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000578
Chris Lattner4c0236f2009-10-29 01:21:20 +0000579#ifndef NDEBUG
David Greene971cc7e2010-01-05 01:27:15 +0000580 dbgs() << "Unknown terminator instruction: " << TI << '\n';
Chris Lattner4c0236f2009-10-29 01:21:20 +0000581#endif
582 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000583}
584
585
Chris Lattner59f0ce22002-05-02 21:18:01 +0000586// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000587// block to the 'To' basic block is currently feasible.
Chris Lattner59f0ce22002-05-02 21:18:01 +0000588//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000589bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000590 assert(BBExecutable.count(To) && "Dest should always be alive!");
591
592 // Make sure the source basic block is executable!!
593 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000594
Chris Lattner2f096252009-11-02 02:33:50 +0000595 // Check to make sure this edge itself is actually feasible now.
Chris Lattner7d275f42003-10-08 15:47:41 +0000596 TerminatorInst *TI = From->getTerminator();
597 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
598 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000599 return true;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000600
Chris Lattner2a0433b2009-11-02 05:55:40 +0000601 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000602
Chris Lattnerea0db072009-11-02 02:30:06 +0000603 // Overdefined condition variables mean the branch could go either way,
604 // undef conditions mean that neither edge is feasible yet.
Chris Lattner36c99522009-11-02 03:21:36 +0000605 ConstantInt *CI = BCValue.getConstantInt();
606 if (CI == 0)
607 return !BCValue.isUndefined();
Jakub Staszak785a7a92012-01-18 21:16:33 +0000608
Chris Lattnerea0db072009-11-02 02:30:06 +0000609 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000610 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000611 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000612
Chris Lattner4c0236f2009-10-29 01:21:20 +0000613 // Invoke instructions successors are always executable.
614 if (isa<InvokeInst>(TI))
Chris Lattner7d275f42003-10-08 15:47:41 +0000615 return true;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000616
Chris Lattner4c0236f2009-10-29 01:21:20 +0000617 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eli Friedman1fc291f2011-08-16 21:12:35 +0000618 if (SI->getNumSuccessors() < 2)
619 return true;
620
Chris Lattner2a0433b2009-11-02 05:55:40 +0000621 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000622 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak785a7a92012-01-18 21:16:33 +0000623
Chris Lattner36c99522009-11-02 03:21:36 +0000624 if (CI == 0)
625 return !SCValue.isUndefined();
Chris Lattner84831642004-01-12 17:40:36 +0000626
Chris Lattner36c99522009-11-02 03:21:36 +0000627 // Make sure to skip the "default value" which isn't a value
628 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
629 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
630 return SI->getSuccessor(i) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000631
Chris Lattner36c99522009-11-02 03:21:36 +0000632 // If the constant value is not equal to any of the branches, we must
633 // execute default branch.
634 return SI->getDefaultDest() == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000635 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000636
Chris Lattner4c0236f2009-10-29 01:21:20 +0000637 // Just mark all destinations executable!
638 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
Eli Friedman21c60902011-05-21 19:13:10 +0000639 if (isa<IndirectBrInst>(TI))
Chris Lattner4c0236f2009-10-29 01:21:20 +0000640 return true;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000641
Chris Lattner4c0236f2009-10-29 01:21:20 +0000642#ifndef NDEBUG
David Greene971cc7e2010-01-05 01:27:15 +0000643 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
Chris Lattner4c0236f2009-10-29 01:21:20 +0000644#endif
645 llvm_unreachable(0);
Chris Lattner59f0ce22002-05-02 21:18:01 +0000646}
Chris Lattner138a1242001-06-27 23:38:11 +0000647
Chris Lattner2f096252009-11-02 02:33:50 +0000648// visit Implementations - Something changed in this instruction, either an
Chris Lattner138a1242001-06-27 23:38:11 +0000649// operand made a transition, or the instruction is newly executable. Change
650// the value type of I to reflect these changes if appropriate. This method
651// makes sure to do the following actions:
652//
653// 1. If a phi node merges two constants in, and has conflicting value coming
654// from different branches, or if the PHI node merges in an overdefined
655// value, then the PHI node becomes overdefined.
656// 2. If a phi node merges only constants in, and they all agree on value, the
657// PHI node becomes a constant value equal to that.
658// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
659// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
660// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
661// 6. If a conditional branch has a value that is constant, make the selected
662// destination executable
663// 7. If a conditional branch has a value that is overdefined, make all
664// successors executable.
665//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000666void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000667 // If this PN returns a struct, just mark the result overdefined.
668 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands1df98592010-02-16 11:11:14 +0000669 if (PN.getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +0000670 return markAnythingOverdefined(&PN);
Jakub Staszak785a7a92012-01-18 21:16:33 +0000671
Eli Friedmanb80f7782011-11-11 01:16:15 +0000672 if (getValueState(&PN).isOverdefined())
Chris Lattner1daee8b2004-01-12 03:57:30 +0000673 return; // Quick exit
Chris Lattner138a1242001-06-27 23:38:11 +0000674
Chris Lattnera2f652d2004-03-16 19:49:59 +0000675 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
676 // and slow us down a lot. Just mark them overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +0000677 if (PN.getNumIncomingValues() > 64)
Chris Lattner2a0433b2009-11-02 05:55:40 +0000678 return markOverdefined(&PN);
Jakub Staszak785a7a92012-01-18 21:16:33 +0000679
Chris Lattner2a632552002-04-18 15:13:15 +0000680 // Look at all of the executable operands of the PHI node. If any of them
681 // are overdefined, the PHI becomes overdefined as well. If they are all
682 // constant, and they agree with each other, the PHI becomes the identical
683 // constant. If they are constant and don't agree, the PHI is overdefined.
684 // If there are no executable operands, the PHI remains undefined.
685 //
Chris Lattner9de28282003-04-25 02:50:03 +0000686 Constant *OperandVal = 0;
687 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000688 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000689 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000690
Chris Lattner38871e42009-11-02 03:03:42 +0000691 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
692 continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000693
Chris Lattner38871e42009-11-02 03:03:42 +0000694 if (IV.isOverdefined()) // PHI node becomes overdefined!
695 return markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000696
Chris Lattner38871e42009-11-02 03:03:42 +0000697 if (OperandVal == 0) { // Grab the first value.
698 OperandVal = IV.getConstant();
699 continue;
Chris Lattner138a1242001-06-27 23:38:11 +0000700 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000701
Chris Lattner38871e42009-11-02 03:03:42 +0000702 // There is already a reachable operand. If we conflict with it,
703 // then the PHI node becomes overdefined. If we agree with it, we
704 // can continue on.
Jakub Staszak785a7a92012-01-18 21:16:33 +0000705
Chris Lattner38871e42009-11-02 03:03:42 +0000706 // Check to see if there are two different constants merging, if so, the PHI
707 // node is overdefined.
708 if (IV.getConstant() != OperandVal)
709 return markOverdefined(&PN);
Chris Lattner138a1242001-06-27 23:38:11 +0000710 }
711
Chris Lattner2a632552002-04-18 15:13:15 +0000712 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000713 // arguments that agree with each other(and OperandVal is the constant) or
714 // OperandVal is null because there are no defined incoming arguments. If
715 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000716 //
Chris Lattner9de28282003-04-25 02:50:03 +0000717 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000718 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000719}
720
Chris Lattner14532d02009-11-03 03:42:51 +0000721
722
723
Chris Lattner59acc7d2004-12-10 08:02:06 +0000724void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000725 if (I.getNumOperands() == 0) return; // ret void
Chris Lattner59acc7d2004-12-10 08:02:06 +0000726
Chris Lattner59acc7d2004-12-10 08:02:06 +0000727 Function *F = I.getParent()->getParent();
Chris Lattnerfc36a562009-11-03 23:40:48 +0000728 Value *ResultOp = I.getOperand(0);
Jakub Staszak785a7a92012-01-18 21:16:33 +0000729
Devang Patel7c490d42008-03-11 05:46:42 +0000730 // If we are tracking the return value of this function, merge it in.
Duncan Sands1df98592010-02-16 11:11:14 +0000731 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000732 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000733 TrackedRetVals.find(F);
Chris Lattner14532d02009-11-03 03:42:51 +0000734 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000735 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patel7c490d42008-03-11 05:46:42 +0000736 return;
737 }
738 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000739
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000740 // Handle functions that return multiple values.
Chris Lattnerfc36a562009-11-03 23:40:48 +0000741 if (!TrackedMultipleRetVals.empty()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000742 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattnerfc36a562009-11-03 23:40:48 +0000743 if (MRVFunctionsTracked.count(F))
744 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
745 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
746 getStructValueState(ResultOp, i));
Jakub Staszak785a7a92012-01-18 21:16:33 +0000747
Chris Lattner59acc7d2004-12-10 08:02:06 +0000748 }
749}
750
Chris Lattner82bec2c2004-11-15 04:44:20 +0000751void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000752 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000753 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000754
Chris Lattner16b18fd2003-10-08 16:55:34 +0000755 BasicBlock *BB = TI.getParent();
756
Chris Lattner2f096252009-11-02 02:33:50 +0000757 // Mark all feasible successors executable.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000758 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000759 if (SuccFeasible[i])
760 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000761}
762
Chris Lattner82bec2c2004-11-15 04:44:20 +0000763void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000764 LatticeVal OpSt = getValueState(I.getOperand(0));
765 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000766 markOverdefined(&I);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000767 else if (OpSt.isConstant()) // Propagate constant value
Jakub Staszak785a7a92012-01-18 21:16:33 +0000768 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattner2a0433b2009-11-02 05:55:40 +0000769 OpSt.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000770}
771
Chris Lattnerfc36a562009-11-03 23:40:48 +0000772
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000773void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000774 // If this returns a struct, mark all elements over defined, we don't track
775 // structs in structs.
Duncan Sands1df98592010-02-16 11:11:14 +0000776 if (EVI.getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +0000777 return markAnythingOverdefined(&EVI);
Jakub Staszak785a7a92012-01-18 21:16:33 +0000778
Chris Lattnerfc36a562009-11-03 23:40:48 +0000779 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner38871e42009-11-02 03:03:42 +0000780 if (EVI.getNumIndices() != 1)
781 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000782
Chris Lattnerfc36a562009-11-03 23:40:48 +0000783 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands1df98592010-02-16 11:11:14 +0000784 if (AggVal->getType()->isStructTy()) {
Chris Lattner103f2432009-11-10 22:02:09 +0000785 unsigned i = *EVI.idx_begin();
786 LatticeVal EltVal = getStructValueState(AggVal, i);
787 mergeInValue(getValueState(&EVI), &EVI, EltVal);
788 } else {
789 // Otherwise, must be extracting from an array.
790 return markOverdefined(&EVI);
791 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000792}
793
794void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000795 StructType *STy = dyn_cast<StructType>(IVI.getType());
Chris Lattnerfc36a562009-11-03 23:40:48 +0000796 if (STy == 0)
Chris Lattner38871e42009-11-02 03:03:42 +0000797 return markOverdefined(&IVI);
Jakub Staszak785a7a92012-01-18 21:16:33 +0000798
Chris Lattnerfc36a562009-11-03 23:40:48 +0000799 // If this has more than one index, we can't handle it, drive all results to
800 // undef.
801 if (IVI.getNumIndices() != 1)
802 return markAnythingOverdefined(&IVI);
Jakub Staszak785a7a92012-01-18 21:16:33 +0000803
Chris Lattnerfc36a562009-11-03 23:40:48 +0000804 Value *Aggr = IVI.getAggregateOperand();
805 unsigned Idx = *IVI.idx_begin();
Jakub Staszak785a7a92012-01-18 21:16:33 +0000806
Chris Lattnerfc36a562009-11-03 23:40:48 +0000807 // Compute the result based on what we're inserting.
808 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
809 // This passes through all values that aren't the inserted element.
810 if (i != Idx) {
811 LatticeVal EltVal = getStructValueState(Aggr, i);
812 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
813 continue;
814 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000815
Chris Lattnerfc36a562009-11-03 23:40:48 +0000816 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands1df98592010-02-16 11:11:14 +0000817 if (Val->getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +0000818 // We don't track structs in structs.
819 markOverdefined(getStructValueState(&IVI, i), &IVI);
820 else {
821 LatticeVal InVal = getValueState(Val);
822 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
823 }
824 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000825}
826
Chris Lattner82bec2c2004-11-15 04:44:20 +0000827void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000828 // If this select returns a struct, just mark the result overdefined.
829 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands1df98592010-02-16 11:11:14 +0000830 if (I.getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +0000831 return markAnythingOverdefined(&I);
Jakub Staszak785a7a92012-01-18 21:16:33 +0000832
Chris Lattner2a0433b2009-11-02 05:55:40 +0000833 LatticeVal CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000834 if (CondValue.isUndefined())
835 return;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000836
Chris Lattner36c99522009-11-02 03:21:36 +0000837 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000838 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
839 mergeInValue(&I, getValueState(OpVal));
Chris Lattner36c99522009-11-02 03:21:36 +0000840 return;
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000841 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000842
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000843 // Otherwise, the condition is overdefined or a constant we can't evaluate.
844 // See if we can produce something better than overdefined based on the T/F
845 // value.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000846 LatticeVal TVal = getValueState(I.getTrueValue());
847 LatticeVal FVal = getValueState(I.getFalseValue());
Jakub Staszak785a7a92012-01-18 21:16:33 +0000848
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000849 // select ?, C, C -> C.
Jakub Staszak785a7a92012-01-18 21:16:33 +0000850 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner38871e42009-11-02 03:03:42 +0000851 TVal.getConstant() == FVal.getConstant())
852 return markConstant(&I, FVal.getConstant());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000853
Chris Lattner2a0433b2009-11-02 05:55:40 +0000854 if (TVal.isUndefined()) // select ?, undef, X -> X.
855 return mergeInValue(&I, FVal);
856 if (FVal.isUndefined()) // select ?, X, undef -> X.
857 return mergeInValue(&I, TVal);
858 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000859}
860
Chris Lattner2a0433b2009-11-02 05:55:40 +0000861// Handle Binary Operators.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000862void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000863 LatticeVal V1State = getValueState(I.getOperand(0));
864 LatticeVal V2State = getValueState(I.getOperand(1));
Jakub Staszak785a7a92012-01-18 21:16:33 +0000865
Chris Lattneref36dfd2004-11-15 05:03:30 +0000866 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000867 if (IV.isOverdefined()) return;
868
Chris Lattner2a0433b2009-11-02 05:55:40 +0000869 if (V1State.isConstant() && V2State.isConstant())
870 return markConstant(IV, &I,
871 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
872 V2State.getConstant()));
Jakub Staszak785a7a92012-01-18 21:16:33 +0000873
Chris Lattner2a0433b2009-11-02 05:55:40 +0000874 // If something is undef, wait for it to resolve.
875 if (!V1State.isOverdefined() && !V2State.isOverdefined())
876 return;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000877
Chris Lattner2a0433b2009-11-02 05:55:40 +0000878 // Otherwise, one of our operands is overdefined. Try to produce something
879 // better than overdefined with some tricks.
Jakub Staszak785a7a92012-01-18 21:16:33 +0000880
Chris Lattner2a0433b2009-11-02 05:55:40 +0000881 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
882 // operand is overdefined.
883 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
884 LatticeVal *NonOverdefVal = 0;
885 if (!V1State.isOverdefined())
886 NonOverdefVal = &V1State;
887 else if (!V2State.isOverdefined())
888 NonOverdefVal = &V2State;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000889
Chris Lattner2a0433b2009-11-02 05:55:40 +0000890 if (NonOverdefVal) {
891 if (NonOverdefVal->isUndefined()) {
892 // Could annihilate value.
893 if (I.getOpcode() == Instruction::And)
894 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000895 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
Chris Lattner2a0433b2009-11-02 05:55:40 +0000896 markConstant(IV, &I, Constant::getAllOnesValue(PT));
897 else
898 markConstant(IV, &I,
899 Constant::getAllOnesValue(I.getType()));
900 return;
Chris Lattnera177c672004-12-11 23:15:19 +0000901 }
Jakub Staszak785a7a92012-01-18 21:16:33 +0000902
Chris Lattner2a0433b2009-11-02 05:55:40 +0000903 if (I.getOpcode() == Instruction::And) {
904 // X and 0 = 0
905 if (NonOverdefVal->getConstant()->isNullValue())
906 return markConstant(IV, &I, NonOverdefVal->getConstant());
907 } else {
908 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
909 if (CI->isAllOnesValue()) // X or -1 = -1
910 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnera177c672004-12-11 23:15:19 +0000911 }
912 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000913 }
Chris Lattnera177c672004-12-11 23:15:19 +0000914
915
Chris Lattner2a0433b2009-11-02 05:55:40 +0000916 markOverdefined(&I);
Chris Lattner2a632552002-04-18 15:13:15 +0000917}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000918
Chris Lattner2f096252009-11-02 02:33:50 +0000919// Handle ICmpInst instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000920void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000921 LatticeVal V1State = getValueState(I.getOperand(0));
922 LatticeVal V2State = getValueState(I.getOperand(1));
923
Reid Spencere4d87aa2006-12-23 06:05:41 +0000924 LatticeVal &IV = ValueState[&I];
925 if (IV.isOverdefined()) return;
926
Chris Lattner2a0433b2009-11-02 05:55:40 +0000927 if (V1State.isConstant() && V2State.isConstant())
Jakub Staszak785a7a92012-01-18 21:16:33 +0000928 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
929 V1State.getConstant(),
Chris Lattner2a0433b2009-11-02 05:55:40 +0000930 V2State.getConstant()));
Jakub Staszak785a7a92012-01-18 21:16:33 +0000931
Chris Lattner2a0433b2009-11-02 05:55:40 +0000932 // If operands are still undefined, wait for it to resolve.
933 if (!V1State.isOverdefined() && !V2State.isOverdefined())
934 return;
Jakub Staszak785a7a92012-01-18 21:16:33 +0000935
Chris Lattner2a0433b2009-11-02 05:55:40 +0000936 markOverdefined(&I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000937}
938
Robert Bocchino56107e22006-01-10 19:05:05 +0000939void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000940 // TODO : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +0000941 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +0000942
943#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +0000944 LatticeVal &ValState = getValueState(I.getOperand(0));
945 LatticeVal &IdxState = getValueState(I.getOperand(1));
946
947 if (ValState.isOverdefined() || IdxState.isOverdefined())
948 markOverdefined(&I);
949 else if(ValState.isConstant() && IdxState.isConstant())
950 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
951 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +0000952#endif
Robert Bocchino56107e22006-01-10 19:05:05 +0000953}
954
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000955void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000956 // TODO : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +0000957 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +0000958#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000959 LatticeVal &ValState = getValueState(I.getOperand(0));
960 LatticeVal &EltState = getValueState(I.getOperand(1));
961 LatticeVal &IdxState = getValueState(I.getOperand(2));
962
963 if (ValState.isOverdefined() || EltState.isOverdefined() ||
964 IdxState.isOverdefined())
965 markOverdefined(&I);
966 else if(ValState.isConstant() && EltState.isConstant() &&
967 IdxState.isConstant())
968 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
969 EltState.getConstant(),
970 IdxState.getConstant()));
971 else if (ValState.isUndefined() && EltState.isConstant() &&
Jakub Staszak785a7a92012-01-18 21:16:33 +0000972 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +0000973 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
974 EltState.getConstant(),
975 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +0000976#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000977}
978
Chris Lattner543abdf2006-04-08 01:19:12 +0000979void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000980 // TODO : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +0000981 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +0000982#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +0000983 LatticeVal &V1State = getValueState(I.getOperand(0));
984 LatticeVal &V2State = getValueState(I.getOperand(1));
985 LatticeVal &MaskState = getValueState(I.getOperand(2));
986
987 if (MaskState.isUndefined() ||
988 (V1State.isUndefined() && V2State.isUndefined()))
989 return; // Undefined output if mask or both inputs undefined.
Jakub Staszak785a7a92012-01-18 21:16:33 +0000990
Chris Lattner543abdf2006-04-08 01:19:12 +0000991 if (V1State.isOverdefined() || V2State.isOverdefined() ||
992 MaskState.isOverdefined()) {
993 markOverdefined(&I);
994 } else {
995 // A mix of constant/undef inputs.
Jakub Staszak785a7a92012-01-18 21:16:33 +0000996 Constant *V1 = V1State.isConstant() ?
Chris Lattner543abdf2006-04-08 01:19:12 +0000997 V1State.getConstant() : UndefValue::get(I.getType());
Jakub Staszak785a7a92012-01-18 21:16:33 +0000998 Constant *V2 = V2State.isConstant() ?
Chris Lattner543abdf2006-04-08 01:19:12 +0000999 V2State.getConstant() : UndefValue::get(I.getType());
Jakub Staszak785a7a92012-01-18 21:16:33 +00001000 Constant *Mask = MaskState.isConstant() ?
Chris Lattner543abdf2006-04-08 01:19:12 +00001001 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1002 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1003 }
Devang Patel67a821d2006-12-04 23:54:59 +00001004#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001005}
1006
Chris Lattner2f096252009-11-02 02:33:50 +00001007// Handle getelementptr instructions. If all operands are constants then we
Chris Lattner2a88bb72002-08-30 23:39:00 +00001008// can turn this into a getelementptr ConstantExpr.
1009//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001010void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner5cc66d92009-11-02 23:25:39 +00001011 if (ValueState[&I].isOverdefined()) return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001012
Chris Lattnere777ff22007-02-02 20:51:48 +00001013 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001014 Operands.reserve(I.getNumOperands());
1015
1016 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001017 LatticeVal State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001018 if (State.isUndefined())
Chris Lattner2f096252009-11-02 02:33:50 +00001019 return; // Operands are not resolved yet.
Jakub Staszak785a7a92012-01-18 21:16:33 +00001020
Chris Lattner38871e42009-11-02 03:03:42 +00001021 if (State.isOverdefined())
Chris Lattner5cc66d92009-11-02 23:25:39 +00001022 return markOverdefined(&I);
Chris Lattner38871e42009-11-02 03:03:42 +00001023
Chris Lattner2a88bb72002-08-30 23:39:00 +00001024 assert(State.isConstant() && "Unknown state!");
1025 Operands.push_back(State.getConstant());
1026 }
1027
1028 Constant *Ptr = Operands[0];
Jay Foaddab3d292011-07-21 14:31:17 +00001029 ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
1030 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001031}
Brian Gaeked0fde302003-11-11 22:41:34 +00001032
Chris Lattner2a0433b2009-11-02 05:55:40 +00001033void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001034 // If this store is of a struct, ignore it.
Duncan Sands1df98592010-02-16 11:11:14 +00001035 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +00001036 return;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001037
Chris Lattnerdd336d12004-12-11 05:15:59 +00001038 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1039 return;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001040
Chris Lattnerdd336d12004-12-11 05:15:59 +00001041 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001042 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001043 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1044
Chris Lattner2a0433b2009-11-02 05:55:40 +00001045 // Get the value we are storing into the global, then merge it.
1046 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattnerdd336d12004-12-11 05:15:59 +00001047 if (I->second.isOverdefined())
1048 TrackedGlobals.erase(I); // No need to keep tracking this!
1049}
1050
1051
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001052// Handle load instructions. If the operand is a constant pointer to a constant
1053// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001054void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001055 // If this load is of a struct, just mark the result overdefined.
Duncan Sands1df98592010-02-16 11:11:14 +00001056 if (I.getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +00001057 return markAnythingOverdefined(&I);
Jakub Staszak785a7a92012-01-18 21:16:33 +00001058
Chris Lattner2a0433b2009-11-02 05:55:40 +00001059 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattner5638dc62009-11-02 06:06:14 +00001060 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Jakub Staszak785a7a92012-01-18 21:16:33 +00001061
Chris Lattneref36dfd2004-11-15 05:03:30 +00001062 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001063 if (IV.isOverdefined()) return;
1064
Chris Lattner2a0433b2009-11-02 05:55:40 +00001065 if (!PtrVal.isConstant() || I.isVolatile())
1066 return markOverdefined(IV, &I);
Jakub Staszak785a7a92012-01-18 21:16:33 +00001067
Chris Lattner5638dc62009-11-02 06:06:14 +00001068 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanfd939082005-04-21 23:48:37 +00001069
Chris Lattner2a0433b2009-11-02 05:55:40 +00001070 // load null -> null
1071 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1072 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
Jakub Staszak785a7a92012-01-18 21:16:33 +00001073
Chris Lattner2a0433b2009-11-02 05:55:40 +00001074 // Transform load (constant global) into the value loaded.
1075 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001076 if (!TrackedGlobals.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001077 // If we are tracking this global, merge in the known value for it.
1078 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1079 TrackedGlobals.find(GV);
1080 if (It != TrackedGlobals.end()) {
1081 mergeInValue(IV, &I, It->second);
1082 return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001083 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001084 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001085 }
1086
Chris Lattner5638dc62009-11-02 06:06:14 +00001087 // Transform load from a constant into a constant if possible.
1088 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1089 return markConstant(IV, &I, C);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001090
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001091 // Otherwise we cannot say for certain what value this load will produce.
1092 // Bail out.
1093 markOverdefined(IV, &I);
1094}
Chris Lattner58b7b082004-04-13 19:43:54 +00001095
Chris Lattner59acc7d2004-12-10 08:02:06 +00001096void SCCPSolver::visitCallSite(CallSite CS) {
1097 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001098 Instruction *I = CS.getInstruction();
Jakub Staszak785a7a92012-01-18 21:16:33 +00001099
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001100 // The common case is that we aren't tracking the callee, either because we
1101 // are not doing interprocedural analysis or the callee is indirect, or is
1102 // external. Handle these cases first.
Chris Lattner14532d02009-11-03 03:42:51 +00001103 if (F == 0 || F->isDeclaration()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001104CallOverdefined:
1105 // Void return and not tracking callee, just bail.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001106 if (I->getType()->isVoidTy()) return;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001107
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001108 // Otherwise, if we have a single return value case, and if the function is
1109 // a declaration, maybe we can constant fold it.
Duncan Sands1df98592010-02-16 11:11:14 +00001110 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001111 canConstantFoldCallTo(F)) {
Jakub Staszak785a7a92012-01-18 21:16:33 +00001112
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001113 SmallVector<Constant*, 8> Operands;
1114 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1115 AI != E; ++AI) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001116 LatticeVal State = getValueState(*AI);
Jakub Staszak785a7a92012-01-18 21:16:33 +00001117
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001118 if (State.isUndefined())
1119 return; // Operands are not resolved yet.
Chris Lattner38871e42009-11-02 03:03:42 +00001120 if (State.isOverdefined())
1121 return markOverdefined(I);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001122 assert(State.isConstant() && "Unknown state!");
1123 Operands.push_back(State.getConstant());
1124 }
Jakub Staszak785a7a92012-01-18 21:16:33 +00001125
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001126 // If we can constant fold this, mark the result of the call as a
1127 // constant.
Chad Rosier00737bd2011-12-01 21:29:16 +00001128 if (Constant *C = ConstantFoldCall(F, Operands, TLI))
Chris Lattner38871e42009-11-02 03:03:42 +00001129 return markConstant(I, C);
Chris Lattner58b7b082004-04-13 19:43:54 +00001130 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001131
1132 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattnerfc36a562009-11-03 23:40:48 +00001133 return markAnythingOverdefined(I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001134 }
1135
Chris Lattner2396cc32009-11-03 19:24:51 +00001136 // If this is a local function that doesn't have its address taken, mark its
1137 // entry block executable and merge in the actual arguments to the call into
1138 // the formal arguments of the function.
1139 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1140 MarkBlockExecutable(F->begin());
Jakub Staszak785a7a92012-01-18 21:16:33 +00001141
Chris Lattner2396cc32009-11-03 19:24:51 +00001142 // Propagate information from this call site into the callee.
1143 CallSite::arg_iterator CAI = CS.arg_begin();
1144 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1145 AI != E; ++AI, ++CAI) {
1146 // If this argument is byval, and if the function is not readonly, there
1147 // will be an implicit copy formed of the input aggregate.
1148 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1149 markOverdefined(AI);
1150 continue;
1151 }
Jakub Staszak785a7a92012-01-18 21:16:33 +00001152
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001153 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner0fb7e182009-11-04 18:57:42 +00001154 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1155 LatticeVal CallArg = getStructValueState(*CAI, i);
1156 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1157 }
Chris Lattnerfc36a562009-11-03 23:40:48 +00001158 } else {
1159 mergeInValue(AI, getValueState(*CAI));
1160 }
Chris Lattner2396cc32009-11-03 19:24:51 +00001161 }
1162 }
Jakub Staszak785a7a92012-01-18 21:16:33 +00001163
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001164 // If this is a single/zero retval case, see if we're tracking the function.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001165 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001166 if (!MRVFunctionsTracked.count(F))
1167 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak785a7a92012-01-18 21:16:33 +00001168
Chris Lattnerfc36a562009-11-03 23:40:48 +00001169 // If we are tracking this callee, propagate the result of the function
1170 // into this call site.
1171 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Jakub Staszak785a7a92012-01-18 21:16:33 +00001172 mergeInValue(getStructValueState(I, i), I,
Chris Lattnerfc36a562009-11-03 23:40:48 +00001173 TrackedMultipleRetVals[std::make_pair(F, i)]);
1174 } else {
1175 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1176 if (TFRVI == TrackedRetVals.end())
1177 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak785a7a92012-01-18 21:16:33 +00001178
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001179 // If so, propagate the return value of the callee into this call result.
1180 mergeInValue(I, TFRVI->second);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001181 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001182}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001183
Chris Lattner82bec2c2004-11-15 04:44:20 +00001184void SCCPSolver::Solve() {
1185 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001186 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001187 !OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001188 // Process the overdefined instruction's work list first, which drives other
1189 // things to overdefined more quickly.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001190 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001191 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001192
David Greene971cc7e2010-01-05 01:27:15 +00001193 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001194
Chris Lattner82bec2c2004-11-15 04:44:20 +00001195 // "I" got into the work list because it either made the transition from
1196 // bottom to constant
1197 //
1198 // Anything on this worklist that is overdefined need not be visited
1199 // since all of its users will have already been marked as overdefined
Chris Lattner2f096252009-11-02 02:33:50 +00001200 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001201 //
1202 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1203 UI != E; ++UI)
Chris Lattner14532d02009-11-03 03:42:51 +00001204 if (Instruction *I = dyn_cast<Instruction>(*UI))
1205 OperandChangedState(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001206 }
Jakub Staszak785a7a92012-01-18 21:16:33 +00001207
Chris Lattner2f096252009-11-02 02:33:50 +00001208 // Process the instruction work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001209 while (!InstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001210 Value *I = InstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001211
David Greene971cc7e2010-01-05 01:27:15 +00001212 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001213
Chris Lattner2a0433b2009-11-02 05:55:40 +00001214 // "I" got into the work list because it made the transition from undef to
1215 // constant.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001216 //
1217 // Anything on this worklist that is overdefined need not be visited
1218 // since all of its users will have already been marked as overdefined.
Chris Lattner2f096252009-11-02 02:33:50 +00001219 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001220 //
Duncan Sands1df98592010-02-16 11:11:14 +00001221 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Chris Lattner82bec2c2004-11-15 04:44:20 +00001222 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1223 UI != E; ++UI)
Chris Lattner14532d02009-11-03 03:42:51 +00001224 if (Instruction *I = dyn_cast<Instruction>(*UI))
1225 OperandChangedState(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001226 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001227
Chris Lattner2f096252009-11-02 02:33:50 +00001228 // Process the basic block work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001229 while (!BBWorkList.empty()) {
1230 BasicBlock *BB = BBWorkList.back();
1231 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001232
David Greene971cc7e2010-01-05 01:27:15 +00001233 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001234
Chris Lattner82bec2c2004-11-15 04:44:20 +00001235 // Notify all instructions in this basic block that they are newly
1236 // executable.
1237 visit(BB);
1238 }
1239 }
1240}
1241
Chris Lattner3bad2532006-12-20 06:21:33 +00001242/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001243/// that branches on undef values cannot reach any of their successors.
1244/// However, this is not a safe assumption. After we solve dataflow, this
1245/// method should be use to handle this. If this returns true, the solver
1246/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001247///
1248/// This method handles this by finding an unresolved branch and marking it one
1249/// of the edges from the block as being feasible, even though the condition
1250/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1251/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001252/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001253/// constraints on the condition of the branch, as that would impact other users
1254/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001255///
1256/// This scan also checks for values that use undefs, whose results are actually
1257/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1258/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1259/// even if X isn't defined.
1260bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001261 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1262 if (!BBExecutable.count(BB))
1263 continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001264
Chris Lattner3bad2532006-12-20 06:21:33 +00001265 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1266 // Look for instructions which produce undef values.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001267 if (I->getType()->isVoidTy()) continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001268
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001269 if (StructType *STy = dyn_cast<StructType>(I->getType())) {
Eli Friedman79782fc2011-09-20 23:28:51 +00001270 // Only a few things that can be structs matter for undef.
1271
1272 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1273 if (CallSite CS = CallSite(I))
1274 if (Function *F = CS.getCalledFunction())
1275 if (MRVFunctionsTracked.count(F))
1276 continue;
1277
1278 // extractvalue and insertvalue don't need to be marked; they are
Jakub Staszak785a7a92012-01-18 21:16:33 +00001279 // tracked as precisely as their operands.
Eli Friedman79782fc2011-09-20 23:28:51 +00001280 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1281 continue;
1282
1283 // Send the results of everything else to overdefined. We could be
1284 // more precise than this but it isn't worth bothering.
1285 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1286 LatticeVal &LV = getStructValueState(I, i);
1287 if (LV.isUndefined())
1288 markOverdefined(LV, I);
Chris Lattnerfc36a562009-11-03 23:40:48 +00001289 }
1290 continue;
1291 }
Eli Friedman054ddf792011-08-16 22:06:31 +00001292
Chris Lattner3bad2532006-12-20 06:21:33 +00001293 LatticeVal &LV = getValueState(I);
1294 if (!LV.isUndefined()) continue;
1295
Eli Friedman447f9522011-08-17 18:10:43 +00001296 // extractvalue is safe; check here because the argument is a struct.
1297 if (isa<ExtractValueInst>(I))
1298 continue;
1299
1300 // Compute the operand LatticeVals, for convenience below.
1301 // Anything taking a struct is conservatively assumed to require
1302 // overdefined markings.
1303 if (I->getOperand(0)->getType()->isStructTy()) {
1304 markOverdefined(I);
1305 return true;
1306 }
Chris Lattner2a0433b2009-11-02 05:55:40 +00001307 LatticeVal Op0LV = getValueState(I->getOperand(0));
Chris Lattner3bad2532006-12-20 06:21:33 +00001308 LatticeVal Op1LV;
Eli Friedman447f9522011-08-17 18:10:43 +00001309 if (I->getNumOperands() == 2) {
1310 if (I->getOperand(1)->getType()->isStructTy()) {
1311 markOverdefined(I);
1312 return true;
1313 }
1314
Chris Lattner3bad2532006-12-20 06:21:33 +00001315 Op1LV = getValueState(I->getOperand(1));
Eli Friedman447f9522011-08-17 18:10:43 +00001316 }
Chris Lattner3bad2532006-12-20 06:21:33 +00001317 // If this is an instructions whose result is defined even if the input is
1318 // not fully defined, propagate the information.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001319 Type *ITy = I->getType();
Chris Lattner3bad2532006-12-20 06:21:33 +00001320 switch (I->getOpcode()) {
Eli Friedman054ddf792011-08-16 22:06:31 +00001321 case Instruction::Add:
1322 case Instruction::Sub:
1323 case Instruction::Trunc:
1324 case Instruction::FPTrunc:
1325 case Instruction::BitCast:
1326 break; // Any undef -> undef
1327 case Instruction::FSub:
1328 case Instruction::FAdd:
1329 case Instruction::FMul:
1330 case Instruction::FDiv:
1331 case Instruction::FRem:
1332 // Floating-point binary operation: be conservative.
1333 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1334 markForcedConstant(I, Constant::getNullValue(ITy));
1335 else
1336 markOverdefined(I);
1337 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001338 case Instruction::ZExt:
Eli Friedman054ddf792011-08-16 22:06:31 +00001339 case Instruction::SExt:
1340 case Instruction::FPToUI:
1341 case Instruction::FPToSI:
1342 case Instruction::FPExt:
1343 case Instruction::PtrToInt:
1344 case Instruction::IntToPtr:
1345 case Instruction::SIToFP:
1346 case Instruction::UIToFP:
1347 // undef -> 0; some outputs are impossible
Chris Lattner2a0433b2009-11-02 05:55:40 +00001348 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001349 return true;
1350 case Instruction::Mul:
1351 case Instruction::And:
Eli Friedman054ddf792011-08-16 22:06:31 +00001352 // Both operands undef -> undef
1353 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1354 break;
Chris Lattner3bad2532006-12-20 06:21:33 +00001355 // undef * X -> 0. X could be zero.
1356 // undef & X -> 0. X could be zero.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001357 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001358 return true;
1359
1360 case Instruction::Or:
Eli Friedman054ddf792011-08-16 22:06:31 +00001361 // Both operands undef -> undef
1362 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1363 break;
Chris Lattner3bad2532006-12-20 06:21:33 +00001364 // undef | X -> -1. X could be -1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001365 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001366 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001367
Eli Friedman054ddf792011-08-16 22:06:31 +00001368 case Instruction::Xor:
1369 // undef ^ undef -> 0; strictly speaking, this is not strictly
1370 // necessary, but we try to be nice to people who expect this
1371 // behavior in simple cases
1372 if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
1373 markForcedConstant(I, Constant::getNullValue(ITy));
1374 return true;
1375 }
1376 // undef ^ X -> undef
1377 break;
1378
Chris Lattner3bad2532006-12-20 06:21:33 +00001379 case Instruction::SDiv:
1380 case Instruction::UDiv:
1381 case Instruction::SRem:
1382 case Instruction::URem:
1383 // X / undef -> undef. No change.
1384 // X % undef -> undef. No change.
1385 if (Op1LV.isUndefined()) break;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001386
Chris Lattner3bad2532006-12-20 06:21:33 +00001387 // undef / X -> 0. X could be maxint.
1388 // undef % X -> 0. X could be 1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001389 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001390 return true;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001391
Chris Lattner3bad2532006-12-20 06:21:33 +00001392 case Instruction::AShr:
Eli Friedman054ddf792011-08-16 22:06:31 +00001393 // X >>a undef -> undef.
1394 if (Op1LV.isUndefined()) break;
1395
1396 // undef >>a X -> all ones
1397 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001398 return true;
1399 case Instruction::LShr:
1400 case Instruction::Shl:
Eli Friedman054ddf792011-08-16 22:06:31 +00001401 // X << undef -> undef.
1402 // X >> undef -> undef.
1403 if (Op1LV.isUndefined()) break;
1404
1405 // undef << X -> 0
1406 // undef >> X -> 0
Chris Lattner2a0433b2009-11-02 05:55:40 +00001407 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001408 return true;
1409 case Instruction::Select:
Eli Friedman054ddf792011-08-16 22:06:31 +00001410 Op1LV = getValueState(I->getOperand(1));
Chris Lattner3bad2532006-12-20 06:21:33 +00001411 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1412 if (Op0LV.isUndefined()) {
1413 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1414 Op1LV = getValueState(I->getOperand(2));
1415 } else if (Op1LV.isUndefined()) {
1416 // c ? undef : undef -> undef. No change.
1417 Op1LV = getValueState(I->getOperand(2));
1418 if (Op1LV.isUndefined())
1419 break;
1420 // Otherwise, c ? undef : x -> x.
1421 } else {
1422 // Leave Op1LV as Operand(1)'s LatticeValue.
1423 }
Jakub Staszak785a7a92012-01-18 21:16:33 +00001424
Chris Lattner3bad2532006-12-20 06:21:33 +00001425 if (Op1LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001426 markForcedConstant(I, Op1LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001427 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001428 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001429 return true;
Eli Friedman054ddf792011-08-16 22:06:31 +00001430 case Instruction::Load:
1431 // A load here means one of two things: a load of undef from a global,
1432 // a load from an unknown pointer. Either way, having it return undef
1433 // is okay.
1434 break;
1435 case Instruction::ICmp:
1436 // X == undef -> undef. Other comparisons get more complicated.
1437 if (cast<ICmpInst>(I)->isEquality())
1438 break;
1439 markOverdefined(I);
1440 return true;
Eli Friedman79782fc2011-09-20 23:28:51 +00001441 case Instruction::Call:
1442 case Instruction::Invoke: {
1443 // There are two reasons a call can have an undef result
1444 // 1. It could be tracked.
1445 // 2. It could be constant-foldable.
1446 // Because of the way we solve return values, tracked calls must
1447 // never be marked overdefined in ResolvedUndefsIn.
1448 if (Function *F = CallSite(I).getCalledFunction())
1449 if (TrackedRetVals.count(F))
1450 break;
1451
1452 // If the call is constant-foldable, we mark it overdefined because
1453 // we do not know what return values are valid.
1454 markOverdefined(I);
1455 return true;
1456 }
Eli Friedman054ddf792011-08-16 22:06:31 +00001457 default:
1458 // If we don't know what should happen here, conservatively mark it
Chris Lattner60301602008-05-24 03:59:33 +00001459 // overdefined.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001460 markOverdefined(I);
Chris Lattner60301602008-05-24 03:59:33 +00001461 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001462 }
1463 }
Jakub Staszak785a7a92012-01-18 21:16:33 +00001464
Chris Lattnere597f002010-04-05 22:14:48 +00001465 // Check to see if we have a branch or switch on an undefined value. If so
1466 // we force the branch to go one way or the other to make the successor
1467 // values live. It doesn't really matter which way we force it.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001468 TerminatorInst *TI = BB->getTerminator();
1469 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1470 if (!BI->isConditional()) continue;
1471 if (!getValueState(BI->getCondition()).isUndefined())
1472 continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001473
Chris Lattnere597f002010-04-05 22:14:48 +00001474 // If the input to SCCP is actually branch on undef, fix the undef to
1475 // false.
1476 if (isa<UndefValue>(BI->getCondition())) {
1477 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1478 markEdgeExecutable(BB, TI->getSuccessor(1));
1479 return true;
1480 }
Jakub Staszak785a7a92012-01-18 21:16:33 +00001481
Chris Lattnere597f002010-04-05 22:14:48 +00001482 // Otherwise, it is a branch on a symbolic value which is currently
1483 // considered to be undef. Handle this by forcing the input value to the
1484 // branch to false.
1485 markForcedConstant(BI->getCondition(),
1486 ConstantInt::getFalse(TI->getContext()));
1487 return true;
1488 }
Jakub Staszak785a7a92012-01-18 21:16:33 +00001489
Chris Lattnere597f002010-04-05 22:14:48 +00001490 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001491 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesen9bca5832008-05-23 01:01:31 +00001492 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001493 if (!getValueState(SI->getCondition()).isUndefined())
1494 continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001495
Chris Lattnere597f002010-04-05 22:14:48 +00001496 // If the input to SCCP is actually switch on undef, fix the undef to
1497 // the first constant.
1498 if (isa<UndefValue>(SI->getCondition())) {
1499 SI->setCondition(SI->getCaseValue(1));
1500 markEdgeExecutable(BB, TI->getSuccessor(1));
1501 return true;
1502 }
Jakub Staszak785a7a92012-01-18 21:16:33 +00001503
Chris Lattnere597f002010-04-05 22:14:48 +00001504 markForcedConstant(SI->getCondition(), SI->getCaseValue(1));
1505 return true;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001506 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001507 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001508
Chris Lattnerd2d86702006-10-22 05:59:17 +00001509 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001510}
1511
Chris Lattner82bec2c2004-11-15 04:44:20 +00001512
1513namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001514 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001515 //
Chris Lattner14051812004-11-15 07:15:04 +00001516 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001517 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001518 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001519 struct SCCP : public FunctionPass {
Chad Rosier00737bd2011-12-01 21:29:16 +00001520 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1521 AU.addRequired<TargetLibraryInfo>();
1522 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001523 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +00001524 SCCP() : FunctionPass(ID) {
1525 initializeSCCPPass(*PassRegistry::getPassRegistry());
1526 }
Devang Patel794fd752007-05-01 21:15:47 +00001527
Chris Lattner14051812004-11-15 07:15:04 +00001528 // runOnFunction - Run the Sparse Conditional Constant Propagation
1529 // algorithm, and return true if the function was modified.
1530 //
1531 bool runOnFunction(Function &F);
Chris Lattner14051812004-11-15 07:15:04 +00001532 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001533} // end anonymous namespace
1534
Dan Gohman844731a2008-05-13 00:00:25 +00001535char SCCP::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +00001536INITIALIZE_PASS(SCCP, "sccp",
Owen Andersonce665bd2010-10-07 22:25:06 +00001537 "Sparse Conditional Constant Propagation", false, false)
Chris Lattner82bec2c2004-11-15 04:44:20 +00001538
Chris Lattner2f096252009-11-02 02:33:50 +00001539// createSCCPPass - This is the public interface to this file.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001540FunctionPass *llvm::createSCCPPass() {
1541 return new SCCP();
1542}
1543
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001544static void DeleteInstructionInBlock(BasicBlock *BB) {
David Greene971cc7e2010-01-05 01:27:15 +00001545 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001546 ++NumDeadBlocks;
Bill Wendling4f8aaa02011-08-31 20:55:20 +00001547
1548 // Check to see if there are non-terminating instructions to delete.
1549 if (isa<TerminatorInst>(BB->begin()))
1550 return;
1551
Bill Wendlinga2684682011-09-04 09:43:36 +00001552 // Delete the instructions backwards, as it has a reduced likelihood of having
1553 // to update as many def-use and use-def chains.
1554 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1555 while (EndInst != BB->begin()) {
1556 // Delete the next to last instruction.
1557 BasicBlock::iterator I = EndInst;
1558 Instruction *Inst = --I;
Bill Wendlingc8c0fd32011-09-01 21:28:33 +00001559 if (!Inst->use_empty())
1560 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
Bill Wendlinga2684682011-09-04 09:43:36 +00001561 if (isa<LandingPadInst>(Inst)) {
1562 EndInst = Inst;
Bill Wendling4f8aaa02011-08-31 20:55:20 +00001563 continue;
Bill Wendlinga2684682011-09-04 09:43:36 +00001564 }
Bill Wendlingc8c0fd32011-09-01 21:28:33 +00001565 BB->getInstList().erase(Inst);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001566 ++NumInstRemoved;
1567 }
1568}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001569
Chris Lattner82bec2c2004-11-15 04:44:20 +00001570// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1571// and return true if the function was modified.
1572//
1573bool SCCP::runOnFunction(Function &F) {
David Greene971cc7e2010-01-05 01:27:15 +00001574 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Chad Rosier00737bd2011-12-01 21:29:16 +00001575 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1576 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1577 SCCPSolver Solver(TD, TLI);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001578
1579 // Mark the first block of the function as being executable.
1580 Solver.MarkBlockExecutable(F.begin());
1581
Chris Lattner7e529e42004-11-15 05:45:33 +00001582 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001583 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattnerfc36a562009-11-03 23:40:48 +00001584 Solver.markAnythingOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001585
Chris Lattner82bec2c2004-11-15 04:44:20 +00001586 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001587 bool ResolvedUndefs = true;
1588 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001589 Solver.Solve();
David Greene971cc7e2010-01-05 01:27:15 +00001590 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001591 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001592 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001593
Chris Lattner7e529e42004-11-15 05:45:33 +00001594 bool MadeChanges = false;
1595
1596 // If we decided that there are basic blocks that are dead in this function,
1597 // delete their contents now. Note that we cannot actually delete the blocks,
1598 // as we cannot modify the CFG of the function.
Chris Lattner57939df2007-03-04 04:50:21 +00001599
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001600 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001601 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001602 DeleteInstructionInBlock(BB);
1603 MadeChanges = true;
1604 continue;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001605 }
Jakub Staszak785a7a92012-01-18 21:16:33 +00001606
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001607 // Iterate over all of the instructions in a function, replacing them with
1608 // constants if we have found them to be of constant values.
1609 //
1610 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1611 Instruction *Inst = BI++;
1612 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1613 continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001614
Chris Lattnerfc36a562009-11-03 23:40:48 +00001615 // TODO: Reconstruct structs from their elements.
Duncan Sands1df98592010-02-16 11:11:14 +00001616 if (Inst->getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +00001617 continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001618
Chris Lattner8db50122009-11-02 02:54:24 +00001619 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1620 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001621 continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001622
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001623 Constant *Const = IV.isConstant()
1624 ? IV.getConstant() : UndefValue::get(Inst->getType());
David Greene971cc7e2010-01-05 01:27:15 +00001625 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001626
1627 // Replaces all of the uses of a variable with uses of the constant.
1628 Inst->replaceAllUsesWith(Const);
Jakub Staszak785a7a92012-01-18 21:16:33 +00001629
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001630 // Delete the instruction.
1631 Inst->eraseFromParent();
Jakub Staszak785a7a92012-01-18 21:16:33 +00001632
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001633 // Hey, we just changed something!
1634 MadeChanges = true;
1635 ++NumInstRemoved;
1636 }
1637 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001638
1639 return MadeChanges;
1640}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001641
1642namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001643 //===--------------------------------------------------------------------===//
1644 //
1645 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1646 /// Constant Propagation.
1647 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001648 struct IPSCCP : public ModulePass {
Chad Rosier00737bd2011-12-01 21:29:16 +00001649 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1650 AU.addRequired<TargetLibraryInfo>();
1651 }
Devang Patel19974732007-05-03 01:11:54 +00001652 static char ID;
Owen Anderson081c34b2010-10-19 17:21:58 +00001653 IPSCCP() : ModulePass(ID) {
1654 initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1655 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001656 bool runOnModule(Module &M);
1657 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001658} // end anonymous namespace
1659
Dan Gohman844731a2008-05-13 00:00:25 +00001660char IPSCCP::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +00001661INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
1662 "Interprocedural Sparse Conditional Constant Propagation",
1663 false, false)
1664INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1665INITIALIZE_PASS_END(IPSCCP, "ipsccp",
Owen Andersond13db2c2010-07-21 22:09:45 +00001666 "Interprocedural Sparse Conditional Constant Propagation",
Owen Andersonce665bd2010-10-07 22:25:06 +00001667 false, false)
Dan Gohman844731a2008-05-13 00:00:25 +00001668
Chris Lattner2f096252009-11-02 02:33:50 +00001669// createIPSCCPPass - This is the public interface to this file.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001670ModulePass *llvm::createIPSCCPPass() {
1671 return new IPSCCP();
1672}
1673
1674
Gabor Greifbd1f9932010-03-24 10:29:52 +00001675static bool AddressIsTaken(const GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001676 // Delete any dead constantexpr klingons.
1677 GV->removeDeadConstantUsers();
1678
Gabor Greif60ad7812010-03-25 23:06:16 +00001679 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifbd1f9932010-03-24 10:29:52 +00001680 UI != E; ++UI) {
1681 const User *U = *UI;
1682 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001683 if (SI->getOperand(0) == GV || SI->isVolatile())
1684 return true; // Storing addr of GV.
Gabor Greifbd1f9932010-03-24 10:29:52 +00001685 } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001686 // Make sure we are calling the function, not passing the address.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001687 ImmutableCallSite CS(cast<Instruction>(U));
Gabor Greifc9f75002010-03-24 13:21:49 +00001688 if (!CS.isCallee(UI))
Nick Lewyckyaf386132008-11-03 03:49:14 +00001689 return true;
Gabor Greifbd1f9932010-03-24 10:29:52 +00001690 } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001691 if (LI->isVolatile())
1692 return true;
Gabor Greifbd1f9932010-03-24 10:29:52 +00001693 } else if (isa<BlockAddress>(U)) {
Chris Lattnerb2710042009-11-01 06:11:53 +00001694 // blockaddress doesn't take the address of the function, it takes addr
1695 // of label.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001696 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001697 return true;
1698 }
Gabor Greifbd1f9932010-03-24 10:29:52 +00001699 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001700 return false;
1701}
1702
1703bool IPSCCP::runOnModule(Module &M) {
Chad Rosier00737bd2011-12-01 21:29:16 +00001704 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1705 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1706 SCCPSolver Solver(TD, TLI);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001707
Chris Lattner1522ce92010-08-12 22:25:23 +00001708 // AddressTakenFunctions - This set keeps track of the address-taken functions
1709 // that are in the input. As IPSCCP runs through and simplifies code,
1710 // functions that were address taken can end up losing their
1711 // address-taken-ness. Because of this, we keep track of their addresses from
1712 // the first pass so we can use them for the later simplification pass.
1713 SmallPtrSet<Function*, 32> AddressTakenFunctions;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001714
Chris Lattner59acc7d2004-12-10 08:02:06 +00001715 // Loop over all functions, marking arguments to those with their addresses
1716 // taken or that are external as overdefined.
1717 //
Chris Lattnerff3ca152009-11-02 06:34:04 +00001718 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1719 if (F->isDeclaration())
1720 continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001721
Chris Lattner14532d02009-11-03 03:42:51 +00001722 // If this is a strong or ODR definition of this function, then we can
1723 // propagate information about its result into callsites of it.
Chris Lattnerfc36a562009-11-03 23:40:48 +00001724 if (!F->mayBeOverridden())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001725 Solver.AddTrackedFunction(F);
Jakub Staszak785a7a92012-01-18 21:16:33 +00001726
Chris Lattner14532d02009-11-03 03:42:51 +00001727 // If this function only has direct calls that we can see, we can track its
1728 // arguments and return value aggressively, and can assume it is not called
1729 // unless we see evidence to the contrary.
Chris Lattner1522ce92010-08-12 22:25:23 +00001730 if (F->hasLocalLinkage()) {
1731 if (AddressIsTaken(F))
1732 AddressTakenFunctions.insert(F);
1733 else {
1734 Solver.AddArgumentTrackedFunction(F);
1735 continue;
1736 }
Chris Lattner2396cc32009-11-03 19:24:51 +00001737 }
Chris Lattner14532d02009-11-03 03:42:51 +00001738
1739 // Assume the function is called.
1740 Solver.MarkBlockExecutable(F->begin());
Jakub Staszak785a7a92012-01-18 21:16:33 +00001741
Chris Lattner14532d02009-11-03 03:42:51 +00001742 // Assume nothing about the incoming arguments.
1743 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1744 AI != E; ++AI)
Chris Lattnerfc36a562009-11-03 23:40:48 +00001745 Solver.markAnythingOverdefined(AI);
Chris Lattnerff3ca152009-11-02 06:34:04 +00001746 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001747
Chris Lattnerdd336d12004-12-11 05:15:59 +00001748 // Loop over global variables. We inform the solver about any internal global
1749 // variables that do not have their 'addresses taken'. If they don't have
1750 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001751 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1752 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001753 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001754 Solver.TrackValueOfGlobalVariable(G);
1755
Chris Lattner59acc7d2004-12-10 08:02:06 +00001756 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001757 bool ResolvedUndefs = true;
1758 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001759 Solver.Solve();
1760
David Greene971cc7e2010-01-05 01:27:15 +00001761 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001762 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001763 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001764 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001765 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001766
1767 bool MadeChanges = false;
1768
1769 // Iterate over all of the instructions in the module, replacing them with
1770 // constants if we have found them to be of constant values.
1771 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001772 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner1c1f1122007-02-02 21:15:06 +00001773
Chris Lattner59acc7d2004-12-10 08:02:06 +00001774 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner89112b62009-11-02 03:25:55 +00001775 if (Solver.isBlockExecutable(F->begin())) {
1776 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1777 AI != E; ++AI) {
Duncan Sands1df98592010-02-16 11:11:14 +00001778 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001779
Chris Lattnerfc36a562009-11-03 23:40:48 +00001780 // TODO: Could use getStructLatticeValueFor to find out if the entire
1781 // result is a constant and replace it entirely if so.
1782
Chris Lattner89112b62009-11-02 03:25:55 +00001783 LatticeVal IV = Solver.getLatticeValueFor(AI);
1784 if (IV.isOverdefined()) continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001785
Chris Lattner89112b62009-11-02 03:25:55 +00001786 Constant *CST = IV.isConstant() ?
1787 IV.getConstant() : UndefValue::get(AI->getType());
David Greene971cc7e2010-01-05 01:27:15 +00001788 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Jakub Staszak785a7a92012-01-18 21:16:33 +00001789
Chris Lattner89112b62009-11-02 03:25:55 +00001790 // Replaces all of the uses of a variable with uses of the
1791 // constant.
1792 AI->replaceAllUsesWith(CST);
1793 ++IPNumArgsElimed;
1794 }
Chris Lattner8db50122009-11-02 02:54:24 +00001795 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001796
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001797 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001798 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001799 DeleteInstructionInBlock(BB);
1800 MadeChanges = true;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001801
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001802 TerminatorInst *TI = BB->getTerminator();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001803 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1804 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001805 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001806 TI->getSuccessor(i)->removePredecessor(BB);
1807 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001808 if (!TI->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001809 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001810 TI->eraseFromParent();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001811
Chris Lattner864737b2004-12-11 05:32:19 +00001812 if (&*BB != &F->front())
1813 BlocksToErase.push_back(BB);
1814 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001815 new UnreachableInst(M.getContext(), BB);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001816 continue;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001817 }
Jakub Staszak785a7a92012-01-18 21:16:33 +00001818
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001819 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1820 Instruction *Inst = BI++;
Duncan Sands1df98592010-02-16 11:11:14 +00001821 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001822 continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001823
Chris Lattnerfc36a562009-11-03 23:40:48 +00001824 // TODO: Could use getStructLatticeValueFor to find out if the entire
1825 // result is a constant and replace it entirely if so.
Jakub Staszak785a7a92012-01-18 21:16:33 +00001826
Chris Lattner8db50122009-11-02 02:54:24 +00001827 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1828 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001829 continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001830
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001831 Constant *Const = IV.isConstant()
1832 ? IV.getConstant() : UndefValue::get(Inst->getType());
David Greene971cc7e2010-01-05 01:27:15 +00001833 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001834
1835 // Replaces all of the uses of a variable with uses of the
1836 // constant.
1837 Inst->replaceAllUsesWith(Const);
Jakub Staszak785a7a92012-01-18 21:16:33 +00001838
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001839 // Delete the instruction.
1840 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1841 Inst->eraseFromParent();
1842
1843 // Hey, we just changed something!
1844 MadeChanges = true;
1845 ++IPNumInstRemoved;
1846 }
1847 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001848
1849 // Now that all instructions in the function are constant folded, erase dead
1850 // blocks, because we can now use ConstantFoldTerminator to get rid of
1851 // in-edges.
1852 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1853 // If there are any PHI nodes in this successor, drop entries for BB now.
1854 BasicBlock *DeadBB = BlocksToErase[i];
Dan Gohman6a239212009-11-20 20:19:14 +00001855 for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1856 UI != UE; ) {
Dan Gohman8f3817f2009-11-23 16:13:39 +00001857 // Grab the user and then increment the iterator early, as the user
1858 // will be deleted. Step past all adjacent uses from the same user.
1859 Instruction *I = dyn_cast<Instruction>(*UI);
1860 do { ++UI; } while (UI != UE && *UI == I);
1861
Dan Gohman6a239212009-11-20 20:19:14 +00001862 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohman6a239212009-11-20 20:19:14 +00001863 if (!I) continue;
1864
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001865 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001866 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001867 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001868 // if this is a branch or switch on undef. Fold it manually as a
1869 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001870#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001871 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1872 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1873 "Branch should be foldable!");
1874 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1875 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1876 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001877 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerddaaa372006-10-23 18:57:02 +00001878 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001879#endif
Jakub Staszak785a7a92012-01-18 21:16:33 +00001880
Chris Lattnerddaaa372006-10-23 18:57:02 +00001881 // Make this an uncond branch to the first successor.
1882 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001883 BranchInst::Create(TI->getSuccessor(0), TI);
Jakub Staszak785a7a92012-01-18 21:16:33 +00001884
Chris Lattnerddaaa372006-10-23 18:57:02 +00001885 // Remove entries in successor phi nodes to remove edges.
1886 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1887 TI->getSuccessor(i)->removePredecessor(TI->getParent());
Jakub Staszak785a7a92012-01-18 21:16:33 +00001888
Chris Lattnerddaaa372006-10-23 18:57:02 +00001889 // Remove the old terminator.
1890 TI->eraseFromParent();
1891 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001892 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001893
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001894 // Finally, delete the basic block.
1895 F->getBasicBlockList().erase(DeadBB);
1896 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001897 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001898 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001899
1900 // If we inferred constant or undef return values for a function, we replaced
1901 // all call uses with the inferred value. This means we don't need to bother
1902 // actually returning anything from the function. Replace all return
1903 // instructions with return undef.
Chris Lattnerd38cdb02010-02-27 00:07:42 +00001904 //
1905 // Do this in two stages: first identify the functions we should process, then
1906 // actually zap their returns. This is important because we can only do this
Chris Lattner9fcd72b2010-02-27 07:50:40 +00001907 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd38cdb02010-02-27 00:07:42 +00001908 // last use of a function, the order of processing functions would affect
Chris Lattner9fcd72b2010-02-27 07:50:40 +00001909 // whether other functions are optimizable.
Chris Lattnerd38cdb02010-02-27 00:07:42 +00001910 SmallVector<ReturnInst*, 8> ReturnsToZap;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001911
Devang Patel9af014f2008-03-11 17:32:05 +00001912 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001913 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001914 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner14532d02009-11-03 03:42:51 +00001915 E = RV.end(); I != E; ++I) {
1916 Function *F = I->first;
1917 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1918 continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001919
Chris Lattner14532d02009-11-03 03:42:51 +00001920 // We can only do this if we know that nothing else can call the function.
Chris Lattner1522ce92010-08-12 22:25:23 +00001921 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
Chris Lattner14532d02009-11-03 03:42:51 +00001922 continue;
Jakub Staszak785a7a92012-01-18 21:16:33 +00001923
Chris Lattner14532d02009-11-03 03:42:51 +00001924 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1925 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1926 if (!isa<UndefValue>(RI->getOperand(0)))
Chris Lattnerd38cdb02010-02-27 00:07:42 +00001927 ReturnsToZap.push_back(RI);
1928 }
1929
1930 // Zap all returns which we've identified as zap to change.
1931 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1932 Function *F = ReturnsToZap[i]->getParent()->getParent();
1933 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattner14532d02009-11-03 03:42:51 +00001934 }
Jakub Staszak785a7a92012-01-18 21:16:33 +00001935
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001936 // If we inferred constant or undef values for globals variables, we can delete
Chris Lattnerdd336d12004-12-11 05:15:59 +00001937 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001938 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1939 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001940 E = TG.end(); I != E; ++I) {
1941 GlobalVariable *GV = I->first;
1942 assert(!I->second.isOverdefined() &&
1943 "Overdefined values should have been taken out of the map!");
David Greene971cc7e2010-01-05 01:27:15 +00001944 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattnerdd336d12004-12-11 05:15:59 +00001945 while (!GV->use_empty()) {
1946 StoreInst *SI = cast<StoreInst>(GV->use_back());
1947 SI->eraseFromParent();
1948 }
1949 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001950 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001951 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001952
Chris Lattner59acc7d2004-12-10 08:02:06 +00001953 return MadeChanges;
1954}