blob: 026c9f568cc5a0d6d40334b0f0f1a0c210ffaf3d [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements sparse conditional constant propagation and merging:
11//
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
16// * Proves conditional branches to be unconditional
17//
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018//===----------------------------------------------------------------------===//
19
20#define DEBUG_TYPE "sccp"
21#include "llvm/Transforms/Scalar.h"
22#include "llvm/Transforms/IPO.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Instructions.h"
26#include "llvm/Pass.h"
27#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohman856193b2008-06-20 01:15:44 +000029#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0148bb22009-11-02 06:06:14 +000031#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032#include "llvm/Support/CallSite.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000034#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include "llvm/Support/InstVisitor.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000036#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/ADT/DenseMap.h"
Chris Lattnerd3123a72008-08-23 23:36:38 +000038#include "llvm/ADT/DenseSet.h"
Chris Lattner1eb405b2009-11-02 02:20:32 +000039#include "llvm/ADT/PointerIntPair.h"
Chris Lattnera5ffa7c2009-11-02 06:11:23 +000040#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/STLExtras.h"
44#include <algorithm>
Dan Gohman249ddbf2008-03-21 23:51:57 +000045#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046using namespace llvm;
47
48STATISTIC(NumInstRemoved, "Number of instructions removed");
49STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
50
Nick Lewyckybbdfc9c2008-03-08 07:48:41 +000051STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
53STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
54
55namespace {
56/// 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 Lattnerfa2d1ba2009-09-02 06:11:42 +000059class LatticeVal {
Chris Lattner1eb405b2009-11-02 02:20:32 +000060 enum LatticeValueTy {
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattner1eb405b2009-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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081
Chris Lattner1eb405b2009-11-02 02:20:32 +000082 LatticeValueTy getLatticeValue() const {
83 return Val.getInt();
84 }
85
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086public:
Chris Lattnerb52f7002009-11-02 03:03:42 +000087 LatticeVal() : Val(0, undefined) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088
Chris Lattnerb52f7002009-11-02 03:03:42 +000089 bool isUndefined() const { return getLatticeValue() == undefined; }
90 bool isConstant() const {
Chris Lattner1eb405b2009-11-02 02:20:32 +000091 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
92 }
Chris Lattnerb52f7002009-11-02 03:03:42 +000093 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Chris Lattner1eb405b2009-11-02 02:20:32 +000094
Chris Lattnerb52f7002009-11-02 03:03:42 +000095 Constant *getConstant() const {
Chris Lattner1eb405b2009-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 Lattnerb52f7002009-11-02 03:03:42 +0000101 bool markOverdefined() {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000102 if (isOverdefined())
103 return false;
104
105 Val.setInt(overdefined);
106 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 }
108
Chris Lattner1eb405b2009-11-02 02:20:32 +0000109 /// markConstant - Return true if this is a change in status.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000110 bool markConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000111 if (isConstant()) {
112 assert(getConstant() == V && "Marking constant with different value");
113 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114 }
Chris Lattner1eb405b2009-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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 }
133
Chris Lattner220571c2009-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 Lattnerb52f7002009-11-02 03:03:42 +0000142 void markForcedConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000143 assert(isUndefined() && "Can't force a defined value!");
144 Val.setInt(forcedconstant);
145 Val.setPointer(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 }
147};
Chris Lattner14513dc2009-11-02 02:47:51 +0000148} // end anonymous namespace.
149
150
151namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153//===----------------------------------------------------------------------===//
154//
155/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
156/// Constant Propagation.
157///
158class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner0148bb22009-11-02 06:06:14 +0000159 const TargetData *TD;
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000160 SmallPtrSet<BasicBlock*, 8> BBExecutable;// The BBs that are executable.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000161 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162
163 /// GlobalValue - If we are tracking any values for the contents of a global
164 /// variable, we keep a mapping from the constant accessor to the element of
165 /// the global, to the currently known value. If the value becomes
166 /// overdefined, it's entry is simply removed from this map.
167 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
168
Devang Pateladd320d2008-03-11 05:46:42 +0000169 /// TrackedRetVals - If we are tracking arguments into and the return
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170 /// value out of a function, it will have an entry in this map, indicating
171 /// what the known return value for the function is.
Devang Pateladd320d2008-03-11 05:46:42 +0000172 DenseMap<Function*, LatticeVal> TrackedRetVals;
173
174 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
175 /// that return multiple values.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000176 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177
Chris Lattnerb52f7002009-11-02 03:03:42 +0000178 /// The reason for two worklists is that overdefined is the lowest state
179 /// on the lattice, and moving things to overdefined as fast as possible
180 /// makes SCCP converge much faster.
181 ///
182 /// By having a separate worklist, we accomplish this because everything
183 /// possibly overdefined will become overdefined at the soonest possible
184 /// point.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000185 SmallVector<Value*, 64> OverdefinedInstWorkList;
186 SmallVector<Value*, 64> InstWorkList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187
188
Chris Lattnerd3123a72008-08-23 23:36:38 +0000189 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190
191 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
192 /// overdefined, despite the fact that the PHI node is overdefined.
193 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
194
195 /// KnownFeasibleEdges - Entries in this set are edges which have already had
196 /// PHI nodes retriggered.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000197 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
198 DenseSet<Edge> KnownFeasibleEdges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199public:
Chris Lattner0148bb22009-11-02 06:06:14 +0000200 SCCPSolver(const TargetData *td) : TD(td) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201
202 /// MarkBlockExecutable - This method can be used by clients to mark all of
203 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000204 ///
205 /// This returns true if the block was not considered live before.
206 bool MarkBlockExecutable(BasicBlock *BB) {
207 if (!BBExecutable.insert(BB)) return false;
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000208 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000210 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 }
212
213 /// TrackValueOfGlobalVariable - Clients can use this method to
214 /// inform the SCCPSolver that it should track loads and stores to the
215 /// specified global variable if it can. This is only legal to call if
216 /// performing Interprocedural SCCP.
217 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
218 const Type *ElTy = GV->getType()->getElementType();
219 if (ElTy->isFirstClassType()) {
220 LatticeVal &IV = TrackedGlobals[GV];
221 if (!isa<UndefValue>(GV->getInitializer()))
222 IV.markConstant(GV->getInitializer());
223 }
224 }
225
226 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
227 /// and out of the specified function (which cannot have its address taken),
228 /// this method must be called.
229 void AddTrackedFunction(Function *F) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000230 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 // Add an entry, F -> undef.
Devang Pateladd320d2008-03-11 05:46:42 +0000232 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
233 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnercd73be02008-04-23 05:38:20 +0000234 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
235 LatticeVal()));
236 } else
237 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 }
239
240 /// Solve - Solve for constants and executable blocks.
241 ///
242 void Solve();
243
244 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
245 /// that branches on undef values cannot reach any of their successors.
246 /// However, this is not a safe assumption. After we solve dataflow, this
247 /// method should be use to handle this. If this returns true, the solver
248 /// should be rerun.
249 bool ResolvedUndefsIn(Function &F);
250
Chris Lattner317e6b62008-08-23 23:39:31 +0000251 bool isBlockExecutable(BasicBlock *BB) const {
252 return BBExecutable.count(BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 }
254
Chris Lattnerc9edab82009-11-02 02:54:24 +0000255 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000256 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattnerc9edab82009-11-02 02:54:24 +0000257 assert(I != ValueState.end() && "V is not in valuemap!");
258 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 }
260
Devang Pateladd320d2008-03-11 05:46:42 +0000261 /// getTrackedRetVals - Get the inferred return value map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 ///
Devang Pateladd320d2008-03-11 05:46:42 +0000263 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
264 return TrackedRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 }
266
267 /// getTrackedGlobals - Get and return the set of inferred initializers for
268 /// global variables.
269 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
270 return TrackedGlobals;
271 }
272
Chris Lattner220571c2009-11-02 03:21:36 +0000273 void markOverdefined(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 markOverdefined(ValueState[V], V);
275 }
276
277private:
278 // markConstant - Make a value be marked as "constant". If the value
279 // is not already a constant, add it to the instruction work list so that
280 // the users of the instruction are updated later.
281 //
Chris Lattnerb52f7002009-11-02 03:03:42 +0000282 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
283 if (!IV.markConstant(C)) return;
284 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
285 InstWorkList.push_back(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 }
287
Chris Lattnerb52f7002009-11-02 03:03:42 +0000288 void markConstant(Value *V, Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 markConstant(ValueState[V], V, C);
290 }
291
Chris Lattner6367c3f2009-11-02 05:55:40 +0000292 void markForcedConstant(Value *V, Constant *C) {
293 ValueState[V].markForcedConstant(C);
294 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
295 InstWorkList.push_back(V);
296 }
297
298
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299 // markOverdefined - Make a value be marked as "overdefined". If the
300 // value is not already overdefined, add it to the overdefined instruction
301 // work list so that the users of the instruction are updated later.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000302 void markOverdefined(LatticeVal &IV, Value *V) {
303 if (!IV.markOverdefined()) return;
304
305 DEBUG(errs() << "markOverdefined: ";
306 if (Function *F = dyn_cast<Function>(V))
307 errs() << "Function '" << F->getName() << "'\n";
308 else
309 errs() << *V << '\n');
310 // Only instructions go on the work list
311 OverdefinedInstWorkList.push_back(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 }
313
Chris Lattner6367c3f2009-11-02 05:55:40 +0000314 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 if (IV.isOverdefined() || MergeWithV.isUndefined())
316 return; // Noop.
317 if (MergeWithV.isOverdefined())
318 markOverdefined(IV, V);
319 else if (IV.isUndefined())
320 markConstant(IV, V, MergeWithV.getConstant());
321 else if (IV.getConstant() != MergeWithV.getConstant())
322 markOverdefined(IV, V);
323 }
324
Chris Lattner6367c3f2009-11-02 05:55:40 +0000325 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Chris Lattner220571c2009-11-02 03:21:36 +0000326 mergeInValue(ValueState[V], V, MergeWithV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327 }
328
329
Chris Lattner6367c3f2009-11-02 05:55:40 +0000330 /// getValueState - Return the LatticeVal object that corresponds to the
331 /// value. This function handles the case when the value hasn't been seen yet
332 /// by properly seeding constants etc.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000333 LatticeVal &getValueState(Value *V) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000334 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335 if (I != ValueState.end()) return I->second; // Common case, in the map
336
Chris Lattner220571c2009-11-02 03:21:36 +0000337 LatticeVal &LV = ValueState[V];
338
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner220571c2009-11-02 03:21:36 +0000340 // Undef values remain undefined.
341 if (!isa<UndefValue>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 LV.markConstant(C); // Constants are constant
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343 }
Chris Lattner220571c2009-11-02 03:21:36 +0000344
Chris Lattnerc8798002009-11-02 02:33:50 +0000345 // All others are underdefined by default.
Chris Lattner220571c2009-11-02 03:21:36 +0000346 return LV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 }
348
Chris Lattner6367c3f2009-11-02 05:55:40 +0000349 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
350 /// work list if it is not already executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000351 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
352 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
353 return; // This edge is already known to be executable!
354
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000355 if (!MarkBlockExecutable(Dest)) {
356 // If the destination is already executable, we just made an *edge*
357 // feasible that wasn't before. Revisit the PHI nodes in the block
358 // because they have potentially new operands.
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000359 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
360 << " -> " << Dest->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000362 PHINode *PN;
363 for (BasicBlock::iterator I = Dest->begin();
364 (PN = dyn_cast<PHINode>(I)); ++I)
365 visitPHINode(*PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 }
367 }
368
369 // getFeasibleSuccessors - Return a vector of booleans to indicate which
370 // successors are reachable from a given terminator instruction.
371 //
372 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
373
374 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000375 // block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376 //
377 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
378
379 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnerc8798002009-11-02 02:33:50 +0000380 // instruction that was just changed state somehow. Based on this
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 // information, we need to update the specified user of this instruction.
382 //
383 void OperandChangedState(User *U) {
384 // Only instructions use other variable values!
385 Instruction &I = cast<Instruction>(*U);
386 if (BBExecutable.count(I.getParent())) // Inst is executable?
387 visit(I);
388 }
389
390private:
391 friend class InstVisitor<SCCPSolver>;
392
Chris Lattnerc8798002009-11-02 02:33:50 +0000393 // visit implementations - Something changed in this instruction. Either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394 // operand made a transition, or the instruction is newly executable. Change
395 // the value type of I to reflect these changes if appropriate.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 void visitPHINode(PHINode &I);
397
398 // Terminators
399 void visitReturnInst(ReturnInst &I);
400 void visitTerminatorInst(TerminatorInst &TI);
401
402 void visitCastInst(CastInst &I);
403 void visitSelectInst(SelectInst &I);
404 void visitBinaryOperator(Instruction &I);
405 void visitCmpInst(CmpInst &I);
406 void visitExtractElementInst(ExtractElementInst &I);
407 void visitInsertElementInst(InsertElementInst &I);
408 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman856193b2008-06-20 01:15:44 +0000409 void visitExtractValueInst(ExtractValueInst &EVI);
410 void visitInsertValueInst(InsertValueInst &IVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411
Chris Lattnerc8798002009-11-02 02:33:50 +0000412 // Instructions that cannot be folded away.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000413 void visitStoreInst (StoreInst &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 void visitLoadInst (LoadInst &I);
415 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez93946082009-10-24 04:23:03 +0000416 void visitCallInst (CallInst &I) {
417 if (isFreeCall(&I))
418 return;
Chris Lattner6ad04a02009-09-27 21:35:11 +0000419 visitCallSite(CallSite::get(&I));
Victor Hernandez48c3c542009-09-18 22:35:49 +0000420 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421 void visitInvokeInst (InvokeInst &II) {
422 visitCallSite(CallSite::get(&II));
423 visitTerminatorInst(II);
424 }
425 void visitCallSite (CallSite CS);
426 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
427 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandezb1687302009-10-23 21:09:37 +0000428 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000429 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
430 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431
432 void visitInstruction(Instruction &I) {
Chris Lattnerc8798002009-11-02 02:33:50 +0000433 // If a new instruction is added to LLVM that we don't handle.
Chris Lattner8a6411c2009-08-23 04:37:46 +0000434 errs() << "SCCP: Don't know how to handle: " << I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435 markOverdefined(&I); // Just in case
436 }
437};
438
Duncan Sands40f67972007-07-20 08:56:21 +0000439} // end anonymous namespace
440
441
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442// getFeasibleSuccessors - Return a vector of booleans to indicate which
443// successors are reachable from a given terminator instruction.
444//
445void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
446 SmallVector<bool, 16> &Succs) {
447 Succs.resize(TI.getNumSuccessors());
448 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
449 if (BI->isUnconditional()) {
450 Succs[0] = true;
Chris Lattneradaf7332009-11-02 02:30:06 +0000451 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 }
Chris Lattneradaf7332009-11-02 02:30:06 +0000453
Chris Lattner6367c3f2009-11-02 05:55:40 +0000454 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000455 ConstantInt *CI = BCValue.getConstantInt();
456 if (CI == 0) {
Chris Lattneradaf7332009-11-02 02:30:06 +0000457 // Overdefined condition variables, and branches on unfoldable constant
458 // conditions, mean the branch could go either way.
Chris Lattner220571c2009-11-02 03:21:36 +0000459 if (!BCValue.isUndefined())
460 Succs[0] = Succs[1] = true;
Chris Lattneradaf7332009-11-02 02:30:06 +0000461 return;
462 }
463
464 // Constant condition variables mean the branch can only go a single way.
Chris Lattner220571c2009-11-02 03:21:36 +0000465 Succs[CI->isZero()] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000466 return;
467 }
468
Chris Lattner220571c2009-11-02 03:21:36 +0000469 if (isa<InvokeInst>(TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000470 // Invoke instructions successors are always executable.
471 Succs[0] = Succs[1] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000472 return;
473 }
474
475 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000476 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000477 ConstantInt *CI = SCValue.getConstantInt();
478
479 if (CI == 0) { // Overdefined or undefined condition?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 // All destinations are executable!
Chris Lattner220571c2009-11-02 03:21:36 +0000481 if (!SCValue.isUndefined())
482 Succs.assign(TI.getNumSuccessors(), true);
483 return;
484 }
485
486 Succs[SI->findCaseValue(CI)] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000487 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000489
490 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
491 if (isa<IndirectBrInst>(&TI)) {
492 // Just mark all destinations executable!
493 Succs.assign(TI.getNumSuccessors(), true);
494 return;
495 }
496
497#ifndef NDEBUG
498 errs() << "Unknown terminator instruction: " << TI << '\n';
499#endif
500 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501}
502
503
504// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000505// block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506//
507bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
508 assert(BBExecutable.count(To) && "Dest should always be alive!");
509
510 // Make sure the source basic block is executable!!
511 if (!BBExecutable.count(From)) return false;
512
Chris Lattnerc8798002009-11-02 02:33:50 +0000513 // Check to make sure this edge itself is actually feasible now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 TerminatorInst *TI = From->getTerminator();
515 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
516 if (BI->isUnconditional())
517 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000518
Chris Lattner6367c3f2009-11-02 05:55:40 +0000519 LatticeVal BCValue = getValueState(BI->getCondition());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520
Chris Lattneradaf7332009-11-02 02:30:06 +0000521 // Overdefined condition variables mean the branch could go either way,
522 // undef conditions mean that neither edge is feasible yet.
Chris Lattner220571c2009-11-02 03:21:36 +0000523 ConstantInt *CI = BCValue.getConstantInt();
524 if (CI == 0)
525 return !BCValue.isUndefined();
Chris Lattneradaf7332009-11-02 02:30:06 +0000526
Chris Lattneradaf7332009-11-02 02:30:06 +0000527 // Constant condition variables mean the branch can only go a single way.
Chris Lattner220571c2009-11-02 03:21:36 +0000528 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000529 }
530
531 // Invoke instructions successors are always executable.
532 if (isa<InvokeInst>(TI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000533 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000534
535 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000536 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000537 ConstantInt *CI = SCValue.getConstantInt();
538
539 if (CI == 0)
540 return !SCValue.isUndefined();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541
Chris Lattner220571c2009-11-02 03:21:36 +0000542 // Make sure to skip the "default value" which isn't a value
543 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
544 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
545 return SI->getSuccessor(i) == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546
Chris Lattner220571c2009-11-02 03:21:36 +0000547 // If the constant value is not equal to any of the branches, we must
548 // execute default branch.
549 return SI->getDefaultDest() == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000550 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000551
552 // Just mark all destinations executable!
553 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
554 if (isa<IndirectBrInst>(&TI))
555 return true;
556
557#ifndef NDEBUG
558 errs() << "Unknown terminator instruction: " << *TI << '\n';
559#endif
560 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561}
562
Chris Lattnerc8798002009-11-02 02:33:50 +0000563// visit Implementations - Something changed in this instruction, either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564// operand made a transition, or the instruction is newly executable. Change
565// the value type of I to reflect these changes if appropriate. This method
566// makes sure to do the following actions:
567//
568// 1. If a phi node merges two constants in, and has conflicting value coming
569// from different branches, or if the PHI node merges in an overdefined
570// value, then the PHI node becomes overdefined.
571// 2. If a phi node merges only constants in, and they all agree on value, the
572// PHI node becomes a constant value equal to that.
573// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
574// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
575// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
576// 6. If a conditional branch has a value that is constant, make the selected
577// destination executable
578// 7. If a conditional branch has a value that is overdefined, make all
579// successors executable.
580//
581void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000582 if (getValueState(&PN).isOverdefined()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 // There may be instructions using this PHI node that are not overdefined
584 // themselves. If so, make sure that they know that the PHI node operand
585 // changed.
586 std::multimap<PHINode*, Instruction*>::iterator I, E;
587 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
Chris Lattner6367c3f2009-11-02 05:55:40 +0000588 if (I == E)
589 return;
590
591 SmallVector<Instruction*, 16> Users;
592 for (; I != E; ++I)
593 Users.push_back(I->second);
594 while (!Users.empty())
595 visit(Users.pop_back_val());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 return; // Quick exit
597 }
598
599 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
600 // and slow us down a lot. Just mark them overdefined.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000601 if (PN.getNumIncomingValues() > 64)
Chris Lattner6367c3f2009-11-02 05:55:40 +0000602 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603
604 // Look at all of the executable operands of the PHI node. If any of them
605 // are overdefined, the PHI becomes overdefined as well. If they are all
606 // constant, and they agree with each other, the PHI becomes the identical
607 // constant. If they are constant and don't agree, the PHI is overdefined.
608 // If there are no executable operands, the PHI remains undefined.
609 //
610 Constant *OperandVal = 0;
611 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000612 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
614
Chris Lattnerb52f7002009-11-02 03:03:42 +0000615 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
616 continue;
617
618 if (IV.isOverdefined()) // PHI node becomes overdefined!
619 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620
Chris Lattnerb52f7002009-11-02 03:03:42 +0000621 if (OperandVal == 0) { // Grab the first value.
622 OperandVal = IV.getConstant();
623 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 }
Chris Lattnerb52f7002009-11-02 03:03:42 +0000625
626 // There is already a reachable operand. If we conflict with it,
627 // then the PHI node becomes overdefined. If we agree with it, we
628 // can continue on.
629
630 // Check to see if there are two different constants merging, if so, the PHI
631 // node is overdefined.
632 if (IV.getConstant() != OperandVal)
633 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 }
635
636 // If we exited the loop, this means that the PHI node only has constant
637 // arguments that agree with each other(and OperandVal is the constant) or
638 // OperandVal is null because there are no defined incoming arguments. If
639 // this is the case, the PHI remains undefined.
640 //
641 if (OperandVal)
Chris Lattnerd3123a72008-08-23 23:36:38 +0000642 markConstant(&PN, OperandVal); // Acquire operand value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643}
644
645void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000646 if (I.getNumOperands() == 0) return; // ret void
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000647
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 Function *F = I.getParent()->getParent();
Devang Pateladd320d2008-03-11 05:46:42 +0000649 // If we are tracking the return value of this function, merge it in.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000650 if (!F->hasLocalLinkage())
Devang Pateladd320d2008-03-11 05:46:42 +0000651 return;
652
Chris Lattner6367c3f2009-11-02 05:55:40 +0000653 if (!TrackedRetVals.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000654 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Pateladd320d2008-03-11 05:46:42 +0000655 TrackedRetVals.find(F);
656 if (TFRVI != TrackedRetVals.end() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000657 !TFRVI->second.isOverdefined()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000658 mergeInValue(TFRVI->second, F, getValueState(I.getOperand(0)));
Devang Pateladd320d2008-03-11 05:46:42 +0000659 return;
660 }
661 }
662
Chris Lattnercd73be02008-04-23 05:38:20 +0000663 // Handle functions that return multiple values.
Chris Lattnerc2a4e202009-11-02 06:17:06 +0000664 if (!TrackedMultipleRetVals.empty() &&
665 isa<StructType>(I.getOperand(0)->getType())) {
Dan Gohman856193b2008-06-20 01:15:44 +0000666 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
667 i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000668 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000669 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
670 if (It == TrackedMultipleRetVals.end()) break;
Owen Anderson175b6542009-07-22 00:24:57 +0000671 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewycky6ad29e02009-06-06 23:13:08 +0000672 mergeInValue(It->second, F, getValueState(Val));
Dan Gohman856193b2008-06-20 01:15:44 +0000673 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000674 }
675}
676
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
678 SmallVector<bool, 16> SuccFeasible;
679 getFeasibleSuccessors(TI, SuccFeasible);
680
681 BasicBlock *BB = TI.getParent();
682
Chris Lattnerc8798002009-11-02 02:33:50 +0000683 // Mark all feasible successors executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
685 if (SuccFeasible[i])
686 markEdgeExecutable(BB, TI.getSuccessor(i));
687}
688
689void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000690 LatticeVal OpSt = getValueState(I.getOperand(0));
691 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692 markOverdefined(&I);
Chris Lattner6367c3f2009-11-02 05:55:40 +0000693 else if (OpSt.isConstant()) // Propagate constant value
Owen Anderson02b48c32009-07-29 18:55:55 +0000694 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattner6367c3f2009-11-02 05:55:40 +0000695 OpSt.getConstant(), I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000696}
697
Dan Gohman856193b2008-06-20 01:15:44 +0000698void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000699 Value *Aggr = EVI.getAggregateOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000700
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000701 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohman856193b2008-06-20 01:15:44 +0000702 if (isa<UndefValue>(Aggr))
703 return;
704
705 // Currently only handle single-index extractvalues.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000706 if (EVI.getNumIndices() != 1)
707 return markOverdefined(&EVI);
Dan Gohman856193b2008-06-20 01:15:44 +0000708
709 Function *F = 0;
710 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
711 F = CI->getCalledFunction();
712 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
713 F = II->getCalledFunction();
714
715 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
716 // result back!
Chris Lattnerb52f7002009-11-02 03:03:42 +0000717 if (F == 0 || TrackedMultipleRetVals.empty())
718 return markOverdefined(&EVI);
Dan Gohman856193b2008-06-20 01:15:44 +0000719
Chris Lattnerd3123a72008-08-23 23:36:38 +0000720 // See if we are tracking the result of the callee. If not tracking this
721 // function (for example, it is a declaration) just move to overdefined.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000722 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin())))
723 return markOverdefined(&EVI);
Dan Gohman856193b2008-06-20 01:15:44 +0000724
725 // Otherwise, the value will be merged in here as a result of CallSite
726 // handling.
727}
728
729void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000730 Value *Aggr = IVI.getAggregateOperand();
731 Value *Val = IVI.getInsertedValueOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000732
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000733 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohman78b2c392008-06-20 16:39:44 +0000734 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohman856193b2008-06-20 01:15:44 +0000735 return;
736
737 // Currently only handle single-index insertvalues.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000738 if (IVI.getNumIndices() != 1)
739 return markOverdefined(&IVI);
Dan Gohman78b2c392008-06-20 16:39:44 +0000740
741 // Currently only handle insertvalue instructions that are in a single-use
742 // chain that builds up a return value.
743 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
Chris Lattnerb52f7002009-11-02 03:03:42 +0000744 if (!TmpIVI->hasOneUse())
745 return markOverdefined(&IVI);
746
Dan Gohman78b2c392008-06-20 16:39:44 +0000747 const Value *V = *TmpIVI->use_begin();
748 if (isa<ReturnInst>(V))
749 break;
750 TmpIVI = dyn_cast<InsertValueInst>(V);
Chris Lattnerb52f7002009-11-02 03:03:42 +0000751 if (!TmpIVI)
752 return markOverdefined(&IVI);
Dan Gohman78b2c392008-06-20 16:39:44 +0000753 }
Dan Gohman856193b2008-06-20 01:15:44 +0000754
755 // See if we are tracking the result of the callee.
756 Function *F = IVI.getParent()->getParent();
Chris Lattnerd3123a72008-08-23 23:36:38 +0000757 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000758 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
759
760 // Merge in the inserted member value.
761 if (It != TrackedMultipleRetVals.end())
762 mergeInValue(It->second, F, getValueState(Val));
763
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000764 // Mark the aggregate result of the IVI overdefined; any tracking that we do
765 // will be done on the individual member values.
Dan Gohman856193b2008-06-20 01:15:44 +0000766 markOverdefined(&IVI);
767}
768
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000770 LatticeVal CondValue = getValueState(I.getCondition());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771 if (CondValue.isUndefined())
772 return;
Chris Lattner220571c2009-11-02 03:21:36 +0000773
774 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000775 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
776 mergeInValue(&I, getValueState(OpVal));
Chris Lattner220571c2009-11-02 03:21:36 +0000777 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000778 }
779
780 // Otherwise, the condition is overdefined or a constant we can't evaluate.
781 // See if we can produce something better than overdefined based on the T/F
782 // value.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000783 LatticeVal TVal = getValueState(I.getTrueValue());
784 LatticeVal FVal = getValueState(I.getFalseValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785
786 // select ?, C, C -> C.
787 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattnerb52f7002009-11-02 03:03:42 +0000788 TVal.getConstant() == FVal.getConstant())
789 return markConstant(&I, FVal.getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000790
Chris Lattner6367c3f2009-11-02 05:55:40 +0000791 if (TVal.isUndefined()) // select ?, undef, X -> X.
792 return mergeInValue(&I, FVal);
793 if (FVal.isUndefined()) // select ?, X, undef -> X.
794 return mergeInValue(&I, TVal);
795 markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000796}
797
Chris Lattner6367c3f2009-11-02 05:55:40 +0000798// Handle Binary Operators.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000800 LatticeVal V1State = getValueState(I.getOperand(0));
801 LatticeVal V2State = getValueState(I.getOperand(1));
802
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803 LatticeVal &IV = ValueState[&I];
804 if (IV.isOverdefined()) return;
805
Chris Lattner6367c3f2009-11-02 05:55:40 +0000806 if (V1State.isConstant() && V2State.isConstant())
807 return markConstant(IV, &I,
808 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
809 V2State.getConstant()));
810
811 // If something is undef, wait for it to resolve.
812 if (!V1State.isOverdefined() && !V2State.isOverdefined())
813 return;
814
815 // Otherwise, one of our operands is overdefined. Try to produce something
816 // better than overdefined with some tricks.
817
818 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
819 // operand is overdefined.
820 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
821 LatticeVal *NonOverdefVal = 0;
822 if (!V1State.isOverdefined())
823 NonOverdefVal = &V1State;
824 else if (!V2State.isOverdefined())
825 NonOverdefVal = &V2State;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000826
Chris Lattner6367c3f2009-11-02 05:55:40 +0000827 if (NonOverdefVal) {
828 if (NonOverdefVal->isUndefined()) {
829 // Could annihilate value.
830 if (I.getOpcode() == Instruction::And)
831 markConstant(IV, &I, Constant::getNullValue(I.getType()));
832 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
833 markConstant(IV, &I, Constant::getAllOnesValue(PT));
834 else
835 markConstant(IV, &I,
836 Constant::getAllOnesValue(I.getType()));
837 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838 }
Chris Lattner6367c3f2009-11-02 05:55:40 +0000839
840 if (I.getOpcode() == Instruction::And) {
841 // X and 0 = 0
842 if (NonOverdefVal->getConstant()->isNullValue())
843 return markConstant(IV, &I, NonOverdefVal->getConstant());
844 } else {
845 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
846 if (CI->isAllOnesValue()) // X or -1 = -1
847 return markConstant(IV, &I, NonOverdefVal->getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848 }
849 }
Chris Lattner6367c3f2009-11-02 05:55:40 +0000850 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851
852
Chris Lattner6367c3f2009-11-02 05:55:40 +0000853 // If both operands are PHI nodes, it is possible that this instruction has
854 // a constant value, despite the fact that the PHI node doesn't. Check for
855 // this condition now.
856 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
857 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
858 if (PN1->getParent() == PN2->getParent()) {
859 // Since the two PHI nodes are in the same basic block, they must have
860 // entries for the same predecessors. Walk the predecessor list, and
861 // if all of the incoming values are constants, and the result of
862 // evaluating this expression with all incoming value pairs is the
863 // same, then this expression is a constant even though the PHI node
864 // is not a constant!
865 LatticeVal Result;
866 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
867 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
868 BasicBlock *InBlock = PN1->getIncomingBlock(i);
869 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870
Chris Lattner6367c3f2009-11-02 05:55:40 +0000871 if (In1.isOverdefined() || In2.isOverdefined()) {
872 Result.markOverdefined();
873 break; // Cannot fold this operation over the PHI nodes!
874 }
875
876 if (In1.isConstant() && In2.isConstant()) {
877 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
878 In2.getConstant());
879 if (Result.isUndefined())
880 Result.markConstant(V);
881 else if (Result.isConstant() && Result.getConstant() != V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000882 Result.markOverdefined();
Chris Lattner6367c3f2009-11-02 05:55:40 +0000883 break;
Chris Lattnerb52f7002009-11-02 03:03:42 +0000884 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000885 }
886 }
887
Chris Lattner6367c3f2009-11-02 05:55:40 +0000888 // If we found a constant value here, then we know the instruction is
889 // constant despite the fact that the PHI nodes are overdefined.
890 if (Result.isConstant()) {
891 markConstant(IV, &I, Result.getConstant());
892 // Remember that this instruction is virtually using the PHI node
893 // operands.
894 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
895 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
896 return;
897 }
898
899 if (Result.isUndefined())
900 return;
901
902 // Okay, this really is overdefined now. Since we might have
903 // speculatively thought that this was not overdefined before, and
904 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
905 // make sure to clean out any entries that we put there, for
906 // efficiency.
907 UsersOfOverdefinedPHIs.erase(PN1);
908 UsersOfOverdefinedPHIs.erase(PN2);
909 }
910
911 markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912}
913
Chris Lattnerc8798002009-11-02 02:33:50 +0000914// Handle ICmpInst instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000916 LatticeVal V1State = getValueState(I.getOperand(0));
917 LatticeVal V2State = getValueState(I.getOperand(1));
918
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919 LatticeVal &IV = ValueState[&I];
920 if (IV.isOverdefined()) return;
921
Chris Lattner6367c3f2009-11-02 05:55:40 +0000922 if (V1State.isConstant() && V2State.isConstant())
923 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
924 V1State.getConstant(),
925 V2State.getConstant()));
926
927 // If operands are still undefined, wait for it to resolve.
928 if (!V1State.isOverdefined() && !V2State.isOverdefined())
929 return;
930
931 // If something is overdefined, use some tricks to avoid ending up and over
932 // defined if we can.
933
934 // If both operands are PHI nodes, it is possible that this instruction has
935 // a constant value, despite the fact that the PHI node doesn't. Check for
936 // this condition now.
937 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
938 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
939 if (PN1->getParent() == PN2->getParent()) {
940 // Since the two PHI nodes are in the same basic block, they must have
941 // entries for the same predecessors. Walk the predecessor list, and
942 // if all of the incoming values are constants, and the result of
943 // evaluating this expression with all incoming value pairs is the
944 // same, then this expression is a constant even though the PHI node
945 // is not a constant!
946 LatticeVal Result;
947 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
948 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
949 BasicBlock *InBlock = PN1->getIncomingBlock(i);
950 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000951
Chris Lattner6367c3f2009-11-02 05:55:40 +0000952 if (In1.isOverdefined() || In2.isOverdefined()) {
953 Result.markOverdefined();
954 break; // Cannot fold this operation over the PHI nodes!
955 }
956
957 if (In1.isConstant() && In2.isConstant()) {
958 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
959 In1.getConstant(),
960 In2.getConstant());
961 if (Result.isUndefined())
962 Result.markConstant(V);
963 else if (Result.isConstant() && Result.getConstant() != V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964 Result.markOverdefined();
Chris Lattner6367c3f2009-11-02 05:55:40 +0000965 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966 }
967 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000968 }
969
Chris Lattner6367c3f2009-11-02 05:55:40 +0000970 // If we found a constant value here, then we know the instruction is
971 // constant despite the fact that the PHI nodes are overdefined.
972 if (Result.isConstant()) {
973 markConstant(&I, Result.getConstant());
974 // Remember that this instruction is virtually using the PHI node
975 // operands.
976 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
977 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
978 return;
979 }
980
981 if (Result.isUndefined())
982 return;
983
984 // Okay, this really is overdefined now. Since we might have
985 // speculatively thought that this was not overdefined before, and
986 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
987 // make sure to clean out any entries that we put there, for
988 // efficiency.
989 UsersOfOverdefinedPHIs.erase(PN1);
990 UsersOfOverdefinedPHIs.erase(PN2);
991 }
992
993 markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994}
995
996void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
997 // FIXME : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000998 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000999
1000#if 0
1001 LatticeVal &ValState = getValueState(I.getOperand(0));
1002 LatticeVal &IdxState = getValueState(I.getOperand(1));
1003
1004 if (ValState.isOverdefined() || IdxState.isOverdefined())
1005 markOverdefined(&I);
1006 else if(ValState.isConstant() && IdxState.isConstant())
1007 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1008 IdxState.getConstant()));
1009#endif
1010}
1011
1012void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1013 // FIXME : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001014 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015#if 0
1016 LatticeVal &ValState = getValueState(I.getOperand(0));
1017 LatticeVal &EltState = getValueState(I.getOperand(1));
1018 LatticeVal &IdxState = getValueState(I.getOperand(2));
1019
1020 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1021 IdxState.isOverdefined())
1022 markOverdefined(&I);
1023 else if(ValState.isConstant() && EltState.isConstant() &&
1024 IdxState.isConstant())
1025 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1026 EltState.getConstant(),
1027 IdxState.getConstant()));
1028 else if (ValState.isUndefined() && EltState.isConstant() &&
1029 IdxState.isConstant())
1030 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1031 EltState.getConstant(),
1032 IdxState.getConstant()));
1033#endif
1034}
1035
1036void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1037 // FIXME : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001038 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039#if 0
1040 LatticeVal &V1State = getValueState(I.getOperand(0));
1041 LatticeVal &V2State = getValueState(I.getOperand(1));
1042 LatticeVal &MaskState = getValueState(I.getOperand(2));
1043
1044 if (MaskState.isUndefined() ||
1045 (V1State.isUndefined() && V2State.isUndefined()))
1046 return; // Undefined output if mask or both inputs undefined.
1047
1048 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1049 MaskState.isOverdefined()) {
1050 markOverdefined(&I);
1051 } else {
1052 // A mix of constant/undef inputs.
1053 Constant *V1 = V1State.isConstant() ?
1054 V1State.getConstant() : UndefValue::get(I.getType());
1055 Constant *V2 = V2State.isConstant() ?
1056 V2State.getConstant() : UndefValue::get(I.getType());
1057 Constant *Mask = MaskState.isConstant() ?
1058 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1059 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1060 }
1061#endif
1062}
1063
Chris Lattnerc8798002009-11-02 02:33:50 +00001064// Handle getelementptr instructions. If all operands are constants then we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065// can turn this into a getelementptr ConstantExpr.
1066//
1067void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1068 LatticeVal &IV = ValueState[&I];
1069 if (IV.isOverdefined()) return;
1070
1071 SmallVector<Constant*, 8> Operands;
1072 Operands.reserve(I.getNumOperands());
1073
1074 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001075 LatticeVal State = getValueState(I.getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076 if (State.isUndefined())
Chris Lattnerc8798002009-11-02 02:33:50 +00001077 return; // Operands are not resolved yet.
1078
Chris Lattnerb52f7002009-11-02 03:03:42 +00001079 if (State.isOverdefined())
1080 return markOverdefined(IV, &I);
1081
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001082 assert(State.isConstant() && "Unknown state!");
1083 Operands.push_back(State.getConstant());
1084 }
1085
1086 Constant *Ptr = Operands[0];
Chris Lattner6367c3f2009-11-02 05:55:40 +00001087 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0]+1,
1088 Operands.size()-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089}
1090
Chris Lattner6367c3f2009-11-02 05:55:40 +00001091void SCCPSolver::visitStoreInst(StoreInst &SI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1093 return;
Chris Lattner6367c3f2009-11-02 05:55:40 +00001094
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1096 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1097 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1098
Chris Lattner6367c3f2009-11-02 05:55:40 +00001099 // Get the value we are storing into the global, then merge it.
1100 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001101 if (I->second.isOverdefined())
1102 TrackedGlobals.erase(I); // No need to keep tracking this!
1103}
1104
1105
1106// Handle load instructions. If the operand is a constant pointer to a constant
1107// global, we can replace the load with the loaded constant value!
1108void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001109 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattner0148bb22009-11-02 06:06:14 +00001110 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Chris Lattner6367c3f2009-11-02 05:55:40 +00001111
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001112 LatticeVal &IV = ValueState[&I];
1113 if (IV.isOverdefined()) return;
1114
Chris Lattner6367c3f2009-11-02 05:55:40 +00001115 if (!PtrVal.isConstant() || I.isVolatile())
1116 return markOverdefined(IV, &I);
1117
Chris Lattner0148bb22009-11-02 06:06:14 +00001118 Constant *Ptr = PtrVal.getConstant();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119
Chris Lattner6367c3f2009-11-02 05:55:40 +00001120 // load null -> null
1121 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1122 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1123
1124 // Transform load (constant global) into the value loaded.
1125 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattner0148bb22009-11-02 06:06:14 +00001126 if (!TrackedGlobals.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001127 // If we are tracking this global, merge in the known value for it.
1128 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1129 TrackedGlobals.find(GV);
1130 if (It != TrackedGlobals.end()) {
1131 mergeInValue(IV, &I, It->second);
1132 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 }
1134 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 }
1136
Chris Lattner0148bb22009-11-02 06:06:14 +00001137 // Transform load from a constant into a constant if possible.
1138 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1139 return markConstant(IV, &I, C);
Chris Lattner6367c3f2009-11-02 05:55:40 +00001140
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 // Otherwise we cannot say for certain what value this load will produce.
1142 // Bail out.
1143 markOverdefined(IV, &I);
1144}
1145
1146void SCCPSolver::visitCallSite(CallSite CS) {
1147 Function *F = CS.getCalledFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 Instruction *I = CS.getInstruction();
Chris Lattnercd73be02008-04-23 05:38:20 +00001149
1150 // The common case is that we aren't tracking the callee, either because we
1151 // are not doing interprocedural analysis or the callee is indirect, or is
1152 // external. Handle these cases first.
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001153 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001154CallOverdefined:
1155 // Void return and not tracking callee, just bail.
Chris Lattner82cdc062009-10-05 05:54:46 +00001156 if (I->getType()->isVoidTy()) return;
Chris Lattnercd73be02008-04-23 05:38:20 +00001157
1158 // Otherwise, if we have a single return value case, and if the function is
1159 // a declaration, maybe we can constant fold it.
1160 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1161 canConstantFoldCallTo(F)) {
1162
1163 SmallVector<Constant*, 8> Operands;
1164 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1165 AI != E; ++AI) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001166 LatticeVal State = getValueState(*AI);
Chris Lattnerb52f7002009-11-02 03:03:42 +00001167
Chris Lattnercd73be02008-04-23 05:38:20 +00001168 if (State.isUndefined())
1169 return; // Operands are not resolved yet.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001170 if (State.isOverdefined())
1171 return markOverdefined(I);
Chris Lattnercd73be02008-04-23 05:38:20 +00001172 assert(State.isConstant() && "Unknown state!");
1173 Operands.push_back(State.getConstant());
1174 }
1175
1176 // If we can constant fold this, mark the result of the call as a
1177 // constant.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001178 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1179 return markConstant(I, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001180 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001181
1182 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001183 return markOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 }
1185
Chris Lattnercd73be02008-04-23 05:38:20 +00001186 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohman856193b2008-06-20 01:15:44 +00001187 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1188 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001189 // If so, propagate the return value of the callee into this call result.
1190 mergeInValue(I, TFRVI->second);
Dan Gohman856193b2008-06-20 01:15:44 +00001191 } else if (isa<StructType>(I->getType())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001192 // Check to see if we're tracking this callee, if not, handle it in the
1193 // common path above.
Chris Lattnerd3123a72008-08-23 23:36:38 +00001194 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1195 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnercd73be02008-04-23 05:38:20 +00001196 if (TMRVI == TrackedMultipleRetVals.end())
1197 goto CallOverdefined;
Edwin Töröka6174642009-10-20 15:15:09 +00001198
1199 // Need to mark as overdefined, otherwise it stays undefined which
1200 // creates extractvalue undef, <idx>
1201 markOverdefined(I);
Chris Lattnerb52f7002009-11-02 03:03:42 +00001202
Chris Lattnercd73be02008-04-23 05:38:20 +00001203 // If we are tracking this callee, propagate the return values of the call
Dan Gohman856193b2008-06-20 01:15:44 +00001204 // into this call site. We do this by walking all the uses. Single-index
1205 // ExtractValueInst uses can be tracked; anything more complicated is
1206 // currently handled conservatively.
Chris Lattnercd73be02008-04-23 05:38:20 +00001207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1208 UI != E; ++UI) {
Dan Gohman856193b2008-06-20 01:15:44 +00001209 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1210 if (EVI->getNumIndices() == 1) {
1211 mergeInValue(EVI,
Dan Gohmanaa7b7802008-06-20 16:41:17 +00001212 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohman856193b2008-06-20 01:15:44 +00001213 continue;
1214 }
1215 }
1216 // The aggregate value is used in a way not handled here. Assume nothing.
1217 markOverdefined(*UI);
Chris Lattnercd73be02008-04-23 05:38:20 +00001218 }
Dan Gohman856193b2008-06-20 01:15:44 +00001219 } else {
1220 // Otherwise we're not tracking this callee, so handle it in the
1221 // common path above.
1222 goto CallOverdefined;
Chris Lattnercd73be02008-04-23 05:38:20 +00001223 }
1224
1225 // Finally, if this is the first call to the function hit, mark its entry
1226 // block executable.
Chris Lattnera5ffa7c2009-11-02 06:11:23 +00001227 MarkBlockExecutable(F->begin());
Chris Lattnercd73be02008-04-23 05:38:20 +00001228
1229 // Propagate information from this call site into the callee.
1230 CallSite::arg_iterator CAI = CS.arg_begin();
1231 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1232 AI != E; ++AI, ++CAI) {
Edwin Török129b2d12009-09-24 18:33:42 +00001233 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001234 markOverdefined(AI);
Edwin Törökd5435372009-09-24 09:47:18 +00001235 continue;
1236 }
Chris Lattner6367c3f2009-11-02 05:55:40 +00001237
1238 mergeInValue(AI, getValueState(*CAI));
Chris Lattnercd73be02008-04-23 05:38:20 +00001239 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240}
1241
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242void SCCPSolver::Solve() {
1243 // Process the work lists until they are empty!
1244 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1245 !OverdefinedInstWorkList.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001246 // Process the overdefined instruction's work list first, which drives other
1247 // things to overdefined more quickly.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001249 Value *I = OverdefinedInstWorkList.pop_back_val();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250
Dan Gohmandff8d172009-08-17 15:25:05 +00001251 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252
1253 // "I" got into the work list because it either made the transition from
1254 // bottom to constant
1255 //
1256 // Anything on this worklist that is overdefined need not be visited
1257 // since all of its users will have already been marked as overdefined
Chris Lattnerc8798002009-11-02 02:33:50 +00001258 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 //
1260 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1261 UI != E; ++UI)
1262 OperandChangedState(*UI);
1263 }
Chris Lattnerc8798002009-11-02 02:33:50 +00001264
1265 // Process the instruction work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266 while (!InstWorkList.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001267 Value *I = InstWorkList.pop_back_val();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268
Dan Gohmandff8d172009-08-17 15:25:05 +00001269 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270
Chris Lattner6367c3f2009-11-02 05:55:40 +00001271 // "I" got into the work list because it made the transition from undef to
1272 // constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 //
1274 // Anything on this worklist that is overdefined need not be visited
1275 // since all of its users will have already been marked as overdefined.
Chris Lattnerc8798002009-11-02 02:33:50 +00001276 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 //
1278 if (!getValueState(I).isOverdefined())
1279 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1280 UI != E; ++UI)
1281 OperandChangedState(*UI);
1282 }
1283
Chris Lattnerc8798002009-11-02 02:33:50 +00001284 // Process the basic block work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 while (!BBWorkList.empty()) {
1286 BasicBlock *BB = BBWorkList.back();
1287 BBWorkList.pop_back();
1288
Dan Gohmandff8d172009-08-17 15:25:05 +00001289 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290
1291 // Notify all instructions in this basic block that they are newly
1292 // executable.
1293 visit(BB);
1294 }
1295 }
1296}
1297
1298/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1299/// that branches on undef values cannot reach any of their successors.
1300/// However, this is not a safe assumption. After we solve dataflow, this
1301/// method should be use to handle this. If this returns true, the solver
1302/// should be rerun.
1303///
1304/// This method handles this by finding an unresolved branch and marking it one
1305/// of the edges from the block as being feasible, even though the condition
1306/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1307/// CFG and only slightly pessimizes the analysis results (by marking one,
1308/// potentially infeasible, edge feasible). This cannot usefully modify the
1309/// constraints on the condition of the branch, as that would impact other users
1310/// of the value.
1311///
1312/// This scan also checks for values that use undefs, whose results are actually
1313/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1314/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1315/// even if X isn't defined.
1316bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1317 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1318 if (!BBExecutable.count(BB))
1319 continue;
1320
1321 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1322 // Look for instructions which produce undef values.
Chris Lattner82cdc062009-10-05 05:54:46 +00001323 if (I->getType()->isVoidTy()) continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324
1325 LatticeVal &LV = getValueState(I);
1326 if (!LV.isUndefined()) continue;
1327
1328 // Get the lattice values of the first two operands for use below.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001329 LatticeVal Op0LV = getValueState(I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 LatticeVal Op1LV;
1331 if (I->getNumOperands() == 2) {
1332 // If this is a two-operand instruction, and if both operands are
1333 // undefs, the result stays undef.
1334 Op1LV = getValueState(I->getOperand(1));
1335 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1336 continue;
1337 }
1338
1339 // If this is an instructions whose result is defined even if the input is
1340 // not fully defined, propagate the information.
1341 const Type *ITy = I->getType();
1342 switch (I->getOpcode()) {
1343 default: break; // Leave the instruction as an undef.
1344 case Instruction::ZExt:
1345 // After a zero extend, we know the top part is zero. SExt doesn't have
1346 // to be handled here, because we don't know whether the top part is 1's
1347 // or 0's.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001348 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 return true;
1350 case Instruction::Mul:
1351 case Instruction::And:
1352 // undef * X -> 0. X could be zero.
1353 // undef & X -> 0. X could be zero.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001354 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 return true;
1356
1357 case Instruction::Or:
1358 // undef | X -> -1. X could be -1.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001359 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 return true;
1361
1362 case Instruction::SDiv:
1363 case Instruction::UDiv:
1364 case Instruction::SRem:
1365 case Instruction::URem:
1366 // X / undef -> undef. No change.
1367 // X % undef -> undef. No change.
1368 if (Op1LV.isUndefined()) break;
1369
1370 // undef / X -> 0. X could be maxint.
1371 // undef % X -> 0. X could be 1.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001372 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001373 return true;
1374
1375 case Instruction::AShr:
1376 // undef >>s X -> undef. No change.
1377 if (Op0LV.isUndefined()) break;
1378
1379 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1380 if (Op0LV.isConstant())
Chris Lattner6367c3f2009-11-02 05:55:40 +00001381 markForcedConstant(I, Op0LV.getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382 else
Chris Lattner6367c3f2009-11-02 05:55:40 +00001383 markOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001384 return true;
1385 case Instruction::LShr:
1386 case Instruction::Shl:
1387 // undef >> X -> undef. No change.
1388 // undef << X -> undef. No change.
1389 if (Op0LV.isUndefined()) break;
1390
1391 // X >> undef -> 0. X could be 0.
1392 // X << undef -> 0. X could be 0.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001393 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001394 return true;
1395 case Instruction::Select:
1396 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1397 if (Op0LV.isUndefined()) {
1398 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1399 Op1LV = getValueState(I->getOperand(2));
1400 } else if (Op1LV.isUndefined()) {
1401 // c ? undef : undef -> undef. No change.
1402 Op1LV = getValueState(I->getOperand(2));
1403 if (Op1LV.isUndefined())
1404 break;
1405 // Otherwise, c ? undef : x -> x.
1406 } else {
1407 // Leave Op1LV as Operand(1)'s LatticeValue.
1408 }
1409
1410 if (Op1LV.isConstant())
Chris Lattner6367c3f2009-11-02 05:55:40 +00001411 markForcedConstant(I, Op1LV.getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001412 else
Chris Lattner6367c3f2009-11-02 05:55:40 +00001413 markOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001414 return true;
Chris Lattner9110ac92008-05-24 03:59:33 +00001415 case Instruction::Call:
1416 // If a call has an undef result, it is because it is constant foldable
1417 // but one of the inputs was undef. Just force the result to
1418 // overdefined.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001419 markOverdefined(I);
Chris Lattner9110ac92008-05-24 03:59:33 +00001420 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001421 }
1422 }
1423
1424 TerminatorInst *TI = BB->getTerminator();
1425 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1426 if (!BI->isConditional()) continue;
1427 if (!getValueState(BI->getCondition()).isUndefined())
1428 continue;
1429 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001430 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesenfb06d0c2008-05-23 01:01:31 +00001431 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001432 if (!getValueState(SI->getCondition()).isUndefined())
1433 continue;
1434 } else {
1435 continue;
1436 }
1437
Chris Lattner6186e8c2008-01-28 00:32:30 +00001438 // If the edge to the second successor isn't thought to be feasible yet,
1439 // mark it so now. We pick the second one so that this goes to some
1440 // enumerated value in a switch instead of going to the default destination.
1441 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442 continue;
1443
1444 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1445 // and return. This will make other blocks reachable, which will allow new
1446 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner6186e8c2008-01-28 00:32:30 +00001447 markEdgeExecutable(BB, TI->getSuccessor(1));
1448
1449 // This must be a conditional branch of switch on undef. At this point,
1450 // force the old terminator to branch to the first successor. This is
1451 // required because we are now influencing the dataflow of the function with
1452 // the assumption that this edge is taken. If we leave the branch condition
1453 // as undef, then further analysis could think the undef went another way
1454 // leading to an inconsistent set of conclusions.
1455 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001456 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner6186e8c2008-01-28 00:32:30 +00001457 } else {
1458 SwitchInst *SI = cast<SwitchInst>(TI);
1459 SI->setCondition(SI->getCaseValue(1));
1460 }
1461
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001462 return true;
1463 }
1464
1465 return false;
1466}
1467
1468
1469namespace {
1470 //===--------------------------------------------------------------------===//
1471 //
1472 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1473 /// Sparse Conditional Constant Propagator.
1474 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001475 struct SCCP : public FunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001476 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +00001477 SCCP() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001478
1479 // runOnFunction - Run the Sparse Conditional Constant Propagation
1480 // algorithm, and return true if the function was modified.
1481 //
1482 bool runOnFunction(Function &F);
1483
1484 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1485 AU.setPreservesCFG();
1486 }
1487 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001488} // end anonymous namespace
1489
Dan Gohman089efff2008-05-13 00:00:25 +00001490char SCCP::ID = 0;
1491static RegisterPass<SCCP>
1492X("sccp", "Sparse Conditional Constant Propagation");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001493
Chris Lattnerc8798002009-11-02 02:33:50 +00001494// createSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001495FunctionPass *llvm::createSCCPPass() {
1496 return new SCCP();
1497}
1498
Chris Lattner14513dc2009-11-02 02:47:51 +00001499static void DeleteInstructionInBlock(BasicBlock *BB) {
1500 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1501 ++NumDeadBlocks;
1502
1503 // Delete the instructions backwards, as it has a reduced likelihood of
1504 // having to update as many def-use and use-def chains.
1505 while (!isa<TerminatorInst>(BB->begin())) {
1506 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1507
1508 if (!I->use_empty())
1509 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1510 BB->getInstList().erase(I);
1511 ++NumInstRemoved;
1512 }
1513}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001514
1515// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1516// and return true if the function was modified.
1517//
1518bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001519 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner0148bb22009-11-02 06:06:14 +00001520 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521
1522 // Mark the first block of the function as being executable.
1523 Solver.MarkBlockExecutable(F.begin());
1524
1525 // Mark all arguments to the function as being overdefined.
1526 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1527 Solver.markOverdefined(AI);
1528
1529 // Solve for constants.
1530 bool ResolvedUndefs = true;
1531 while (ResolvedUndefs) {
1532 Solver.Solve();
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001533 DEBUG(errs() << "RESOLVING UNDEFs\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001534 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1535 }
1536
1537 bool MadeChanges = false;
1538
1539 // If we decided that there are basic blocks that are dead in this function,
1540 // delete their contents now. Note that we cannot actually delete the blocks,
1541 // as we cannot modify the CFG of the function.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542
Chris Lattner14513dc2009-11-02 02:47:51 +00001543 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner317e6b62008-08-23 23:39:31 +00001544 if (!Solver.isBlockExecutable(BB)) {
Chris Lattner14513dc2009-11-02 02:47:51 +00001545 DeleteInstructionInBlock(BB);
1546 MadeChanges = true;
1547 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001548 }
Chris Lattner14513dc2009-11-02 02:47:51 +00001549
1550 // Iterate over all of the instructions in a function, replacing them with
1551 // constants if we have found them to be of constant values.
1552 //
1553 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1554 Instruction *Inst = BI++;
1555 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1556 continue;
1557
Chris Lattnerc9edab82009-11-02 02:54:24 +00001558 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1559 if (IV.isOverdefined())
Chris Lattner14513dc2009-11-02 02:47:51 +00001560 continue;
1561
1562 Constant *Const = IV.isConstant()
1563 ? IV.getConstant() : UndefValue::get(Inst->getType());
1564 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1565
1566 // Replaces all of the uses of a variable with uses of the constant.
1567 Inst->replaceAllUsesWith(Const);
1568
1569 // Delete the instruction.
1570 Inst->eraseFromParent();
1571
1572 // Hey, we just changed something!
1573 MadeChanges = true;
1574 ++NumInstRemoved;
1575 }
1576 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001577
1578 return MadeChanges;
1579}
1580
1581namespace {
1582 //===--------------------------------------------------------------------===//
1583 //
1584 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1585 /// Constant Propagation.
1586 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001587 struct IPSCCP : public ModulePass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001588 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +00001589 IPSCCP() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001590 bool runOnModule(Module &M);
1591 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001592} // end anonymous namespace
1593
Dan Gohman089efff2008-05-13 00:00:25 +00001594char IPSCCP::ID = 0;
1595static RegisterPass<IPSCCP>
1596Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1597
Chris Lattnerc8798002009-11-02 02:33:50 +00001598// createIPSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001599ModulePass *llvm::createIPSCCPPass() {
1600 return new IPSCCP();
1601}
1602
1603
1604static bool AddressIsTaken(GlobalValue *GV) {
1605 // Delete any dead constantexpr klingons.
1606 GV->removeDeadConstantUsers();
1607
1608 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1609 UI != E; ++UI)
1610 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1611 if (SI->getOperand(0) == GV || SI->isVolatile())
1612 return true; // Storing addr of GV.
1613 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1614 // Make sure we are calling the function, not passing the address.
Chris Lattner2f487502009-11-01 06:11:53 +00001615 if (UI.getOperandNo() != 0)
Nick Lewycky1cc2e102008-11-03 03:49:14 +00001616 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001617 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1618 if (LI->isVolatile())
1619 return true;
Chris Lattner2f487502009-11-01 06:11:53 +00001620 } else if (isa<BlockAddress>(*UI)) {
1621 // blockaddress doesn't take the address of the function, it takes addr
1622 // of label.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001623 } else {
1624 return true;
1625 }
1626 return false;
1627}
1628
1629bool IPSCCP::runOnModule(Module &M) {
Chris Lattner0148bb22009-11-02 06:06:14 +00001630 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001631
1632 // Loop over all functions, marking arguments to those with their addresses
1633 // taken or that are external as overdefined.
1634 //
1635 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001636 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001637 if (!F->isDeclaration())
1638 Solver.MarkBlockExecutable(F->begin());
1639 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1640 AI != E; ++AI)
1641 Solver.markOverdefined(AI);
1642 } else {
1643 Solver.AddTrackedFunction(F);
1644 }
1645
1646 // Loop over global variables. We inform the solver about any internal global
1647 // variables that do not have their 'addresses taken'. If they don't have
1648 // their addresses taken, we can propagate constants through them.
1649 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1650 G != E; ++G)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001651 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001652 Solver.TrackValueOfGlobalVariable(G);
1653
1654 // Solve for constants.
1655 bool ResolvedUndefs = true;
1656 while (ResolvedUndefs) {
1657 Solver.Solve();
1658
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001659 DEBUG(errs() << "RESOLVING UNDEFS\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001660 ResolvedUndefs = false;
1661 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1662 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1663 }
1664
1665 bool MadeChanges = false;
1666
1667 // Iterate over all of the instructions in the module, replacing them with
1668 // constants if we have found them to be of constant values.
1669 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001670 SmallVector<BasicBlock*, 512> BlocksToErase;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001671
1672 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner84388f12009-11-02 03:25:55 +00001673 if (Solver.isBlockExecutable(F->begin())) {
1674 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1675 AI != E; ++AI) {
1676 if (AI->use_empty()) continue;
1677
1678 LatticeVal IV = Solver.getLatticeValueFor(AI);
1679 if (IV.isOverdefined()) continue;
1680
1681 Constant *CST = IV.isConstant() ?
1682 IV.getConstant() : UndefValue::get(AI->getType());
1683 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1684
1685 // Replaces all of the uses of a variable with uses of the
1686 // constant.
1687 AI->replaceAllUsesWith(CST);
1688 ++IPNumArgsElimed;
1689 }
Chris Lattnerc9edab82009-11-02 02:54:24 +00001690 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001691
Chris Lattner14513dc2009-11-02 02:47:51 +00001692 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner317e6b62008-08-23 23:39:31 +00001693 if (!Solver.isBlockExecutable(BB)) {
Chris Lattner14513dc2009-11-02 02:47:51 +00001694 DeleteInstructionInBlock(BB);
1695 MadeChanges = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001696
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001697 TerminatorInst *TI = BB->getTerminator();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001698 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1699 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohman3f7d94b2007-10-03 19:26:29 +00001700 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001701 TI->getSuccessor(i)->removePredecessor(BB);
1702 }
1703 if (!TI->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001704 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner14513dc2009-11-02 02:47:51 +00001705 TI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001706
1707 if (&*BB != &F->front())
1708 BlocksToErase.push_back(BB);
1709 else
Owen Anderson35b47072009-08-13 21:58:54 +00001710 new UnreachableInst(M.getContext(), BB);
Chris Lattner14513dc2009-11-02 02:47:51 +00001711 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712 }
Chris Lattner14513dc2009-11-02 02:47:51 +00001713
1714 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1715 Instruction *Inst = BI++;
1716 if (Inst->getType()->isVoidTy())
1717 continue;
1718
Chris Lattnerc9edab82009-11-02 02:54:24 +00001719 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1720 if (IV.isOverdefined())
Chris Lattner14513dc2009-11-02 02:47:51 +00001721 continue;
1722
1723 Constant *Const = IV.isConstant()
1724 ? IV.getConstant() : UndefValue::get(Inst->getType());
1725 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1726
1727 // Replaces all of the uses of a variable with uses of the
1728 // constant.
1729 Inst->replaceAllUsesWith(Const);
1730
1731 // Delete the instruction.
1732 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1733 Inst->eraseFromParent();
1734
1735 // Hey, we just changed something!
1736 MadeChanges = true;
1737 ++IPNumInstRemoved;
1738 }
1739 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001740
1741 // Now that all instructions in the function are constant folded, erase dead
1742 // blocks, because we can now use ConstantFoldTerminator to get rid of
1743 // in-edges.
1744 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1745 // If there are any PHI nodes in this successor, drop entries for BB now.
1746 BasicBlock *DeadBB = BlocksToErase[i];
1747 while (!DeadBB->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001748 Instruction *I = cast<Instruction>(DeadBB->use_back());
1749 bool Folded = ConstantFoldTerminator(I->getParent());
1750 if (!Folded) {
1751 // The constant folder may not have been able to fold the terminator
1752 // if this is a branch or switch on undef. Fold it manually as a
1753 // branch to the first successor.
Devang Patele92c16d2008-11-21 01:52:59 +00001754#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001755 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1756 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1757 "Branch should be foldable!");
1758 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1759 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1760 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001761 llvm_unreachable("Didn't fold away reference to block!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001762 }
Devang Patele92c16d2008-11-21 01:52:59 +00001763#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001764
1765 // Make this an uncond branch to the first successor.
1766 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001767 BranchInst::Create(TI->getSuccessor(0), TI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001768
1769 // Remove entries in successor phi nodes to remove edges.
1770 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1771 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1772
1773 // Remove the old terminator.
1774 TI->eraseFromParent();
1775 }
1776 }
1777
1778 // Finally, delete the basic block.
1779 F->getBasicBlockList().erase(DeadBB);
1780 }
1781 BlocksToErase.clear();
1782 }
1783
1784 // If we inferred constant or undef return values for a function, we replaced
1785 // all call uses with the inferred value. This means we don't need to bother
1786 // actually returning anything from the function. Replace all return
1787 // instructions with return undef.
Devang Pateld04d42b2008-03-11 17:32:05 +00001788 // TODO: Process multiple value ret instructions also.
Devang Pateladd320d2008-03-11 05:46:42 +00001789 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001790 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1791 E = RV.end(); I != E; ++I)
1792 if (!I->second.isOverdefined() &&
Chris Lattner82cdc062009-10-05 05:54:46 +00001793 !I->first->getReturnType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001794 Function *F = I->first;
1795 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1796 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1797 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +00001798 RI->setOperand(0, UndefValue::get(F->getReturnType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001799 }
1800
1801 // If we infered constant or undef values for globals variables, we can delete
1802 // the global and any stores that remain to it.
1803 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1804 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1805 E = TG.end(); I != E; ++I) {
1806 GlobalVariable *GV = I->first;
1807 assert(!I->second.isOverdefined() &&
1808 "Overdefined values should have been taken out of the map!");
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001809 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001810 while (!GV->use_empty()) {
1811 StoreInst *SI = cast<StoreInst>(GV->use_back());
1812 SI->eraseFromParent();
1813 }
1814 M.getGlobalList().erase(GV);
1815 ++IPNumGlobalConst;
1816 }
1817
1818 return MadeChanges;
1819}