blob: e4cb55c37bcd919833d8c659ae37e27893251437 [file] [log] [blame]
Misha Brukman82c89b92003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +00009//
Misha Brukman82c89b92003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner138a1242001-06-27 23:38:11 +000011//
12// Specifically, this:
13// * Assumes values are constant unless proven otherwise
14// * Assumes BasicBlocks are dead unless proven otherwise
15// * Proves values to be constant, and replaces them with constants
Chris Lattner2a88bb72002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner138a1242001-06-27 23:38:11 +000017//
Chris Lattner138a1242001-06-27 23:38:11 +000018//===----------------------------------------------------------------------===//
19
Chris Lattneref36dfd2004-11-15 05:03:30 +000020#define DEBUG_TYPE "sccp"
Chris Lattner022103b2002-05-07 20:03:00 +000021#include "llvm/Transforms/Scalar.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000022#include "llvm/Transforms/IPO.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000023#include "llvm/Constants.h"
Chris Lattnerdd336d12004-12-11 05:15:59 +000024#include "llvm/DerivedTypes.h"
Chris Lattner9de28282003-04-25 02:50:03 +000025#include "llvm/Instructions.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000026#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000027#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanc4b65ea2008-06-20 01:15:44 +000028#include "llvm/Analysis/ValueTracking.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000029#include "llvm/Transforms/Utils/Local.h"
Chris Lattner5638dc62009-11-02 06:06:14 +000030#include "llvm/Target/TargetData.h"
Chad Rosier00737bd2011-12-01 21:29:16 +000031#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000032#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000034#include "llvm/Support/ErrorHandling.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000035#include "llvm/Support/InstVisitor.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000036#include "llvm/Support/raw_ostream.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000037#include "llvm/ADT/DenseMap.h"
Chris Lattnercf712de2008-08-23 23:36:38 +000038#include "llvm/ADT/DenseSet.h"
Chris Lattner79272202009-11-02 02:20:32 +000039#include "llvm/ADT/PointerIntPair.h"
Chris Lattner09275292009-11-02 06:11:23 +000040#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000041#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000042#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000044#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000045#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000046using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000047
Chris Lattner0e5f4992006-12-19 21:40:18 +000048STATISTIC(NumInstRemoved, "Number of instructions removed");
49STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
50
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000051STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000052STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
53STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
54
Chris Lattner0dbfc052002-04-29 21:26:08 +000055namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000056/// LatticeVal class - This class represents the different lattice values that
57/// an LLVM value may occupy. It is a simple class with value semantics.
58///
Chris Lattner3e8b6632009-09-02 06:11:42 +000059class LatticeVal {
Chris Lattner79272202009-11-02 02:20:32 +000060 enum LatticeValueTy {
Chris Lattner3bad2532006-12-20 06:21:33 +000061 /// undefined - This LLVM Value has no known value yet.
62 undefined,
63
64 /// constant - This LLVM Value has a specific constant value.
65 constant,
66
67 /// forcedconstant - This LLVM Value was thought to be undef until
68 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
69 /// with another (different) constant, it goes to overdefined, instead of
70 /// asserting.
71 forcedconstant,
72
73 /// overdefined - This instruction is not known to be constant, and we know
74 /// it has a value.
75 overdefined
Chris Lattner79272202009-11-02 02:20:32 +000076 };
77
78 /// Val: This stores the current lattice value along with the Constant* for
79 /// the constant if this is a 'constant' or 'forcedconstant' value.
80 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Chris Lattner3bad2532006-12-20 06:21:33 +000081
Chris Lattner79272202009-11-02 02:20:32 +000082 LatticeValueTy getLatticeValue() const {
83 return Val.getInt();
84 }
85
Chris Lattner138a1242001-06-27 23:38:11 +000086public:
Chris Lattner38871e42009-11-02 03:03:42 +000087 LatticeVal() : Val(0, undefined) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000088
Chris Lattner38871e42009-11-02 03:03:42 +000089 bool isUndefined() const { return getLatticeValue() == undefined; }
90 bool isConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000091 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
92 }
Chris Lattner38871e42009-11-02 03:03:42 +000093 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Chris Lattner79272202009-11-02 02:20:32 +000094
Chris Lattner38871e42009-11-02 03:03:42 +000095 Constant *getConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000096 assert(isConstant() && "Cannot get the constant of a non-constant!");
97 return Val.getPointer();
98 }
99
100 /// markOverdefined - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000101 bool markOverdefined() {
Chris Lattner79272202009-11-02 02:20:32 +0000102 if (isOverdefined())
103 return false;
104
105 Val.setInt(overdefined);
106 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000107 }
108
Chris Lattner79272202009-11-02 02:20:32 +0000109 /// markConstant - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000110 bool markConstant(Constant *V) {
Chris Lattnerc175e5d2009-11-03 16:50:11 +0000111 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattner79272202009-11-02 02:20:32 +0000112 assert(getConstant() == V && "Marking constant with different value");
113 return false;
Chris Lattner138a1242001-06-27 23:38:11 +0000114 }
Chris Lattner79272202009-11-02 02:20:32 +0000115
116 if (isUndefined()) {
117 Val.setInt(constant);
118 assert(V && "Marking constant with NULL");
119 Val.setPointer(V);
120 } else {
121 assert(getLatticeValue() == forcedconstant &&
122 "Cannot move from overdefined to constant!");
123 // Stay at forcedconstant if the constant is the same.
124 if (V == getConstant()) return false;
125
126 // Otherwise, we go to overdefined. Assumptions made based on the
127 // forced value are possibly wrong. Assuming this is another constant
128 // could expose a contradiction.
129 Val.setInt(overdefined);
130 }
131 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000132 }
133
Chris Lattner36c99522009-11-02 03:21:36 +0000134 /// getConstantInt - If this is a constant with a ConstantInt value, return it
135 /// otherwise return null.
136 ConstantInt *getConstantInt() const {
137 if (isConstant())
138 return dyn_cast<ConstantInt>(getConstant());
139 return 0;
140 }
141
Chris Lattner38871e42009-11-02 03:03:42 +0000142 void markForcedConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000143 assert(isUndefined() && "Can't force a defined value!");
144 Val.setInt(forcedconstant);
145 Val.setPointer(V);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000146 }
Chris Lattner138a1242001-06-27 23:38:11 +0000147};
Chris Lattnercc4f60b2009-11-02 02:47:51 +0000148} // end anonymous namespace.
149
150
151namespace {
Chris Lattner138a1242001-06-27 23:38:11 +0000152
Chris Lattner138a1242001-06-27 23:38:11 +0000153//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000154//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000155/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
156/// Constant Propagation.
157///
158class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner5638dc62009-11-02 06:06:14 +0000159 const TargetData *TD;
Chad Rosier00737bd2011-12-01 21:29:16 +0000160 const TargetLibraryInfo *TLI;
Nick Lewyckyfd47a592011-07-25 21:16:04 +0000161 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000162 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000163
Chris Lattnerfc36a562009-11-03 23:40:48 +0000164 /// StructValueState - This maintains ValueState for values that have
165 /// StructType, for example for formal arguments, calls, insertelement, etc.
166 ///
167 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
168
Chris Lattnerdd336d12004-12-11 05:15:59 +0000169 /// GlobalValue - If we are tracking any values for the contents of a global
170 /// variable, we keep a mapping from the constant accessor to the element of
171 /// the global, to the currently known value. If the value becomes
172 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000173 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000174
Devang Patel7c490d42008-03-11 05:46:42 +0000175 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000176 /// value out of a function, it will have an entry in this map, indicating
177 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000178 DenseMap<Function*, LatticeVal> TrackedRetVals;
179
180 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
181 /// that return multiple values.
Chris Lattnercf712de2008-08-23 23:36:38 +0000182 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattnerfc36a562009-11-03 23:40:48 +0000183
184 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
185 /// represented here for efficient lookup.
186 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000187
Chris Lattnerabf67ef2009-11-03 20:52:57 +0000188 /// TrackingIncomingArguments - This is the set of functions for whose
189 /// arguments we make optimistic assumptions about and try to prove as
190 /// constants.
Chris Lattner2396cc32009-11-03 19:24:51 +0000191 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
192
Chris Lattner38871e42009-11-02 03:03:42 +0000193 /// The reason for two worklists is that overdefined is the lowest state
194 /// on the lattice, and moving things to overdefined as fast as possible
195 /// makes SCCP converge much faster.
196 ///
197 /// By having a separate worklist, we accomplish this because everything
198 /// possibly overdefined will become overdefined at the soonest possible
199 /// point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000200 SmallVector<Value*, 64> OverdefinedInstWorkList;
201 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000202
203
Chris Lattnercf712de2008-08-23 23:36:38 +0000204 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000205
206 /// KnownFeasibleEdges - Entries in this set are edges which have already had
207 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000208 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
209 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000210public:
Chad Rosier00737bd2011-12-01 21:29:16 +0000211 SCCPSolver(const TargetData *td, const TargetLibraryInfo *tli)
212 : TD(td), TLI(tli) {}
Chris Lattner138a1242001-06-27 23:38:11 +0000213
Chris Lattner82bec2c2004-11-15 04:44:20 +0000214 /// MarkBlockExecutable - This method can be used by clients to mark all of
215 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner09275292009-11-02 06:11:23 +0000216 ///
217 /// This returns true if the block was not considered live before.
218 bool MarkBlockExecutable(BasicBlock *BB) {
219 if (!BBExecutable.insert(BB)) return false;
David Greene971cc7e2010-01-05 01:27:15 +0000220 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +0000221 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner09275292009-11-02 06:11:23 +0000222 return true;
Chris Lattner0dbfc052002-04-29 21:26:08 +0000223 }
224
Chris Lattnerdd336d12004-12-11 05:15:59 +0000225 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000226 /// inform the SCCPSolver that it should track loads and stores to the
227 /// specified global variable if it can. This is only legal to call if
228 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000229 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000230 // We only track the contents of scalar globals.
231 if (GV->getType()->getElementType()->isSingleValueType()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000232 LatticeVal &IV = TrackedGlobals[GV];
233 if (!isa<UndefValue>(GV->getInitializer()))
234 IV.markConstant(GV->getInitializer());
235 }
236 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000237
238 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
239 /// and out of the specified function (which cannot have its address taken),
240 /// this method must be called.
241 void AddTrackedFunction(Function *F) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000242 // Add an entry, F -> undef.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000243 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000244 MRVFunctionsTracked.insert(F);
Devang Patel7c490d42008-03-11 05:46:42 +0000245 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000246 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
247 LatticeVal()));
248 } else
249 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000250 }
251
Chris Lattner2396cc32009-11-03 19:24:51 +0000252 void AddArgumentTrackedFunction(Function *F) {
253 TrackingIncomingArguments.insert(F);
254 }
255
Chris Lattner82bec2c2004-11-15 04:44:20 +0000256 /// Solve - Solve for constants and executable blocks.
257 ///
258 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000259
Chris Lattner3bad2532006-12-20 06:21:33 +0000260 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000261 /// that branches on undef values cannot reach any of their successors.
262 /// However, this is not a safe assumption. After we solve dataflow, this
263 /// method should be use to handle this. If this returns true, the solver
264 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000265 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000266
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000267 bool isBlockExecutable(BasicBlock *BB) const {
268 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000269 }
270
Chris Lattner8db50122009-11-02 02:54:24 +0000271 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000272 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattner8db50122009-11-02 02:54:24 +0000273 assert(I != ValueState.end() && "V is not in valuemap!");
274 return I->second;
Chris Lattner82bec2c2004-11-15 04:44:20 +0000275 }
Chris Lattnerfc36a562009-11-03 23:40:48 +0000276
Chris Lattner473fc962010-08-18 02:41:56 +0000277 /*LatticeVal getStructLatticeValueFor(Value *V, unsigned i) const {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000278 DenseMap<std::pair<Value*, unsigned>, LatticeVal>::const_iterator I =
279 StructValueState.find(std::make_pair(V, i));
280 assert(I != StructValueState.end() && "V is not in valuemap!");
281 return I->second;
Chris Lattner473fc962010-08-18 02:41:56 +0000282 }*/
Chris Lattner82bec2c2004-11-15 04:44:20 +0000283
Devang Patel7c490d42008-03-11 05:46:42 +0000284 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000285 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000286 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
287 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000288 }
289
Chris Lattnerdd336d12004-12-11 05:15:59 +0000290 /// getTrackedGlobals - Get and return the set of inferred initializers for
291 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000292 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000293 return TrackedGlobals;
294 }
295
Chris Lattner36c99522009-11-02 03:21:36 +0000296 void markOverdefined(Value *V) {
Duncan Sands1df98592010-02-16 11:11:14 +0000297 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner57939df2007-03-04 04:50:21 +0000298 markOverdefined(ValueState[V], V);
299 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000300
Chris Lattnerfc36a562009-11-03 23:40:48 +0000301 /// markAnythingOverdefined - Mark the specified value overdefined. This
302 /// works with both scalars and structs.
303 void markAnythingOverdefined(Value *V) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000304 if (StructType *STy = dyn_cast<StructType>(V->getType()))
Chris Lattnerfc36a562009-11-03 23:40:48 +0000305 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
306 markOverdefined(getStructValueState(V, i), V);
307 else
308 markOverdefined(V);
309 }
310
Chris Lattner138a1242001-06-27 23:38:11 +0000311private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000312 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000313 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000314 // the users of the instruction are updated later.
315 //
Chris Lattner38871e42009-11-02 03:03:42 +0000316 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
317 if (!IV.markConstant(C)) return;
David Greene971cc7e2010-01-05 01:27:15 +0000318 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Chris Lattner8829cec2010-04-09 01:14:31 +0000319 if (IV.isOverdefined())
320 OverdefinedInstWorkList.push_back(V);
321 else
322 InstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000323 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000324
Chris Lattner38871e42009-11-02 03:03:42 +0000325 void markConstant(Value *V, Constant *C) {
Duncan Sands1df98592010-02-16 11:11:14 +0000326 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner59acc7d2004-12-10 08:02:06 +0000327 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000328 }
329
Chris Lattner2a0433b2009-11-02 05:55:40 +0000330 void markForcedConstant(Value *V, Constant *C) {
Duncan Sands1df98592010-02-16 11:11:14 +0000331 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner8829cec2010-04-09 01:14:31 +0000332 LatticeVal &IV = ValueState[V];
333 IV.markForcedConstant(C);
David Greene971cc7e2010-01-05 01:27:15 +0000334 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Chris Lattner8829cec2010-04-09 01:14:31 +0000335 if (IV.isOverdefined())
336 OverdefinedInstWorkList.push_back(V);
337 else
338 InstWorkList.push_back(V);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000339 }
340
341
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000342 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000343 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000344 // work list so that the users of the instruction are updated later.
Chris Lattner38871e42009-11-02 03:03:42 +0000345 void markOverdefined(LatticeVal &IV, Value *V) {
346 if (!IV.markOverdefined()) return;
347
David Greene971cc7e2010-01-05 01:27:15 +0000348 DEBUG(dbgs() << "markOverdefined: ";
Chris Lattner38871e42009-11-02 03:03:42 +0000349 if (Function *F = dyn_cast<Function>(V))
David Greene971cc7e2010-01-05 01:27:15 +0000350 dbgs() << "Function '" << F->getName() << "'\n";
Chris Lattner38871e42009-11-02 03:03:42 +0000351 else
David Greene971cc7e2010-01-05 01:27:15 +0000352 dbgs() << *V << '\n');
Chris Lattner38871e42009-11-02 03:03:42 +0000353 // Only instructions go on the work list
354 OverdefinedInstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000355 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000356
Chris Lattner2a0433b2009-11-02 05:55:40 +0000357 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000358 if (IV.isOverdefined() || MergeWithV.isUndefined())
359 return; // Noop.
360 if (MergeWithV.isOverdefined())
361 markOverdefined(IV, V);
362 else if (IV.isUndefined())
363 markConstant(IV, V, MergeWithV.getConstant());
364 else if (IV.getConstant() != MergeWithV.getConstant())
365 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000366 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000367
Chris Lattner2a0433b2009-11-02 05:55:40 +0000368 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Duncan Sands1df98592010-02-16 11:11:14 +0000369 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner36c99522009-11-02 03:21:36 +0000370 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000371 }
372
Chris Lattner138a1242001-06-27 23:38:11 +0000373
Chris Lattner2a0433b2009-11-02 05:55:40 +0000374 /// getValueState - Return the LatticeVal object that corresponds to the
375 /// value. This function handles the case when the value hasn't been seen yet
376 /// by properly seeding constants etc.
Chris Lattner38871e42009-11-02 03:03:42 +0000377 LatticeVal &getValueState(Value *V) {
Duncan Sands1df98592010-02-16 11:11:14 +0000378 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Chris Lattner5d356a72004-10-16 18:09:41 +0000379
Benjamin Kramerbcaa2152009-11-05 14:33:27 +0000380 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
381 ValueState.insert(std::make_pair(V, LatticeVal()));
382 LatticeVal &LV = I.first->second;
383
384 if (!I.second)
385 return LV; // Common case, already in the map.
Chris Lattner36c99522009-11-02 03:21:36 +0000386
Chris Lattner3bad2532006-12-20 06:21:33 +0000387 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner36c99522009-11-02 03:21:36 +0000388 // Undef values remain undefined.
389 if (!isa<UndefValue>(V))
Chris Lattnerb59673e2007-02-02 20:38:30 +0000390 LV.markConstant(C); // Constants are constant
Chris Lattner2a88bb72002-08-30 23:39:00 +0000391 }
Chris Lattner36c99522009-11-02 03:21:36 +0000392
Chris Lattner2f096252009-11-02 02:33:50 +0000393 // All others are underdefined by default.
Chris Lattner36c99522009-11-02 03:21:36 +0000394 return LV;
Chris Lattner138a1242001-06-27 23:38:11 +0000395 }
396
Chris Lattnerfc36a562009-11-03 23:40:48 +0000397 /// getStructValueState - Return the LatticeVal object that corresponds to the
398 /// value/field pair. This function handles the case when the value hasn't
399 /// been seen yet by properly seeding constants etc.
400 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands1df98592010-02-16 11:11:14 +0000401 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattnerfc36a562009-11-03 23:40:48 +0000402 assert(i < cast<StructType>(V->getType())->getNumElements() &&
403 "Invalid element #");
Benjamin Kramerbcaa2152009-11-05 14:33:27 +0000404
405 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
406 bool> I = StructValueState.insert(
407 std::make_pair(std::make_pair(V, i), LatticeVal()));
408 LatticeVal &LV = I.first->second;
409
410 if (!I.second)
411 return LV; // Common case, already in the map.
412
Chris Lattnerfc36a562009-11-03 23:40:48 +0000413 if (Constant *C = dyn_cast<Constant>(V)) {
414 if (isa<UndefValue>(C))
415 ; // Undef values remain undefined.
416 else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C))
417 LV.markConstant(CS->getOperand(i)); // Constants are constant.
418 else if (isa<ConstantAggregateZero>(C)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000419 Type *FieldTy = cast<StructType>(V->getType())->getElementType(i);
Chris Lattnerfc36a562009-11-03 23:40:48 +0000420 LV.markConstant(Constant::getNullValue(FieldTy));
421 } else
422 LV.markOverdefined(); // Unknown sort of constant.
423 }
424
425 // All others are underdefined by default.
426 return LV;
427 }
428
429
Chris Lattner2a0433b2009-11-02 05:55:40 +0000430 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
431 /// work list if it is not already executable.
Chris Lattner16b18fd2003-10-08 16:55:34 +0000432 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
433 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
434 return; // This edge is already known to be executable!
435
Chris Lattner09275292009-11-02 06:11:23 +0000436 if (!MarkBlockExecutable(Dest)) {
437 // If the destination is already executable, we just made an *edge*
438 // feasible that wasn't before. Revisit the PHI nodes in the block
439 // because they have potentially new operands.
David Greene971cc7e2010-01-05 01:27:15 +0000440 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000441 << " -> " << Dest->getName() << "\n");
Chris Lattner16b18fd2003-10-08 16:55:34 +0000442
Chris Lattner09275292009-11-02 06:11:23 +0000443 PHINode *PN;
444 for (BasicBlock::iterator I = Dest->begin();
445 (PN = dyn_cast<PHINode>(I)); ++I)
446 visitPHINode(*PN);
Chris Lattner9de28282003-04-25 02:50:03 +0000447 }
Chris Lattner138a1242001-06-27 23:38:11 +0000448 }
449
Chris Lattner82bec2c2004-11-15 04:44:20 +0000450 // getFeasibleSuccessors - Return a vector of booleans to indicate which
451 // successors are reachable from a given terminator instruction.
452 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000453 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000454
455 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000456 // block to the 'To' basic block is currently feasible.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000457 //
458 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
459
460 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattner2f096252009-11-02 02:33:50 +0000461 // instruction that was just changed state somehow. Based on this
Chris Lattner82bec2c2004-11-15 04:44:20 +0000462 // information, we need to update the specified user of this instruction.
463 //
Chris Lattner14532d02009-11-03 03:42:51 +0000464 void OperandChangedState(Instruction *I) {
465 if (BBExecutable.count(I->getParent())) // Inst is executable?
466 visit(*I);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000467 }
Dale Johannesenf619b5a2010-11-30 20:23:21 +0000468
Chris Lattner82bec2c2004-11-15 04:44:20 +0000469private:
470 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000471
Chris Lattner2f096252009-11-02 02:33:50 +0000472 // visit implementations - Something changed in this instruction. Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000473 // operand made a transition, or the instruction is newly executable. Change
474 // the value type of I to reflect these changes if appropriate.
Chris Lattner7e708292002-06-25 16:13:24 +0000475 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000476
477 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000478 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000479 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000480
Chris Lattnerb8047602002-08-14 17:53:45 +0000481 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000482 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000483 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000484 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000485 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000486 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000487 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000488 void visitExtractValueInst(ExtractValueInst &EVI);
489 void visitInsertValueInst(InsertValueInst &IVI);
Bill Wendlinge6e88262011-08-12 20:24:12 +0000490 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000491
Chris Lattner2f096252009-11-02 02:33:50 +0000492 // Instructions that cannot be folded away.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000493 void visitStoreInst (StoreInst &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000494 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000495 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez66284e02009-10-24 04:23:03 +0000496 void visitCallInst (CallInst &I) {
Gabor Greif7d3056b2010-07-28 22:50:26 +0000497 visitCallSite(&I);
Victor Hernandez83d63912009-09-18 22:35:49 +0000498 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000499 void visitInvokeInst (InvokeInst &II) {
Gabor Greif7d3056b2010-07-28 22:50:26 +0000500 visitCallSite(&II);
Chris Lattner59acc7d2004-12-10 08:02:06 +0000501 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000502 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000503 void visitCallSite (CallSite CS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +0000504 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner36143fc2003-09-08 18:54:55 +0000505 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000506 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Eli Friedman8a552bb2011-07-27 01:08:30 +0000507 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Eli Friedmanfe1926e2011-08-02 21:35:16 +0000508 void visitAtomicCmpXchgInst (AtomicCmpXchgInst &I) { markOverdefined(&I); }
509 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
Victor Hernandez7b929da2009-10-23 21:09:37 +0000510 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnerfc36a562009-11-03 23:40:48 +0000511 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000512
Chris Lattner7e708292002-06-25 16:13:24 +0000513 void visitInstruction(Instruction &I) {
Chris Lattner2f096252009-11-02 02:33:50 +0000514 // If a new instruction is added to LLVM that we don't handle.
David Greene971cc7e2010-01-05 01:27:15 +0000515 dbgs() << "SCCP: Don't know how to handle: " << I;
Chris Lattnerfc36a562009-11-03 23:40:48 +0000516 markAnythingOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000517 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000518};
Chris Lattnerf6293092002-07-23 18:06:35 +0000519
Duncan Sandse2abf122007-07-20 08:56:21 +0000520} // end anonymous namespace
521
522
Chris Lattnerb9a66342002-05-02 21:44:00 +0000523// getFeasibleSuccessors - Return a vector of booleans to indicate which
524// successors are reachable from a given terminator instruction.
525//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000526void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000527 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000528 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000529 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000530 if (BI->isUnconditional()) {
531 Succs[0] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000532 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000533 }
Chris Lattnerea0db072009-11-02 02:30:06 +0000534
Chris Lattner2a0433b2009-11-02 05:55:40 +0000535 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000536 ConstantInt *CI = BCValue.getConstantInt();
537 if (CI == 0) {
Chris Lattnerea0db072009-11-02 02:30:06 +0000538 // Overdefined condition variables, and branches on unfoldable constant
539 // conditions, mean the branch could go either way.
Chris Lattner36c99522009-11-02 03:21:36 +0000540 if (!BCValue.isUndefined())
541 Succs[0] = Succs[1] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000542 return;
543 }
544
545 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000546 Succs[CI->isZero()] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000547 return;
548 }
549
Chris Lattner36c99522009-11-02 03:21:36 +0000550 if (isa<InvokeInst>(TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000551 // Invoke instructions successors are always executable.
552 Succs[0] = Succs[1] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000553 return;
554 }
555
556 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Eli Friedman1fc291f2011-08-16 21:12:35 +0000557 if (TI.getNumSuccessors() < 2) {
558 Succs[0] = true;
559 return;
560 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000561 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000562 ConstantInt *CI = SCValue.getConstantInt();
563
564 if (CI == 0) { // Overdefined or undefined condition?
Chris Lattnerb9a66342002-05-02 21:44:00 +0000565 // All destinations are executable!
Chris Lattner36c99522009-11-02 03:21:36 +0000566 if (!SCValue.isUndefined())
567 Succs.assign(TI.getNumSuccessors(), true);
568 return;
569 }
570
571 Succs[SI->findCaseValue(CI)] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000572 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000573 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000574
575 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
576 if (isa<IndirectBrInst>(&TI)) {
577 // Just mark all destinations executable!
578 Succs.assign(TI.getNumSuccessors(), true);
579 return;
580 }
581
582#ifndef NDEBUG
David Greene971cc7e2010-01-05 01:27:15 +0000583 dbgs() << "Unknown terminator instruction: " << TI << '\n';
Chris Lattner4c0236f2009-10-29 01:21:20 +0000584#endif
585 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000586}
587
588
Chris Lattner59f0ce22002-05-02 21:18:01 +0000589// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000590// block to the 'To' basic block is currently feasible.
Chris Lattner59f0ce22002-05-02 21:18:01 +0000591//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000592bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000593 assert(BBExecutable.count(To) && "Dest should always be alive!");
594
595 // Make sure the source basic block is executable!!
596 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000597
Chris Lattner2f096252009-11-02 02:33:50 +0000598 // Check to make sure this edge itself is actually feasible now.
Chris Lattner7d275f42003-10-08 15:47:41 +0000599 TerminatorInst *TI = From->getTerminator();
600 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
601 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000602 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000603
Chris Lattner2a0433b2009-11-02 05:55:40 +0000604 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000605
Chris Lattnerea0db072009-11-02 02:30:06 +0000606 // Overdefined condition variables mean the branch could go either way,
607 // undef conditions mean that neither edge is feasible yet.
Chris Lattner36c99522009-11-02 03:21:36 +0000608 ConstantInt *CI = BCValue.getConstantInt();
609 if (CI == 0)
610 return !BCValue.isUndefined();
Chris Lattnerea0db072009-11-02 02:30:06 +0000611
Chris Lattnerea0db072009-11-02 02:30:06 +0000612 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000613 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000614 }
615
616 // Invoke instructions successors are always executable.
617 if (isa<InvokeInst>(TI))
Chris Lattner7d275f42003-10-08 15:47:41 +0000618 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000619
620 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eli Friedman1fc291f2011-08-16 21:12:35 +0000621 if (SI->getNumSuccessors() < 2)
622 return true;
623
Chris Lattner2a0433b2009-11-02 05:55:40 +0000624 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000625 ConstantInt *CI = SCValue.getConstantInt();
626
627 if (CI == 0)
628 return !SCValue.isUndefined();
Chris Lattner84831642004-01-12 17:40:36 +0000629
Chris Lattner36c99522009-11-02 03:21:36 +0000630 // Make sure to skip the "default value" which isn't a value
631 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
632 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
633 return SI->getSuccessor(i) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000634
Chris Lattner36c99522009-11-02 03:21:36 +0000635 // If the constant value is not equal to any of the branches, we must
636 // execute default branch.
637 return SI->getDefaultDest() == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000638 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000639
640 // Just mark all destinations executable!
641 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
Eli Friedman21c60902011-05-21 19:13:10 +0000642 if (isa<IndirectBrInst>(TI))
Chris Lattner4c0236f2009-10-29 01:21:20 +0000643 return true;
644
645#ifndef NDEBUG
David Greene971cc7e2010-01-05 01:27:15 +0000646 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
Chris Lattner4c0236f2009-10-29 01:21:20 +0000647#endif
648 llvm_unreachable(0);
Chris Lattner59f0ce22002-05-02 21:18:01 +0000649}
Chris Lattner138a1242001-06-27 23:38:11 +0000650
Chris Lattner2f096252009-11-02 02:33:50 +0000651// visit Implementations - Something changed in this instruction, either an
Chris Lattner138a1242001-06-27 23:38:11 +0000652// operand made a transition, or the instruction is newly executable. Change
653// the value type of I to reflect these changes if appropriate. This method
654// makes sure to do the following actions:
655//
656// 1. If a phi node merges two constants in, and has conflicting value coming
657// from different branches, or if the PHI node merges in an overdefined
658// value, then the PHI node becomes overdefined.
659// 2. If a phi node merges only constants in, and they all agree on value, the
660// PHI node becomes a constant value equal to that.
661// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
662// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
663// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
664// 6. If a conditional branch has a value that is constant, make the selected
665// destination executable
666// 7. If a conditional branch has a value that is overdefined, make all
667// successors executable.
668//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000669void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000670 // If this PN returns a struct, just mark the result overdefined.
671 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands1df98592010-02-16 11:11:14 +0000672 if (PN.getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +0000673 return markAnythingOverdefined(&PN);
674
Eli Friedmanb80f7782011-11-11 01:16:15 +0000675 if (getValueState(&PN).isOverdefined())
Chris Lattner1daee8b2004-01-12 03:57:30 +0000676 return; // Quick exit
Chris Lattner138a1242001-06-27 23:38:11 +0000677
Chris Lattnera2f652d2004-03-16 19:49:59 +0000678 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
679 // and slow us down a lot. Just mark them overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +0000680 if (PN.getNumIncomingValues() > 64)
Chris Lattner2a0433b2009-11-02 05:55:40 +0000681 return markOverdefined(&PN);
Chris Lattnerfc36a562009-11-03 23:40:48 +0000682
Chris Lattner2a632552002-04-18 15:13:15 +0000683 // Look at all of the executable operands of the PHI node. If any of them
684 // are overdefined, the PHI becomes overdefined as well. If they are all
685 // constant, and they agree with each other, the PHI becomes the identical
686 // constant. If they are constant and don't agree, the PHI is overdefined.
687 // If there are no executable operands, the PHI remains undefined.
688 //
Chris Lattner9de28282003-04-25 02:50:03 +0000689 Constant *OperandVal = 0;
690 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000691 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000692 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000693
Chris Lattner38871e42009-11-02 03:03:42 +0000694 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
695 continue;
696
697 if (IV.isOverdefined()) // PHI node becomes overdefined!
698 return markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000699
Chris Lattner38871e42009-11-02 03:03:42 +0000700 if (OperandVal == 0) { // Grab the first value.
701 OperandVal = IV.getConstant();
702 continue;
Chris Lattner138a1242001-06-27 23:38:11 +0000703 }
Chris Lattner38871e42009-11-02 03:03:42 +0000704
705 // There is already a reachable operand. If we conflict with it,
706 // then the PHI node becomes overdefined. If we agree with it, we
707 // can continue on.
708
709 // Check to see if there are two different constants merging, if so, the PHI
710 // node is overdefined.
711 if (IV.getConstant() != OperandVal)
712 return markOverdefined(&PN);
Chris Lattner138a1242001-06-27 23:38:11 +0000713 }
714
Chris Lattner2a632552002-04-18 15:13:15 +0000715 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000716 // arguments that agree with each other(and OperandVal is the constant) or
717 // OperandVal is null because there are no defined incoming arguments. If
718 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000719 //
Chris Lattner9de28282003-04-25 02:50:03 +0000720 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000721 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000722}
723
Chris Lattner14532d02009-11-03 03:42:51 +0000724
725
726
Chris Lattner59acc7d2004-12-10 08:02:06 +0000727void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000728 if (I.getNumOperands() == 0) return; // ret void
Chris Lattner59acc7d2004-12-10 08:02:06 +0000729
Chris Lattner59acc7d2004-12-10 08:02:06 +0000730 Function *F = I.getParent()->getParent();
Chris Lattnerfc36a562009-11-03 23:40:48 +0000731 Value *ResultOp = I.getOperand(0);
Chris Lattner14532d02009-11-03 03:42:51 +0000732
Devang Patel7c490d42008-03-11 05:46:42 +0000733 // If we are tracking the return value of this function, merge it in.
Duncan Sands1df98592010-02-16 11:11:14 +0000734 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000735 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000736 TrackedRetVals.find(F);
Chris Lattner14532d02009-11-03 03:42:51 +0000737 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000738 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patel7c490d42008-03-11 05:46:42 +0000739 return;
740 }
741 }
742
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000743 // Handle functions that return multiple values.
Chris Lattnerfc36a562009-11-03 23:40:48 +0000744 if (!TrackedMultipleRetVals.empty()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000745 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattnerfc36a562009-11-03 23:40:48 +0000746 if (MRVFunctionsTracked.count(F))
747 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
748 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
749 getStructValueState(ResultOp, i));
750
Chris Lattner59acc7d2004-12-10 08:02:06 +0000751 }
752}
753
Chris Lattner82bec2c2004-11-15 04:44:20 +0000754void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000755 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000756 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000757
Chris Lattner16b18fd2003-10-08 16:55:34 +0000758 BasicBlock *BB = TI.getParent();
759
Chris Lattner2f096252009-11-02 02:33:50 +0000760 // Mark all feasible successors executable.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000761 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000762 if (SuccFeasible[i])
763 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000764}
765
Chris Lattner82bec2c2004-11-15 04:44:20 +0000766void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000767 LatticeVal OpSt = getValueState(I.getOperand(0));
768 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000769 markOverdefined(&I);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000770 else if (OpSt.isConstant()) // Propagate constant value
Owen Andersonbaf3c402009-07-29 18:55:55 +0000771 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattner2a0433b2009-11-02 05:55:40 +0000772 OpSt.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000773}
774
Chris Lattnerfc36a562009-11-03 23:40:48 +0000775
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000776void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000777 // If this returns a struct, mark all elements over defined, we don't track
778 // structs in structs.
Duncan Sands1df98592010-02-16 11:11:14 +0000779 if (EVI.getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +0000780 return markAnythingOverdefined(&EVI);
781
782 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner38871e42009-11-02 03:03:42 +0000783 if (EVI.getNumIndices() != 1)
784 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000785
Chris Lattnerfc36a562009-11-03 23:40:48 +0000786 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands1df98592010-02-16 11:11:14 +0000787 if (AggVal->getType()->isStructTy()) {
Chris Lattner103f2432009-11-10 22:02:09 +0000788 unsigned i = *EVI.idx_begin();
789 LatticeVal EltVal = getStructValueState(AggVal, i);
790 mergeInValue(getValueState(&EVI), &EVI, EltVal);
791 } else {
792 // Otherwise, must be extracting from an array.
793 return markOverdefined(&EVI);
794 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000795}
796
797void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000798 StructType *STy = dyn_cast<StructType>(IVI.getType());
Chris Lattnerfc36a562009-11-03 23:40:48 +0000799 if (STy == 0)
Chris Lattner38871e42009-11-02 03:03:42 +0000800 return markOverdefined(&IVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000801
Chris Lattnerfc36a562009-11-03 23:40:48 +0000802 // If this has more than one index, we can't handle it, drive all results to
803 // undef.
804 if (IVI.getNumIndices() != 1)
805 return markAnythingOverdefined(&IVI);
806
807 Value *Aggr = IVI.getAggregateOperand();
808 unsigned Idx = *IVI.idx_begin();
809
810 // Compute the result based on what we're inserting.
811 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
812 // This passes through all values that aren't the inserted element.
813 if (i != Idx) {
814 LatticeVal EltVal = getStructValueState(Aggr, i);
815 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
816 continue;
817 }
818
819 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands1df98592010-02-16 11:11:14 +0000820 if (Val->getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +0000821 // We don't track structs in structs.
822 markOverdefined(getStructValueState(&IVI, i), &IVI);
823 else {
824 LatticeVal InVal = getValueState(Val);
825 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
826 }
827 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000828}
829
Chris Lattner82bec2c2004-11-15 04:44:20 +0000830void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000831 // If this select returns a struct, just mark the result overdefined.
832 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands1df98592010-02-16 11:11:14 +0000833 if (I.getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +0000834 return markAnythingOverdefined(&I);
835
Chris Lattner2a0433b2009-11-02 05:55:40 +0000836 LatticeVal CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000837 if (CondValue.isUndefined())
838 return;
Chris Lattner36c99522009-11-02 03:21:36 +0000839
840 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000841 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
842 mergeInValue(&I, getValueState(OpVal));
Chris Lattner36c99522009-11-02 03:21:36 +0000843 return;
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000844 }
845
846 // Otherwise, the condition is overdefined or a constant we can't evaluate.
847 // See if we can produce something better than overdefined based on the T/F
848 // value.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000849 LatticeVal TVal = getValueState(I.getTrueValue());
850 LatticeVal FVal = getValueState(I.getFalseValue());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000851
852 // select ?, C, C -> C.
853 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner38871e42009-11-02 03:03:42 +0000854 TVal.getConstant() == FVal.getConstant())
855 return markConstant(&I, FVal.getConstant());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000856
Chris Lattner2a0433b2009-11-02 05:55:40 +0000857 if (TVal.isUndefined()) // select ?, undef, X -> X.
858 return mergeInValue(&I, FVal);
859 if (FVal.isUndefined()) // select ?, X, undef -> X.
860 return mergeInValue(&I, TVal);
861 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000862}
863
Chris Lattner2a0433b2009-11-02 05:55:40 +0000864// Handle Binary Operators.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000865void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000866 LatticeVal V1State = getValueState(I.getOperand(0));
867 LatticeVal V2State = getValueState(I.getOperand(1));
868
Chris Lattneref36dfd2004-11-15 05:03:30 +0000869 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000870 if (IV.isOverdefined()) return;
871
Chris Lattner2a0433b2009-11-02 05:55:40 +0000872 if (V1State.isConstant() && V2State.isConstant())
873 return markConstant(IV, &I,
874 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
875 V2State.getConstant()));
876
877 // If something is undef, wait for it to resolve.
878 if (!V1State.isOverdefined() && !V2State.isOverdefined())
879 return;
880
881 // Otherwise, one of our operands is overdefined. Try to produce something
882 // better than overdefined with some tricks.
883
884 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
885 // operand is overdefined.
886 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
887 LatticeVal *NonOverdefVal = 0;
888 if (!V1State.isOverdefined())
889 NonOverdefVal = &V1State;
890 else if (!V2State.isOverdefined())
891 NonOverdefVal = &V2State;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000892
Chris Lattner2a0433b2009-11-02 05:55:40 +0000893 if (NonOverdefVal) {
894 if (NonOverdefVal->isUndefined()) {
895 // Could annihilate value.
896 if (I.getOpcode() == Instruction::And)
897 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000898 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
Chris Lattner2a0433b2009-11-02 05:55:40 +0000899 markConstant(IV, &I, Constant::getAllOnesValue(PT));
900 else
901 markConstant(IV, &I,
902 Constant::getAllOnesValue(I.getType()));
903 return;
Chris Lattnera177c672004-12-11 23:15:19 +0000904 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000905
906 if (I.getOpcode() == Instruction::And) {
907 // X and 0 = 0
908 if (NonOverdefVal->getConstant()->isNullValue())
909 return markConstant(IV, &I, NonOverdefVal->getConstant());
910 } else {
911 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
912 if (CI->isAllOnesValue()) // X or -1 = -1
913 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnera177c672004-12-11 23:15:19 +0000914 }
915 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000916 }
Chris Lattnera177c672004-12-11 23:15:19 +0000917
918
Chris Lattner2a0433b2009-11-02 05:55:40 +0000919 markOverdefined(&I);
Chris Lattner2a632552002-04-18 15:13:15 +0000920}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000921
Chris Lattner2f096252009-11-02 02:33:50 +0000922// Handle ICmpInst instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000923void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000924 LatticeVal V1State = getValueState(I.getOperand(0));
925 LatticeVal V2State = getValueState(I.getOperand(1));
926
Reid Spencere4d87aa2006-12-23 06:05:41 +0000927 LatticeVal &IV = ValueState[&I];
928 if (IV.isOverdefined()) return;
929
Chris Lattner2a0433b2009-11-02 05:55:40 +0000930 if (V1State.isConstant() && V2State.isConstant())
931 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
932 V1State.getConstant(),
933 V2State.getConstant()));
934
935 // If operands are still undefined, wait for it to resolve.
936 if (!V1State.isOverdefined() && !V2State.isOverdefined())
937 return;
938
Chris Lattner2a0433b2009-11-02 05:55:40 +0000939 markOverdefined(&I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000940}
941
Robert Bocchino56107e22006-01-10 19:05:05 +0000942void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000943 // TODO : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +0000944 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +0000945
946#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +0000947 LatticeVal &ValState = getValueState(I.getOperand(0));
948 LatticeVal &IdxState = getValueState(I.getOperand(1));
949
950 if (ValState.isOverdefined() || IdxState.isOverdefined())
951 markOverdefined(&I);
952 else if(ValState.isConstant() && IdxState.isConstant())
953 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
954 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +0000955#endif
Robert Bocchino56107e22006-01-10 19:05:05 +0000956}
957
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000958void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000959 // TODO : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +0000960 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +0000961#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000962 LatticeVal &ValState = getValueState(I.getOperand(0));
963 LatticeVal &EltState = getValueState(I.getOperand(1));
964 LatticeVal &IdxState = getValueState(I.getOperand(2));
965
966 if (ValState.isOverdefined() || EltState.isOverdefined() ||
967 IdxState.isOverdefined())
968 markOverdefined(&I);
969 else if(ValState.isConstant() && EltState.isConstant() &&
970 IdxState.isConstant())
971 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
972 EltState.getConstant(),
973 IdxState.getConstant()));
974 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +0000975 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +0000976 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
977 EltState.getConstant(),
978 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +0000979#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000980}
981
Chris Lattner543abdf2006-04-08 01:19:12 +0000982void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000983 // TODO : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +0000984 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +0000985#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +0000986 LatticeVal &V1State = getValueState(I.getOperand(0));
987 LatticeVal &V2State = getValueState(I.getOperand(1));
988 LatticeVal &MaskState = getValueState(I.getOperand(2));
989
990 if (MaskState.isUndefined() ||
991 (V1State.isUndefined() && V2State.isUndefined()))
992 return; // Undefined output if mask or both inputs undefined.
993
994 if (V1State.isOverdefined() || V2State.isOverdefined() ||
995 MaskState.isOverdefined()) {
996 markOverdefined(&I);
997 } else {
998 // A mix of constant/undef inputs.
999 Constant *V1 = V1State.isConstant() ?
1000 V1State.getConstant() : UndefValue::get(I.getType());
1001 Constant *V2 = V2State.isConstant() ?
1002 V2State.getConstant() : UndefValue::get(I.getType());
1003 Constant *Mask = MaskState.isConstant() ?
1004 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1005 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1006 }
Devang Patel67a821d2006-12-04 23:54:59 +00001007#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001008}
1009
Chris Lattner2f096252009-11-02 02:33:50 +00001010// Handle getelementptr instructions. If all operands are constants then we
Chris Lattner2a88bb72002-08-30 23:39:00 +00001011// can turn this into a getelementptr ConstantExpr.
1012//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001013void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner5cc66d92009-11-02 23:25:39 +00001014 if (ValueState[&I].isOverdefined()) return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001015
Chris Lattnere777ff22007-02-02 20:51:48 +00001016 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001017 Operands.reserve(I.getNumOperands());
1018
1019 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001020 LatticeVal State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001021 if (State.isUndefined())
Chris Lattner2f096252009-11-02 02:33:50 +00001022 return; // Operands are not resolved yet.
1023
Chris Lattner38871e42009-11-02 03:03:42 +00001024 if (State.isOverdefined())
Chris Lattner5cc66d92009-11-02 23:25:39 +00001025 return markOverdefined(&I);
Chris Lattner38871e42009-11-02 03:03:42 +00001026
Chris Lattner2a88bb72002-08-30 23:39:00 +00001027 assert(State.isConstant() && "Unknown state!");
1028 Operands.push_back(State.getConstant());
1029 }
1030
1031 Constant *Ptr = Operands[0];
Jay Foaddab3d292011-07-21 14:31:17 +00001032 ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
1033 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001034}
Brian Gaeked0fde302003-11-11 22:41:34 +00001035
Chris Lattner2a0433b2009-11-02 05:55:40 +00001036void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001037 // If this store is of a struct, ignore it.
Duncan Sands1df98592010-02-16 11:11:14 +00001038 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +00001039 return;
1040
Chris Lattnerdd336d12004-12-11 05:15:59 +00001041 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1042 return;
Chris Lattner2a0433b2009-11-02 05:55:40 +00001043
Chris Lattnerdd336d12004-12-11 05:15:59 +00001044 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001045 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001046 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1047
Chris Lattner2a0433b2009-11-02 05:55:40 +00001048 // Get the value we are storing into the global, then merge it.
1049 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattnerdd336d12004-12-11 05:15:59 +00001050 if (I->second.isOverdefined())
1051 TrackedGlobals.erase(I); // No need to keep tracking this!
1052}
1053
1054
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001055// Handle load instructions. If the operand is a constant pointer to a constant
1056// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001057void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001058 // If this load is of a struct, just mark the result overdefined.
Duncan Sands1df98592010-02-16 11:11:14 +00001059 if (I.getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +00001060 return markAnythingOverdefined(&I);
1061
Chris Lattner2a0433b2009-11-02 05:55:40 +00001062 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattner5638dc62009-11-02 06:06:14 +00001063 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Chris Lattner2a0433b2009-11-02 05:55:40 +00001064
Chris Lattneref36dfd2004-11-15 05:03:30 +00001065 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001066 if (IV.isOverdefined()) return;
1067
Chris Lattner2a0433b2009-11-02 05:55:40 +00001068 if (!PtrVal.isConstant() || I.isVolatile())
1069 return markOverdefined(IV, &I);
1070
Chris Lattner5638dc62009-11-02 06:06:14 +00001071 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanfd939082005-04-21 23:48:37 +00001072
Chris Lattner2a0433b2009-11-02 05:55:40 +00001073 // load null -> null
1074 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1075 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1076
1077 // Transform load (constant global) into the value loaded.
1078 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001079 if (!TrackedGlobals.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001080 // If we are tracking this global, merge in the known value for it.
1081 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1082 TrackedGlobals.find(GV);
1083 if (It != TrackedGlobals.end()) {
1084 mergeInValue(IV, &I, It->second);
1085 return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001086 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001087 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001088 }
1089
Chris Lattner5638dc62009-11-02 06:06:14 +00001090 // Transform load from a constant into a constant if possible.
1091 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1092 return markConstant(IV, &I, C);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001093
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001094 // Otherwise we cannot say for certain what value this load will produce.
1095 // Bail out.
1096 markOverdefined(IV, &I);
1097}
Chris Lattner58b7b082004-04-13 19:43:54 +00001098
Chris Lattner59acc7d2004-12-10 08:02:06 +00001099void SCCPSolver::visitCallSite(CallSite CS) {
1100 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001101 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001102
1103 // The common case is that we aren't tracking the callee, either because we
1104 // are not doing interprocedural analysis or the callee is indirect, or is
1105 // external. Handle these cases first.
Chris Lattner14532d02009-11-03 03:42:51 +00001106 if (F == 0 || F->isDeclaration()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001107CallOverdefined:
1108 // Void return and not tracking callee, just bail.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001109 if (I->getType()->isVoidTy()) return;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001110
1111 // Otherwise, if we have a single return value case, and if the function is
1112 // a declaration, maybe we can constant fold it.
Duncan Sands1df98592010-02-16 11:11:14 +00001113 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001114 canConstantFoldCallTo(F)) {
1115
1116 SmallVector<Constant*, 8> Operands;
1117 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1118 AI != E; ++AI) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001119 LatticeVal State = getValueState(*AI);
Chris Lattner38871e42009-11-02 03:03:42 +00001120
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001121 if (State.isUndefined())
1122 return; // Operands are not resolved yet.
Chris Lattner38871e42009-11-02 03:03:42 +00001123 if (State.isOverdefined())
1124 return markOverdefined(I);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001125 assert(State.isConstant() && "Unknown state!");
1126 Operands.push_back(State.getConstant());
1127 }
1128
1129 // If we can constant fold this, mark the result of the call as a
1130 // constant.
Chad Rosier00737bd2011-12-01 21:29:16 +00001131 if (Constant *C = ConstantFoldCall(F, Operands, TLI))
Chris Lattner38871e42009-11-02 03:03:42 +00001132 return markConstant(I, C);
Chris Lattner58b7b082004-04-13 19:43:54 +00001133 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001134
1135 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattnerfc36a562009-11-03 23:40:48 +00001136 return markAnythingOverdefined(I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001137 }
1138
Chris Lattner2396cc32009-11-03 19:24:51 +00001139 // If this is a local function that doesn't have its address taken, mark its
1140 // entry block executable and merge in the actual arguments to the call into
1141 // the formal arguments of the function.
1142 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1143 MarkBlockExecutable(F->begin());
1144
1145 // Propagate information from this call site into the callee.
1146 CallSite::arg_iterator CAI = CS.arg_begin();
1147 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1148 AI != E; ++AI, ++CAI) {
1149 // If this argument is byval, and if the function is not readonly, there
1150 // will be an implicit copy formed of the input aggregate.
1151 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1152 markOverdefined(AI);
1153 continue;
1154 }
1155
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001156 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner0fb7e182009-11-04 18:57:42 +00001157 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1158 LatticeVal CallArg = getStructValueState(*CAI, i);
1159 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1160 }
Chris Lattnerfc36a562009-11-03 23:40:48 +00001161 } else {
1162 mergeInValue(AI, getValueState(*CAI));
1163 }
Chris Lattner2396cc32009-11-03 19:24:51 +00001164 }
1165 }
1166
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001167 // If this is a single/zero retval case, see if we're tracking the function.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001168 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001169 if (!MRVFunctionsTracked.count(F))
1170 goto CallOverdefined; // Not tracking this callee.
1171
1172 // If we are tracking this callee, propagate the result of the function
1173 // into this call site.
1174 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1175 mergeInValue(getStructValueState(I, i), I,
1176 TrackedMultipleRetVals[std::make_pair(F, i)]);
1177 } else {
1178 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1179 if (TFRVI == TrackedRetVals.end())
1180 goto CallOverdefined; // Not tracking this callee.
1181
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001182 // If so, propagate the return value of the callee into this call result.
1183 mergeInValue(I, TFRVI->second);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001184 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001185}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001186
Chris Lattner82bec2c2004-11-15 04:44:20 +00001187void SCCPSolver::Solve() {
1188 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001189 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001190 !OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001191 // Process the overdefined instruction's work list first, which drives other
1192 // things to overdefined more quickly.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001193 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001194 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001195
David Greene971cc7e2010-01-05 01:27:15 +00001196 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001197
Chris Lattner82bec2c2004-11-15 04:44:20 +00001198 // "I" got into the work list because it either made the transition from
1199 // bottom to constant
1200 //
1201 // Anything on this worklist that is overdefined need not be visited
1202 // since all of its users will have already been marked as overdefined
Chris Lattner2f096252009-11-02 02:33:50 +00001203 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001204 //
1205 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1206 UI != E; ++UI)
Chris Lattner14532d02009-11-03 03:42:51 +00001207 if (Instruction *I = dyn_cast<Instruction>(*UI))
1208 OperandChangedState(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001209 }
Chris Lattner2f096252009-11-02 02:33:50 +00001210
1211 // Process the instruction work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001212 while (!InstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001213 Value *I = InstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001214
David Greene971cc7e2010-01-05 01:27:15 +00001215 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001216
Chris Lattner2a0433b2009-11-02 05:55:40 +00001217 // "I" got into the work list because it made the transition from undef to
1218 // constant.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001219 //
1220 // Anything on this worklist that is overdefined need not be visited
1221 // since all of its users will have already been marked as overdefined.
Chris Lattner2f096252009-11-02 02:33:50 +00001222 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001223 //
Duncan Sands1df98592010-02-16 11:11:14 +00001224 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Chris Lattner82bec2c2004-11-15 04:44:20 +00001225 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1226 UI != E; ++UI)
Chris Lattner14532d02009-11-03 03:42:51 +00001227 if (Instruction *I = dyn_cast<Instruction>(*UI))
1228 OperandChangedState(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001229 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001230
Chris Lattner2f096252009-11-02 02:33:50 +00001231 // Process the basic block work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001232 while (!BBWorkList.empty()) {
1233 BasicBlock *BB = BBWorkList.back();
1234 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001235
David Greene971cc7e2010-01-05 01:27:15 +00001236 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001237
Chris Lattner82bec2c2004-11-15 04:44:20 +00001238 // Notify all instructions in this basic block that they are newly
1239 // executable.
1240 visit(BB);
1241 }
1242 }
1243}
1244
Chris Lattner3bad2532006-12-20 06:21:33 +00001245/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001246/// that branches on undef values cannot reach any of their successors.
1247/// However, this is not a safe assumption. After we solve dataflow, this
1248/// method should be use to handle this. If this returns true, the solver
1249/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001250///
1251/// This method handles this by finding an unresolved branch and marking it one
1252/// of the edges from the block as being feasible, even though the condition
1253/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1254/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001255/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001256/// constraints on the condition of the branch, as that would impact other users
1257/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001258///
1259/// This scan also checks for values that use undefs, whose results are actually
1260/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1261/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1262/// even if X isn't defined.
1263bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001264 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1265 if (!BBExecutable.count(BB))
1266 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001267
1268 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1269 // Look for instructions which produce undef values.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001270 if (I->getType()->isVoidTy()) continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001271
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001272 if (StructType *STy = dyn_cast<StructType>(I->getType())) {
Eli Friedman79782fc2011-09-20 23:28:51 +00001273 // Only a few things that can be structs matter for undef.
1274
1275 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1276 if (CallSite CS = CallSite(I))
1277 if (Function *F = CS.getCalledFunction())
1278 if (MRVFunctionsTracked.count(F))
1279 continue;
1280
1281 // extractvalue and insertvalue don't need to be marked; they are
1282 // tracked as precisely as their operands.
1283 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1284 continue;
1285
1286 // Send the results of everything else to overdefined. We could be
1287 // more precise than this but it isn't worth bothering.
1288 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1289 LatticeVal &LV = getStructValueState(I, i);
1290 if (LV.isUndefined())
1291 markOverdefined(LV, I);
Chris Lattnerfc36a562009-11-03 23:40:48 +00001292 }
1293 continue;
1294 }
Eli Friedman054ddf792011-08-16 22:06:31 +00001295
Chris Lattner3bad2532006-12-20 06:21:33 +00001296 LatticeVal &LV = getValueState(I);
1297 if (!LV.isUndefined()) continue;
1298
Eli Friedman447f9522011-08-17 18:10:43 +00001299 // extractvalue is safe; check here because the argument is a struct.
1300 if (isa<ExtractValueInst>(I))
1301 continue;
1302
1303 // Compute the operand LatticeVals, for convenience below.
1304 // Anything taking a struct is conservatively assumed to require
1305 // overdefined markings.
1306 if (I->getOperand(0)->getType()->isStructTy()) {
1307 markOverdefined(I);
1308 return true;
1309 }
Chris Lattner2a0433b2009-11-02 05:55:40 +00001310 LatticeVal Op0LV = getValueState(I->getOperand(0));
Chris Lattner3bad2532006-12-20 06:21:33 +00001311 LatticeVal Op1LV;
Eli Friedman447f9522011-08-17 18:10:43 +00001312 if (I->getNumOperands() == 2) {
1313 if (I->getOperand(1)->getType()->isStructTy()) {
1314 markOverdefined(I);
1315 return true;
1316 }
1317
Chris Lattner3bad2532006-12-20 06:21:33 +00001318 Op1LV = getValueState(I->getOperand(1));
Eli Friedman447f9522011-08-17 18:10:43 +00001319 }
Chris Lattner3bad2532006-12-20 06:21:33 +00001320 // If this is an instructions whose result is defined even if the input is
1321 // not fully defined, propagate the information.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001322 Type *ITy = I->getType();
Chris Lattner3bad2532006-12-20 06:21:33 +00001323 switch (I->getOpcode()) {
Eli Friedman054ddf792011-08-16 22:06:31 +00001324 case Instruction::Add:
1325 case Instruction::Sub:
1326 case Instruction::Trunc:
1327 case Instruction::FPTrunc:
1328 case Instruction::BitCast:
1329 break; // Any undef -> undef
1330 case Instruction::FSub:
1331 case Instruction::FAdd:
1332 case Instruction::FMul:
1333 case Instruction::FDiv:
1334 case Instruction::FRem:
1335 // Floating-point binary operation: be conservative.
1336 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1337 markForcedConstant(I, Constant::getNullValue(ITy));
1338 else
1339 markOverdefined(I);
1340 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001341 case Instruction::ZExt:
Eli Friedman054ddf792011-08-16 22:06:31 +00001342 case Instruction::SExt:
1343 case Instruction::FPToUI:
1344 case Instruction::FPToSI:
1345 case Instruction::FPExt:
1346 case Instruction::PtrToInt:
1347 case Instruction::IntToPtr:
1348 case Instruction::SIToFP:
1349 case Instruction::UIToFP:
1350 // undef -> 0; some outputs are impossible
Chris Lattner2a0433b2009-11-02 05:55:40 +00001351 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001352 return true;
1353 case Instruction::Mul:
1354 case Instruction::And:
Eli Friedman054ddf792011-08-16 22:06:31 +00001355 // Both operands undef -> undef
1356 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1357 break;
Chris Lattner3bad2532006-12-20 06:21:33 +00001358 // undef * X -> 0. X could be zero.
1359 // undef & X -> 0. X could be zero.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001360 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001361 return true;
1362
1363 case Instruction::Or:
Eli Friedman054ddf792011-08-16 22:06:31 +00001364 // Both operands undef -> undef
1365 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1366 break;
Chris Lattner3bad2532006-12-20 06:21:33 +00001367 // undef | X -> -1. X could be -1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001368 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001369 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001370
Eli Friedman054ddf792011-08-16 22:06:31 +00001371 case Instruction::Xor:
1372 // undef ^ undef -> 0; strictly speaking, this is not strictly
1373 // necessary, but we try to be nice to people who expect this
1374 // behavior in simple cases
1375 if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
1376 markForcedConstant(I, Constant::getNullValue(ITy));
1377 return true;
1378 }
1379 // undef ^ X -> undef
1380 break;
1381
Chris Lattner3bad2532006-12-20 06:21:33 +00001382 case Instruction::SDiv:
1383 case Instruction::UDiv:
1384 case Instruction::SRem:
1385 case Instruction::URem:
1386 // X / undef -> undef. No change.
1387 // X % undef -> undef. No change.
1388 if (Op1LV.isUndefined()) break;
1389
1390 // undef / X -> 0. X could be maxint.
1391 // undef % X -> 0. X could be 1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001392 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001393 return true;
1394
1395 case Instruction::AShr:
Eli Friedman054ddf792011-08-16 22:06:31 +00001396 // X >>a undef -> undef.
1397 if (Op1LV.isUndefined()) break;
1398
1399 // undef >>a X -> all ones
1400 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001401 return true;
1402 case Instruction::LShr:
1403 case Instruction::Shl:
Eli Friedman054ddf792011-08-16 22:06:31 +00001404 // X << undef -> undef.
1405 // X >> undef -> undef.
1406 if (Op1LV.isUndefined()) break;
1407
1408 // undef << X -> 0
1409 // undef >> X -> 0
Chris Lattner2a0433b2009-11-02 05:55:40 +00001410 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001411 return true;
1412 case Instruction::Select:
Eli Friedman054ddf792011-08-16 22:06:31 +00001413 Op1LV = getValueState(I->getOperand(1));
Chris Lattner3bad2532006-12-20 06:21:33 +00001414 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1415 if (Op0LV.isUndefined()) {
1416 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1417 Op1LV = getValueState(I->getOperand(2));
1418 } else if (Op1LV.isUndefined()) {
1419 // c ? undef : undef -> undef. No change.
1420 Op1LV = getValueState(I->getOperand(2));
1421 if (Op1LV.isUndefined())
1422 break;
1423 // Otherwise, c ? undef : x -> x.
1424 } else {
1425 // Leave Op1LV as Operand(1)'s LatticeValue.
1426 }
1427
1428 if (Op1LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001429 markForcedConstant(I, Op1LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001430 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001431 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001432 return true;
Eli Friedman054ddf792011-08-16 22:06:31 +00001433 case Instruction::Load:
1434 // A load here means one of two things: a load of undef from a global,
1435 // a load from an unknown pointer. Either way, having it return undef
1436 // is okay.
1437 break;
1438 case Instruction::ICmp:
1439 // X == undef -> undef. Other comparisons get more complicated.
1440 if (cast<ICmpInst>(I)->isEquality())
1441 break;
1442 markOverdefined(I);
1443 return true;
Eli Friedman79782fc2011-09-20 23:28:51 +00001444 case Instruction::Call:
1445 case Instruction::Invoke: {
1446 // There are two reasons a call can have an undef result
1447 // 1. It could be tracked.
1448 // 2. It could be constant-foldable.
1449 // Because of the way we solve return values, tracked calls must
1450 // never be marked overdefined in ResolvedUndefsIn.
1451 if (Function *F = CallSite(I).getCalledFunction())
1452 if (TrackedRetVals.count(F))
1453 break;
1454
1455 // If the call is constant-foldable, we mark it overdefined because
1456 // we do not know what return values are valid.
1457 markOverdefined(I);
1458 return true;
1459 }
Eli Friedman054ddf792011-08-16 22:06:31 +00001460 default:
1461 // If we don't know what should happen here, conservatively mark it
Chris Lattner60301602008-05-24 03:59:33 +00001462 // overdefined.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001463 markOverdefined(I);
Chris Lattner60301602008-05-24 03:59:33 +00001464 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001465 }
1466 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001467
Chris Lattnere597f002010-04-05 22:14:48 +00001468 // Check to see if we have a branch or switch on an undefined value. If so
1469 // we force the branch to go one way or the other to make the successor
1470 // values live. It doesn't really matter which way we force it.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001471 TerminatorInst *TI = BB->getTerminator();
1472 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1473 if (!BI->isConditional()) continue;
1474 if (!getValueState(BI->getCondition()).isUndefined())
1475 continue;
Chris Lattnere597f002010-04-05 22:14:48 +00001476
1477 // If the input to SCCP is actually branch on undef, fix the undef to
1478 // false.
1479 if (isa<UndefValue>(BI->getCondition())) {
1480 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1481 markEdgeExecutable(BB, TI->getSuccessor(1));
1482 return true;
1483 }
1484
1485 // Otherwise, it is a branch on a symbolic value which is currently
1486 // considered to be undef. Handle this by forcing the input value to the
1487 // branch to false.
1488 markForcedConstant(BI->getCondition(),
1489 ConstantInt::getFalse(TI->getContext()));
1490 return true;
1491 }
1492
1493 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001494 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesen9bca5832008-05-23 01:01:31 +00001495 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001496 if (!getValueState(SI->getCondition()).isUndefined())
1497 continue;
Chris Lattnere597f002010-04-05 22:14:48 +00001498
1499 // If the input to SCCP is actually switch on undef, fix the undef to
1500 // the first constant.
1501 if (isa<UndefValue>(SI->getCondition())) {
1502 SI->setCondition(SI->getCaseValue(1));
1503 markEdgeExecutable(BB, TI->getSuccessor(1));
1504 return true;
1505 }
1506
1507 markForcedConstant(SI->getCondition(), SI->getCaseValue(1));
1508 return true;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001509 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001510 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001511
Chris Lattnerd2d86702006-10-22 05:59:17 +00001512 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001513}
1514
Chris Lattner82bec2c2004-11-15 04:44:20 +00001515
1516namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001517 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001518 //
Chris Lattner14051812004-11-15 07:15:04 +00001519 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001520 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001521 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001522 struct SCCP : public FunctionPass {
Chad Rosier00737bd2011-12-01 21:29:16 +00001523 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1524 AU.addRequired<TargetLibraryInfo>();
1525 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001526 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +00001527 SCCP() : FunctionPass(ID) {
1528 initializeSCCPPass(*PassRegistry::getPassRegistry());
1529 }
Devang Patel794fd752007-05-01 21:15:47 +00001530
Chris Lattner14051812004-11-15 07:15:04 +00001531 // runOnFunction - Run the Sparse Conditional Constant Propagation
1532 // algorithm, and return true if the function was modified.
1533 //
1534 bool runOnFunction(Function &F);
Chris Lattner14051812004-11-15 07:15:04 +00001535 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001536} // end anonymous namespace
1537
Dan Gohman844731a2008-05-13 00:00:25 +00001538char SCCP::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +00001539INITIALIZE_PASS(SCCP, "sccp",
Owen Andersonce665bd2010-10-07 22:25:06 +00001540 "Sparse Conditional Constant Propagation", false, false)
Chris Lattner82bec2c2004-11-15 04:44:20 +00001541
Chris Lattner2f096252009-11-02 02:33:50 +00001542// createSCCPPass - This is the public interface to this file.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001543FunctionPass *llvm::createSCCPPass() {
1544 return new SCCP();
1545}
1546
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001547static void DeleteInstructionInBlock(BasicBlock *BB) {
David Greene971cc7e2010-01-05 01:27:15 +00001548 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001549 ++NumDeadBlocks;
Bill Wendling4f8aaa02011-08-31 20:55:20 +00001550
1551 // Check to see if there are non-terminating instructions to delete.
1552 if (isa<TerminatorInst>(BB->begin()))
1553 return;
1554
Bill Wendlinga2684682011-09-04 09:43:36 +00001555 // Delete the instructions backwards, as it has a reduced likelihood of having
1556 // to update as many def-use and use-def chains.
1557 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1558 while (EndInst != BB->begin()) {
1559 // Delete the next to last instruction.
1560 BasicBlock::iterator I = EndInst;
1561 Instruction *Inst = --I;
Bill Wendlingc8c0fd32011-09-01 21:28:33 +00001562 if (!Inst->use_empty())
1563 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
Bill Wendlinga2684682011-09-04 09:43:36 +00001564 if (isa<LandingPadInst>(Inst)) {
1565 EndInst = Inst;
Bill Wendling4f8aaa02011-08-31 20:55:20 +00001566 continue;
Bill Wendlinga2684682011-09-04 09:43:36 +00001567 }
Bill Wendlingc8c0fd32011-09-01 21:28:33 +00001568 BB->getInstList().erase(Inst);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001569 ++NumInstRemoved;
1570 }
1571}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001572
Chris Lattner82bec2c2004-11-15 04:44:20 +00001573// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1574// and return true if the function was modified.
1575//
1576bool SCCP::runOnFunction(Function &F) {
David Greene971cc7e2010-01-05 01:27:15 +00001577 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Chad Rosier00737bd2011-12-01 21:29:16 +00001578 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1579 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1580 SCCPSolver Solver(TD, TLI);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001581
1582 // Mark the first block of the function as being executable.
1583 Solver.MarkBlockExecutable(F.begin());
1584
Chris Lattner7e529e42004-11-15 05:45:33 +00001585 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001586 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattnerfc36a562009-11-03 23:40:48 +00001587 Solver.markAnythingOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001588
Chris Lattner82bec2c2004-11-15 04:44:20 +00001589 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001590 bool ResolvedUndefs = true;
1591 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001592 Solver.Solve();
David Greene971cc7e2010-01-05 01:27:15 +00001593 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001594 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001595 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001596
Chris Lattner7e529e42004-11-15 05:45:33 +00001597 bool MadeChanges = false;
1598
1599 // If we decided that there are basic blocks that are dead in this function,
1600 // delete their contents now. Note that we cannot actually delete the blocks,
1601 // as we cannot modify the CFG of the function.
Chris Lattner57939df2007-03-04 04:50:21 +00001602
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001603 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001604 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001605 DeleteInstructionInBlock(BB);
1606 MadeChanges = true;
1607 continue;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001608 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001609
1610 // Iterate over all of the instructions in a function, replacing them with
1611 // constants if we have found them to be of constant values.
1612 //
1613 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1614 Instruction *Inst = BI++;
1615 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1616 continue;
1617
Chris Lattnerfc36a562009-11-03 23:40:48 +00001618 // TODO: Reconstruct structs from their elements.
Duncan Sands1df98592010-02-16 11:11:14 +00001619 if (Inst->getType()->isStructTy())
Chris Lattnerfc36a562009-11-03 23:40:48 +00001620 continue;
1621
Chris Lattner8db50122009-11-02 02:54:24 +00001622 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1623 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001624 continue;
1625
1626 Constant *Const = IV.isConstant()
1627 ? IV.getConstant() : UndefValue::get(Inst->getType());
David Greene971cc7e2010-01-05 01:27:15 +00001628 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001629
1630 // Replaces all of the uses of a variable with uses of the constant.
1631 Inst->replaceAllUsesWith(Const);
1632
1633 // Delete the instruction.
1634 Inst->eraseFromParent();
1635
1636 // Hey, we just changed something!
1637 MadeChanges = true;
1638 ++NumInstRemoved;
1639 }
1640 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001641
1642 return MadeChanges;
1643}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001644
1645namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001646 //===--------------------------------------------------------------------===//
1647 //
1648 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1649 /// Constant Propagation.
1650 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001651 struct IPSCCP : public ModulePass {
Chad Rosier00737bd2011-12-01 21:29:16 +00001652 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1653 AU.addRequired<TargetLibraryInfo>();
1654 }
Devang Patel19974732007-05-03 01:11:54 +00001655 static char ID;
Owen Anderson081c34b2010-10-19 17:21:58 +00001656 IPSCCP() : ModulePass(ID) {
1657 initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1658 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001659 bool runOnModule(Module &M);
1660 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001661} // end anonymous namespace
1662
Dan Gohman844731a2008-05-13 00:00:25 +00001663char IPSCCP::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +00001664INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
1665 "Interprocedural Sparse Conditional Constant Propagation",
1666 false, false)
1667INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1668INITIALIZE_PASS_END(IPSCCP, "ipsccp",
Owen Andersond13db2c2010-07-21 22:09:45 +00001669 "Interprocedural Sparse Conditional Constant Propagation",
Owen Andersonce665bd2010-10-07 22:25:06 +00001670 false, false)
Dan Gohman844731a2008-05-13 00:00:25 +00001671
Chris Lattner2f096252009-11-02 02:33:50 +00001672// createIPSCCPPass - This is the public interface to this file.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001673ModulePass *llvm::createIPSCCPPass() {
1674 return new IPSCCP();
1675}
1676
1677
Gabor Greifbd1f9932010-03-24 10:29:52 +00001678static bool AddressIsTaken(const GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001679 // Delete any dead constantexpr klingons.
1680 GV->removeDeadConstantUsers();
1681
Gabor Greif60ad7812010-03-25 23:06:16 +00001682 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifbd1f9932010-03-24 10:29:52 +00001683 UI != E; ++UI) {
1684 const User *U = *UI;
1685 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001686 if (SI->getOperand(0) == GV || SI->isVolatile())
1687 return true; // Storing addr of GV.
Gabor Greifbd1f9932010-03-24 10:29:52 +00001688 } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001689 // Make sure we are calling the function, not passing the address.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001690 ImmutableCallSite CS(cast<Instruction>(U));
Gabor Greifc9f75002010-03-24 13:21:49 +00001691 if (!CS.isCallee(UI))
Nick Lewyckyaf386132008-11-03 03:49:14 +00001692 return true;
Gabor Greifbd1f9932010-03-24 10:29:52 +00001693 } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001694 if (LI->isVolatile())
1695 return true;
Gabor Greifbd1f9932010-03-24 10:29:52 +00001696 } else if (isa<BlockAddress>(U)) {
Chris Lattnerb2710042009-11-01 06:11:53 +00001697 // blockaddress doesn't take the address of the function, it takes addr
1698 // of label.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001699 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001700 return true;
1701 }
Gabor Greifbd1f9932010-03-24 10:29:52 +00001702 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001703 return false;
1704}
1705
1706bool IPSCCP::runOnModule(Module &M) {
Chad Rosier00737bd2011-12-01 21:29:16 +00001707 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1708 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1709 SCCPSolver Solver(TD, TLI);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001710
Chris Lattner1522ce92010-08-12 22:25:23 +00001711 // AddressTakenFunctions - This set keeps track of the address-taken functions
1712 // that are in the input. As IPSCCP runs through and simplifies code,
1713 // functions that were address taken can end up losing their
1714 // address-taken-ness. Because of this, we keep track of their addresses from
1715 // the first pass so we can use them for the later simplification pass.
1716 SmallPtrSet<Function*, 32> AddressTakenFunctions;
1717
Chris Lattner59acc7d2004-12-10 08:02:06 +00001718 // Loop over all functions, marking arguments to those with their addresses
1719 // taken or that are external as overdefined.
1720 //
Chris Lattnerff3ca152009-11-02 06:34:04 +00001721 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1722 if (F->isDeclaration())
1723 continue;
1724
Chris Lattner14532d02009-11-03 03:42:51 +00001725 // If this is a strong or ODR definition of this function, then we can
1726 // propagate information about its result into callsites of it.
Chris Lattnerfc36a562009-11-03 23:40:48 +00001727 if (!F->mayBeOverridden())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001728 Solver.AddTrackedFunction(F);
Chris Lattner14532d02009-11-03 03:42:51 +00001729
1730 // If this function only has direct calls that we can see, we can track its
1731 // arguments and return value aggressively, and can assume it is not called
1732 // unless we see evidence to the contrary.
Chris Lattner1522ce92010-08-12 22:25:23 +00001733 if (F->hasLocalLinkage()) {
1734 if (AddressIsTaken(F))
1735 AddressTakenFunctions.insert(F);
1736 else {
1737 Solver.AddArgumentTrackedFunction(F);
1738 continue;
1739 }
Chris Lattner2396cc32009-11-03 19:24:51 +00001740 }
Chris Lattner14532d02009-11-03 03:42:51 +00001741
1742 // Assume the function is called.
1743 Solver.MarkBlockExecutable(F->begin());
1744
1745 // Assume nothing about the incoming arguments.
1746 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1747 AI != E; ++AI)
Chris Lattnerfc36a562009-11-03 23:40:48 +00001748 Solver.markAnythingOverdefined(AI);
Chris Lattnerff3ca152009-11-02 06:34:04 +00001749 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001750
Chris Lattnerdd336d12004-12-11 05:15:59 +00001751 // Loop over global variables. We inform the solver about any internal global
1752 // variables that do not have their 'addresses taken'. If they don't have
1753 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001754 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1755 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001756 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001757 Solver.TrackValueOfGlobalVariable(G);
1758
Chris Lattner59acc7d2004-12-10 08:02:06 +00001759 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001760 bool ResolvedUndefs = true;
1761 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001762 Solver.Solve();
1763
David Greene971cc7e2010-01-05 01:27:15 +00001764 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001765 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001766 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001767 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001768 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001769
1770 bool MadeChanges = false;
1771
1772 // Iterate over all of the instructions in the module, replacing them with
1773 // constants if we have found them to be of constant values.
1774 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001775 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner1c1f1122007-02-02 21:15:06 +00001776
Chris Lattner59acc7d2004-12-10 08:02:06 +00001777 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner89112b62009-11-02 03:25:55 +00001778 if (Solver.isBlockExecutable(F->begin())) {
1779 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1780 AI != E; ++AI) {
Duncan Sands1df98592010-02-16 11:11:14 +00001781 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
Chris Lattner89112b62009-11-02 03:25:55 +00001782
Chris Lattnerfc36a562009-11-03 23:40:48 +00001783 // TODO: Could use getStructLatticeValueFor to find out if the entire
1784 // result is a constant and replace it entirely if so.
1785
Chris Lattner89112b62009-11-02 03:25:55 +00001786 LatticeVal IV = Solver.getLatticeValueFor(AI);
1787 if (IV.isOverdefined()) continue;
1788
1789 Constant *CST = IV.isConstant() ?
1790 IV.getConstant() : UndefValue::get(AI->getType());
David Greene971cc7e2010-01-05 01:27:15 +00001791 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Chris Lattner89112b62009-11-02 03:25:55 +00001792
1793 // Replaces all of the uses of a variable with uses of the
1794 // constant.
1795 AI->replaceAllUsesWith(CST);
1796 ++IPNumArgsElimed;
1797 }
Chris Lattner8db50122009-11-02 02:54:24 +00001798 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001799
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001800 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001801 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001802 DeleteInstructionInBlock(BB);
1803 MadeChanges = true;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001804
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001805 TerminatorInst *TI = BB->getTerminator();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001806 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1807 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001808 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001809 TI->getSuccessor(i)->removePredecessor(BB);
1810 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001811 if (!TI->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001812 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001813 TI->eraseFromParent();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001814
Chris Lattner864737b2004-12-11 05:32:19 +00001815 if (&*BB != &F->front())
1816 BlocksToErase.push_back(BB);
1817 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001818 new UnreachableInst(M.getContext(), BB);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001819 continue;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001820 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001821
1822 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1823 Instruction *Inst = BI++;
Duncan Sands1df98592010-02-16 11:11:14 +00001824 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001825 continue;
1826
Chris Lattnerfc36a562009-11-03 23:40:48 +00001827 // TODO: Could use getStructLatticeValueFor to find out if the entire
1828 // result is a constant and replace it entirely if so.
1829
Chris Lattner8db50122009-11-02 02:54:24 +00001830 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1831 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001832 continue;
1833
1834 Constant *Const = IV.isConstant()
1835 ? IV.getConstant() : UndefValue::get(Inst->getType());
David Greene971cc7e2010-01-05 01:27:15 +00001836 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001837
1838 // Replaces all of the uses of a variable with uses of the
1839 // constant.
1840 Inst->replaceAllUsesWith(Const);
1841
1842 // Delete the instruction.
1843 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1844 Inst->eraseFromParent();
1845
1846 // Hey, we just changed something!
1847 MadeChanges = true;
1848 ++IPNumInstRemoved;
1849 }
1850 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001851
1852 // Now that all instructions in the function are constant folded, erase dead
1853 // blocks, because we can now use ConstantFoldTerminator to get rid of
1854 // in-edges.
1855 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1856 // If there are any PHI nodes in this successor, drop entries for BB now.
1857 BasicBlock *DeadBB = BlocksToErase[i];
Dan Gohman6a239212009-11-20 20:19:14 +00001858 for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1859 UI != UE; ) {
Dan Gohman8f3817f2009-11-23 16:13:39 +00001860 // Grab the user and then increment the iterator early, as the user
1861 // will be deleted. Step past all adjacent uses from the same user.
1862 Instruction *I = dyn_cast<Instruction>(*UI);
1863 do { ++UI; } while (UI != UE && *UI == I);
1864
Dan Gohman6a239212009-11-20 20:19:14 +00001865 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohman6a239212009-11-20 20:19:14 +00001866 if (!I) continue;
1867
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001868 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001869 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001870 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001871 // if this is a branch or switch on undef. Fold it manually as a
1872 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001873#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001874 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1875 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1876 "Branch should be foldable!");
1877 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1878 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1879 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001880 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerddaaa372006-10-23 18:57:02 +00001881 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001882#endif
Chris Lattnerddaaa372006-10-23 18:57:02 +00001883
1884 // Make this an uncond branch to the first successor.
1885 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001886 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001887
1888 // Remove entries in successor phi nodes to remove edges.
1889 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1890 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1891
1892 // Remove the old terminator.
1893 TI->eraseFromParent();
1894 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001895 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001896
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001897 // Finally, delete the basic block.
1898 F->getBasicBlockList().erase(DeadBB);
1899 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001900 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001901 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001902
1903 // If we inferred constant or undef return values for a function, we replaced
1904 // all call uses with the inferred value. This means we don't need to bother
1905 // actually returning anything from the function. Replace all return
1906 // instructions with return undef.
Chris Lattnerd38cdb02010-02-27 00:07:42 +00001907 //
1908 // Do this in two stages: first identify the functions we should process, then
1909 // actually zap their returns. This is important because we can only do this
Chris Lattner9fcd72b2010-02-27 07:50:40 +00001910 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd38cdb02010-02-27 00:07:42 +00001911 // last use of a function, the order of processing functions would affect
Chris Lattner9fcd72b2010-02-27 07:50:40 +00001912 // whether other functions are optimizable.
Chris Lattnerd38cdb02010-02-27 00:07:42 +00001913 SmallVector<ReturnInst*, 8> ReturnsToZap;
1914
Devang Patel9af014f2008-03-11 17:32:05 +00001915 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001916 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001917 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner14532d02009-11-03 03:42:51 +00001918 E = RV.end(); I != E; ++I) {
1919 Function *F = I->first;
1920 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1921 continue;
1922
1923 // We can only do this if we know that nothing else can call the function.
Chris Lattner1522ce92010-08-12 22:25:23 +00001924 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
Chris Lattner14532d02009-11-03 03:42:51 +00001925 continue;
1926
1927 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1928 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1929 if (!isa<UndefValue>(RI->getOperand(0)))
Chris Lattnerd38cdb02010-02-27 00:07:42 +00001930 ReturnsToZap.push_back(RI);
1931 }
1932
1933 // Zap all returns which we've identified as zap to change.
1934 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1935 Function *F = ReturnsToZap[i]->getParent()->getParent();
1936 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattner14532d02009-11-03 03:42:51 +00001937 }
1938
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001939 // If we inferred constant or undef values for globals variables, we can delete
Chris Lattnerdd336d12004-12-11 05:15:59 +00001940 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001941 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1942 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001943 E = TG.end(); I != E; ++I) {
1944 GlobalVariable *GV = I->first;
1945 assert(!I->second.isOverdefined() &&
1946 "Overdefined values should have been taken out of the map!");
David Greene971cc7e2010-01-05 01:27:15 +00001947 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattnerdd336d12004-12-11 05:15:59 +00001948 while (!GV->use_empty()) {
1949 StoreInst *SI = cast<StoreInst>(GV->use_back());
1950 SI->eraseFromParent();
1951 }
1952 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001953 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001954 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001955
Chris Lattner59acc7d2004-12-10 08:02:06 +00001956 return MadeChanges;
1957}