blob: fb6101b0b99d8f99305fd80e232b34ba207b003f [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"
Dan Gohman856193b2008-06-20 01:15:44 +000028#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0148bb22009-11-02 06:06:14 +000030#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/Support/CallSite.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034#include "llvm/Support/InstVisitor.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattnerd3123a72008-08-23 23:36:38 +000037#include "llvm/ADT/DenseSet.h"
Chris Lattner1eb405b2009-11-02 02:20:32 +000038#include "llvm/ADT/PointerIntPair.h"
Chris Lattnera5ffa7c2009-11-02 06:11:23 +000039#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/STLExtras.h"
43#include <algorithm>
Dan Gohman249ddbf2008-03-21 23:51:57 +000044#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000045using namespace llvm;
46
47STATISTIC(NumInstRemoved, "Number of instructions removed");
48STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49
Nick Lewyckybbdfc9c2008-03-08 07:48:41 +000050STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
53
54namespace {
55/// LatticeVal class - This class represents the different lattice values that
56/// an LLVM value may occupy. It is a simple class with value semantics.
57///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +000058class LatticeVal {
Chris Lattner1eb405b2009-11-02 02:20:32 +000059 enum LatticeValueTy {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060 /// undefined - This LLVM Value has no known value yet.
61 undefined,
62
63 /// constant - This LLVM Value has a specific constant value.
64 constant,
65
66 /// forcedconstant - This LLVM Value was thought to be undef until
67 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
68 /// with another (different) constant, it goes to overdefined, instead of
69 /// asserting.
70 forcedconstant,
71
72 /// overdefined - This instruction is not known to be constant, and we know
73 /// it has a value.
74 overdefined
Chris Lattner1eb405b2009-11-02 02:20:32 +000075 };
76
77 /// Val: This stores the current lattice value along with the Constant* for
78 /// the constant if this is a 'constant' or 'forcedconstant' value.
79 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080
Chris Lattner1eb405b2009-11-02 02:20:32 +000081 LatticeValueTy getLatticeValue() const {
82 return Val.getInt();
83 }
84
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085public:
Chris Lattnerb52f7002009-11-02 03:03:42 +000086 LatticeVal() : Val(0, undefined) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087
Chris Lattnerb52f7002009-11-02 03:03:42 +000088 bool isUndefined() const { return getLatticeValue() == undefined; }
89 bool isConstant() const {
Chris Lattner1eb405b2009-11-02 02:20:32 +000090 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
91 }
Chris Lattnerb52f7002009-11-02 03:03:42 +000092 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Chris Lattner1eb405b2009-11-02 02:20:32 +000093
Chris Lattnerb52f7002009-11-02 03:03:42 +000094 Constant *getConstant() const {
Chris Lattner1eb405b2009-11-02 02:20:32 +000095 assert(isConstant() && "Cannot get the constant of a non-constant!");
96 return Val.getPointer();
97 }
98
99 /// markOverdefined - Return true if this is a change in status.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000100 bool markOverdefined() {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000101 if (isOverdefined())
102 return false;
103
104 Val.setInt(overdefined);
105 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106 }
107
Chris Lattner1eb405b2009-11-02 02:20:32 +0000108 /// markConstant - Return true if this is a change in status.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000109 bool markConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000110 if (isConstant()) {
111 assert(getConstant() == V && "Marking constant with different value");
112 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113 }
Chris Lattner1eb405b2009-11-02 02:20:32 +0000114
115 if (isUndefined()) {
116 Val.setInt(constant);
117 assert(V && "Marking constant with NULL");
118 Val.setPointer(V);
119 } else {
120 assert(getLatticeValue() == forcedconstant &&
121 "Cannot move from overdefined to constant!");
122 // Stay at forcedconstant if the constant is the same.
123 if (V == getConstant()) return false;
124
125 // Otherwise, we go to overdefined. Assumptions made based on the
126 // forced value are possibly wrong. Assuming this is another constant
127 // could expose a contradiction.
128 Val.setInt(overdefined);
129 }
130 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131 }
132
Chris Lattner220571c2009-11-02 03:21:36 +0000133 /// getConstantInt - If this is a constant with a ConstantInt value, return it
134 /// otherwise return null.
135 ConstantInt *getConstantInt() const {
136 if (isConstant())
137 return dyn_cast<ConstantInt>(getConstant());
138 return 0;
139 }
140
Chris Lattnerb52f7002009-11-02 03:03:42 +0000141 void markForcedConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000142 assert(isUndefined() && "Can't force a defined value!");
143 Val.setInt(forcedconstant);
144 Val.setPointer(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 }
146};
Chris Lattner14513dc2009-11-02 02:47:51 +0000147} // end anonymous namespace.
148
149
150namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152//===----------------------------------------------------------------------===//
153//
154/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
155/// Constant Propagation.
156///
157class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner0148bb22009-11-02 06:06:14 +0000158 const TargetData *TD;
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000159 SmallPtrSet<BasicBlock*, 8> BBExecutable;// The BBs that are executable.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000160 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161
162 /// GlobalValue - If we are tracking any values for the contents of a global
163 /// variable, we keep a mapping from the constant accessor to the element of
164 /// the global, to the currently known value. If the value becomes
165 /// overdefined, it's entry is simply removed from this map.
166 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
167
Devang Pateladd320d2008-03-11 05:46:42 +0000168 /// TrackedRetVals - If we are tracking arguments into and the return
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 /// value out of a function, it will have an entry in this map, indicating
170 /// what the known return value for the function is.
Devang Pateladd320d2008-03-11 05:46:42 +0000171 DenseMap<Function*, LatticeVal> TrackedRetVals;
172
173 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
174 /// that return multiple values.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000175 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176
Chris Lattnerb52f7002009-11-02 03:03:42 +0000177 /// The reason for two worklists is that overdefined is the lowest state
178 /// on the lattice, and moving things to overdefined as fast as possible
179 /// makes SCCP converge much faster.
180 ///
181 /// By having a separate worklist, we accomplish this because everything
182 /// possibly overdefined will become overdefined at the soonest possible
183 /// point.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000184 SmallVector<Value*, 64> OverdefinedInstWorkList;
185 SmallVector<Value*, 64> InstWorkList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186
187
Chris Lattnerd3123a72008-08-23 23:36:38 +0000188 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189
190 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
191 /// overdefined, despite the fact that the PHI node is overdefined.
192 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
193
194 /// KnownFeasibleEdges - Entries in this set are edges which have already had
195 /// PHI nodes retriggered.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000196 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
197 DenseSet<Edge> KnownFeasibleEdges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198public:
Chris Lattner0148bb22009-11-02 06:06:14 +0000199 SCCPSolver(const TargetData *td) : TD(td) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200
201 /// MarkBlockExecutable - This method can be used by clients to mark all of
202 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000203 ///
204 /// This returns true if the block was not considered live before.
205 bool MarkBlockExecutable(BasicBlock *BB) {
206 if (!BBExecutable.insert(BB)) return false;
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000207 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000209 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 }
211
212 /// TrackValueOfGlobalVariable - Clients can use this method to
213 /// inform the SCCPSolver that it should track loads and stores to the
214 /// specified global variable if it can. This is only legal to call if
215 /// performing Interprocedural SCCP.
216 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
217 const Type *ElTy = GV->getType()->getElementType();
218 if (ElTy->isFirstClassType()) {
219 LatticeVal &IV = TrackedGlobals[GV];
220 if (!isa<UndefValue>(GV->getInitializer()))
221 IV.markConstant(GV->getInitializer());
222 }
223 }
224
225 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
226 /// and out of the specified function (which cannot have its address taken),
227 /// this method must be called.
228 void AddTrackedFunction(Function *F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229 // Add an entry, F -> undef.
Devang Pateladd320d2008-03-11 05:46:42 +0000230 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
231 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnercd73be02008-04-23 05:38:20 +0000232 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
233 LatticeVal()));
234 } else
235 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 }
237
238 /// Solve - Solve for constants and executable blocks.
239 ///
240 void Solve();
241
242 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
243 /// that branches on undef values cannot reach any of their successors.
244 /// However, this is not a safe assumption. After we solve dataflow, this
245 /// method should be use to handle this. If this returns true, the solver
246 /// should be rerun.
247 bool ResolvedUndefsIn(Function &F);
248
Chris Lattner317e6b62008-08-23 23:39:31 +0000249 bool isBlockExecutable(BasicBlock *BB) const {
250 return BBExecutable.count(BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 }
252
Chris Lattnerc9edab82009-11-02 02:54:24 +0000253 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000254 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattnerc9edab82009-11-02 02:54:24 +0000255 assert(I != ValueState.end() && "V is not in valuemap!");
256 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 }
258
Devang Pateladd320d2008-03-11 05:46:42 +0000259 /// getTrackedRetVals - Get the inferred return value map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 ///
Devang Pateladd320d2008-03-11 05:46:42 +0000261 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
262 return TrackedRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 }
264
265 /// getTrackedGlobals - Get and return the set of inferred initializers for
266 /// global variables.
267 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
268 return TrackedGlobals;
269 }
270
Chris Lattner220571c2009-11-02 03:21:36 +0000271 void markOverdefined(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 markOverdefined(ValueState[V], V);
273 }
274
275private:
276 // markConstant - Make a value be marked as "constant". If the value
277 // is not already a constant, add it to the instruction work list so that
278 // the users of the instruction are updated later.
279 //
Chris Lattnerb52f7002009-11-02 03:03:42 +0000280 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
281 if (!IV.markConstant(C)) return;
282 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
283 InstWorkList.push_back(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 }
285
Chris Lattnerb52f7002009-11-02 03:03:42 +0000286 void markConstant(Value *V, Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 markConstant(ValueState[V], V, C);
288 }
289
Chris Lattner6367c3f2009-11-02 05:55:40 +0000290 void markForcedConstant(Value *V, Constant *C) {
291 ValueState[V].markForcedConstant(C);
292 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
293 InstWorkList.push_back(V);
294 }
295
296
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297 // markOverdefined - Make a value be marked as "overdefined". If the
298 // value is not already overdefined, add it to the overdefined instruction
299 // work list so that the users of the instruction are updated later.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000300 void markOverdefined(LatticeVal &IV, Value *V) {
301 if (!IV.markOverdefined()) return;
302
303 DEBUG(errs() << "markOverdefined: ";
304 if (Function *F = dyn_cast<Function>(V))
305 errs() << "Function '" << F->getName() << "'\n";
306 else
307 errs() << *V << '\n');
308 // Only instructions go on the work list
309 OverdefinedInstWorkList.push_back(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310 }
311
Chris Lattner6367c3f2009-11-02 05:55:40 +0000312 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 if (IV.isOverdefined() || MergeWithV.isUndefined())
314 return; // Noop.
315 if (MergeWithV.isOverdefined())
316 markOverdefined(IV, V);
317 else if (IV.isUndefined())
318 markConstant(IV, V, MergeWithV.getConstant());
319 else if (IV.getConstant() != MergeWithV.getConstant())
320 markOverdefined(IV, V);
321 }
322
Chris Lattner6367c3f2009-11-02 05:55:40 +0000323 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Chris Lattner220571c2009-11-02 03:21:36 +0000324 mergeInValue(ValueState[V], V, MergeWithV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325 }
326
327
Chris Lattner6367c3f2009-11-02 05:55:40 +0000328 /// getValueState - Return the LatticeVal object that corresponds to the
329 /// value. This function handles the case when the value hasn't been seen yet
330 /// by properly seeding constants etc.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000331 LatticeVal &getValueState(Value *V) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000332 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333 if (I != ValueState.end()) return I->second; // Common case, in the map
334
Chris Lattner220571c2009-11-02 03:21:36 +0000335 LatticeVal &LV = ValueState[V];
336
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner220571c2009-11-02 03:21:36 +0000338 // Undef values remain undefined.
339 if (!isa<UndefValue>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340 LV.markConstant(C); // Constants are constant
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 }
Chris Lattner220571c2009-11-02 03:21:36 +0000342
Chris Lattnerc8798002009-11-02 02:33:50 +0000343 // All others are underdefined by default.
Chris Lattner220571c2009-11-02 03:21:36 +0000344 return LV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345 }
346
Chris Lattner6367c3f2009-11-02 05:55:40 +0000347 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
348 /// work list if it is not already executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
350 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
351 return; // This edge is already known to be executable!
352
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000353 if (!MarkBlockExecutable(Dest)) {
354 // If the destination is already executable, we just made an *edge*
355 // feasible that wasn't before. Revisit the PHI nodes in the block
356 // because they have potentially new operands.
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000357 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
358 << " -> " << Dest->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000360 PHINode *PN;
361 for (BasicBlock::iterator I = Dest->begin();
362 (PN = dyn_cast<PHINode>(I)); ++I)
363 visitPHINode(*PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000364 }
365 }
366
367 // getFeasibleSuccessors - Return a vector of booleans to indicate which
368 // successors are reachable from a given terminator instruction.
369 //
370 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
371
372 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000373 // block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374 //
375 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
376
377 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnerc8798002009-11-02 02:33:50 +0000378 // instruction that was just changed state somehow. Based on this
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379 // information, we need to update the specified user of this instruction.
380 //
Chris Lattner3a2499a2009-11-03 03:42:51 +0000381 void OperandChangedState(Instruction *I) {
382 if (BBExecutable.count(I->getParent())) // Inst is executable?
383 visit(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384 }
Chris Lattnere84f1232009-11-02 06:28:16 +0000385
386 /// RemoveFromOverdefinedPHIs - If I has any entries in the
387 /// UsersOfOverdefinedPHIs map for PN, remove them now.
388 void RemoveFromOverdefinedPHIs(Instruction *I, PHINode *PN) {
389 if (UsersOfOverdefinedPHIs.empty()) return;
390 std::multimap<PHINode*, Instruction*>::iterator It, E;
391 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN);
392 while (It != E) {
393 if (It->second == I)
394 UsersOfOverdefinedPHIs.erase(It++);
395 else
396 ++It;
397 }
398 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399
400private:
401 friend class InstVisitor<SCCPSolver>;
402
Chris Lattnerc8798002009-11-02 02:33:50 +0000403 // visit implementations - Something changed in this instruction. Either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 // operand made a transition, or the instruction is newly executable. Change
405 // the value type of I to reflect these changes if appropriate.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000406 void visitPHINode(PHINode &I);
407
408 // Terminators
409 void visitReturnInst(ReturnInst &I);
410 void visitTerminatorInst(TerminatorInst &TI);
411
412 void visitCastInst(CastInst &I);
413 void visitSelectInst(SelectInst &I);
414 void visitBinaryOperator(Instruction &I);
415 void visitCmpInst(CmpInst &I);
416 void visitExtractElementInst(ExtractElementInst &I);
417 void visitInsertElementInst(InsertElementInst &I);
418 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman856193b2008-06-20 01:15:44 +0000419 void visitExtractValueInst(ExtractValueInst &EVI);
420 void visitInsertValueInst(InsertValueInst &IVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421
Chris Lattnerc8798002009-11-02 02:33:50 +0000422 // Instructions that cannot be folded away.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000423 void visitStoreInst (StoreInst &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 void visitLoadInst (LoadInst &I);
425 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez93946082009-10-24 04:23:03 +0000426 void visitCallInst (CallInst &I) {
Chris Lattner6ad04a02009-09-27 21:35:11 +0000427 visitCallSite(CallSite::get(&I));
Victor Hernandez48c3c542009-09-18 22:35:49 +0000428 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000429 void visitInvokeInst (InvokeInst &II) {
430 visitCallSite(CallSite::get(&II));
431 visitTerminatorInst(II);
432 }
433 void visitCallSite (CallSite CS);
434 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
435 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandezb1687302009-10-23 21:09:37 +0000436 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
438 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439
440 void visitInstruction(Instruction &I) {
Chris Lattnerc8798002009-11-02 02:33:50 +0000441 // If a new instruction is added to LLVM that we don't handle.
Chris Lattner8a6411c2009-08-23 04:37:46 +0000442 errs() << "SCCP: Don't know how to handle: " << I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 markOverdefined(&I); // Just in case
444 }
445};
446
Duncan Sands40f67972007-07-20 08:56:21 +0000447} // end anonymous namespace
448
449
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450// getFeasibleSuccessors - Return a vector of booleans to indicate which
451// successors are reachable from a given terminator instruction.
452//
453void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
454 SmallVector<bool, 16> &Succs) {
455 Succs.resize(TI.getNumSuccessors());
456 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
457 if (BI->isUnconditional()) {
458 Succs[0] = true;
Chris Lattneradaf7332009-11-02 02:30:06 +0000459 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460 }
Chris Lattneradaf7332009-11-02 02:30:06 +0000461
Chris Lattner6367c3f2009-11-02 05:55:40 +0000462 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000463 ConstantInt *CI = BCValue.getConstantInt();
464 if (CI == 0) {
Chris Lattneradaf7332009-11-02 02:30:06 +0000465 // Overdefined condition variables, and branches on unfoldable constant
466 // conditions, mean the branch could go either way.
Chris Lattner220571c2009-11-02 03:21:36 +0000467 if (!BCValue.isUndefined())
468 Succs[0] = Succs[1] = true;
Chris Lattneradaf7332009-11-02 02:30:06 +0000469 return;
470 }
471
472 // Constant condition variables mean the branch can only go a single way.
Chris Lattner220571c2009-11-02 03:21:36 +0000473 Succs[CI->isZero()] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000474 return;
475 }
476
Chris Lattner220571c2009-11-02 03:21:36 +0000477 if (isa<InvokeInst>(TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000478 // Invoke instructions successors are always executable.
479 Succs[0] = Succs[1] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000480 return;
481 }
482
483 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000484 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000485 ConstantInt *CI = SCValue.getConstantInt();
486
487 if (CI == 0) { // Overdefined or undefined condition?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488 // All destinations are executable!
Chris Lattner220571c2009-11-02 03:21:36 +0000489 if (!SCValue.isUndefined())
490 Succs.assign(TI.getNumSuccessors(), true);
491 return;
492 }
493
494 Succs[SI->findCaseValue(CI)] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000495 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000496 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000497
498 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
499 if (isa<IndirectBrInst>(&TI)) {
500 // Just mark all destinations executable!
501 Succs.assign(TI.getNumSuccessors(), true);
502 return;
503 }
504
505#ifndef NDEBUG
506 errs() << "Unknown terminator instruction: " << TI << '\n';
507#endif
508 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000509}
510
511
512// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000513// block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514//
515bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
516 assert(BBExecutable.count(To) && "Dest should always be alive!");
517
518 // Make sure the source basic block is executable!!
519 if (!BBExecutable.count(From)) return false;
520
Chris Lattnerc8798002009-11-02 02:33:50 +0000521 // Check to make sure this edge itself is actually feasible now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000522 TerminatorInst *TI = From->getTerminator();
523 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
524 if (BI->isUnconditional())
525 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000526
Chris Lattner6367c3f2009-11-02 05:55:40 +0000527 LatticeVal BCValue = getValueState(BI->getCondition());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528
Chris Lattneradaf7332009-11-02 02:30:06 +0000529 // Overdefined condition variables mean the branch could go either way,
530 // undef conditions mean that neither edge is feasible yet.
Chris Lattner220571c2009-11-02 03:21:36 +0000531 ConstantInt *CI = BCValue.getConstantInt();
532 if (CI == 0)
533 return !BCValue.isUndefined();
Chris Lattneradaf7332009-11-02 02:30:06 +0000534
Chris Lattneradaf7332009-11-02 02:30:06 +0000535 // Constant condition variables mean the branch can only go a single way.
Chris Lattner220571c2009-11-02 03:21:36 +0000536 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000537 }
538
539 // Invoke instructions successors are always executable.
540 if (isa<InvokeInst>(TI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000542
543 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000544 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000545 ConstantInt *CI = SCValue.getConstantInt();
546
547 if (CI == 0)
548 return !SCValue.isUndefined();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000549
Chris Lattner220571c2009-11-02 03:21:36 +0000550 // Make sure to skip the "default value" which isn't a value
551 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
552 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
553 return SI->getSuccessor(i) == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554
Chris Lattner220571c2009-11-02 03:21:36 +0000555 // If the constant value is not equal to any of the branches, we must
556 // execute default branch.
557 return SI->getDefaultDest() == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000559
560 // Just mark all destinations executable!
561 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
562 if (isa<IndirectBrInst>(&TI))
563 return true;
564
565#ifndef NDEBUG
566 errs() << "Unknown terminator instruction: " << *TI << '\n';
567#endif
568 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000569}
570
Chris Lattnerc8798002009-11-02 02:33:50 +0000571// visit Implementations - Something changed in this instruction, either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000572// operand made a transition, or the instruction is newly executable. Change
573// the value type of I to reflect these changes if appropriate. This method
574// makes sure to do the following actions:
575//
576// 1. If a phi node merges two constants in, and has conflicting value coming
577// from different branches, or if the PHI node merges in an overdefined
578// value, then the PHI node becomes overdefined.
579// 2. If a phi node merges only constants in, and they all agree on value, the
580// PHI node becomes a constant value equal to that.
581// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
582// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
583// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
584// 6. If a conditional branch has a value that is constant, make the selected
585// destination executable
586// 7. If a conditional branch has a value that is overdefined, make all
587// successors executable.
588//
589void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000590 if (getValueState(&PN).isOverdefined()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591 // There may be instructions using this PHI node that are not overdefined
592 // themselves. If so, make sure that they know that the PHI node operand
593 // changed.
594 std::multimap<PHINode*, Instruction*>::iterator I, E;
595 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
Chris Lattner6367c3f2009-11-02 05:55:40 +0000596 if (I == E)
597 return;
598
599 SmallVector<Instruction*, 16> Users;
600 for (; I != E; ++I)
601 Users.push_back(I->second);
602 while (!Users.empty())
603 visit(Users.pop_back_val());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 return; // Quick exit
605 }
606
607 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
608 // and slow us down a lot. Just mark them overdefined.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000609 if (PN.getNumIncomingValues() > 64)
Chris Lattner6367c3f2009-11-02 05:55:40 +0000610 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611
612 // Look at all of the executable operands of the PHI node. If any of them
613 // are overdefined, the PHI becomes overdefined as well. If they are all
614 // constant, and they agree with each other, the PHI becomes the identical
615 // constant. If they are constant and don't agree, the PHI is overdefined.
616 // If there are no executable operands, the PHI remains undefined.
617 //
618 Constant *OperandVal = 0;
619 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000620 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
622
Chris Lattnerb52f7002009-11-02 03:03:42 +0000623 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
624 continue;
625
626 if (IV.isOverdefined()) // PHI node becomes overdefined!
627 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628
Chris Lattnerb52f7002009-11-02 03:03:42 +0000629 if (OperandVal == 0) { // Grab the first value.
630 OperandVal = IV.getConstant();
631 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 }
Chris Lattnerb52f7002009-11-02 03:03:42 +0000633
634 // There is already a reachable operand. If we conflict with it,
635 // then the PHI node becomes overdefined. If we agree with it, we
636 // can continue on.
637
638 // Check to see if there are two different constants merging, if so, the PHI
639 // node is overdefined.
640 if (IV.getConstant() != OperandVal)
641 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 }
643
644 // If we exited the loop, this means that the PHI node only has constant
645 // arguments that agree with each other(and OperandVal is the constant) or
646 // OperandVal is null because there are no defined incoming arguments. If
647 // this is the case, the PHI remains undefined.
648 //
649 if (OperandVal)
Chris Lattnerd3123a72008-08-23 23:36:38 +0000650 markConstant(&PN, OperandVal); // Acquire operand value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651}
652
Chris Lattner3a2499a2009-11-03 03:42:51 +0000653
654
655
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000657 if (I.getNumOperands() == 0) return; // ret void
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659 Function *F = I.getParent()->getParent();
Chris Lattner3a2499a2009-11-03 03:42:51 +0000660
Devang Pateladd320d2008-03-11 05:46:42 +0000661 // If we are tracking the return value of this function, merge it in.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000662 if (!TrackedRetVals.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Pateladd320d2008-03-11 05:46:42 +0000664 TrackedRetVals.find(F);
Chris Lattner3a2499a2009-11-03 03:42:51 +0000665 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000666 mergeInValue(TFRVI->second, F, getValueState(I.getOperand(0)));
Devang Pateladd320d2008-03-11 05:46:42 +0000667 return;
668 }
669 }
670
Chris Lattnercd73be02008-04-23 05:38:20 +0000671 // Handle functions that return multiple values.
Chris Lattnerc2a4e202009-11-02 06:17:06 +0000672 if (!TrackedMultipleRetVals.empty() &&
673 isa<StructType>(I.getOperand(0)->getType())) {
Dan Gohman856193b2008-06-20 01:15:44 +0000674 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
675 i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000676 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000677 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
678 if (It == TrackedMultipleRetVals.end()) break;
Owen Anderson175b6542009-07-22 00:24:57 +0000679 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewycky6ad29e02009-06-06 23:13:08 +0000680 mergeInValue(It->second, F, getValueState(Val));
Dan Gohman856193b2008-06-20 01:15:44 +0000681 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 }
683}
684
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
686 SmallVector<bool, 16> SuccFeasible;
687 getFeasibleSuccessors(TI, SuccFeasible);
688
689 BasicBlock *BB = TI.getParent();
690
Chris Lattnerc8798002009-11-02 02:33:50 +0000691 // Mark all feasible successors executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
693 if (SuccFeasible[i])
694 markEdgeExecutable(BB, TI.getSuccessor(i));
695}
696
697void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000698 LatticeVal OpSt = getValueState(I.getOperand(0));
699 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 markOverdefined(&I);
Chris Lattner6367c3f2009-11-02 05:55:40 +0000701 else if (OpSt.isConstant()) // Propagate constant value
Owen Anderson02b48c32009-07-29 18:55:55 +0000702 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattner6367c3f2009-11-02 05:55:40 +0000703 OpSt.getConstant(), I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704}
705
Dan Gohman856193b2008-06-20 01:15:44 +0000706void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000707 Value *Aggr = EVI.getAggregateOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000708
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000709 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohman856193b2008-06-20 01:15:44 +0000710 if (isa<UndefValue>(Aggr))
711 return;
712
713 // Currently only handle single-index extractvalues.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000714 if (EVI.getNumIndices() != 1)
715 return markOverdefined(&EVI);
Dan Gohman856193b2008-06-20 01:15:44 +0000716
717 Function *F = 0;
718 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
719 F = CI->getCalledFunction();
720 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
721 F = II->getCalledFunction();
722
723 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
724 // result back!
Chris Lattnerb52f7002009-11-02 03:03:42 +0000725 if (F == 0 || TrackedMultipleRetVals.empty())
726 return markOverdefined(&EVI);
Dan Gohman856193b2008-06-20 01:15:44 +0000727
Chris Lattnerd3123a72008-08-23 23:36:38 +0000728 // See if we are tracking the result of the callee. If not tracking this
729 // function (for example, it is a declaration) just move to overdefined.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000730 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin())))
731 return markOverdefined(&EVI);
Dan Gohman856193b2008-06-20 01:15:44 +0000732
733 // Otherwise, the value will be merged in here as a result of CallSite
734 // handling.
735}
736
737void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000738 Value *Aggr = IVI.getAggregateOperand();
739 Value *Val = IVI.getInsertedValueOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000740
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000741 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohman78b2c392008-06-20 16:39:44 +0000742 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohman856193b2008-06-20 01:15:44 +0000743 return;
744
745 // Currently only handle single-index insertvalues.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000746 if (IVI.getNumIndices() != 1)
747 return markOverdefined(&IVI);
Dan Gohman78b2c392008-06-20 16:39:44 +0000748
749 // Currently only handle insertvalue instructions that are in a single-use
750 // chain that builds up a return value.
751 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
Chris Lattnerb52f7002009-11-02 03:03:42 +0000752 if (!TmpIVI->hasOneUse())
753 return markOverdefined(&IVI);
754
Dan Gohman78b2c392008-06-20 16:39:44 +0000755 const Value *V = *TmpIVI->use_begin();
756 if (isa<ReturnInst>(V))
757 break;
758 TmpIVI = dyn_cast<InsertValueInst>(V);
Chris Lattnerb52f7002009-11-02 03:03:42 +0000759 if (!TmpIVI)
760 return markOverdefined(&IVI);
Dan Gohman78b2c392008-06-20 16:39:44 +0000761 }
Dan Gohman856193b2008-06-20 01:15:44 +0000762
763 // See if we are tracking the result of the callee.
764 Function *F = IVI.getParent()->getParent();
Chris Lattnerd3123a72008-08-23 23:36:38 +0000765 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000766 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
767
768 // Merge in the inserted member value.
769 if (It != TrackedMultipleRetVals.end())
770 mergeInValue(It->second, F, getValueState(Val));
771
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000772 // Mark the aggregate result of the IVI overdefined; any tracking that we do
773 // will be done on the individual member values.
Dan Gohman856193b2008-06-20 01:15:44 +0000774 markOverdefined(&IVI);
775}
776
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000777void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000778 LatticeVal CondValue = getValueState(I.getCondition());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779 if (CondValue.isUndefined())
780 return;
Chris Lattner220571c2009-11-02 03:21:36 +0000781
782 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000783 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
784 mergeInValue(&I, getValueState(OpVal));
Chris Lattner220571c2009-11-02 03:21:36 +0000785 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 }
787
788 // Otherwise, the condition is overdefined or a constant we can't evaluate.
789 // See if we can produce something better than overdefined based on the T/F
790 // value.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000791 LatticeVal TVal = getValueState(I.getTrueValue());
792 LatticeVal FVal = getValueState(I.getFalseValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000793
794 // select ?, C, C -> C.
795 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattnerb52f7002009-11-02 03:03:42 +0000796 TVal.getConstant() == FVal.getConstant())
797 return markConstant(&I, FVal.getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000798
Chris Lattner6367c3f2009-11-02 05:55:40 +0000799 if (TVal.isUndefined()) // select ?, undef, X -> X.
800 return mergeInValue(&I, FVal);
801 if (FVal.isUndefined()) // select ?, X, undef -> X.
802 return mergeInValue(&I, TVal);
803 markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804}
805
Chris Lattner6367c3f2009-11-02 05:55:40 +0000806// Handle Binary Operators.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000808 LatticeVal V1State = getValueState(I.getOperand(0));
809 LatticeVal V2State = getValueState(I.getOperand(1));
810
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 LatticeVal &IV = ValueState[&I];
812 if (IV.isOverdefined()) return;
813
Chris Lattner6367c3f2009-11-02 05:55:40 +0000814 if (V1State.isConstant() && V2State.isConstant())
815 return markConstant(IV, &I,
816 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
817 V2State.getConstant()));
818
819 // If something is undef, wait for it to resolve.
820 if (!V1State.isOverdefined() && !V2State.isOverdefined())
821 return;
822
823 // Otherwise, one of our operands is overdefined. Try to produce something
824 // better than overdefined with some tricks.
825
826 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
827 // operand is overdefined.
828 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
829 LatticeVal *NonOverdefVal = 0;
830 if (!V1State.isOverdefined())
831 NonOverdefVal = &V1State;
832 else if (!V2State.isOverdefined())
833 NonOverdefVal = &V2State;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834
Chris Lattner6367c3f2009-11-02 05:55:40 +0000835 if (NonOverdefVal) {
836 if (NonOverdefVal->isUndefined()) {
837 // Could annihilate value.
838 if (I.getOpcode() == Instruction::And)
839 markConstant(IV, &I, Constant::getNullValue(I.getType()));
840 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
841 markConstant(IV, &I, Constant::getAllOnesValue(PT));
842 else
843 markConstant(IV, &I,
844 Constant::getAllOnesValue(I.getType()));
845 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 }
Chris Lattner6367c3f2009-11-02 05:55:40 +0000847
848 if (I.getOpcode() == Instruction::And) {
849 // X and 0 = 0
850 if (NonOverdefVal->getConstant()->isNullValue())
851 return markConstant(IV, &I, NonOverdefVal->getConstant());
852 } else {
853 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
854 if (CI->isAllOnesValue()) // X or -1 = -1
855 return markConstant(IV, &I, NonOverdefVal->getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856 }
857 }
Chris Lattner6367c3f2009-11-02 05:55:40 +0000858 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000859
860
Chris Lattner6367c3f2009-11-02 05:55:40 +0000861 // If both operands are PHI nodes, it is possible that this instruction has
862 // a constant value, despite the fact that the PHI node doesn't. Check for
863 // this condition now.
864 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
865 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
866 if (PN1->getParent() == PN2->getParent()) {
867 // Since the two PHI nodes are in the same basic block, they must have
868 // entries for the same predecessors. Walk the predecessor list, and
869 // if all of the incoming values are constants, and the result of
870 // evaluating this expression with all incoming value pairs is the
871 // same, then this expression is a constant even though the PHI node
872 // is not a constant!
873 LatticeVal Result;
874 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
875 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
876 BasicBlock *InBlock = PN1->getIncomingBlock(i);
877 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000878
Chris Lattner6367c3f2009-11-02 05:55:40 +0000879 if (In1.isOverdefined() || In2.isOverdefined()) {
880 Result.markOverdefined();
881 break; // Cannot fold this operation over the PHI nodes!
882 }
883
884 if (In1.isConstant() && In2.isConstant()) {
885 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
886 In2.getConstant());
887 if (Result.isUndefined())
888 Result.markConstant(V);
889 else if (Result.isConstant() && Result.getConstant() != V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890 Result.markOverdefined();
Chris Lattner6367c3f2009-11-02 05:55:40 +0000891 break;
Chris Lattnerb52f7002009-11-02 03:03:42 +0000892 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 }
894 }
895
Chris Lattner6367c3f2009-11-02 05:55:40 +0000896 // If we found a constant value here, then we know the instruction is
897 // constant despite the fact that the PHI nodes are overdefined.
898 if (Result.isConstant()) {
899 markConstant(IV, &I, Result.getConstant());
900 // Remember that this instruction is virtually using the PHI node
901 // operands.
902 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
903 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
904 return;
905 }
906
907 if (Result.isUndefined())
908 return;
909
910 // Okay, this really is overdefined now. Since we might have
911 // speculatively thought that this was not overdefined before, and
912 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
913 // make sure to clean out any entries that we put there, for
914 // efficiency.
Chris Lattnere84f1232009-11-02 06:28:16 +0000915 RemoveFromOverdefinedPHIs(&I, PN1);
916 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner6367c3f2009-11-02 05:55:40 +0000917 }
918
919 markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920}
921
Chris Lattnerc8798002009-11-02 02:33:50 +0000922// Handle ICmpInst instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000924 LatticeVal V1State = getValueState(I.getOperand(0));
925 LatticeVal V2State = getValueState(I.getOperand(1));
926
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927 LatticeVal &IV = ValueState[&I];
928 if (IV.isOverdefined()) return;
929
Chris Lattner6367c3f2009-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
939 // If something is overdefined, use some tricks to avoid ending up and over
940 // defined if we can.
941
942 // If both operands are PHI nodes, it is possible that this instruction has
943 // a constant value, despite the fact that the PHI node doesn't. Check for
944 // this condition now.
945 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
946 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
947 if (PN1->getParent() == PN2->getParent()) {
948 // Since the two PHI nodes are in the same basic block, they must have
949 // entries for the same predecessors. Walk the predecessor list, and
950 // if all of the incoming values are constants, and the result of
951 // evaluating this expression with all incoming value pairs is the
952 // same, then this expression is a constant even though the PHI node
953 // is not a constant!
954 LatticeVal Result;
955 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
956 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
957 BasicBlock *InBlock = PN1->getIncomingBlock(i);
958 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000959
Chris Lattner6367c3f2009-11-02 05:55:40 +0000960 if (In1.isOverdefined() || In2.isOverdefined()) {
961 Result.markOverdefined();
962 break; // Cannot fold this operation over the PHI nodes!
963 }
964
965 if (In1.isConstant() && In2.isConstant()) {
966 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
967 In1.getConstant(),
968 In2.getConstant());
969 if (Result.isUndefined())
970 Result.markConstant(V);
971 else if (Result.isConstant() && Result.getConstant() != V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 Result.markOverdefined();
Chris Lattner6367c3f2009-11-02 05:55:40 +0000973 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974 }
975 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976 }
977
Chris Lattner6367c3f2009-11-02 05:55:40 +0000978 // If we found a constant value here, then we know the instruction is
979 // constant despite the fact that the PHI nodes are overdefined.
980 if (Result.isConstant()) {
981 markConstant(&I, Result.getConstant());
982 // Remember that this instruction is virtually using the PHI node
983 // operands.
984 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
985 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
986 return;
987 }
988
989 if (Result.isUndefined())
990 return;
991
992 // Okay, this really is overdefined now. Since we might have
993 // speculatively thought that this was not overdefined before, and
994 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
995 // make sure to clean out any entries that we put there, for
996 // efficiency.
Chris Lattnere84f1232009-11-02 06:28:16 +0000997 RemoveFromOverdefinedPHIs(&I, PN1);
998 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner6367c3f2009-11-02 05:55:40 +0000999 }
1000
1001 markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002}
1003
1004void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1005 // FIXME : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001006 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001007
1008#if 0
1009 LatticeVal &ValState = getValueState(I.getOperand(0));
1010 LatticeVal &IdxState = getValueState(I.getOperand(1));
1011
1012 if (ValState.isOverdefined() || IdxState.isOverdefined())
1013 markOverdefined(&I);
1014 else if(ValState.isConstant() && IdxState.isConstant())
1015 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1016 IdxState.getConstant()));
1017#endif
1018}
1019
1020void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1021 // FIXME : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001022 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023#if 0
1024 LatticeVal &ValState = getValueState(I.getOperand(0));
1025 LatticeVal &EltState = getValueState(I.getOperand(1));
1026 LatticeVal &IdxState = getValueState(I.getOperand(2));
1027
1028 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1029 IdxState.isOverdefined())
1030 markOverdefined(&I);
1031 else if(ValState.isConstant() && EltState.isConstant() &&
1032 IdxState.isConstant())
1033 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1034 EltState.getConstant(),
1035 IdxState.getConstant()));
1036 else if (ValState.isUndefined() && EltState.isConstant() &&
1037 IdxState.isConstant())
1038 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1039 EltState.getConstant(),
1040 IdxState.getConstant()));
1041#endif
1042}
1043
1044void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1045 // FIXME : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001046 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047#if 0
1048 LatticeVal &V1State = getValueState(I.getOperand(0));
1049 LatticeVal &V2State = getValueState(I.getOperand(1));
1050 LatticeVal &MaskState = getValueState(I.getOperand(2));
1051
1052 if (MaskState.isUndefined() ||
1053 (V1State.isUndefined() && V2State.isUndefined()))
1054 return; // Undefined output if mask or both inputs undefined.
1055
1056 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1057 MaskState.isOverdefined()) {
1058 markOverdefined(&I);
1059 } else {
1060 // A mix of constant/undef inputs.
1061 Constant *V1 = V1State.isConstant() ?
1062 V1State.getConstant() : UndefValue::get(I.getType());
1063 Constant *V2 = V2State.isConstant() ?
1064 V2State.getConstant() : UndefValue::get(I.getType());
1065 Constant *Mask = MaskState.isConstant() ?
1066 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1067 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1068 }
1069#endif
1070}
1071
Chris Lattnerc8798002009-11-02 02:33:50 +00001072// Handle getelementptr instructions. If all operands are constants then we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073// can turn this into a getelementptr ConstantExpr.
1074//
1075void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerdd355c42009-11-02 23:25:39 +00001076 if (ValueState[&I].isOverdefined()) return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001077
1078 SmallVector<Constant*, 8> Operands;
1079 Operands.reserve(I.getNumOperands());
1080
1081 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001082 LatticeVal State = getValueState(I.getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083 if (State.isUndefined())
Chris Lattnerc8798002009-11-02 02:33:50 +00001084 return; // Operands are not resolved yet.
1085
Chris Lattnerb52f7002009-11-02 03:03:42 +00001086 if (State.isOverdefined())
Chris Lattnerdd355c42009-11-02 23:25:39 +00001087 return markOverdefined(&I);
Chris Lattnerb52f7002009-11-02 03:03:42 +00001088
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089 assert(State.isConstant() && "Unknown state!");
1090 Operands.push_back(State.getConstant());
1091 }
1092
1093 Constant *Ptr = Operands[0];
Chris Lattner6367c3f2009-11-02 05:55:40 +00001094 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0]+1,
1095 Operands.size()-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096}
1097
Chris Lattner6367c3f2009-11-02 05:55:40 +00001098void SCCPSolver::visitStoreInst(StoreInst &SI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1100 return;
Chris Lattner6367c3f2009-11-02 05:55:40 +00001101
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1103 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1104 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1105
Chris Lattner6367c3f2009-11-02 05:55:40 +00001106 // Get the value we are storing into the global, then merge it.
1107 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 if (I->second.isOverdefined())
1109 TrackedGlobals.erase(I); // No need to keep tracking this!
1110}
1111
1112
1113// Handle load instructions. If the operand is a constant pointer to a constant
1114// global, we can replace the load with the loaded constant value!
1115void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001116 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattner0148bb22009-11-02 06:06:14 +00001117 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Chris Lattner6367c3f2009-11-02 05:55:40 +00001118
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 LatticeVal &IV = ValueState[&I];
1120 if (IV.isOverdefined()) return;
1121
Chris Lattner6367c3f2009-11-02 05:55:40 +00001122 if (!PtrVal.isConstant() || I.isVolatile())
1123 return markOverdefined(IV, &I);
1124
Chris Lattner0148bb22009-11-02 06:06:14 +00001125 Constant *Ptr = PtrVal.getConstant();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126
Chris Lattner6367c3f2009-11-02 05:55:40 +00001127 // load null -> null
1128 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1129 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1130
1131 // Transform load (constant global) into the value loaded.
1132 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattner0148bb22009-11-02 06:06:14 +00001133 if (!TrackedGlobals.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001134 // If we are tracking this global, merge in the known value for it.
1135 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1136 TrackedGlobals.find(GV);
1137 if (It != TrackedGlobals.end()) {
1138 mergeInValue(IV, &I, It->second);
1139 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 }
1141 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 }
1143
Chris Lattner0148bb22009-11-02 06:06:14 +00001144 // Transform load from a constant into a constant if possible.
1145 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1146 return markConstant(IV, &I, C);
Chris Lattner6367c3f2009-11-02 05:55:40 +00001147
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 // Otherwise we cannot say for certain what value this load will produce.
1149 // Bail out.
1150 markOverdefined(IV, &I);
1151}
1152
1153void SCCPSolver::visitCallSite(CallSite CS) {
1154 Function *F = CS.getCalledFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001155 Instruction *I = CS.getInstruction();
Chris Lattnercd73be02008-04-23 05:38:20 +00001156
1157 // The common case is that we aren't tracking the callee, either because we
1158 // are not doing interprocedural analysis or the callee is indirect, or is
1159 // external. Handle these cases first.
Chris Lattner3a2499a2009-11-03 03:42:51 +00001160 if (F == 0 || F->isDeclaration()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001161CallOverdefined:
1162 // Void return and not tracking callee, just bail.
Chris Lattner82cdc062009-10-05 05:54:46 +00001163 if (I->getType()->isVoidTy()) return;
Chris Lattnercd73be02008-04-23 05:38:20 +00001164
1165 // Otherwise, if we have a single return value case, and if the function is
1166 // a declaration, maybe we can constant fold it.
Chris Lattner3a2499a2009-11-03 03:42:51 +00001167 if (F && F->isDeclaration() && !isa<StructType>(I->getType()) &&
Chris Lattnercd73be02008-04-23 05:38:20 +00001168 canConstantFoldCallTo(F)) {
1169
1170 SmallVector<Constant*, 8> Operands;
1171 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1172 AI != E; ++AI) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001173 LatticeVal State = getValueState(*AI);
Chris Lattnerb52f7002009-11-02 03:03:42 +00001174
Chris Lattnercd73be02008-04-23 05:38:20 +00001175 if (State.isUndefined())
1176 return; // Operands are not resolved yet.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001177 if (State.isOverdefined())
1178 return markOverdefined(I);
Chris Lattnercd73be02008-04-23 05:38:20 +00001179 assert(State.isConstant() && "Unknown state!");
1180 Operands.push_back(State.getConstant());
1181 }
1182
1183 // If we can constant fold this, mark the result of the call as a
1184 // constant.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001185 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1186 return markConstant(I, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001188
1189 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001190 return markOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001191 }
1192
Chris Lattnercd73be02008-04-23 05:38:20 +00001193 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohman856193b2008-06-20 01:15:44 +00001194 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1195 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001196 // If so, propagate the return value of the callee into this call result.
1197 mergeInValue(I, TFRVI->second);
Dan Gohman856193b2008-06-20 01:15:44 +00001198 } else if (isa<StructType>(I->getType())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001199 // Check to see if we're tracking this callee, if not, handle it in the
1200 // common path above.
Chris Lattnerd3123a72008-08-23 23:36:38 +00001201 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1202 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnercd73be02008-04-23 05:38:20 +00001203 if (TMRVI == TrackedMultipleRetVals.end())
1204 goto CallOverdefined;
Edwin Töröka6174642009-10-20 15:15:09 +00001205
1206 // Need to mark as overdefined, otherwise it stays undefined which
1207 // creates extractvalue undef, <idx>
1208 markOverdefined(I);
Chris Lattnerb52f7002009-11-02 03:03:42 +00001209
Chris Lattnercd73be02008-04-23 05:38:20 +00001210 // If we are tracking this callee, propagate the return values of the call
Dan Gohman856193b2008-06-20 01:15:44 +00001211 // into this call site. We do this by walking all the uses. Single-index
1212 // ExtractValueInst uses can be tracked; anything more complicated is
1213 // currently handled conservatively.
Chris Lattnercd73be02008-04-23 05:38:20 +00001214 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1215 UI != E; ++UI) {
Dan Gohman856193b2008-06-20 01:15:44 +00001216 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1217 if (EVI->getNumIndices() == 1) {
1218 mergeInValue(EVI,
Dan Gohmanaa7b7802008-06-20 16:41:17 +00001219 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohman856193b2008-06-20 01:15:44 +00001220 continue;
1221 }
1222 }
1223 // The aggregate value is used in a way not handled here. Assume nothing.
1224 markOverdefined(*UI);
Chris Lattnercd73be02008-04-23 05:38:20 +00001225 }
Dan Gohman856193b2008-06-20 01:15:44 +00001226 } else {
1227 // Otherwise we're not tracking this callee, so handle it in the
1228 // common path above.
1229 goto CallOverdefined;
Chris Lattnercd73be02008-04-23 05:38:20 +00001230 }
Chris Lattner3a2499a2009-11-03 03:42:51 +00001231
Chris Lattnercd73be02008-04-23 05:38:20 +00001232 // Finally, if this is the first call to the function hit, mark its entry
1233 // block executable.
Chris Lattnera5ffa7c2009-11-02 06:11:23 +00001234 MarkBlockExecutable(F->begin());
Chris Lattnercd73be02008-04-23 05:38:20 +00001235
1236 // Propagate information from this call site into the callee.
1237 CallSite::arg_iterator CAI = CS.arg_begin();
1238 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1239 AI != E; ++AI, ++CAI) {
Chris Lattner3a2499a2009-11-03 03:42:51 +00001240 // If this argument is byval, and if the function is not readonly, there
1241 // will be an implicit copy formed of the input aggregate.
Edwin Török129b2d12009-09-24 18:33:42 +00001242 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001243 markOverdefined(AI);
Edwin Törökd5435372009-09-24 09:47:18 +00001244 continue;
1245 }
Chris Lattner6367c3f2009-11-02 05:55:40 +00001246
1247 mergeInValue(AI, getValueState(*CAI));
Chris Lattnercd73be02008-04-23 05:38:20 +00001248 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001249}
1250
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251void SCCPSolver::Solve() {
1252 // Process the work lists until they are empty!
1253 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1254 !OverdefinedInstWorkList.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001255 // Process the overdefined instruction's work list first, which drives other
1256 // things to overdefined more quickly.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001258 Value *I = OverdefinedInstWorkList.pop_back_val();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259
Dan Gohmandff8d172009-08-17 15:25:05 +00001260 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001261
1262 // "I" got into the work list because it either made the transition from
1263 // bottom to constant
1264 //
1265 // Anything on this worklist that is overdefined need not be visited
1266 // since all of its users will have already been marked as overdefined
Chris Lattnerc8798002009-11-02 02:33:50 +00001267 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 //
1269 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1270 UI != E; ++UI)
Chris Lattner3a2499a2009-11-03 03:42:51 +00001271 if (Instruction *I = dyn_cast<Instruction>(*UI))
1272 OperandChangedState(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 }
Chris Lattnerc8798002009-11-02 02:33:50 +00001274
1275 // Process the instruction work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276 while (!InstWorkList.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001277 Value *I = InstWorkList.pop_back_val();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278
Dan Gohmandff8d172009-08-17 15:25:05 +00001279 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001280
Chris Lattner6367c3f2009-11-02 05:55:40 +00001281 // "I" got into the work list because it made the transition from undef to
1282 // constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 //
1284 // Anything on this worklist that is overdefined need not be visited
1285 // since all of its users will have already been marked as overdefined.
Chris Lattnerc8798002009-11-02 02:33:50 +00001286 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287 //
1288 if (!getValueState(I).isOverdefined())
1289 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1290 UI != E; ++UI)
Chris Lattner3a2499a2009-11-03 03:42:51 +00001291 if (Instruction *I = dyn_cast<Instruction>(*UI))
1292 OperandChangedState(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 }
1294
Chris Lattnerc8798002009-11-02 02:33:50 +00001295 // Process the basic block work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001296 while (!BBWorkList.empty()) {
1297 BasicBlock *BB = BBWorkList.back();
1298 BBWorkList.pop_back();
1299
Dan Gohmandff8d172009-08-17 15:25:05 +00001300 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301
1302 // Notify all instructions in this basic block that they are newly
1303 // executable.
1304 visit(BB);
1305 }
1306 }
1307}
1308
1309/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1310/// that branches on undef values cannot reach any of their successors.
1311/// However, this is not a safe assumption. After we solve dataflow, this
1312/// method should be use to handle this. If this returns true, the solver
1313/// should be rerun.
1314///
1315/// This method handles this by finding an unresolved branch and marking it one
1316/// of the edges from the block as being feasible, even though the condition
1317/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1318/// CFG and only slightly pessimizes the analysis results (by marking one,
1319/// potentially infeasible, edge feasible). This cannot usefully modify the
1320/// constraints on the condition of the branch, as that would impact other users
1321/// of the value.
1322///
1323/// This scan also checks for values that use undefs, whose results are actually
1324/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1325/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1326/// even if X isn't defined.
1327bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1328 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1329 if (!BBExecutable.count(BB))
1330 continue;
1331
1332 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1333 // Look for instructions which produce undef values.
Chris Lattner82cdc062009-10-05 05:54:46 +00001334 if (I->getType()->isVoidTy()) continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335
1336 LatticeVal &LV = getValueState(I);
1337 if (!LV.isUndefined()) continue;
1338
1339 // Get the lattice values of the first two operands for use below.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001340 LatticeVal Op0LV = getValueState(I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 LatticeVal Op1LV;
1342 if (I->getNumOperands() == 2) {
1343 // If this is a two-operand instruction, and if both operands are
1344 // undefs, the result stays undef.
1345 Op1LV = getValueState(I->getOperand(1));
1346 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1347 continue;
1348 }
1349
1350 // If this is an instructions whose result is defined even if the input is
1351 // not fully defined, propagate the information.
1352 const Type *ITy = I->getType();
1353 switch (I->getOpcode()) {
1354 default: break; // Leave the instruction as an undef.
1355 case Instruction::ZExt:
1356 // After a zero extend, we know the top part is zero. SExt doesn't have
1357 // to be handled here, because we don't know whether the top part is 1's
1358 // or 0's.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001359 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 return true;
1361 case Instruction::Mul:
1362 case Instruction::And:
1363 // undef * X -> 0. X could be zero.
1364 // undef & X -> 0. X could be zero.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001365 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001366 return true;
1367
1368 case Instruction::Or:
1369 // undef | X -> -1. X could be -1.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001370 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371 return true;
1372
1373 case Instruction::SDiv:
1374 case Instruction::UDiv:
1375 case Instruction::SRem:
1376 case Instruction::URem:
1377 // X / undef -> undef. No change.
1378 // X % undef -> undef. No change.
1379 if (Op1LV.isUndefined()) break;
1380
1381 // undef / X -> 0. X could be maxint.
1382 // undef % X -> 0. X could be 1.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001383 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001384 return true;
1385
1386 case Instruction::AShr:
1387 // undef >>s X -> undef. No change.
1388 if (Op0LV.isUndefined()) break;
1389
1390 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1391 if (Op0LV.isConstant())
Chris Lattner6367c3f2009-11-02 05:55:40 +00001392 markForcedConstant(I, Op0LV.getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393 else
Chris Lattner6367c3f2009-11-02 05:55:40 +00001394 markOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001395 return true;
1396 case Instruction::LShr:
1397 case Instruction::Shl:
1398 // undef >> X -> undef. No change.
1399 // undef << X -> undef. No change.
1400 if (Op0LV.isUndefined()) break;
1401
1402 // X >> undef -> 0. X could be 0.
1403 // X << undef -> 0. X could be 0.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001404 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405 return true;
1406 case Instruction::Select:
1407 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1408 if (Op0LV.isUndefined()) {
1409 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1410 Op1LV = getValueState(I->getOperand(2));
1411 } else if (Op1LV.isUndefined()) {
1412 // c ? undef : undef -> undef. No change.
1413 Op1LV = getValueState(I->getOperand(2));
1414 if (Op1LV.isUndefined())
1415 break;
1416 // Otherwise, c ? undef : x -> x.
1417 } else {
1418 // Leave Op1LV as Operand(1)'s LatticeValue.
1419 }
1420
1421 if (Op1LV.isConstant())
Chris Lattner6367c3f2009-11-02 05:55:40 +00001422 markForcedConstant(I, Op1LV.getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423 else
Chris Lattner6367c3f2009-11-02 05:55:40 +00001424 markOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001425 return true;
Chris Lattner9110ac92008-05-24 03:59:33 +00001426 case Instruction::Call:
1427 // If a call has an undef result, it is because it is constant foldable
1428 // but one of the inputs was undef. Just force the result to
1429 // overdefined.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001430 markOverdefined(I);
Chris Lattner9110ac92008-05-24 03:59:33 +00001431 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001432 }
1433 }
1434
1435 TerminatorInst *TI = BB->getTerminator();
1436 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1437 if (!BI->isConditional()) continue;
1438 if (!getValueState(BI->getCondition()).isUndefined())
1439 continue;
1440 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001441 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesenfb06d0c2008-05-23 01:01:31 +00001442 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001443 if (!getValueState(SI->getCondition()).isUndefined())
1444 continue;
1445 } else {
1446 continue;
1447 }
1448
Chris Lattner6186e8c2008-01-28 00:32:30 +00001449 // If the edge to the second successor isn't thought to be feasible yet,
1450 // mark it so now. We pick the second one so that this goes to some
1451 // enumerated value in a switch instead of going to the default destination.
1452 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453 continue;
1454
1455 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1456 // and return. This will make other blocks reachable, which will allow new
1457 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner6186e8c2008-01-28 00:32:30 +00001458 markEdgeExecutable(BB, TI->getSuccessor(1));
1459
1460 // This must be a conditional branch of switch on undef. At this point,
1461 // force the old terminator to branch to the first successor. This is
1462 // required because we are now influencing the dataflow of the function with
1463 // the assumption that this edge is taken. If we leave the branch condition
1464 // as undef, then further analysis could think the undef went another way
1465 // leading to an inconsistent set of conclusions.
1466 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001467 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner6186e8c2008-01-28 00:32:30 +00001468 } else {
1469 SwitchInst *SI = cast<SwitchInst>(TI);
1470 SI->setCondition(SI->getCaseValue(1));
1471 }
1472
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001473 return true;
1474 }
1475
1476 return false;
1477}
1478
1479
1480namespace {
1481 //===--------------------------------------------------------------------===//
1482 //
1483 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1484 /// Sparse Conditional Constant Propagator.
1485 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001486 struct SCCP : public FunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001487 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +00001488 SCCP() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001489
1490 // runOnFunction - Run the Sparse Conditional Constant Propagation
1491 // algorithm, and return true if the function was modified.
1492 //
1493 bool runOnFunction(Function &F);
1494
1495 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1496 AU.setPreservesCFG();
1497 }
1498 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001499} // end anonymous namespace
1500
Dan Gohman089efff2008-05-13 00:00:25 +00001501char SCCP::ID = 0;
1502static RegisterPass<SCCP>
1503X("sccp", "Sparse Conditional Constant Propagation");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001504
Chris Lattnerc8798002009-11-02 02:33:50 +00001505// createSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001506FunctionPass *llvm::createSCCPPass() {
1507 return new SCCP();
1508}
1509
Chris Lattner14513dc2009-11-02 02:47:51 +00001510static void DeleteInstructionInBlock(BasicBlock *BB) {
1511 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1512 ++NumDeadBlocks;
1513
1514 // Delete the instructions backwards, as it has a reduced likelihood of
1515 // having to update as many def-use and use-def chains.
1516 while (!isa<TerminatorInst>(BB->begin())) {
1517 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1518
1519 if (!I->use_empty())
1520 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1521 BB->getInstList().erase(I);
1522 ++NumInstRemoved;
1523 }
1524}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001525
1526// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1527// and return true if the function was modified.
1528//
1529bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001530 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner0148bb22009-11-02 06:06:14 +00001531 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001532
1533 // Mark the first block of the function as being executable.
1534 Solver.MarkBlockExecutable(F.begin());
1535
1536 // Mark all arguments to the function as being overdefined.
1537 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1538 Solver.markOverdefined(AI);
1539
1540 // Solve for constants.
1541 bool ResolvedUndefs = true;
1542 while (ResolvedUndefs) {
1543 Solver.Solve();
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001544 DEBUG(errs() << "RESOLVING UNDEFs\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001545 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1546 }
1547
1548 bool MadeChanges = false;
1549
1550 // If we decided that there are basic blocks that are dead in this function,
1551 // delete their contents now. Note that we cannot actually delete the blocks,
1552 // as we cannot modify the CFG of the function.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001553
Chris Lattner14513dc2009-11-02 02:47:51 +00001554 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner317e6b62008-08-23 23:39:31 +00001555 if (!Solver.isBlockExecutable(BB)) {
Chris Lattner14513dc2009-11-02 02:47:51 +00001556 DeleteInstructionInBlock(BB);
1557 MadeChanges = true;
1558 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001559 }
Chris Lattner14513dc2009-11-02 02:47:51 +00001560
1561 // Iterate over all of the instructions in a function, replacing them with
1562 // constants if we have found them to be of constant values.
1563 //
1564 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1565 Instruction *Inst = BI++;
1566 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1567 continue;
1568
Chris Lattnerc9edab82009-11-02 02:54:24 +00001569 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1570 if (IV.isOverdefined())
Chris Lattner14513dc2009-11-02 02:47:51 +00001571 continue;
1572
1573 Constant *Const = IV.isConstant()
1574 ? IV.getConstant() : UndefValue::get(Inst->getType());
1575 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1576
1577 // Replaces all of the uses of a variable with uses of the constant.
1578 Inst->replaceAllUsesWith(Const);
1579
1580 // Delete the instruction.
1581 Inst->eraseFromParent();
1582
1583 // Hey, we just changed something!
1584 MadeChanges = true;
1585 ++NumInstRemoved;
1586 }
1587 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001588
1589 return MadeChanges;
1590}
1591
1592namespace {
1593 //===--------------------------------------------------------------------===//
1594 //
1595 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1596 /// Constant Propagation.
1597 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001598 struct IPSCCP : public ModulePass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001599 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +00001600 IPSCCP() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001601 bool runOnModule(Module &M);
1602 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001603} // end anonymous namespace
1604
Dan Gohman089efff2008-05-13 00:00:25 +00001605char IPSCCP::ID = 0;
1606static RegisterPass<IPSCCP>
1607Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1608
Chris Lattnerc8798002009-11-02 02:33:50 +00001609// createIPSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001610ModulePass *llvm::createIPSCCPPass() {
1611 return new IPSCCP();
1612}
1613
1614
1615static bool AddressIsTaken(GlobalValue *GV) {
1616 // Delete any dead constantexpr klingons.
1617 GV->removeDeadConstantUsers();
1618
1619 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1620 UI != E; ++UI)
1621 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1622 if (SI->getOperand(0) == GV || SI->isVolatile())
1623 return true; // Storing addr of GV.
1624 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1625 // Make sure we are calling the function, not passing the address.
Chris Lattner2f487502009-11-01 06:11:53 +00001626 if (UI.getOperandNo() != 0)
Nick Lewycky1cc2e102008-11-03 03:49:14 +00001627 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001628 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1629 if (LI->isVolatile())
1630 return true;
Chris Lattner2f487502009-11-01 06:11:53 +00001631 } else if (isa<BlockAddress>(*UI)) {
1632 // blockaddress doesn't take the address of the function, it takes addr
1633 // of label.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001634 } else {
1635 return true;
1636 }
1637 return false;
1638}
1639
1640bool IPSCCP::runOnModule(Module &M) {
Chris Lattner0148bb22009-11-02 06:06:14 +00001641 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642
1643 // Loop over all functions, marking arguments to those with their addresses
1644 // taken or that are external as overdefined.
1645 //
Chris Lattner74f9ed22009-11-02 06:34:04 +00001646 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1647 if (F->isDeclaration())
1648 continue;
1649
Chris Lattner3a2499a2009-11-03 03:42:51 +00001650 // If this is a strong or ODR definition of this function, then we can
1651 // propagate information about its result into callsites of it.
1652 if (!F->mayBeOverridden() &&
1653 !isa<StructType>(F->getReturnType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001654 Solver.AddTrackedFunction(F);
Chris Lattner3a2499a2009-11-03 03:42:51 +00001655
1656 // If this function only has direct calls that we can see, we can track its
1657 // arguments and return value aggressively, and can assume it is not called
1658 // unless we see evidence to the contrary.
1659 if (F->hasLocalLinkage() && !AddressIsTaken(F))
1660 continue;
1661
1662 // Assume the function is called.
1663 Solver.MarkBlockExecutable(F->begin());
1664
1665 // Assume nothing about the incoming arguments.
1666 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1667 AI != E; ++AI)
1668 Solver.markOverdefined(AI);
Chris Lattner74f9ed22009-11-02 06:34:04 +00001669 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001670
1671 // Loop over global variables. We inform the solver about any internal global
1672 // variables that do not have their 'addresses taken'. If they don't have
1673 // their addresses taken, we can propagate constants through them.
1674 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1675 G != E; ++G)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001676 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001677 Solver.TrackValueOfGlobalVariable(G);
1678
1679 // Solve for constants.
1680 bool ResolvedUndefs = true;
1681 while (ResolvedUndefs) {
1682 Solver.Solve();
1683
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001684 DEBUG(errs() << "RESOLVING UNDEFS\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001685 ResolvedUndefs = false;
1686 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1687 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1688 }
1689
1690 bool MadeChanges = false;
1691
1692 // Iterate over all of the instructions in the module, replacing them with
1693 // constants if we have found them to be of constant values.
1694 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001695 SmallVector<BasicBlock*, 512> BlocksToErase;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001696
1697 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner84388f12009-11-02 03:25:55 +00001698 if (Solver.isBlockExecutable(F->begin())) {
1699 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1700 AI != E; ++AI) {
1701 if (AI->use_empty()) continue;
1702
1703 LatticeVal IV = Solver.getLatticeValueFor(AI);
1704 if (IV.isOverdefined()) continue;
1705
1706 Constant *CST = IV.isConstant() ?
1707 IV.getConstant() : UndefValue::get(AI->getType());
1708 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1709
1710 // Replaces all of the uses of a variable with uses of the
1711 // constant.
1712 AI->replaceAllUsesWith(CST);
1713 ++IPNumArgsElimed;
1714 }
Chris Lattnerc9edab82009-11-02 02:54:24 +00001715 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001716
Chris Lattner14513dc2009-11-02 02:47:51 +00001717 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner317e6b62008-08-23 23:39:31 +00001718 if (!Solver.isBlockExecutable(BB)) {
Chris Lattner14513dc2009-11-02 02:47:51 +00001719 DeleteInstructionInBlock(BB);
1720 MadeChanges = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001721
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001722 TerminatorInst *TI = BB->getTerminator();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001723 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1724 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohman3f7d94b2007-10-03 19:26:29 +00001725 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001726 TI->getSuccessor(i)->removePredecessor(BB);
1727 }
1728 if (!TI->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001729 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner14513dc2009-11-02 02:47:51 +00001730 TI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001731
1732 if (&*BB != &F->front())
1733 BlocksToErase.push_back(BB);
1734 else
Owen Anderson35b47072009-08-13 21:58:54 +00001735 new UnreachableInst(M.getContext(), BB);
Chris Lattner14513dc2009-11-02 02:47:51 +00001736 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001737 }
Chris Lattner14513dc2009-11-02 02:47:51 +00001738
1739 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1740 Instruction *Inst = BI++;
1741 if (Inst->getType()->isVoidTy())
1742 continue;
1743
Chris Lattnerc9edab82009-11-02 02:54:24 +00001744 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1745 if (IV.isOverdefined())
Chris Lattner14513dc2009-11-02 02:47:51 +00001746 continue;
1747
1748 Constant *Const = IV.isConstant()
1749 ? IV.getConstant() : UndefValue::get(Inst->getType());
1750 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1751
1752 // Replaces all of the uses of a variable with uses of the
1753 // constant.
1754 Inst->replaceAllUsesWith(Const);
1755
1756 // Delete the instruction.
1757 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1758 Inst->eraseFromParent();
1759
1760 // Hey, we just changed something!
1761 MadeChanges = true;
1762 ++IPNumInstRemoved;
1763 }
1764 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001765
1766 // Now that all instructions in the function are constant folded, erase dead
1767 // blocks, because we can now use ConstantFoldTerminator to get rid of
1768 // in-edges.
1769 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1770 // If there are any PHI nodes in this successor, drop entries for BB now.
1771 BasicBlock *DeadBB = BlocksToErase[i];
1772 while (!DeadBB->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001773 Instruction *I = cast<Instruction>(DeadBB->use_back());
1774 bool Folded = ConstantFoldTerminator(I->getParent());
1775 if (!Folded) {
1776 // The constant folder may not have been able to fold the terminator
1777 // if this is a branch or switch on undef. Fold it manually as a
1778 // branch to the first successor.
Devang Patele92c16d2008-11-21 01:52:59 +00001779#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001780 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1781 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1782 "Branch should be foldable!");
1783 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1784 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1785 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001786 llvm_unreachable("Didn't fold away reference to block!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001787 }
Devang Patele92c16d2008-11-21 01:52:59 +00001788#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001789
1790 // Make this an uncond branch to the first successor.
1791 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001792 BranchInst::Create(TI->getSuccessor(0), TI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001793
1794 // Remove entries in successor phi nodes to remove edges.
1795 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1796 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1797
1798 // Remove the old terminator.
1799 TI->eraseFromParent();
1800 }
1801 }
1802
1803 // Finally, delete the basic block.
1804 F->getBasicBlockList().erase(DeadBB);
1805 }
1806 BlocksToErase.clear();
1807 }
1808
1809 // If we inferred constant or undef return values for a function, we replaced
1810 // all call uses with the inferred value. This means we don't need to bother
1811 // actually returning anything from the function. Replace all return
1812 // instructions with return undef.
Devang Pateld04d42b2008-03-11 17:32:05 +00001813 // TODO: Process multiple value ret instructions also.
Devang Pateladd320d2008-03-11 05:46:42 +00001814 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001815 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner3a2499a2009-11-03 03:42:51 +00001816 E = RV.end(); I != E; ++I) {
1817 Function *F = I->first;
1818 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1819 continue;
1820
1821 // We can only do this if we know that nothing else can call the function.
1822 if (!F->hasLocalLinkage() || AddressIsTaken(F))
1823 continue;
1824
1825 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1826 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1827 if (!isa<UndefValue>(RI->getOperand(0)))
1828 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1829 }
1830
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001831 // If we infered constant or undef values for globals variables, we can delete
1832 // the global and any stores that remain to it.
1833 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1834 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1835 E = TG.end(); I != E; ++I) {
1836 GlobalVariable *GV = I->first;
1837 assert(!I->second.isOverdefined() &&
1838 "Overdefined values should have been taken out of the map!");
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001839 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001840 while (!GV->use_empty()) {
1841 StoreInst *SI = cast<StoreInst>(GV->use_back());
1842 SI->eraseFromParent();
1843 }
1844 M.getGlobalList().erase(GV);
1845 ++IPNumGlobalConst;
1846 }
1847
1848 return MadeChanges;
1849}