blob: 0451cb32cae2289b74b98bf52249fd653068adac [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"
Owen Andersonfa089ab2009-07-03 19:42:02 +000026#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/Pass.h"
28#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000029#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohman856193b2008-06-20 01:15:44 +000030#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/Transforms/Utils/Local.h"
32#include "llvm/Support/CallSite.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000034#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include "llvm/Support/InstVisitor.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000036#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/ADT/DenseMap.h"
Chris Lattnerd3123a72008-08-23 23:36:38 +000038#include "llvm/ADT/DenseSet.h"
Chris Lattner1eb405b2009-11-02 02:20:32 +000039#include "llvm/ADT/PointerIntPair.h"
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(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
52STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
53STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
54
55namespace {
56/// LatticeVal class - This class represents the different lattice values that
57/// an LLVM value may occupy. It is a simple class with value semantics.
58///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +000059class LatticeVal {
Chris Lattner1eb405b2009-11-02 02:20:32 +000060 enum LatticeValueTy {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061 /// undefined - This LLVM Value has no known value yet.
62 undefined,
63
64 /// constant - This LLVM Value has a specific constant value.
65 constant,
66
67 /// forcedconstant - This LLVM Value was thought to be undef until
68 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
69 /// with another (different) constant, it goes to overdefined, instead of
70 /// asserting.
71 forcedconstant,
72
73 /// overdefined - This instruction is not known to be constant, and we know
74 /// it has a value.
75 overdefined
Chris Lattner1eb405b2009-11-02 02:20:32 +000076 };
77
78 /// Val: This stores the current lattice value along with the Constant* for
79 /// the constant if this is a 'constant' or 'forcedconstant' value.
80 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081
Chris Lattner1eb405b2009-11-02 02:20:32 +000082 LatticeValueTy getLatticeValue() const {
83 return Val.getInt();
84 }
85
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086public:
Chris Lattner1eb405b2009-11-02 02:20:32 +000087 inline LatticeVal() : Val(0, undefined) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088
Chris Lattner1eb405b2009-11-02 02:20:32 +000089 inline bool isUndefined() const { return getLatticeValue() == undefined; }
90 inline bool isConstant() const {
91 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
92 }
93 inline bool isOverdefined() const { return getLatticeValue() == overdefined; }
94
95 inline Constant *getConstant() const {
96 assert(isConstant() && "Cannot get the constant of a non-constant!");
97 return Val.getPointer();
98 }
99
100 /// markOverdefined - Return true if this is a change in status.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101 inline bool markOverdefined() {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000102 if (isOverdefined())
103 return false;
104
105 Val.setInt(overdefined);
106 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 }
108
Chris Lattner1eb405b2009-11-02 02:20:32 +0000109 /// markConstant - Return true if this is a change in status.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000110 inline bool markConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000111 if (isConstant()) {
112 assert(getConstant() == V && "Marking constant with different value");
113 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114 }
Chris Lattner1eb405b2009-11-02 02:20:32 +0000115
116 if (isUndefined()) {
117 Val.setInt(constant);
118 assert(V && "Marking constant with NULL");
119 Val.setPointer(V);
120 } else {
121 assert(getLatticeValue() == forcedconstant &&
122 "Cannot move from overdefined to constant!");
123 // Stay at forcedconstant if the constant is the same.
124 if (V == getConstant()) return false;
125
126 // Otherwise, we go to overdefined. Assumptions made based on the
127 // forced value are possibly wrong. Assuming this is another constant
128 // could expose a contradiction.
129 Val.setInt(overdefined);
130 }
131 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 }
133
134 inline void markForcedConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000135 assert(isUndefined() && "Can't force a defined value!");
136 Val.setInt(forcedconstant);
137 Val.setPointer(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 }
139};
140
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141//===----------------------------------------------------------------------===//
142//
143/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
144/// Constant Propagation.
145///
146class SCCPSolver : public InstVisitor<SCCPSolver> {
Owen Anderson5349f052009-07-06 23:00:19 +0000147 LLVMContext *Context;
Chris Lattnerd3123a72008-08-23 23:36:38 +0000148 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Bill Wendling03488ae2008-08-14 23:05:24 +0000149 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150
151 /// GlobalValue - If we are tracking any values for the contents of a global
152 /// variable, we keep a mapping from the constant accessor to the element of
153 /// the global, to the currently known value. If the value becomes
154 /// overdefined, it's entry is simply removed from this map.
155 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
156
Devang Pateladd320d2008-03-11 05:46:42 +0000157 /// TrackedRetVals - If we are tracking arguments into and the return
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 /// value out of a function, it will have an entry in this map, indicating
159 /// what the known return value for the function is.
Devang Pateladd320d2008-03-11 05:46:42 +0000160 DenseMap<Function*, LatticeVal> TrackedRetVals;
161
162 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
163 /// that return multiple values.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000164 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165
166 // The reason for two worklists is that overdefined is the lowest state
167 // on the lattice, and moving things to overdefined as fast as possible
168 // makes SCCP converge much faster.
169 // By having a separate worklist, we accomplish this because everything
170 // possibly overdefined will become overdefined at the soonest possible
171 // point.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000172 SmallVector<Value*, 64> OverdefinedInstWorkList;
173 SmallVector<Value*, 64> InstWorkList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174
175
Chris Lattnerd3123a72008-08-23 23:36:38 +0000176 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177
178 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
179 /// overdefined, despite the fact that the PHI node is overdefined.
180 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
181
182 /// KnownFeasibleEdges - Entries in this set are edges which have already had
183 /// PHI nodes retriggered.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000184 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
185 DenseSet<Edge> KnownFeasibleEdges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186public:
Owen Anderson5349f052009-07-06 23:00:19 +0000187 void setContext(LLVMContext *C) { Context = C; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188
189 /// MarkBlockExecutable - This method can be used by clients to mark all of
190 /// the blocks that are known to be intrinsically live in the processed unit.
191 void MarkBlockExecutable(BasicBlock *BB) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000192 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 BBExecutable.insert(BB); // Basic block is executable!
194 BBWorkList.push_back(BB); // Add the block to the work list!
195 }
196
197 /// TrackValueOfGlobalVariable - Clients can use this method to
198 /// inform the SCCPSolver that it should track loads and stores to the
199 /// specified global variable if it can. This is only legal to call if
200 /// performing Interprocedural SCCP.
201 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
202 const Type *ElTy = GV->getType()->getElementType();
203 if (ElTy->isFirstClassType()) {
204 LatticeVal &IV = TrackedGlobals[GV];
205 if (!isa<UndefValue>(GV->getInitializer()))
206 IV.markConstant(GV->getInitializer());
207 }
208 }
209
210 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
211 /// and out of the specified function (which cannot have its address taken),
212 /// this method must be called.
213 void AddTrackedFunction(Function *F) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000214 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 // Add an entry, F -> undef.
Devang Pateladd320d2008-03-11 05:46:42 +0000216 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
217 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnercd73be02008-04-23 05:38:20 +0000218 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
219 LatticeVal()));
220 } else
221 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 }
223
224 /// Solve - Solve for constants and executable blocks.
225 ///
226 void Solve();
227
228 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
229 /// that branches on undef values cannot reach any of their successors.
230 /// However, this is not a safe assumption. After we solve dataflow, this
231 /// method should be use to handle this. If this returns true, the solver
232 /// should be rerun.
233 bool ResolvedUndefsIn(Function &F);
234
Chris Lattner317e6b62008-08-23 23:39:31 +0000235 bool isBlockExecutable(BasicBlock *BB) const {
236 return BBExecutable.count(BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 }
238
239 /// getValueMapping - Once we have solved for constants, return the mapping of
240 /// LLVM values to LatticeVals.
Bill Wendling03488ae2008-08-14 23:05:24 +0000241 std::map<Value*, LatticeVal> &getValueMapping() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 return ValueState;
243 }
244
Devang Pateladd320d2008-03-11 05:46:42 +0000245 /// getTrackedRetVals - Get the inferred return value map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 ///
Devang Pateladd320d2008-03-11 05:46:42 +0000247 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
248 return TrackedRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 }
250
251 /// getTrackedGlobals - Get and return the set of inferred initializers for
252 /// global variables.
253 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
254 return TrackedGlobals;
255 }
256
257 inline void markOverdefined(Value *V) {
258 markOverdefined(ValueState[V], V);
259 }
260
261private:
262 // markConstant - Make a value be marked as "constant". If the value
263 // is not already a constant, add it to the instruction work list so that
264 // the users of the instruction are updated later.
265 //
266 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
267 if (IV.markConstant(C)) {
Dan Gohmandff8d172009-08-17 15:25:05 +0000268 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 InstWorkList.push_back(V);
270 }
271 }
272
273 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
274 IV.markForcedConstant(C);
Dan Gohmandff8d172009-08-17 15:25:05 +0000275 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 InstWorkList.push_back(V);
277 }
278
279 inline void markConstant(Value *V, Constant *C) {
280 markConstant(ValueState[V], V, C);
281 }
282
283 // markOverdefined - Make a value be marked as "overdefined". If the
284 // value is not already overdefined, add it to the overdefined instruction
285 // work list so that the users of the instruction are updated later.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 inline void markOverdefined(LatticeVal &IV, Value *V) {
287 if (IV.markOverdefined()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +0000288 DEBUG(errs() << "markOverdefined: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 if (Function *F = dyn_cast<Function>(V))
Daniel Dunbar005975c2009-07-25 00:23:56 +0000290 errs() << "Function '" << F->getName() << "'\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291 else
Dan Gohmandff8d172009-08-17 15:25:05 +0000292 errs() << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293 // Only instructions go on the work list
294 OverdefinedInstWorkList.push_back(V);
295 }
296 }
297
298 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
299 if (IV.isOverdefined() || MergeWithV.isUndefined())
300 return; // Noop.
301 if (MergeWithV.isOverdefined())
302 markOverdefined(IV, V);
303 else if (IV.isUndefined())
304 markConstant(IV, V, MergeWithV.getConstant());
305 else if (IV.getConstant() != MergeWithV.getConstant())
306 markOverdefined(IV, V);
307 }
308
309 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
310 return mergeInValue(ValueState[V], V, MergeWithV);
311 }
312
313
314 // getValueState - Return the LatticeVal object that corresponds to the value.
315 // This function is necessary because not all values should start out in the
316 // underdefined state... Argument's should be overdefined, and
317 // constants should be marked as constants. If a value is not known to be an
318 // Instruction object, then use this accessor to get its value from the map.
319 //
320 inline LatticeVal &getValueState(Value *V) {
Bill Wendling03488ae2008-08-14 23:05:24 +0000321 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 if (I != ValueState.end()) return I->second; // Common case, in the map
323
324 if (Constant *C = dyn_cast<Constant>(V)) {
325 if (isa<UndefValue>(V)) {
326 // Nothing to do, remain undefined.
327 } else {
328 LatticeVal &LV = ValueState[C];
329 LV.markConstant(C); // Constants are constant
330 return LV;
331 }
332 }
333 // All others are underdefined by default...
334 return ValueState[V];
335 }
336
337 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
338 // work list if it is not already executable...
339 //
340 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
341 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
342 return; // This edge is already known to be executable!
343
344 if (BBExecutable.count(Dest)) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000345 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
346 << " -> " << Dest->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347
348 // The destination is already executable, but we just made an edge
349 // feasible that wasn't before. Revisit the PHI nodes in the block
350 // because they have potentially new operands.
351 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
352 visitPHINode(*cast<PHINode>(I));
353
354 } else {
355 MarkBlockExecutable(Dest);
356 }
357 }
358
359 // getFeasibleSuccessors - Return a vector of booleans to indicate which
360 // successors are reachable from a given terminator instruction.
361 //
362 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
363
364 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
365 // block to the 'To' basic block is currently feasible...
366 //
367 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
368
369 // OperandChangedState - This method is invoked on all of the users of an
370 // instruction that was just changed state somehow.... Based on this
371 // information, we need to update the specified user of this instruction.
372 //
373 void OperandChangedState(User *U) {
374 // Only instructions use other variable values!
375 Instruction &I = cast<Instruction>(*U);
376 if (BBExecutable.count(I.getParent())) // Inst is executable?
377 visit(I);
378 }
379
380private:
381 friend class InstVisitor<SCCPSolver>;
382
383 // visit implementations - Something changed in this instruction... Either an
384 // operand made a transition, or the instruction is newly executable. Change
385 // the value type of I to reflect these changes if appropriate.
386 //
387 void visitPHINode(PHINode &I);
388
389 // Terminators
390 void visitReturnInst(ReturnInst &I);
391 void visitTerminatorInst(TerminatorInst &TI);
392
393 void visitCastInst(CastInst &I);
394 void visitSelectInst(SelectInst &I);
395 void visitBinaryOperator(Instruction &I);
396 void visitCmpInst(CmpInst &I);
397 void visitExtractElementInst(ExtractElementInst &I);
398 void visitInsertElementInst(InsertElementInst &I);
399 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman856193b2008-06-20 01:15:44 +0000400 void visitExtractValueInst(ExtractValueInst &EVI);
401 void visitInsertValueInst(InsertValueInst &IVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402
403 // Instructions that cannot be folded away...
404 void visitStoreInst (Instruction &I);
405 void visitLoadInst (LoadInst &I);
406 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez93946082009-10-24 04:23:03 +0000407 void visitCallInst (CallInst &I) {
408 if (isFreeCall(&I))
409 return;
Chris Lattner6ad04a02009-09-27 21:35:11 +0000410 visitCallSite(CallSite::get(&I));
Victor Hernandez48c3c542009-09-18 22:35:49 +0000411 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 void visitInvokeInst (InvokeInst &II) {
413 visitCallSite(CallSite::get(&II));
414 visitTerminatorInst(II);
415 }
416 void visitCallSite (CallSite CS);
417 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
418 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandezb1687302009-10-23 21:09:37 +0000419 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
421 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000422
423 void visitInstruction(Instruction &I) {
424 // If a new instruction is added to LLVM that we don't handle...
Chris Lattner8a6411c2009-08-23 04:37:46 +0000425 errs() << "SCCP: Don't know how to handle: " << I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 markOverdefined(&I); // Just in case
427 }
428};
429
Duncan Sands40f67972007-07-20 08:56:21 +0000430} // end anonymous namespace
431
432
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433// getFeasibleSuccessors - Return a vector of booleans to indicate which
434// successors are reachable from a given terminator instruction.
435//
436void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
437 SmallVector<bool, 16> &Succs) {
438 Succs.resize(TI.getNumSuccessors());
439 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
440 if (BI->isUnconditional()) {
441 Succs[0] = true;
442 } else {
443 LatticeVal &BCValue = getValueState(BI->getCondition());
444 if (BCValue.isOverdefined() ||
445 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
446 // Overdefined condition variables, and branches on unfoldable constant
447 // conditions, mean the branch could go either way.
448 Succs[0] = Succs[1] = true;
449 } else if (BCValue.isConstant()) {
450 // Constant condition variables mean the branch can only go a single way
Owen Anderson4f720fa2009-07-31 17:39:07 +0000451 Succs[BCValue.getConstant() == ConstantInt::getFalse(*Context)] = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 }
453 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000454 return;
455 }
456
457 if (isa<InvokeInst>(&TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000458 // Invoke instructions successors are always executable.
459 Succs[0] = Succs[1] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000460 return;
461 }
462
463 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000464 LatticeVal &SCValue = getValueState(SI->getCondition());
465 if (SCValue.isOverdefined() || // Overdefined condition?
466 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
467 // All destinations are executable!
468 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner81335532008-05-10 23:56:54 +0000469 } else if (SCValue.isConstant())
470 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000471 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000472 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000473
474 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
475 if (isa<IndirectBrInst>(&TI)) {
476 // Just mark all destinations executable!
477 Succs.assign(TI.getNumSuccessors(), true);
478 return;
479 }
480
481#ifndef NDEBUG
482 errs() << "Unknown terminator instruction: " << TI << '\n';
483#endif
484 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000485}
486
487
488// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
489// block to the 'To' basic block is currently feasible...
490//
491bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
492 assert(BBExecutable.count(To) && "Dest should always be alive!");
493
494 // Make sure the source basic block is executable!!
495 if (!BBExecutable.count(From)) return false;
496
497 // Check to make sure this edge itself is actually feasible now...
498 TerminatorInst *TI = From->getTerminator();
499 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
500 if (BI->isUnconditional())
501 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000502
503 LatticeVal &BCValue = getValueState(BI->getCondition());
504 if (BCValue.isOverdefined()) {
505 // Overdefined condition variables mean the branch could go either way.
506 return true;
507 } else if (BCValue.isConstant()) {
508 // Not branching on an evaluatable constant?
509 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000510
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000511 // Constant condition variables mean the branch can only go a single way
512 return BI->getSuccessor(BCValue.getConstant() ==
513 ConstantInt::getFalse(*Context)) == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000515 return false;
516 }
517
518 // Invoke instructions successors are always executable.
519 if (isa<InvokeInst>(TI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000521
522 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523 LatticeVal &SCValue = getValueState(SI->getCondition());
524 if (SCValue.isOverdefined()) { // Overdefined condition?
525 // All destinations are executable!
526 return true;
527 } else if (SCValue.isConstant()) {
528 Constant *CPV = SCValue.getConstant();
529 if (!isa<ConstantInt>(CPV))
530 return true; // not a foldable constant?
531
532 // Make sure to skip the "default value" which isn't a value
533 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
534 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
535 return SI->getSuccessor(i) == To;
536
537 // Constant value not equal to any of the branches... must execute
538 // default branch then...
539 return SI->getDefaultDest() == To;
540 }
541 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000542 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000543
544 // Just mark all destinations executable!
545 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
546 if (isa<IndirectBrInst>(&TI))
547 return true;
548
549#ifndef NDEBUG
550 errs() << "Unknown terminator instruction: " << *TI << '\n';
551#endif
552 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000553}
554
555// visit Implementations - Something changed in this instruction... Either an
556// operand made a transition, or the instruction is newly executable. Change
557// the value type of I to reflect these changes if appropriate. This method
558// makes sure to do the following actions:
559//
560// 1. If a phi node merges two constants in, and has conflicting value coming
561// from different branches, or if the PHI node merges in an overdefined
562// value, then the PHI node becomes overdefined.
563// 2. If a phi node merges only constants in, and they all agree on value, the
564// PHI node becomes a constant value equal to that.
565// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
566// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
567// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
568// 6. If a conditional branch has a value that is constant, make the selected
569// destination executable
570// 7. If a conditional branch has a value that is overdefined, make all
571// successors executable.
572//
573void SCCPSolver::visitPHINode(PHINode &PN) {
574 LatticeVal &PNIV = getValueState(&PN);
575 if (PNIV.isOverdefined()) {
576 // There may be instructions using this PHI node that are not overdefined
577 // themselves. If so, make sure that they know that the PHI node operand
578 // changed.
579 std::multimap<PHINode*, Instruction*>::iterator I, E;
580 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
581 if (I != E) {
582 SmallVector<Instruction*, 16> Users;
583 for (; I != E; ++I) Users.push_back(I->second);
584 while (!Users.empty()) {
585 visit(Users.back());
586 Users.pop_back();
587 }
588 }
589 return; // Quick exit
590 }
591
592 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
593 // and slow us down a lot. Just mark them overdefined.
594 if (PN.getNumIncomingValues() > 64) {
595 markOverdefined(PNIV, &PN);
596 return;
597 }
598
599 // Look at all of the executable operands of the PHI node. If any of them
600 // are overdefined, the PHI becomes overdefined as well. If they are all
601 // constant, and they agree with each other, the PHI becomes the identical
602 // constant. If they are constant and don't agree, the PHI is overdefined.
603 // If there are no executable operands, the PHI remains undefined.
604 //
605 Constant *OperandVal = 0;
606 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
607 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
608 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
609
610 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
611 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattnerd3123a72008-08-23 23:36:38 +0000612 markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 return;
614 }
615
616 if (OperandVal == 0) { // Grab the first value...
617 OperandVal = IV.getConstant();
618 } else { // Another value is being merged in!
619 // There is already a reachable operand. If we conflict with it,
620 // then the PHI node becomes overdefined. If we agree with it, we
621 // can continue on.
622
623 // Check to see if there are two different constants merging...
624 if (IV.getConstant() != OperandVal) {
625 // Yes there is. This means the PHI node is not constant.
626 // You must be overdefined poor PHI.
627 //
Chris Lattnerd3123a72008-08-23 23:36:38 +0000628 markOverdefined(&PN); // The PHI node now becomes overdefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629 return; // I'm done analyzing you
630 }
631 }
632 }
633 }
634
635 // If we exited the loop, this means that the PHI node only has constant
636 // arguments that agree with each other(and OperandVal is the constant) or
637 // OperandVal is null because there are no defined incoming arguments. If
638 // this is the case, the PHI remains undefined.
639 //
640 if (OperandVal)
Chris Lattnerd3123a72008-08-23 23:36:38 +0000641 markConstant(&PN, OperandVal); // Acquire operand value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642}
643
644void SCCPSolver::visitReturnInst(ReturnInst &I) {
645 if (I.getNumOperands() == 0) return; // Ret void
646
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000647 Function *F = I.getParent()->getParent();
Devang Pateladd320d2008-03-11 05:46:42 +0000648 // If we are tracking the return value of this function, merge it in.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000649 if (!F->hasLocalLinkage())
Devang Pateladd320d2008-03-11 05:46:42 +0000650 return;
651
Chris Lattnercd73be02008-04-23 05:38:20 +0000652 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Pateladd320d2008-03-11 05:46:42 +0000654 TrackedRetVals.find(F);
655 if (TFRVI != TrackedRetVals.end() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656 !TFRVI->second.isOverdefined()) {
657 LatticeVal &IV = getValueState(I.getOperand(0));
658 mergeInValue(TFRVI->second, F, IV);
Devang Pateladd320d2008-03-11 05:46:42 +0000659 return;
660 }
661 }
662
Chris Lattnercd73be02008-04-23 05:38:20 +0000663 // Handle functions that return multiple values.
664 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
665 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000666 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnercd73be02008-04-23 05:38:20 +0000667 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
668 if (It == TrackedMultipleRetVals.end()) break;
669 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670 }
Dan Gohman856193b2008-06-20 01:15:44 +0000671 } else if (!TrackedMultipleRetVals.empty() &&
672 I.getNumOperands() == 1 &&
673 isa<StructType>(I.getOperand(0)->getType())) {
674 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
691 // Mark all feasible successors executable...
692 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) {
698 Value *V = I.getOperand(0);
699 LatticeVal &VState = getValueState(V);
700 if (VState.isOverdefined()) // Inherit overdefinedness of operand
701 markOverdefined(&I);
702 else if (VState.isConstant()) // Propagate constant value
Owen Anderson02b48c32009-07-29 18:55:55 +0000703 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704 VState.getConstant(), I.getType()));
705}
706
Dan Gohman856193b2008-06-20 01:15:44 +0000707void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000708 Value *Aggr = EVI.getAggregateOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000709
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000710 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohman856193b2008-06-20 01:15:44 +0000711 if (isa<UndefValue>(Aggr))
712 return;
713
714 // Currently only handle single-index extractvalues.
715 if (EVI.getNumIndices() != 1) {
716 markOverdefined(&EVI);
717 return;
718 }
719
720 Function *F = 0;
721 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
722 F = CI->getCalledFunction();
723 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
724 F = II->getCalledFunction();
725
726 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
727 // result back!
728 if (F == 0 || TrackedMultipleRetVals.empty()) {
729 markOverdefined(&EVI);
730 return;
731 }
732
Chris Lattnerd3123a72008-08-23 23:36:38 +0000733 // See if we are tracking the result of the callee. If not tracking this
734 // function (for example, it is a declaration) just move to overdefined.
735 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
Dan Gohman856193b2008-06-20 01:15:44 +0000736 markOverdefined(&EVI);
737 return;
738 }
739
740 // Otherwise, the value will be merged in here as a result of CallSite
741 // handling.
742}
743
744void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000745 Value *Aggr = IVI.getAggregateOperand();
746 Value *Val = IVI.getInsertedValueOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000747
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000748 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohman78b2c392008-06-20 16:39:44 +0000749 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohman856193b2008-06-20 01:15:44 +0000750 return;
751
752 // Currently only handle single-index insertvalues.
753 if (IVI.getNumIndices() != 1) {
754 markOverdefined(&IVI);
755 return;
756 }
Dan Gohman78b2c392008-06-20 16:39:44 +0000757
758 // Currently only handle insertvalue instructions that are in a single-use
759 // chain that builds up a return value.
760 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
761 if (!TmpIVI->hasOneUse()) {
762 markOverdefined(&IVI);
763 return;
764 }
765 const Value *V = *TmpIVI->use_begin();
766 if (isa<ReturnInst>(V))
767 break;
768 TmpIVI = dyn_cast<InsertValueInst>(V);
769 if (!TmpIVI) {
770 markOverdefined(&IVI);
771 return;
772 }
773 }
Dan Gohman856193b2008-06-20 01:15:44 +0000774
775 // See if we are tracking the result of the callee.
776 Function *F = IVI.getParent()->getParent();
Chris Lattnerd3123a72008-08-23 23:36:38 +0000777 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000778 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
779
780 // Merge in the inserted member value.
781 if (It != TrackedMultipleRetVals.end())
782 mergeInValue(It->second, F, getValueState(Val));
783
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000784 // Mark the aggregate result of the IVI overdefined; any tracking that we do
785 // will be done on the individual member values.
Dan Gohman856193b2008-06-20 01:15:44 +0000786 markOverdefined(&IVI);
787}
788
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789void SCCPSolver::visitSelectInst(SelectInst &I) {
790 LatticeVal &CondValue = getValueState(I.getCondition());
791 if (CondValue.isUndefined())
792 return;
793 if (CondValue.isConstant()) {
794 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
795 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
796 : I.getFalseValue()));
797 return;
798 }
799 }
800
801 // Otherwise, the condition is overdefined or a constant we can't evaluate.
802 // See if we can produce something better than overdefined based on the T/F
803 // value.
804 LatticeVal &TVal = getValueState(I.getTrueValue());
805 LatticeVal &FVal = getValueState(I.getFalseValue());
806
807 // select ?, C, C -> C.
808 if (TVal.isConstant() && FVal.isConstant() &&
809 TVal.getConstant() == FVal.getConstant()) {
810 markConstant(&I, FVal.getConstant());
811 return;
812 }
813
814 if (TVal.isUndefined()) { // select ?, undef, X -> X.
815 mergeInValue(&I, FVal);
816 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
817 mergeInValue(&I, TVal);
818 } else {
819 markOverdefined(&I);
820 }
821}
822
823// Handle BinaryOperators and Shift Instructions...
824void SCCPSolver::visitBinaryOperator(Instruction &I) {
825 LatticeVal &IV = ValueState[&I];
826 if (IV.isOverdefined()) return;
827
828 LatticeVal &V1State = getValueState(I.getOperand(0));
829 LatticeVal &V2State = getValueState(I.getOperand(1));
830
831 if (V1State.isOverdefined() || V2State.isOverdefined()) {
832 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
833 // operand is overdefined.
834 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
835 LatticeVal *NonOverdefVal = 0;
836 if (!V1State.isOverdefined()) {
837 NonOverdefVal = &V1State;
838 } else if (!V2State.isOverdefined()) {
839 NonOverdefVal = &V2State;
840 }
841
842 if (NonOverdefVal) {
843 if (NonOverdefVal->isUndefined()) {
844 // Could annihilate value.
845 if (I.getOpcode() == Instruction::And)
Owen Andersonaac28372009-07-31 20:28:14 +0000846 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
Owen Andersonaac28372009-07-31 20:28:14 +0000848 markConstant(IV, &I, Constant::getAllOnesValue(PT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 else
Owen Andersonfa089ab2009-07-03 19:42:02 +0000850 markConstant(IV, &I,
Owen Andersonaac28372009-07-31 20:28:14 +0000851 Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852 return;
853 } else {
854 if (I.getOpcode() == Instruction::And) {
855 if (NonOverdefVal->getConstant()->isNullValue()) {
856 markConstant(IV, &I, NonOverdefVal->getConstant());
857 return; // X and 0 = 0
858 }
859 } else {
860 if (ConstantInt *CI =
861 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
862 if (CI->isAllOnesValue()) {
863 markConstant(IV, &I, NonOverdefVal->getConstant());
864 return; // X or -1 = -1
865 }
866 }
867 }
868 }
869 }
870
871
872 // If both operands are PHI nodes, it is possible that this instruction has
873 // a constant value, despite the fact that the PHI node doesn't. Check for
874 // this condition now.
875 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
876 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
877 if (PN1->getParent() == PN2->getParent()) {
878 // Since the two PHI nodes are in the same basic block, they must have
879 // entries for the same predecessors. Walk the predecessor list, and
880 // if all of the incoming values are constants, and the result of
881 // evaluating this expression with all incoming value pairs is the
882 // same, then this expression is a constant even though the PHI node
883 // is not a constant!
884 LatticeVal Result;
885 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
886 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
887 BasicBlock *InBlock = PN1->getIncomingBlock(i);
888 LatticeVal &In2 =
889 getValueState(PN2->getIncomingValueForBlock(InBlock));
890
891 if (In1.isOverdefined() || In2.isOverdefined()) {
892 Result.markOverdefined();
893 break; // Cannot fold this operation over the PHI nodes!
894 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000895 Constant *V =
Owen Anderson02b48c32009-07-29 18:55:55 +0000896 ConstantExpr::get(I.getOpcode(), In1.getConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 In2.getConstant());
898 if (Result.isUndefined())
899 Result.markConstant(V);
900 else if (Result.isConstant() && Result.getConstant() != V) {
901 Result.markOverdefined();
902 break;
903 }
904 }
905 }
906
907 // If we found a constant value here, then we know the instruction is
908 // constant despite the fact that the PHI nodes are overdefined.
909 if (Result.isConstant()) {
910 markConstant(IV, &I, Result.getConstant());
911 // Remember that this instruction is virtually using the PHI node
912 // operands.
913 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
914 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
915 return;
916 } else if (Result.isUndefined()) {
917 return;
918 }
919
920 // Okay, this really is overdefined now. Since we might have
921 // speculatively thought that this was not overdefined before, and
922 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
923 // make sure to clean out any entries that we put there, for
924 // efficiency.
925 std::multimap<PHINode*, Instruction*>::iterator It, E;
926 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
927 while (It != E) {
928 if (It->second == &I) {
929 UsersOfOverdefinedPHIs.erase(It++);
930 } else
931 ++It;
932 }
933 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
934 while (It != E) {
935 if (It->second == &I) {
936 UsersOfOverdefinedPHIs.erase(It++);
937 } else
938 ++It;
939 }
940 }
941
942 markOverdefined(IV, &I);
943 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000944 markConstant(IV, &I,
Owen Anderson02b48c32009-07-29 18:55:55 +0000945 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946 V2State.getConstant()));
947 }
948}
949
950// Handle ICmpInst instruction...
951void SCCPSolver::visitCmpInst(CmpInst &I) {
952 LatticeVal &IV = ValueState[&I];
953 if (IV.isOverdefined()) return;
954
955 LatticeVal &V1State = getValueState(I.getOperand(0));
956 LatticeVal &V2State = getValueState(I.getOperand(1));
957
958 if (V1State.isOverdefined() || V2State.isOverdefined()) {
959 // If both operands are PHI nodes, it is possible that this instruction has
960 // a constant value, despite the fact that the PHI node doesn't. Check for
961 // this condition now.
962 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
963 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
964 if (PN1->getParent() == PN2->getParent()) {
965 // Since the two PHI nodes are in the same basic block, they must have
966 // entries for the same predecessors. Walk the predecessor list, and
967 // if all of the incoming values are constants, and the result of
968 // evaluating this expression with all incoming value pairs is the
969 // same, then this expression is a constant even though the PHI node
970 // is not a constant!
971 LatticeVal Result;
972 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
973 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
974 BasicBlock *InBlock = PN1->getIncomingBlock(i);
975 LatticeVal &In2 =
976 getValueState(PN2->getIncomingValueForBlock(InBlock));
977
978 if (In1.isOverdefined() || In2.isOverdefined()) {
979 Result.markOverdefined();
980 break; // Cannot fold this operation over the PHI nodes!
981 } else if (In1.isConstant() && In2.isConstant()) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000982 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983 In1.getConstant(),
984 In2.getConstant());
985 if (Result.isUndefined())
986 Result.markConstant(V);
987 else if (Result.isConstant() && Result.getConstant() != V) {
988 Result.markOverdefined();
989 break;
990 }
991 }
992 }
993
994 // If we found a constant value here, then we know the instruction is
995 // constant despite the fact that the PHI nodes are overdefined.
996 if (Result.isConstant()) {
997 markConstant(IV, &I, Result.getConstant());
998 // Remember that this instruction is virtually using the PHI node
999 // operands.
1000 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
1001 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
1002 return;
1003 } else if (Result.isUndefined()) {
1004 return;
1005 }
1006
1007 // Okay, this really is overdefined now. Since we might have
1008 // speculatively thought that this was not overdefined before, and
1009 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1010 // make sure to clean out any entries that we put there, for
1011 // efficiency.
1012 std::multimap<PHINode*, Instruction*>::iterator It, E;
1013 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
1014 while (It != E) {
1015 if (It->second == &I) {
1016 UsersOfOverdefinedPHIs.erase(It++);
1017 } else
1018 ++It;
1019 }
1020 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
1021 while (It != E) {
1022 if (It->second == &I) {
1023 UsersOfOverdefinedPHIs.erase(It++);
1024 } else
1025 ++It;
1026 }
1027 }
1028
1029 markOverdefined(IV, &I);
1030 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00001031 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032 V1State.getConstant(),
1033 V2State.getConstant()));
1034 }
1035}
1036
1037void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1038 // FIXME : SCCP does not handle vectors properly.
1039 markOverdefined(&I);
1040 return;
1041
1042#if 0
1043 LatticeVal &ValState = getValueState(I.getOperand(0));
1044 LatticeVal &IdxState = getValueState(I.getOperand(1));
1045
1046 if (ValState.isOverdefined() || IdxState.isOverdefined())
1047 markOverdefined(&I);
1048 else if(ValState.isConstant() && IdxState.isConstant())
1049 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1050 IdxState.getConstant()));
1051#endif
1052}
1053
1054void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1055 // FIXME : SCCP does not handle vectors properly.
1056 markOverdefined(&I);
1057 return;
1058#if 0
1059 LatticeVal &ValState = getValueState(I.getOperand(0));
1060 LatticeVal &EltState = getValueState(I.getOperand(1));
1061 LatticeVal &IdxState = getValueState(I.getOperand(2));
1062
1063 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1064 IdxState.isOverdefined())
1065 markOverdefined(&I);
1066 else if(ValState.isConstant() && EltState.isConstant() &&
1067 IdxState.isConstant())
1068 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1069 EltState.getConstant(),
1070 IdxState.getConstant()));
1071 else if (ValState.isUndefined() && EltState.isConstant() &&
1072 IdxState.isConstant())
1073 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1074 EltState.getConstant(),
1075 IdxState.getConstant()));
1076#endif
1077}
1078
1079void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1080 // FIXME : SCCP does not handle vectors properly.
1081 markOverdefined(&I);
1082 return;
1083#if 0
1084 LatticeVal &V1State = getValueState(I.getOperand(0));
1085 LatticeVal &V2State = getValueState(I.getOperand(1));
1086 LatticeVal &MaskState = getValueState(I.getOperand(2));
1087
1088 if (MaskState.isUndefined() ||
1089 (V1State.isUndefined() && V2State.isUndefined()))
1090 return; // Undefined output if mask or both inputs undefined.
1091
1092 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1093 MaskState.isOverdefined()) {
1094 markOverdefined(&I);
1095 } else {
1096 // A mix of constant/undef inputs.
1097 Constant *V1 = V1State.isConstant() ?
1098 V1State.getConstant() : UndefValue::get(I.getType());
1099 Constant *V2 = V2State.isConstant() ?
1100 V2State.getConstant() : UndefValue::get(I.getType());
1101 Constant *Mask = MaskState.isConstant() ?
1102 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1103 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1104 }
1105#endif
1106}
1107
1108// Handle getelementptr instructions... if all operands are constants then we
1109// can turn this into a getelementptr ConstantExpr.
1110//
1111void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1112 LatticeVal &IV = ValueState[&I];
1113 if (IV.isOverdefined()) return;
1114
1115 SmallVector<Constant*, 8> Operands;
1116 Operands.reserve(I.getNumOperands());
1117
1118 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1119 LatticeVal &State = getValueState(I.getOperand(i));
1120 if (State.isUndefined())
1121 return; // Operands are not resolved yet...
1122 else if (State.isOverdefined()) {
1123 markOverdefined(IV, &I);
1124 return;
1125 }
1126 assert(State.isConstant() && "Unknown state!");
1127 Operands.push_back(State.getConstant());
1128 }
1129
1130 Constant *Ptr = Operands[0];
1131 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1132
Owen Anderson02b48c32009-07-29 18:55:55 +00001133 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 Operands.size()));
1135}
1136
1137void SCCPSolver::visitStoreInst(Instruction &SI) {
1138 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1139 return;
1140 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1141 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1142 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1143
1144 // Get the value we are storing into the global.
1145 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1146
1147 mergeInValue(I->second, GV, PtrVal);
1148 if (I->second.isOverdefined())
1149 TrackedGlobals.erase(I); // No need to keep tracking this!
1150}
1151
1152
1153// Handle load instructions. If the operand is a constant pointer to a constant
1154// global, we can replace the load with the loaded constant value!
1155void SCCPSolver::visitLoadInst(LoadInst &I) {
1156 LatticeVal &IV = ValueState[&I];
1157 if (IV.isOverdefined()) return;
1158
1159 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1160 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1161 if (PtrVal.isConstant() && !I.isVolatile()) {
1162 Value *Ptr = PtrVal.getConstant();
Christopher Lamb2c175392007-12-29 07:56:53 +00001163 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +00001164 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 // load null -> null
Owen Andersonaac28372009-07-31 20:28:14 +00001166 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 return;
1168 }
1169
1170 // Transform load (constant global) into the value loaded.
1171 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1172 if (GV->isConstant()) {
Duncan Sands54e70f62009-03-21 21:27:31 +00001173 if (GV->hasDefinitiveInitializer()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001174 markConstant(IV, &I, GV->getInitializer());
1175 return;
1176 }
1177 } else if (!TrackedGlobals.empty()) {
1178 // If we are tracking this global, merge in the known value for it.
1179 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1180 TrackedGlobals.find(GV);
1181 if (It != TrackedGlobals.end()) {
1182 mergeInValue(IV, &I, It->second);
1183 return;
1184 }
1185 }
1186 }
1187
1188 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1189 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1190 if (CE->getOpcode() == Instruction::GetElementPtr)
1191 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +00001192 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001193 if (Constant *V =
Dan Gohmanf49f7b02009-10-05 16:36:26 +00001194 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001195 markConstant(IV, &I, V);
1196 return;
1197 }
1198 }
1199
1200 // Otherwise we cannot say for certain what value this load will produce.
1201 // Bail out.
1202 markOverdefined(IV, &I);
1203}
1204
1205void SCCPSolver::visitCallSite(CallSite CS) {
1206 Function *F = CS.getCalledFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001207 Instruction *I = CS.getInstruction();
Chris Lattnercd73be02008-04-23 05:38:20 +00001208
1209 // The common case is that we aren't tracking the callee, either because we
1210 // are not doing interprocedural analysis or the callee is indirect, or is
1211 // external. Handle these cases first.
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001212 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001213CallOverdefined:
1214 // Void return and not tracking callee, just bail.
Chris Lattner82cdc062009-10-05 05:54:46 +00001215 if (I->getType()->isVoidTy()) return;
Chris Lattnercd73be02008-04-23 05:38:20 +00001216
1217 // Otherwise, if we have a single return value case, and if the function is
1218 // a declaration, maybe we can constant fold it.
1219 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1220 canConstantFoldCallTo(F)) {
1221
1222 SmallVector<Constant*, 8> Operands;
1223 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1224 AI != E; ++AI) {
1225 LatticeVal &State = getValueState(*AI);
1226 if (State.isUndefined())
1227 return; // Operands are not resolved yet.
1228 else if (State.isOverdefined()) {
1229 markOverdefined(I);
1230 return;
1231 }
1232 assert(State.isConstant() && "Unknown state!");
1233 Operands.push_back(State.getConstant());
1234 }
1235
1236 // If we can constant fold this, mark the result of the call as a
1237 // constant.
Nick Lewyckye9279352009-05-28 04:08:10 +00001238 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001239 markConstant(I, C);
1240 return;
1241 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001243
1244 // Otherwise, we don't know anything about this call, mark it overdefined.
1245 markOverdefined(I);
1246 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001247 }
1248
Chris Lattnercd73be02008-04-23 05:38:20 +00001249 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohman856193b2008-06-20 01:15:44 +00001250 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1251 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001252 // If so, propagate the return value of the callee into this call result.
1253 mergeInValue(I, TFRVI->second);
Dan Gohman856193b2008-06-20 01:15:44 +00001254 } else if (isa<StructType>(I->getType())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001255 // Check to see if we're tracking this callee, if not, handle it in the
1256 // common path above.
Chris Lattnerd3123a72008-08-23 23:36:38 +00001257 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1258 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnercd73be02008-04-23 05:38:20 +00001259 if (TMRVI == TrackedMultipleRetVals.end())
1260 goto CallOverdefined;
Edwin Töröka6174642009-10-20 15:15:09 +00001261
1262 // Need to mark as overdefined, otherwise it stays undefined which
1263 // creates extractvalue undef, <idx>
1264 markOverdefined(I);
Chris Lattnercd73be02008-04-23 05:38:20 +00001265 // If we are tracking this callee, propagate the return values of the call
Dan Gohman856193b2008-06-20 01:15:44 +00001266 // into this call site. We do this by walking all the uses. Single-index
1267 // ExtractValueInst uses can be tracked; anything more complicated is
1268 // currently handled conservatively.
Chris Lattnercd73be02008-04-23 05:38:20 +00001269 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1270 UI != E; ++UI) {
Dan Gohman856193b2008-06-20 01:15:44 +00001271 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1272 if (EVI->getNumIndices() == 1) {
1273 mergeInValue(EVI,
Dan Gohmanaa7b7802008-06-20 16:41:17 +00001274 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohman856193b2008-06-20 01:15:44 +00001275 continue;
1276 }
1277 }
1278 // The aggregate value is used in a way not handled here. Assume nothing.
1279 markOverdefined(*UI);
Chris Lattnercd73be02008-04-23 05:38:20 +00001280 }
Dan Gohman856193b2008-06-20 01:15:44 +00001281 } else {
1282 // Otherwise we're not tracking this callee, so handle it in the
1283 // common path above.
1284 goto CallOverdefined;
Chris Lattnercd73be02008-04-23 05:38:20 +00001285 }
1286
1287 // Finally, if this is the first call to the function hit, mark its entry
1288 // block executable.
1289 if (!BBExecutable.count(F->begin()))
1290 MarkBlockExecutable(F->begin());
1291
1292 // Propagate information from this call site into the callee.
1293 CallSite::arg_iterator CAI = CS.arg_begin();
1294 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1295 AI != E; ++AI, ++CAI) {
1296 LatticeVal &IV = ValueState[AI];
Edwin Török129b2d12009-09-24 18:33:42 +00001297 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Edwin Törökd5435372009-09-24 09:47:18 +00001298 IV.markOverdefined();
1299 continue;
1300 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001301 if (!IV.isOverdefined())
1302 mergeInValue(IV, AI, getValueState(*CAI));
1303 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304}
1305
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306void SCCPSolver::Solve() {
1307 // Process the work lists until they are empty!
1308 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1309 !OverdefinedInstWorkList.empty()) {
1310 // Process the instruction work list...
1311 while (!OverdefinedInstWorkList.empty()) {
1312 Value *I = OverdefinedInstWorkList.back();
1313 OverdefinedInstWorkList.pop_back();
1314
Dan Gohmandff8d172009-08-17 15:25:05 +00001315 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001316
1317 // "I" got into the work list because it either made the transition from
1318 // bottom to constant
1319 //
1320 // Anything on this worklist that is overdefined need not be visited
1321 // since all of its users will have already been marked as overdefined
1322 // Update all of the users of this instruction's value...
1323 //
1324 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1325 UI != E; ++UI)
1326 OperandChangedState(*UI);
1327 }
1328 // Process the instruction work list...
1329 while (!InstWorkList.empty()) {
1330 Value *I = InstWorkList.back();
1331 InstWorkList.pop_back();
1332
Dan Gohmandff8d172009-08-17 15:25:05 +00001333 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334
1335 // "I" got into the work list because it either made the transition from
1336 // bottom to constant
1337 //
1338 // Anything on this worklist that is overdefined need not be visited
1339 // since all of its users will have already been marked as overdefined.
1340 // Update all of the users of this instruction's value...
1341 //
1342 if (!getValueState(I).isOverdefined())
1343 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1344 UI != E; ++UI)
1345 OperandChangedState(*UI);
1346 }
1347
1348 // Process the basic block work list...
1349 while (!BBWorkList.empty()) {
1350 BasicBlock *BB = BBWorkList.back();
1351 BBWorkList.pop_back();
1352
Dan Gohmandff8d172009-08-17 15:25:05 +00001353 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001354
1355 // Notify all instructions in this basic block that they are newly
1356 // executable.
1357 visit(BB);
1358 }
1359 }
1360}
1361
1362/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1363/// that branches on undef values cannot reach any of their successors.
1364/// However, this is not a safe assumption. After we solve dataflow, this
1365/// method should be use to handle this. If this returns true, the solver
1366/// should be rerun.
1367///
1368/// This method handles this by finding an unresolved branch and marking it one
1369/// of the edges from the block as being feasible, even though the condition
1370/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1371/// CFG and only slightly pessimizes the analysis results (by marking one,
1372/// potentially infeasible, edge feasible). This cannot usefully modify the
1373/// constraints on the condition of the branch, as that would impact other users
1374/// of the value.
1375///
1376/// This scan also checks for values that use undefs, whose results are actually
1377/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1378/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1379/// even if X isn't defined.
1380bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1381 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1382 if (!BBExecutable.count(BB))
1383 continue;
1384
1385 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1386 // Look for instructions which produce undef values.
Chris Lattner82cdc062009-10-05 05:54:46 +00001387 if (I->getType()->isVoidTy()) continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388
1389 LatticeVal &LV = getValueState(I);
1390 if (!LV.isUndefined()) continue;
1391
1392 // Get the lattice values of the first two operands for use below.
1393 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1394 LatticeVal Op1LV;
1395 if (I->getNumOperands() == 2) {
1396 // If this is a two-operand instruction, and if both operands are
1397 // undefs, the result stays undef.
1398 Op1LV = getValueState(I->getOperand(1));
1399 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1400 continue;
1401 }
1402
1403 // If this is an instructions whose result is defined even if the input is
1404 // not fully defined, propagate the information.
1405 const Type *ITy = I->getType();
1406 switch (I->getOpcode()) {
1407 default: break; // Leave the instruction as an undef.
1408 case Instruction::ZExt:
1409 // After a zero extend, we know the top part is zero. SExt doesn't have
1410 // to be handled here, because we don't know whether the top part is 1's
1411 // or 0's.
1412 assert(Op0LV.isUndefined());
Owen Andersonaac28372009-07-31 20:28:14 +00001413 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001414 return true;
1415 case Instruction::Mul:
1416 case Instruction::And:
1417 // undef * X -> 0. X could be zero.
1418 // undef & X -> 0. X could be zero.
Owen Andersonaac28372009-07-31 20:28:14 +00001419 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001420 return true;
1421
1422 case Instruction::Or:
1423 // undef | X -> -1. X could be -1.
1424 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
Owen Andersonfa089ab2009-07-03 19:42:02 +00001425 markForcedConstant(LV, I,
Owen Andersonaac28372009-07-31 20:28:14 +00001426 Constant::getAllOnesValue(PTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427 else
Owen Andersonaac28372009-07-31 20:28:14 +00001428 markForcedConstant(LV, I, Constant::getAllOnesValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429 return true;
1430
1431 case Instruction::SDiv:
1432 case Instruction::UDiv:
1433 case Instruction::SRem:
1434 case Instruction::URem:
1435 // X / undef -> undef. No change.
1436 // X % undef -> undef. No change.
1437 if (Op1LV.isUndefined()) break;
1438
1439 // undef / X -> 0. X could be maxint.
1440 // undef % X -> 0. X could be 1.
Owen Andersonaac28372009-07-31 20:28:14 +00001441 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442 return true;
1443
1444 case Instruction::AShr:
1445 // undef >>s X -> undef. No change.
1446 if (Op0LV.isUndefined()) break;
1447
1448 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1449 if (Op0LV.isConstant())
1450 markForcedConstant(LV, I, Op0LV.getConstant());
1451 else
1452 markOverdefined(LV, I);
1453 return true;
1454 case Instruction::LShr:
1455 case Instruction::Shl:
1456 // undef >> X -> undef. No change.
1457 // undef << X -> undef. No change.
1458 if (Op0LV.isUndefined()) break;
1459
1460 // X >> undef -> 0. X could be 0.
1461 // X << undef -> 0. X could be 0.
Owen Andersonaac28372009-07-31 20:28:14 +00001462 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001463 return true;
1464 case Instruction::Select:
1465 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1466 if (Op0LV.isUndefined()) {
1467 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1468 Op1LV = getValueState(I->getOperand(2));
1469 } else if (Op1LV.isUndefined()) {
1470 // c ? undef : undef -> undef. No change.
1471 Op1LV = getValueState(I->getOperand(2));
1472 if (Op1LV.isUndefined())
1473 break;
1474 // Otherwise, c ? undef : x -> x.
1475 } else {
1476 // Leave Op1LV as Operand(1)'s LatticeValue.
1477 }
1478
1479 if (Op1LV.isConstant())
1480 markForcedConstant(LV, I, Op1LV.getConstant());
1481 else
1482 markOverdefined(LV, I);
1483 return true;
Chris Lattner9110ac92008-05-24 03:59:33 +00001484 case Instruction::Call:
1485 // If a call has an undef result, it is because it is constant foldable
1486 // but one of the inputs was undef. Just force the result to
1487 // overdefined.
1488 markOverdefined(LV, I);
1489 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001490 }
1491 }
1492
1493 TerminatorInst *TI = BB->getTerminator();
1494 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1495 if (!BI->isConditional()) continue;
1496 if (!getValueState(BI->getCondition()).isUndefined())
1497 continue;
1498 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Dale Johannesenfb06d0c2008-05-23 01:01:31 +00001499 if (SI->getNumSuccessors()<2) // no cases
1500 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001501 if (!getValueState(SI->getCondition()).isUndefined())
1502 continue;
1503 } else {
1504 continue;
1505 }
1506
Chris Lattner6186e8c2008-01-28 00:32:30 +00001507 // If the edge to the second successor isn't thought to be feasible yet,
1508 // mark it so now. We pick the second one so that this goes to some
1509 // enumerated value in a switch instead of going to the default destination.
1510 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001511 continue;
1512
1513 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1514 // and return. This will make other blocks reachable, which will allow new
1515 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner6186e8c2008-01-28 00:32:30 +00001516 markEdgeExecutable(BB, TI->getSuccessor(1));
1517
1518 // This must be a conditional branch of switch on undef. At this point,
1519 // force the old terminator to branch to the first successor. This is
1520 // required because we are now influencing the dataflow of the function with
1521 // the assumption that this edge is taken. If we leave the branch condition
1522 // as undef, then further analysis could think the undef went another way
1523 // leading to an inconsistent set of conclusions.
1524 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00001525 BI->setCondition(ConstantInt::getFalse(*Context));
Chris Lattner6186e8c2008-01-28 00:32:30 +00001526 } else {
1527 SwitchInst *SI = cast<SwitchInst>(TI);
1528 SI->setCondition(SI->getCaseValue(1));
1529 }
1530
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001531 return true;
1532 }
1533
1534 return false;
1535}
1536
1537
1538namespace {
1539 //===--------------------------------------------------------------------===//
1540 //
1541 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1542 /// Sparse Conditional Constant Propagator.
1543 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001544 struct SCCP : public FunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001545 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +00001546 SCCP() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001547
1548 // runOnFunction - Run the Sparse Conditional Constant Propagation
1549 // algorithm, and return true if the function was modified.
1550 //
1551 bool runOnFunction(Function &F);
1552
1553 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1554 AU.setPreservesCFG();
1555 }
1556 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001557} // end anonymous namespace
1558
Dan Gohman089efff2008-05-13 00:00:25 +00001559char SCCP::ID = 0;
1560static RegisterPass<SCCP>
1561X("sccp", "Sparse Conditional Constant Propagation");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001562
1563// createSCCPPass - This is the public interface to this file...
1564FunctionPass *llvm::createSCCPPass() {
1565 return new SCCP();
1566}
1567
1568
1569// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1570// and return true if the function was modified.
1571//
1572bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001573 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001574 SCCPSolver Solver;
Owen Anderson175b6542009-07-22 00:24:57 +00001575 Solver.setContext(&F.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001576
1577 // Mark the first block of the function as being executable.
1578 Solver.MarkBlockExecutable(F.begin());
1579
1580 // Mark all arguments to the function as being overdefined.
1581 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1582 Solver.markOverdefined(AI);
1583
1584 // Solve for constants.
1585 bool ResolvedUndefs = true;
1586 while (ResolvedUndefs) {
1587 Solver.Solve();
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001588 DEBUG(errs() << "RESOLVING UNDEFs\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001589 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1590 }
1591
1592 bool MadeChanges = false;
1593
1594 // If we decided that there are basic blocks that are dead in this function,
1595 // delete their contents now. Note that we cannot actually delete the blocks,
1596 // as we cannot modify the CFG of the function.
1597 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001598 SmallVector<Instruction*, 512> Insts;
Bill Wendling03488ae2008-08-14 23:05:24 +00001599 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001600
1601 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattner317e6b62008-08-23 23:39:31 +00001602 if (!Solver.isBlockExecutable(BB)) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001603 DEBUG(errs() << " BasicBlock Dead:" << *BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001604 ++NumDeadBlocks;
1605
1606 // Delete the instructions backwards, as it has a reduced likelihood of
1607 // having to update as many def-use and use-def chains.
1608 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1609 I != E; ++I)
1610 Insts.push_back(I);
1611 while (!Insts.empty()) {
1612 Instruction *I = Insts.back();
1613 Insts.pop_back();
1614 if (!I->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001615 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001616 BB->getInstList().erase(I);
1617 MadeChanges = true;
1618 ++NumInstRemoved;
1619 }
1620 } else {
1621 // Iterate over all of the instructions in a function, replacing them with
1622 // constants if we have found them to be of constant values.
1623 //
1624 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1625 Instruction *Inst = BI++;
Chris Lattner82cdc062009-10-05 05:54:46 +00001626 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
Chris Lattnerb6f89362008-04-24 00:16:28 +00001627 continue;
1628
1629 LatticeVal &IV = Values[Inst];
1630 if (!IV.isConstant() && !IV.isUndefined())
1631 continue;
1632
1633 Constant *Const = IV.isConstant()
Owen Andersonb99ecca2009-07-30 23:03:37 +00001634 ? IV.getConstant() : UndefValue::get(Inst->getType());
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001635 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636
Chris Lattnerb6f89362008-04-24 00:16:28 +00001637 // Replaces all of the uses of a variable with uses of the constant.
1638 Inst->replaceAllUsesWith(Const);
1639
1640 // Delete the instruction.
1641 Inst->eraseFromParent();
1642
1643 // Hey, we just changed something!
1644 MadeChanges = true;
1645 ++NumInstRemoved;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001646 }
1647 }
1648
1649 return MadeChanges;
1650}
1651
1652namespace {
1653 //===--------------------------------------------------------------------===//
1654 //
1655 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1656 /// Constant Propagation.
1657 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001658 struct IPSCCP : public ModulePass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001659 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +00001660 IPSCCP() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001661 bool runOnModule(Module &M);
1662 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663} // end anonymous namespace
1664
Dan Gohman089efff2008-05-13 00:00:25 +00001665char IPSCCP::ID = 0;
1666static RegisterPass<IPSCCP>
1667Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1668
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001669// createIPSCCPPass - This is the public interface to this file...
1670ModulePass *llvm::createIPSCCPPass() {
1671 return new IPSCCP();
1672}
1673
1674
1675static bool AddressIsTaken(GlobalValue *GV) {
1676 // Delete any dead constantexpr klingons.
1677 GV->removeDeadConstantUsers();
1678
1679 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1680 UI != E; ++UI)
1681 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1682 if (SI->getOperand(0) == GV || SI->isVolatile())
1683 return true; // Storing addr of GV.
1684 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1685 // Make sure we are calling the function, not passing the address.
Chris Lattner2f487502009-11-01 06:11:53 +00001686 if (UI.getOperandNo() != 0)
Nick Lewycky1cc2e102008-11-03 03:49:14 +00001687 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001688 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1689 if (LI->isVolatile())
1690 return true;
Chris Lattner2f487502009-11-01 06:11:53 +00001691 } else if (isa<BlockAddress>(*UI)) {
1692 // blockaddress doesn't take the address of the function, it takes addr
1693 // of label.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001694 } else {
1695 return true;
1696 }
1697 return false;
1698}
1699
1700bool IPSCCP::runOnModule(Module &M) {
Owen Anderson175b6542009-07-22 00:24:57 +00001701 LLVMContext *Context = &M.getContext();
Owen Andersone1f1f822009-07-16 18:04:31 +00001702
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001703 SCCPSolver Solver;
Owen Andersone1f1f822009-07-16 18:04:31 +00001704 Solver.setContext(Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001705
1706 // Loop over all functions, marking arguments to those with their addresses
1707 // taken or that are external as overdefined.
1708 //
1709 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001710 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001711 if (!F->isDeclaration())
1712 Solver.MarkBlockExecutable(F->begin());
1713 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1714 AI != E; ++AI)
1715 Solver.markOverdefined(AI);
1716 } else {
1717 Solver.AddTrackedFunction(F);
1718 }
1719
1720 // Loop over global variables. We inform the solver about any internal global
1721 // variables that do not have their 'addresses taken'. If they don't have
1722 // their addresses taken, we can propagate constants through them.
1723 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1724 G != E; ++G)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001725 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001726 Solver.TrackValueOfGlobalVariable(G);
1727
1728 // Solve for constants.
1729 bool ResolvedUndefs = true;
1730 while (ResolvedUndefs) {
1731 Solver.Solve();
1732
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001733 DEBUG(errs() << "RESOLVING UNDEFS\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001734 ResolvedUndefs = false;
1735 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1736 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1737 }
1738
1739 bool MadeChanges = false;
1740
1741 // Iterate over all of the instructions in the module, replacing them with
1742 // constants if we have found them to be of constant values.
1743 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001744 SmallVector<Instruction*, 512> Insts;
1745 SmallVector<BasicBlock*, 512> BlocksToErase;
Bill Wendling03488ae2008-08-14 23:05:24 +00001746 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001747
1748 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1749 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1750 AI != E; ++AI)
1751 if (!AI->use_empty()) {
1752 LatticeVal &IV = Values[AI];
1753 if (IV.isConstant() || IV.isUndefined()) {
1754 Constant *CST = IV.isConstant() ?
Owen Andersonb99ecca2009-07-30 23:03:37 +00001755 IV.getConstant() : UndefValue::get(AI->getType());
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001756 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001757
1758 // Replaces all of the uses of a variable with uses of the
1759 // constant.
1760 AI->replaceAllUsesWith(CST);
1761 ++IPNumArgsElimed;
1762 }
1763 }
1764
1765 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
Chris Lattner317e6b62008-08-23 23:39:31 +00001766 if (!Solver.isBlockExecutable(BB)) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001767 DEBUG(errs() << " BasicBlock Dead:" << *BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001768 ++IPNumDeadBlocks;
1769
1770 // Delete the instructions backwards, as it has a reduced likelihood of
1771 // having to update as many def-use and use-def chains.
1772 TerminatorInst *TI = BB->getTerminator();
1773 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1774 Insts.push_back(I);
1775
1776 while (!Insts.empty()) {
1777 Instruction *I = Insts.back();
1778 Insts.pop_back();
1779 if (!I->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001780 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001781 BB->getInstList().erase(I);
1782 MadeChanges = true;
1783 ++IPNumInstRemoved;
1784 }
1785
1786 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1787 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohman3f7d94b2007-10-03 19:26:29 +00001788 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001789 TI->getSuccessor(i)->removePredecessor(BB);
1790 }
1791 if (!TI->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001792 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001793 BB->getInstList().erase(TI);
1794
1795 if (&*BB != &F->front())
1796 BlocksToErase.push_back(BB);
1797 else
Owen Anderson35b47072009-08-13 21:58:54 +00001798 new UnreachableInst(M.getContext(), BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001799
1800 } else {
1801 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1802 Instruction *Inst = BI++;
Chris Lattner82cdc062009-10-05 05:54:46 +00001803 if (Inst->getType()->isVoidTy())
Chris Lattner50846cf2008-04-24 00:21:50 +00001804 continue;
1805
1806 LatticeVal &IV = Values[Inst];
1807 if (!IV.isConstant() && !IV.isUndefined())
1808 continue;
1809
1810 Constant *Const = IV.isConstant()
Owen Andersonb99ecca2009-07-30 23:03:37 +00001811 ? IV.getConstant() : UndefValue::get(Inst->getType());
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001812 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001813
Chris Lattner50846cf2008-04-24 00:21:50 +00001814 // Replaces all of the uses of a variable with uses of the
1815 // constant.
1816 Inst->replaceAllUsesWith(Const);
1817
1818 // Delete the instruction.
Chris Lattnerc27ce6d2009-01-14 21:01:16 +00001819 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
Chris Lattner50846cf2008-04-24 00:21:50 +00001820 Inst->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001821
Chris Lattner50846cf2008-04-24 00:21:50 +00001822 // Hey, we just changed something!
1823 MadeChanges = true;
1824 ++IPNumInstRemoved;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001825 }
1826 }
1827
1828 // Now that all instructions in the function are constant folded, erase dead
1829 // blocks, because we can now use ConstantFoldTerminator to get rid of
1830 // in-edges.
1831 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1832 // If there are any PHI nodes in this successor, drop entries for BB now.
1833 BasicBlock *DeadBB = BlocksToErase[i];
1834 while (!DeadBB->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001835 Instruction *I = cast<Instruction>(DeadBB->use_back());
1836 bool Folded = ConstantFoldTerminator(I->getParent());
1837 if (!Folded) {
1838 // The constant folder may not have been able to fold the terminator
1839 // if this is a branch or switch on undef. Fold it manually as a
1840 // branch to the first successor.
Devang Patele92c16d2008-11-21 01:52:59 +00001841#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001842 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1843 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1844 "Branch should be foldable!");
1845 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1846 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1847 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001848 llvm_unreachable("Didn't fold away reference to block!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001849 }
Devang Patele92c16d2008-11-21 01:52:59 +00001850#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001851
1852 // Make this an uncond branch to the first successor.
1853 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001854 BranchInst::Create(TI->getSuccessor(0), TI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001855
1856 // Remove entries in successor phi nodes to remove edges.
1857 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1858 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1859
1860 // Remove the old terminator.
1861 TI->eraseFromParent();
1862 }
1863 }
1864
1865 // Finally, delete the basic block.
1866 F->getBasicBlockList().erase(DeadBB);
1867 }
1868 BlocksToErase.clear();
1869 }
1870
1871 // If we inferred constant or undef return values for a function, we replaced
1872 // all call uses with the inferred value. This means we don't need to bother
1873 // actually returning anything from the function. Replace all return
1874 // instructions with return undef.
Devang Pateld04d42b2008-03-11 17:32:05 +00001875 // TODO: Process multiple value ret instructions also.
Devang Pateladd320d2008-03-11 05:46:42 +00001876 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001877 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1878 E = RV.end(); I != E; ++I)
1879 if (!I->second.isOverdefined() &&
Chris Lattner82cdc062009-10-05 05:54:46 +00001880 !I->first->getReturnType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001881 Function *F = I->first;
1882 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1883 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1884 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +00001885 RI->setOperand(0, UndefValue::get(F->getReturnType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001886 }
1887
1888 // If we infered constant or undef values for globals variables, we can delete
1889 // the global and any stores that remain to it.
1890 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1891 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1892 E = TG.end(); I != E; ++I) {
1893 GlobalVariable *GV = I->first;
1894 assert(!I->second.isOverdefined() &&
1895 "Overdefined values should have been taken out of the map!");
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001896 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001897 while (!GV->use_empty()) {
1898 StoreInst *SI = cast<StoreInst>(GV->use_back());
1899 SI->eraseFromParent();
1900 }
1901 M.getGlobalList().erase(GV);
1902 ++IPNumGlobalConst;
1903 }
1904
1905 return MadeChanges;
1906}