blob: 1c227be8d93f4a8b26471a9d820e510b46fd4d35 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements sparse conditional constant propagation and merging:
11//
12// Specifically, this:
13// * Assumes values are constant unless proven otherwise
14// * Assumes BasicBlocks are dead unless proven otherwise
15// * Proves values to be constant, and replaces them with constants
16// * Proves conditional branches to be unconditional
17//
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018//===----------------------------------------------------------------------===//
19
20#define DEBUG_TYPE "sccp"
21#include "llvm/Transforms/Scalar.h"
22#include "llvm/Transforms/IPO.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Instructions.h"
26#include "llvm/Pass.h"
27#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohman856193b2008-06-20 01:15:44 +000029#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/Transforms/Utils/Local.h"
31#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"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/STLExtras.h"
42#include <algorithm>
Dan Gohman249ddbf2008-03-21 23:51:57 +000043#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044using namespace llvm;
45
46STATISTIC(NumInstRemoved, "Number of instructions removed");
47STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
48
Nick Lewyckybbdfc9c2008-03-08 07:48:41 +000049STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
51STATISTIC(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 Lattner1eb405b2009-11-02 02:20:32 +000086 inline LatticeVal() : Val(0, undefined) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087
Chris Lattner1eb405b2009-11-02 02:20:32 +000088 inline bool isUndefined() const { return getLatticeValue() == undefined; }
89 inline bool isConstant() const {
90 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
91 }
92 inline bool isOverdefined() const { return getLatticeValue() == overdefined; }
93
94 inline Constant *getConstant() const {
95 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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100 inline 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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000109 inline 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
133 inline void markForcedConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000134 assert(isUndefined() && "Can't force a defined value!");
135 Val.setInt(forcedconstant);
136 Val.setPointer(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137 }
138};
139
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140//===----------------------------------------------------------------------===//
141//
142/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
143/// Constant Propagation.
144///
145class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000146 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Bill Wendling03488ae2008-08-14 23:05:24 +0000147 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148
149 /// GlobalValue - If we are tracking any values for the contents of a global
150 /// variable, we keep a mapping from the constant accessor to the element of
151 /// the global, to the currently known value. If the value becomes
152 /// overdefined, it's entry is simply removed from this map.
153 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
154
Devang Pateladd320d2008-03-11 05:46:42 +0000155 /// TrackedRetVals - If we are tracking arguments into and the return
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 /// value out of a function, it will have an entry in this map, indicating
157 /// what the known return value for the function is.
Devang Pateladd320d2008-03-11 05:46:42 +0000158 DenseMap<Function*, LatticeVal> TrackedRetVals;
159
160 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
161 /// that return multiple values.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000162 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163
164 // The reason for two worklists is that overdefined is the lowest state
165 // on the lattice, and moving things to overdefined as fast as possible
166 // makes SCCP converge much faster.
167 // By having a separate worklist, we accomplish this because everything
168 // possibly overdefined will become overdefined at the soonest possible
169 // point.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000170 SmallVector<Value*, 64> OverdefinedInstWorkList;
171 SmallVector<Value*, 64> InstWorkList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172
173
Chris Lattnerd3123a72008-08-23 23:36:38 +0000174 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175
176 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
177 /// overdefined, despite the fact that the PHI node is overdefined.
178 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
179
180 /// KnownFeasibleEdges - Entries in this set are edges which have already had
181 /// PHI nodes retriggered.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000182 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
183 DenseSet<Edge> KnownFeasibleEdges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184public:
185
186 /// MarkBlockExecutable - This method can be used by clients to mark all of
187 /// the blocks that are known to be intrinsically live in the processed unit.
188 void MarkBlockExecutable(BasicBlock *BB) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000189 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 BBExecutable.insert(BB); // Basic block is executable!
191 BBWorkList.push_back(BB); // Add the block to the work list!
192 }
193
194 /// TrackValueOfGlobalVariable - Clients can use this method to
195 /// inform the SCCPSolver that it should track loads and stores to the
196 /// specified global variable if it can. This is only legal to call if
197 /// performing Interprocedural SCCP.
198 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
199 const Type *ElTy = GV->getType()->getElementType();
200 if (ElTy->isFirstClassType()) {
201 LatticeVal &IV = TrackedGlobals[GV];
202 if (!isa<UndefValue>(GV->getInitializer()))
203 IV.markConstant(GV->getInitializer());
204 }
205 }
206
207 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
208 /// and out of the specified function (which cannot have its address taken),
209 /// this method must be called.
210 void AddTrackedFunction(Function *F) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000211 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 // Add an entry, F -> undef.
Devang Pateladd320d2008-03-11 05:46:42 +0000213 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
214 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnercd73be02008-04-23 05:38:20 +0000215 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
216 LatticeVal()));
217 } else
218 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 }
220
221 /// Solve - Solve for constants and executable blocks.
222 ///
223 void Solve();
224
225 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
226 /// that branches on undef values cannot reach any of their successors.
227 /// However, this is not a safe assumption. After we solve dataflow, this
228 /// method should be use to handle this. If this returns true, the solver
229 /// should be rerun.
230 bool ResolvedUndefsIn(Function &F);
231
Chris Lattner317e6b62008-08-23 23:39:31 +0000232 bool isBlockExecutable(BasicBlock *BB) const {
233 return BBExecutable.count(BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 }
235
236 /// getValueMapping - Once we have solved for constants, return the mapping of
237 /// LLVM values to LatticeVals.
Bill Wendling03488ae2008-08-14 23:05:24 +0000238 std::map<Value*, LatticeVal> &getValueMapping() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 return ValueState;
240 }
241
Devang Pateladd320d2008-03-11 05:46:42 +0000242 /// getTrackedRetVals - Get the inferred return value map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243 ///
Devang Pateladd320d2008-03-11 05:46:42 +0000244 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
245 return TrackedRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 }
247
248 /// getTrackedGlobals - Get and return the set of inferred initializers for
249 /// global variables.
250 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
251 return TrackedGlobals;
252 }
253
254 inline void markOverdefined(Value *V) {
255 markOverdefined(ValueState[V], V);
256 }
257
258private:
259 // markConstant - Make a value be marked as "constant". If the value
260 // is not already a constant, add it to the instruction work list so that
261 // the users of the instruction are updated later.
262 //
263 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
264 if (IV.markConstant(C)) {
Dan Gohmandff8d172009-08-17 15:25:05 +0000265 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266 InstWorkList.push_back(V);
267 }
268 }
269
270 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
271 IV.markForcedConstant(C);
Dan Gohmandff8d172009-08-17 15:25:05 +0000272 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 InstWorkList.push_back(V);
274 }
275
276 inline void markConstant(Value *V, Constant *C) {
277 markConstant(ValueState[V], V, C);
278 }
279
280 // markOverdefined - Make a value be marked as "overdefined". If the
281 // value is not already overdefined, add it to the overdefined instruction
282 // work list so that the users of the instruction are updated later.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 inline void markOverdefined(LatticeVal &IV, Value *V) {
284 if (IV.markOverdefined()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +0000285 DEBUG(errs() << "markOverdefined: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 if (Function *F = dyn_cast<Function>(V))
Daniel Dunbar005975c2009-07-25 00:23:56 +0000287 errs() << "Function '" << F->getName() << "'\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 else
Dan Gohmandff8d172009-08-17 15:25:05 +0000289 errs() << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 // Only instructions go on the work list
291 OverdefinedInstWorkList.push_back(V);
292 }
293 }
294
295 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
296 if (IV.isOverdefined() || MergeWithV.isUndefined())
297 return; // Noop.
298 if (MergeWithV.isOverdefined())
299 markOverdefined(IV, V);
300 else if (IV.isUndefined())
301 markConstant(IV, V, MergeWithV.getConstant());
302 else if (IV.getConstant() != MergeWithV.getConstant())
303 markOverdefined(IV, V);
304 }
305
306 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
307 return mergeInValue(ValueState[V], V, MergeWithV);
308 }
309
310
311 // getValueState - Return the LatticeVal object that corresponds to the value.
312 // This function is necessary because not all values should start out in the
Chris Lattnerc8798002009-11-02 02:33:50 +0000313 // underdefined state. Argument's should be overdefined, and
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314 // constants should be marked as constants. If a value is not known to be an
315 // Instruction object, then use this accessor to get its value from the map.
316 //
317 inline LatticeVal &getValueState(Value *V) {
Bill Wendling03488ae2008-08-14 23:05:24 +0000318 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 if (I != ValueState.end()) return I->second; // Common case, in the map
320
321 if (Constant *C = dyn_cast<Constant>(V)) {
322 if (isa<UndefValue>(V)) {
323 // Nothing to do, remain undefined.
324 } else {
325 LatticeVal &LV = ValueState[C];
326 LV.markConstant(C); // Constants are constant
327 return LV;
328 }
329 }
Chris Lattnerc8798002009-11-02 02:33:50 +0000330 // All others are underdefined by default.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 return ValueState[V];
332 }
333
334 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattnerc8798002009-11-02 02:33:50 +0000335 // work list if it is not already executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336 //
337 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
338 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
339 return; // This edge is already known to be executable!
340
341 if (BBExecutable.count(Dest)) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000342 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
343 << " -> " << Dest->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344
345 // The destination is already executable, but we just made an edge
346 // feasible that wasn't before. Revisit the PHI nodes in the block
347 // because they have potentially new operands.
348 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
349 visitPHINode(*cast<PHINode>(I));
350
351 } else {
352 MarkBlockExecutable(Dest);
353 }
354 }
355
356 // getFeasibleSuccessors - Return a vector of booleans to indicate which
357 // successors are reachable from a given terminator instruction.
358 //
359 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
360
361 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000362 // block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 //
364 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
365
366 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnerc8798002009-11-02 02:33:50 +0000367 // instruction that was just changed state somehow. Based on this
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368 // information, we need to update the specified user of this instruction.
369 //
370 void OperandChangedState(User *U) {
371 // Only instructions use other variable values!
372 Instruction &I = cast<Instruction>(*U);
373 if (BBExecutable.count(I.getParent())) // Inst is executable?
374 visit(I);
375 }
376
377private:
378 friend class InstVisitor<SCCPSolver>;
379
Chris Lattnerc8798002009-11-02 02:33:50 +0000380 // visit implementations - Something changed in this instruction. Either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 // operand made a transition, or the instruction is newly executable. Change
382 // the value type of I to reflect these changes if appropriate.
383 //
384 void visitPHINode(PHINode &I);
385
386 // Terminators
387 void visitReturnInst(ReturnInst &I);
388 void visitTerminatorInst(TerminatorInst &TI);
389
390 void visitCastInst(CastInst &I);
391 void visitSelectInst(SelectInst &I);
392 void visitBinaryOperator(Instruction &I);
393 void visitCmpInst(CmpInst &I);
394 void visitExtractElementInst(ExtractElementInst &I);
395 void visitInsertElementInst(InsertElementInst &I);
396 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman856193b2008-06-20 01:15:44 +0000397 void visitExtractValueInst(ExtractValueInst &EVI);
398 void visitInsertValueInst(InsertValueInst &IVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399
Chris Lattnerc8798002009-11-02 02:33:50 +0000400 // Instructions that cannot be folded away.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401 void visitStoreInst (Instruction &I);
402 void visitLoadInst (LoadInst &I);
403 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez93946082009-10-24 04:23:03 +0000404 void visitCallInst (CallInst &I) {
405 if (isFreeCall(&I))
406 return;
Chris Lattner6ad04a02009-09-27 21:35:11 +0000407 visitCallSite(CallSite::get(&I));
Victor Hernandez48c3c542009-09-18 22:35:49 +0000408 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409 void visitInvokeInst (InvokeInst &II) {
410 visitCallSite(CallSite::get(&II));
411 visitTerminatorInst(II);
412 }
413 void visitCallSite (CallSite CS);
414 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
415 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandezb1687302009-10-23 21:09:37 +0000416 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
418 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419
420 void visitInstruction(Instruction &I) {
Chris Lattnerc8798002009-11-02 02:33:50 +0000421 // If a new instruction is added to LLVM that we don't handle.
Chris Lattner8a6411c2009-08-23 04:37:46 +0000422 errs() << "SCCP: Don't know how to handle: " << I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423 markOverdefined(&I); // Just in case
424 }
425};
426
Duncan Sands40f67972007-07-20 08:56:21 +0000427} // end anonymous namespace
428
429
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430// getFeasibleSuccessors - Return a vector of booleans to indicate which
431// successors are reachable from a given terminator instruction.
432//
433void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
434 SmallVector<bool, 16> &Succs) {
435 Succs.resize(TI.getNumSuccessors());
436 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
437 if (BI->isUnconditional()) {
438 Succs[0] = true;
Chris Lattneradaf7332009-11-02 02:30:06 +0000439 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440 }
Chris Lattneradaf7332009-11-02 02:30:06 +0000441
442 LatticeVal &BCValue = getValueState(BI->getCondition());
443 if (BCValue.isOverdefined() ||
444 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
445 // Overdefined condition variables, and branches on unfoldable constant
446 // conditions, mean the branch could go either way.
447 Succs[0] = Succs[1] = true;
448 return;
449 }
450
451 // Constant condition variables mean the branch can only go a single way.
452 Succs[cast<ConstantInt>(BCValue.getConstant())->isZero()] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000453 return;
454 }
455
456 if (isa<InvokeInst>(&TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000457 // Invoke instructions successors are always executable.
458 Succs[0] = Succs[1] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000459 return;
460 }
461
462 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000463 LatticeVal &SCValue = getValueState(SI->getCondition());
464 if (SCValue.isOverdefined() || // Overdefined condition?
465 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
466 // All destinations are executable!
467 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner81335532008-05-10 23:56:54 +0000468 } else if (SCValue.isConstant())
469 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000470 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000471 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000472
473 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
474 if (isa<IndirectBrInst>(&TI)) {
475 // Just mark all destinations executable!
476 Succs.assign(TI.getNumSuccessors(), true);
477 return;
478 }
479
480#ifndef NDEBUG
481 errs() << "Unknown terminator instruction: " << TI << '\n';
482#endif
483 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000484}
485
486
487// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000488// block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000489//
490bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
491 assert(BBExecutable.count(To) && "Dest should always be alive!");
492
493 // Make sure the source basic block is executable!!
494 if (!BBExecutable.count(From)) return false;
495
Chris Lattnerc8798002009-11-02 02:33:50 +0000496 // Check to make sure this edge itself is actually feasible now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 TerminatorInst *TI = From->getTerminator();
498 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
499 if (BI->isUnconditional())
500 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000501
502 LatticeVal &BCValue = getValueState(BI->getCondition());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503
Chris Lattneradaf7332009-11-02 02:30:06 +0000504 // Overdefined condition variables mean the branch could go either way,
505 // undef conditions mean that neither edge is feasible yet.
506 if (!BCValue.isConstant())
507 return BCValue.isOverdefined();
508
509 // Not branching on an evaluatable constant?
510 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
511
512 // Constant condition variables mean the branch can only go a single way.
513 bool CondIsFalse = cast<ConstantInt>(BCValue.getConstant())->isZero();
514 return BI->getSuccessor(CondIsFalse) == To;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000515 }
516
517 // Invoke instructions successors are always executable.
518 if (isa<InvokeInst>(TI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000520
521 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000522 LatticeVal &SCValue = getValueState(SI->getCondition());
523 if (SCValue.isOverdefined()) { // Overdefined condition?
524 // All destinations are executable!
525 return true;
526 } else if (SCValue.isConstant()) {
527 Constant *CPV = SCValue.getConstant();
528 if (!isa<ConstantInt>(CPV))
529 return true; // not a foldable constant?
530
531 // Make sure to skip the "default value" which isn't a value
532 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
Chris Lattnerc8798002009-11-02 02:33:50 +0000533 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 return SI->getSuccessor(i) == To;
535
Chris Lattnerc8798002009-11-02 02:33:50 +0000536 // If the constant value is not equal to any of the branches, we must
537 // execute default branch.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538 return SI->getDefaultDest() == To;
539 }
540 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000542
543 // Just mark all destinations executable!
544 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
545 if (isa<IndirectBrInst>(&TI))
546 return true;
547
548#ifndef NDEBUG
549 errs() << "Unknown terminator instruction: " << *TI << '\n';
550#endif
551 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000552}
553
Chris Lattnerc8798002009-11-02 02:33:50 +0000554// visit Implementations - Something changed in this instruction, either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000555// operand made a transition, or the instruction is newly executable. Change
556// the value type of I to reflect these changes if appropriate. This method
557// makes sure to do the following actions:
558//
559// 1. If a phi node merges two constants in, and has conflicting value coming
560// from different branches, or if the PHI node merges in an overdefined
561// value, then the PHI node becomes overdefined.
562// 2. If a phi node merges only constants in, and they all agree on value, the
563// PHI node becomes a constant value equal to that.
564// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
565// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
566// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
567// 6. If a conditional branch has a value that is constant, make the selected
568// destination executable
569// 7. If a conditional branch has a value that is overdefined, make all
570// successors executable.
571//
572void SCCPSolver::visitPHINode(PHINode &PN) {
573 LatticeVal &PNIV = getValueState(&PN);
574 if (PNIV.isOverdefined()) {
575 // There may be instructions using this PHI node that are not overdefined
576 // themselves. If so, make sure that they know that the PHI node operand
577 // changed.
578 std::multimap<PHINode*, Instruction*>::iterator I, E;
579 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
580 if (I != E) {
581 SmallVector<Instruction*, 16> Users;
582 for (; I != E; ++I) Users.push_back(I->second);
583 while (!Users.empty()) {
584 visit(Users.back());
585 Users.pop_back();
586 }
587 }
588 return; // Quick exit
589 }
590
591 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
592 // and slow us down a lot. Just mark them overdefined.
593 if (PN.getNumIncomingValues() > 64) {
594 markOverdefined(PNIV, &PN);
595 return;
596 }
597
598 // Look at all of the executable operands of the PHI node. If any of them
599 // are overdefined, the PHI becomes overdefined as well. If they are all
600 // constant, and they agree with each other, the PHI becomes the identical
601 // constant. If they are constant and don't agree, the PHI is overdefined.
602 // If there are no executable operands, the PHI remains undefined.
603 //
604 Constant *OperandVal = 0;
605 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
606 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
607 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
608
609 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
610 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattnerd3123a72008-08-23 23:36:38 +0000611 markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000612 return;
613 }
614
Chris Lattnerc8798002009-11-02 02:33:50 +0000615 if (OperandVal == 0) { // Grab the first value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 OperandVal = IV.getConstant();
617 } else { // Another value is being merged in!
618 // There is already a reachable operand. If we conflict with it,
619 // then the PHI node becomes overdefined. If we agree with it, we
620 // can continue on.
621
Chris Lattnerc8798002009-11-02 02:33:50 +0000622 // Check to see if there are two different constants merging.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623 if (IV.getConstant() != OperandVal) {
624 // Yes there is. This means the PHI node is not constant.
625 // You must be overdefined poor PHI.
626 //
Chris Lattnerd3123a72008-08-23 23:36:38 +0000627 markOverdefined(&PN); // The PHI node now becomes overdefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 return; // I'm done analyzing you
629 }
630 }
631 }
632 }
633
634 // If we exited the loop, this means that the PHI node only has constant
635 // arguments that agree with each other(and OperandVal is the constant) or
636 // OperandVal is null because there are no defined incoming arguments. If
637 // this is the case, the PHI remains undefined.
638 //
639 if (OperandVal)
Chris Lattnerd3123a72008-08-23 23:36:38 +0000640 markConstant(&PN, OperandVal); // Acquire operand value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641}
642
643void SCCPSolver::visitReturnInst(ReturnInst &I) {
644 if (I.getNumOperands() == 0) return; // Ret void
645
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646 Function *F = I.getParent()->getParent();
Devang Pateladd320d2008-03-11 05:46:42 +0000647 // If we are tracking the return value of this function, merge it in.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000648 if (!F->hasLocalLinkage())
Devang Pateladd320d2008-03-11 05:46:42 +0000649 return;
650
Chris Lattnercd73be02008-04-23 05:38:20 +0000651 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Pateladd320d2008-03-11 05:46:42 +0000653 TrackedRetVals.find(F);
654 if (TFRVI != TrackedRetVals.end() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 !TFRVI->second.isOverdefined()) {
656 LatticeVal &IV = getValueState(I.getOperand(0));
657 mergeInValue(TFRVI->second, F, IV);
Devang Pateladd320d2008-03-11 05:46:42 +0000658 return;
659 }
660 }
661
Chris Lattnercd73be02008-04-23 05:38:20 +0000662 // Handle functions that return multiple values.
663 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
664 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000665 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnercd73be02008-04-23 05:38:20 +0000666 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
667 if (It == TrackedMultipleRetVals.end()) break;
668 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 }
Dan Gohman856193b2008-06-20 01:15:44 +0000670 } else if (!TrackedMultipleRetVals.empty() &&
671 I.getNumOperands() == 1 &&
672 isa<StructType>(I.getOperand(0)->getType())) {
673 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
674 i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000675 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000676 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
677 if (It == TrackedMultipleRetVals.end()) break;
Owen Anderson175b6542009-07-22 00:24:57 +0000678 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewycky6ad29e02009-06-06 23:13:08 +0000679 mergeInValue(It->second, F, getValueState(Val));
Dan Gohman856193b2008-06-20 01:15:44 +0000680 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681 }
682}
683
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
685 SmallVector<bool, 16> SuccFeasible;
686 getFeasibleSuccessors(TI, SuccFeasible);
687
688 BasicBlock *BB = TI.getParent();
689
Chris Lattnerc8798002009-11-02 02:33:50 +0000690 // Mark all feasible successors executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
692 if (SuccFeasible[i])
693 markEdgeExecutable(BB, TI.getSuccessor(i));
694}
695
696void SCCPSolver::visitCastInst(CastInst &I) {
697 Value *V = I.getOperand(0);
698 LatticeVal &VState = getValueState(V);
699 if (VState.isOverdefined()) // Inherit overdefinedness of operand
700 markOverdefined(&I);
701 else if (VState.isConstant()) // Propagate constant value
Owen Anderson02b48c32009-07-29 18:55:55 +0000702 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000703 VState.getConstant(), I.getType()));
704}
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.
714 if (EVI.getNumIndices() != 1) {
715 markOverdefined(&EVI);
716 return;
717 }
718
719 Function *F = 0;
720 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
721 F = CI->getCalledFunction();
722 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
723 F = II->getCalledFunction();
724
725 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
726 // result back!
727 if (F == 0 || TrackedMultipleRetVals.empty()) {
728 markOverdefined(&EVI);
729 return;
730 }
731
Chris Lattnerd3123a72008-08-23 23:36:38 +0000732 // See if we are tracking the result of the callee. If not tracking this
733 // function (for example, it is a declaration) just move to overdefined.
734 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
Dan Gohman856193b2008-06-20 01:15:44 +0000735 markOverdefined(&EVI);
736 return;
737 }
738
739 // Otherwise, the value will be merged in here as a result of CallSite
740 // handling.
741}
742
743void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000744 Value *Aggr = IVI.getAggregateOperand();
745 Value *Val = IVI.getInsertedValueOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000746
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000747 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohman78b2c392008-06-20 16:39:44 +0000748 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohman856193b2008-06-20 01:15:44 +0000749 return;
750
751 // Currently only handle single-index insertvalues.
752 if (IVI.getNumIndices() != 1) {
753 markOverdefined(&IVI);
754 return;
755 }
Dan Gohman78b2c392008-06-20 16:39:44 +0000756
757 // Currently only handle insertvalue instructions that are in a single-use
758 // chain that builds up a return value.
759 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
760 if (!TmpIVI->hasOneUse()) {
761 markOverdefined(&IVI);
762 return;
763 }
764 const Value *V = *TmpIVI->use_begin();
765 if (isa<ReturnInst>(V))
766 break;
767 TmpIVI = dyn_cast<InsertValueInst>(V);
768 if (!TmpIVI) {
769 markOverdefined(&IVI);
770 return;
771 }
772 }
Dan Gohman856193b2008-06-20 01:15:44 +0000773
774 // See if we are tracking the result of the callee.
775 Function *F = IVI.getParent()->getParent();
Chris Lattnerd3123a72008-08-23 23:36:38 +0000776 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000777 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
778
779 // Merge in the inserted member value.
780 if (It != TrackedMultipleRetVals.end())
781 mergeInValue(It->second, F, getValueState(Val));
782
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000783 // Mark the aggregate result of the IVI overdefined; any tracking that we do
784 // will be done on the individual member values.
Dan Gohman856193b2008-06-20 01:15:44 +0000785 markOverdefined(&IVI);
786}
787
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788void SCCPSolver::visitSelectInst(SelectInst &I) {
789 LatticeVal &CondValue = getValueState(I.getCondition());
790 if (CondValue.isUndefined())
791 return;
792 if (CondValue.isConstant()) {
793 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
794 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
795 : I.getFalseValue()));
796 return;
797 }
798 }
799
800 // Otherwise, the condition is overdefined or a constant we can't evaluate.
801 // See if we can produce something better than overdefined based on the T/F
802 // value.
803 LatticeVal &TVal = getValueState(I.getTrueValue());
804 LatticeVal &FVal = getValueState(I.getFalseValue());
805
806 // select ?, C, C -> C.
807 if (TVal.isConstant() && FVal.isConstant() &&
808 TVal.getConstant() == FVal.getConstant()) {
809 markConstant(&I, FVal.getConstant());
810 return;
811 }
812
813 if (TVal.isUndefined()) { // select ?, undef, X -> X.
814 mergeInValue(&I, FVal);
815 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
816 mergeInValue(&I, TVal);
817 } else {
818 markOverdefined(&I);
819 }
820}
821
Chris Lattnerc8798002009-11-02 02:33:50 +0000822// Handle BinaryOperators and Shift Instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000823void SCCPSolver::visitBinaryOperator(Instruction &I) {
824 LatticeVal &IV = ValueState[&I];
825 if (IV.isOverdefined()) return;
826
827 LatticeVal &V1State = getValueState(I.getOperand(0));
828 LatticeVal &V2State = getValueState(I.getOperand(1));
829
830 if (V1State.isOverdefined() || V2State.isOverdefined()) {
831 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
832 // operand is overdefined.
833 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
834 LatticeVal *NonOverdefVal = 0;
835 if (!V1State.isOverdefined()) {
836 NonOverdefVal = &V1State;
837 } else if (!V2State.isOverdefined()) {
838 NonOverdefVal = &V2State;
839 }
840
841 if (NonOverdefVal) {
842 if (NonOverdefVal->isUndefined()) {
843 // Could annihilate value.
844 if (I.getOpcode() == Instruction::And)
Owen Andersonaac28372009-07-31 20:28:14 +0000845 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
Owen Andersonaac28372009-07-31 20:28:14 +0000847 markConstant(IV, &I, Constant::getAllOnesValue(PT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848 else
Owen Andersonfa089ab2009-07-03 19:42:02 +0000849 markConstant(IV, &I,
Owen Andersonaac28372009-07-31 20:28:14 +0000850 Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 return;
852 } else {
853 if (I.getOpcode() == Instruction::And) {
854 if (NonOverdefVal->getConstant()->isNullValue()) {
855 markConstant(IV, &I, NonOverdefVal->getConstant());
856 return; // X and 0 = 0
857 }
858 } else {
859 if (ConstantInt *CI =
860 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
861 if (CI->isAllOnesValue()) {
862 markConstant(IV, &I, NonOverdefVal->getConstant());
863 return; // X or -1 = -1
864 }
865 }
866 }
867 }
868 }
869
870
871 // If both operands are PHI nodes, it is possible that this instruction has
872 // a constant value, despite the fact that the PHI node doesn't. Check for
873 // this condition now.
874 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
875 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
876 if (PN1->getParent() == PN2->getParent()) {
877 // Since the two PHI nodes are in the same basic block, they must have
878 // entries for the same predecessors. Walk the predecessor list, and
879 // if all of the incoming values are constants, and the result of
880 // evaluating this expression with all incoming value pairs is the
881 // same, then this expression is a constant even though the PHI node
882 // is not a constant!
883 LatticeVal Result;
884 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
885 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
886 BasicBlock *InBlock = PN1->getIncomingBlock(i);
887 LatticeVal &In2 =
888 getValueState(PN2->getIncomingValueForBlock(InBlock));
889
890 if (In1.isOverdefined() || In2.isOverdefined()) {
891 Result.markOverdefined();
892 break; // Cannot fold this operation over the PHI nodes!
893 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000894 Constant *V =
Owen Anderson02b48c32009-07-29 18:55:55 +0000895 ConstantExpr::get(I.getOpcode(), In1.getConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000896 In2.getConstant());
897 if (Result.isUndefined())
898 Result.markConstant(V);
899 else if (Result.isConstant() && Result.getConstant() != V) {
900 Result.markOverdefined();
901 break;
902 }
903 }
904 }
905
906 // If we found a constant value here, then we know the instruction is
907 // constant despite the fact that the PHI nodes are overdefined.
908 if (Result.isConstant()) {
909 markConstant(IV, &I, Result.getConstant());
910 // Remember that this instruction is virtually using the PHI node
911 // operands.
912 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
913 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
914 return;
915 } else if (Result.isUndefined()) {
916 return;
917 }
918
919 // Okay, this really is overdefined now. Since we might have
920 // speculatively thought that this was not overdefined before, and
921 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
922 // make sure to clean out any entries that we put there, for
923 // efficiency.
924 std::multimap<PHINode*, Instruction*>::iterator It, E;
925 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
926 while (It != E) {
927 if (It->second == &I) {
928 UsersOfOverdefinedPHIs.erase(It++);
929 } else
930 ++It;
931 }
932 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
933 while (It != E) {
934 if (It->second == &I) {
935 UsersOfOverdefinedPHIs.erase(It++);
936 } else
937 ++It;
938 }
939 }
940
941 markOverdefined(IV, &I);
942 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000943 markConstant(IV, &I,
Owen Anderson02b48c32009-07-29 18:55:55 +0000944 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945 V2State.getConstant()));
946 }
947}
948
Chris Lattnerc8798002009-11-02 02:33:50 +0000949// Handle ICmpInst instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000950void SCCPSolver::visitCmpInst(CmpInst &I) {
951 LatticeVal &IV = ValueState[&I];
952 if (IV.isOverdefined()) return;
953
954 LatticeVal &V1State = getValueState(I.getOperand(0));
955 LatticeVal &V2State = getValueState(I.getOperand(1));
956
957 if (V1State.isOverdefined() || V2State.isOverdefined()) {
958 // If both operands are PHI nodes, it is possible that this instruction has
959 // a constant value, despite the fact that the PHI node doesn't. Check for
960 // this condition now.
961 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
962 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
963 if (PN1->getParent() == PN2->getParent()) {
964 // Since the two PHI nodes are in the same basic block, they must have
965 // entries for the same predecessors. Walk the predecessor list, and
966 // if all of the incoming values are constants, and the result of
967 // evaluating this expression with all incoming value pairs is the
968 // same, then this expression is a constant even though the PHI node
969 // is not a constant!
970 LatticeVal Result;
971 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
972 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
973 BasicBlock *InBlock = PN1->getIncomingBlock(i);
974 LatticeVal &In2 =
975 getValueState(PN2->getIncomingValueForBlock(InBlock));
976
977 if (In1.isOverdefined() || In2.isOverdefined()) {
978 Result.markOverdefined();
979 break; // Cannot fold this operation over the PHI nodes!
980 } else if (In1.isConstant() && In2.isConstant()) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000981 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 In1.getConstant(),
983 In2.getConstant());
984 if (Result.isUndefined())
985 Result.markConstant(V);
986 else if (Result.isConstant() && Result.getConstant() != V) {
987 Result.markOverdefined();
988 break;
989 }
990 }
991 }
992
993 // If we found a constant value here, then we know the instruction is
994 // constant despite the fact that the PHI nodes are overdefined.
995 if (Result.isConstant()) {
996 markConstant(IV, &I, Result.getConstant());
997 // Remember that this instruction is virtually using the PHI node
998 // operands.
999 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
1000 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
1001 return;
1002 } else if (Result.isUndefined()) {
1003 return;
1004 }
1005
1006 // Okay, this really is overdefined now. Since we might have
1007 // speculatively thought that this was not overdefined before, and
1008 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1009 // make sure to clean out any entries that we put there, for
1010 // efficiency.
1011 std::multimap<PHINode*, Instruction*>::iterator It, E;
1012 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
1013 while (It != E) {
1014 if (It->second == &I) {
1015 UsersOfOverdefinedPHIs.erase(It++);
1016 } else
1017 ++It;
1018 }
1019 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
1020 while (It != E) {
1021 if (It->second == &I) {
1022 UsersOfOverdefinedPHIs.erase(It++);
1023 } else
1024 ++It;
1025 }
1026 }
1027
1028 markOverdefined(IV, &I);
1029 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00001030 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 V1State.getConstant(),
1032 V2State.getConstant()));
1033 }
1034}
1035
1036void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1037 // FIXME : SCCP does not handle vectors properly.
1038 markOverdefined(&I);
1039 return;
1040
1041#if 0
1042 LatticeVal &ValState = getValueState(I.getOperand(0));
1043 LatticeVal &IdxState = getValueState(I.getOperand(1));
1044
1045 if (ValState.isOverdefined() || IdxState.isOverdefined())
1046 markOverdefined(&I);
1047 else if(ValState.isConstant() && IdxState.isConstant())
1048 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1049 IdxState.getConstant()));
1050#endif
1051}
1052
1053void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1054 // FIXME : SCCP does not handle vectors properly.
1055 markOverdefined(&I);
1056 return;
1057#if 0
1058 LatticeVal &ValState = getValueState(I.getOperand(0));
1059 LatticeVal &EltState = getValueState(I.getOperand(1));
1060 LatticeVal &IdxState = getValueState(I.getOperand(2));
1061
1062 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1063 IdxState.isOverdefined())
1064 markOverdefined(&I);
1065 else if(ValState.isConstant() && EltState.isConstant() &&
1066 IdxState.isConstant())
1067 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1068 EltState.getConstant(),
1069 IdxState.getConstant()));
1070 else if (ValState.isUndefined() && EltState.isConstant() &&
1071 IdxState.isConstant())
1072 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1073 EltState.getConstant(),
1074 IdxState.getConstant()));
1075#endif
1076}
1077
1078void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1079 // FIXME : SCCP does not handle vectors properly.
1080 markOverdefined(&I);
1081 return;
1082#if 0
1083 LatticeVal &V1State = getValueState(I.getOperand(0));
1084 LatticeVal &V2State = getValueState(I.getOperand(1));
1085 LatticeVal &MaskState = getValueState(I.getOperand(2));
1086
1087 if (MaskState.isUndefined() ||
1088 (V1State.isUndefined() && V2State.isUndefined()))
1089 return; // Undefined output if mask or both inputs undefined.
1090
1091 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1092 MaskState.isOverdefined()) {
1093 markOverdefined(&I);
1094 } else {
1095 // A mix of constant/undef inputs.
1096 Constant *V1 = V1State.isConstant() ?
1097 V1State.getConstant() : UndefValue::get(I.getType());
1098 Constant *V2 = V2State.isConstant() ?
1099 V2State.getConstant() : UndefValue::get(I.getType());
1100 Constant *Mask = MaskState.isConstant() ?
1101 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1102 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1103 }
1104#endif
1105}
1106
Chris Lattnerc8798002009-11-02 02:33:50 +00001107// Handle getelementptr instructions. If all operands are constants then we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108// can turn this into a getelementptr ConstantExpr.
1109//
1110void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1111 LatticeVal &IV = ValueState[&I];
1112 if (IV.isOverdefined()) return;
1113
1114 SmallVector<Constant*, 8> Operands;
1115 Operands.reserve(I.getNumOperands());
1116
1117 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1118 LatticeVal &State = getValueState(I.getOperand(i));
1119 if (State.isUndefined())
Chris Lattnerc8798002009-11-02 02:33:50 +00001120 return; // Operands are not resolved yet.
1121
1122 if (State.isOverdefined()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001123 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];
Chris Lattnerc8798002009-11-02 02:33:50 +00001131 Operands.erase(Operands.begin()); // Erase the pointer from idx list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132
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()) {
Chris Lattnerc8798002009-11-02 02:33:50 +00001310 // Process the instruction work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 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
Chris Lattnerc8798002009-11-02 02:33:50 +00001322 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 //
1324 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1325 UI != E; ++UI)
1326 OperandChangedState(*UI);
1327 }
Chris Lattnerc8798002009-11-02 02:33:50 +00001328
1329 // Process the instruction work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 while (!InstWorkList.empty()) {
1331 Value *I = InstWorkList.back();
1332 InstWorkList.pop_back();
1333
Dan Gohmandff8d172009-08-17 15:25:05 +00001334 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335
1336 // "I" got into the work list because it either made the transition from
1337 // bottom to constant
1338 //
1339 // Anything on this worklist that is overdefined need not be visited
1340 // since all of its users will have already been marked as overdefined.
Chris Lattnerc8798002009-11-02 02:33:50 +00001341 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342 //
1343 if (!getValueState(I).isOverdefined())
1344 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1345 UI != E; ++UI)
1346 OperandChangedState(*UI);
1347 }
1348
Chris Lattnerc8798002009-11-02 02:33:50 +00001349 // Process the basic block work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001350 while (!BBWorkList.empty()) {
1351 BasicBlock *BB = BBWorkList.back();
1352 BBWorkList.pop_back();
1353
Dan Gohmandff8d172009-08-17 15:25:05 +00001354 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355
1356 // Notify all instructions in this basic block that they are newly
1357 // executable.
1358 visit(BB);
1359 }
1360 }
1361}
1362
1363/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1364/// that branches on undef values cannot reach any of their successors.
1365/// However, this is not a safe assumption. After we solve dataflow, this
1366/// method should be use to handle this. If this returns true, the solver
1367/// should be rerun.
1368///
1369/// This method handles this by finding an unresolved branch and marking it one
1370/// of the edges from the block as being feasible, even though the condition
1371/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1372/// CFG and only slightly pessimizes the analysis results (by marking one,
1373/// potentially infeasible, edge feasible). This cannot usefully modify the
1374/// constraints on the condition of the branch, as that would impact other users
1375/// of the value.
1376///
1377/// This scan also checks for values that use undefs, whose results are actually
1378/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1379/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1380/// even if X isn't defined.
1381bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1382 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1383 if (!BBExecutable.count(BB))
1384 continue;
1385
1386 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1387 // Look for instructions which produce undef values.
Chris Lattner82cdc062009-10-05 05:54:46 +00001388 if (I->getType()->isVoidTy()) continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001389
1390 LatticeVal &LV = getValueState(I);
1391 if (!LV.isUndefined()) continue;
1392
1393 // Get the lattice values of the first two operands for use below.
1394 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1395 LatticeVal Op1LV;
1396 if (I->getNumOperands() == 2) {
1397 // If this is a two-operand instruction, and if both operands are
1398 // undefs, the result stays undef.
1399 Op1LV = getValueState(I->getOperand(1));
1400 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1401 continue;
1402 }
1403
1404 // If this is an instructions whose result is defined even if the input is
1405 // not fully defined, propagate the information.
1406 const Type *ITy = I->getType();
1407 switch (I->getOpcode()) {
1408 default: break; // Leave the instruction as an undef.
1409 case Instruction::ZExt:
1410 // After a zero extend, we know the top part is zero. SExt doesn't have
1411 // to be handled here, because we don't know whether the top part is 1's
1412 // or 0's.
1413 assert(Op0LV.isUndefined());
Owen Andersonaac28372009-07-31 20:28:14 +00001414 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001415 return true;
1416 case Instruction::Mul:
1417 case Instruction::And:
1418 // undef * X -> 0. X could be zero.
1419 // undef & X -> 0. X could be zero.
Owen Andersonaac28372009-07-31 20:28:14 +00001420 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001421 return true;
1422
1423 case Instruction::Or:
1424 // undef | X -> -1. X could be -1.
1425 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
Owen Andersonfa089ab2009-07-03 19:42:02 +00001426 markForcedConstant(LV, I,
Owen Andersonaac28372009-07-31 20:28:14 +00001427 Constant::getAllOnesValue(PTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001428 else
Owen Andersonaac28372009-07-31 20:28:14 +00001429 markForcedConstant(LV, I, Constant::getAllOnesValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001430 return true;
1431
1432 case Instruction::SDiv:
1433 case Instruction::UDiv:
1434 case Instruction::SRem:
1435 case Instruction::URem:
1436 // X / undef -> undef. No change.
1437 // X % undef -> undef. No change.
1438 if (Op1LV.isUndefined()) break;
1439
1440 // undef / X -> 0. X could be maxint.
1441 // undef % X -> 0. X could be 1.
Owen Andersonaac28372009-07-31 20:28:14 +00001442 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001443 return true;
1444
1445 case Instruction::AShr:
1446 // undef >>s X -> undef. No change.
1447 if (Op0LV.isUndefined()) break;
1448
1449 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1450 if (Op0LV.isConstant())
1451 markForcedConstant(LV, I, Op0LV.getConstant());
1452 else
1453 markOverdefined(LV, I);
1454 return true;
1455 case Instruction::LShr:
1456 case Instruction::Shl:
1457 // undef >> X -> undef. No change.
1458 // undef << X -> undef. No change.
1459 if (Op0LV.isUndefined()) break;
1460
1461 // X >> undef -> 0. X could be 0.
1462 // X << undef -> 0. X could be 0.
Owen Andersonaac28372009-07-31 20:28:14 +00001463 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001464 return true;
1465 case Instruction::Select:
1466 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1467 if (Op0LV.isUndefined()) {
1468 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1469 Op1LV = getValueState(I->getOperand(2));
1470 } else if (Op1LV.isUndefined()) {
1471 // c ? undef : undef -> undef. No change.
1472 Op1LV = getValueState(I->getOperand(2));
1473 if (Op1LV.isUndefined())
1474 break;
1475 // Otherwise, c ? undef : x -> x.
1476 } else {
1477 // Leave Op1LV as Operand(1)'s LatticeValue.
1478 }
1479
1480 if (Op1LV.isConstant())
1481 markForcedConstant(LV, I, Op1LV.getConstant());
1482 else
1483 markOverdefined(LV, I);
1484 return true;
Chris Lattner9110ac92008-05-24 03:59:33 +00001485 case Instruction::Call:
1486 // If a call has an undef result, it is because it is constant foldable
1487 // but one of the inputs was undef. Just force the result to
1488 // overdefined.
1489 markOverdefined(LV, I);
1490 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001491 }
1492 }
1493
1494 TerminatorInst *TI = BB->getTerminator();
1495 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1496 if (!BI->isConditional()) continue;
1497 if (!getValueState(BI->getCondition()).isUndefined())
1498 continue;
1499 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001500 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesenfb06d0c2008-05-23 01:01:31 +00001501 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001502 if (!getValueState(SI->getCondition()).isUndefined())
1503 continue;
1504 } else {
1505 continue;
1506 }
1507
Chris Lattner6186e8c2008-01-28 00:32:30 +00001508 // If the edge to the second successor isn't thought to be feasible yet,
1509 // mark it so now. We pick the second one so that this goes to some
1510 // enumerated value in a switch instead of going to the default destination.
1511 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512 continue;
1513
1514 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1515 // and return. This will make other blocks reachable, which will allow new
1516 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner6186e8c2008-01-28 00:32:30 +00001517 markEdgeExecutable(BB, TI->getSuccessor(1));
1518
1519 // This must be a conditional branch of switch on undef. At this point,
1520 // force the old terminator to branch to the first successor. This is
1521 // required because we are now influencing the dataflow of the function with
1522 // the assumption that this edge is taken. If we leave the branch condition
1523 // as undef, then further analysis could think the undef went another way
1524 // leading to an inconsistent set of conclusions.
1525 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001526 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner6186e8c2008-01-28 00:32:30 +00001527 } else {
1528 SwitchInst *SI = cast<SwitchInst>(TI);
1529 SI->setCondition(SI->getCaseValue(1));
1530 }
1531
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001532 return true;
1533 }
1534
1535 return false;
1536}
1537
1538
1539namespace {
1540 //===--------------------------------------------------------------------===//
1541 //
1542 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1543 /// Sparse Conditional Constant Propagator.
1544 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001545 struct SCCP : public FunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001546 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +00001547 SCCP() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001548
1549 // runOnFunction - Run the Sparse Conditional Constant Propagation
1550 // algorithm, and return true if the function was modified.
1551 //
1552 bool runOnFunction(Function &F);
1553
1554 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1555 AU.setPreservesCFG();
1556 }
1557 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001558} // end anonymous namespace
1559
Dan Gohman089efff2008-05-13 00:00:25 +00001560char SCCP::ID = 0;
1561static RegisterPass<SCCP>
1562X("sccp", "Sparse Conditional Constant Propagation");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001563
Chris Lattnerc8798002009-11-02 02:33:50 +00001564// createSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001565FunctionPass *llvm::createSCCPPass() {
1566 return new SCCP();
1567}
1568
1569
1570// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1571// and return true if the function was modified.
1572//
1573bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001574 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001575 SCCPSolver Solver;
1576
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
Chris Lattnerc8798002009-11-02 02:33:50 +00001669// createIPSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001670ModulePass *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) {
1701 SCCPSolver Solver;
1702
1703 // Loop over all functions, marking arguments to those with their addresses
1704 // taken or that are external as overdefined.
1705 //
1706 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001707 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001708 if (!F->isDeclaration())
1709 Solver.MarkBlockExecutable(F->begin());
1710 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1711 AI != E; ++AI)
1712 Solver.markOverdefined(AI);
1713 } else {
1714 Solver.AddTrackedFunction(F);
1715 }
1716
1717 // Loop over global variables. We inform the solver about any internal global
1718 // variables that do not have their 'addresses taken'. If they don't have
1719 // their addresses taken, we can propagate constants through them.
1720 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1721 G != E; ++G)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001722 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001723 Solver.TrackValueOfGlobalVariable(G);
1724
1725 // Solve for constants.
1726 bool ResolvedUndefs = true;
1727 while (ResolvedUndefs) {
1728 Solver.Solve();
1729
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001730 DEBUG(errs() << "RESOLVING UNDEFS\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001731 ResolvedUndefs = false;
1732 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1733 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1734 }
1735
1736 bool MadeChanges = false;
1737
1738 // Iterate over all of the instructions in the module, replacing them with
1739 // constants if we have found them to be of constant values.
1740 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001741 SmallVector<Instruction*, 512> Insts;
1742 SmallVector<BasicBlock*, 512> BlocksToErase;
Bill Wendling03488ae2008-08-14 23:05:24 +00001743 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001744
1745 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1746 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1747 AI != E; ++AI)
1748 if (!AI->use_empty()) {
1749 LatticeVal &IV = Values[AI];
1750 if (IV.isConstant() || IV.isUndefined()) {
1751 Constant *CST = IV.isConstant() ?
Owen Andersonb99ecca2009-07-30 23:03:37 +00001752 IV.getConstant() : UndefValue::get(AI->getType());
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001753 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001754
1755 // Replaces all of the uses of a variable with uses of the
1756 // constant.
1757 AI->replaceAllUsesWith(CST);
1758 ++IPNumArgsElimed;
1759 }
1760 }
1761
1762 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
Chris Lattner317e6b62008-08-23 23:39:31 +00001763 if (!Solver.isBlockExecutable(BB)) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001764 DEBUG(errs() << " BasicBlock Dead:" << *BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001765 ++IPNumDeadBlocks;
1766
1767 // Delete the instructions backwards, as it has a reduced likelihood of
1768 // having to update as many def-use and use-def chains.
1769 TerminatorInst *TI = BB->getTerminator();
1770 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1771 Insts.push_back(I);
1772
1773 while (!Insts.empty()) {
1774 Instruction *I = Insts.back();
1775 Insts.pop_back();
1776 if (!I->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001777 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001778 BB->getInstList().erase(I);
1779 MadeChanges = true;
1780 ++IPNumInstRemoved;
1781 }
1782
1783 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1784 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohman3f7d94b2007-10-03 19:26:29 +00001785 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001786 TI->getSuccessor(i)->removePredecessor(BB);
1787 }
1788 if (!TI->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001789 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001790 BB->getInstList().erase(TI);
1791
1792 if (&*BB != &F->front())
1793 BlocksToErase.push_back(BB);
1794 else
Owen Anderson35b47072009-08-13 21:58:54 +00001795 new UnreachableInst(M.getContext(), BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796
1797 } else {
1798 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1799 Instruction *Inst = BI++;
Chris Lattner82cdc062009-10-05 05:54:46 +00001800 if (Inst->getType()->isVoidTy())
Chris Lattner50846cf2008-04-24 00:21:50 +00001801 continue;
1802
1803 LatticeVal &IV = Values[Inst];
1804 if (!IV.isConstant() && !IV.isUndefined())
1805 continue;
1806
1807 Constant *Const = IV.isConstant()
Owen Andersonb99ecca2009-07-30 23:03:37 +00001808 ? IV.getConstant() : UndefValue::get(Inst->getType());
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001809 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001810
Chris Lattner50846cf2008-04-24 00:21:50 +00001811 // Replaces all of the uses of a variable with uses of the
1812 // constant.
1813 Inst->replaceAllUsesWith(Const);
1814
1815 // Delete the instruction.
Chris Lattnerc27ce6d2009-01-14 21:01:16 +00001816 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
Chris Lattner50846cf2008-04-24 00:21:50 +00001817 Inst->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001818
Chris Lattner50846cf2008-04-24 00:21:50 +00001819 // Hey, we just changed something!
1820 MadeChanges = true;
1821 ++IPNumInstRemoved;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001822 }
1823 }
1824
1825 // Now that all instructions in the function are constant folded, erase dead
1826 // blocks, because we can now use ConstantFoldTerminator to get rid of
1827 // in-edges.
1828 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1829 // If there are any PHI nodes in this successor, drop entries for BB now.
1830 BasicBlock *DeadBB = BlocksToErase[i];
1831 while (!DeadBB->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001832 Instruction *I = cast<Instruction>(DeadBB->use_back());
1833 bool Folded = ConstantFoldTerminator(I->getParent());
1834 if (!Folded) {
1835 // The constant folder may not have been able to fold the terminator
1836 // if this is a branch or switch on undef. Fold it manually as a
1837 // branch to the first successor.
Devang Patele92c16d2008-11-21 01:52:59 +00001838#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001839 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1840 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1841 "Branch should be foldable!");
1842 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1843 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1844 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001845 llvm_unreachable("Didn't fold away reference to block!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001846 }
Devang Patele92c16d2008-11-21 01:52:59 +00001847#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001848
1849 // Make this an uncond branch to the first successor.
1850 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001851 BranchInst::Create(TI->getSuccessor(0), TI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001852
1853 // Remove entries in successor phi nodes to remove edges.
1854 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1855 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1856
1857 // Remove the old terminator.
1858 TI->eraseFromParent();
1859 }
1860 }
1861
1862 // Finally, delete the basic block.
1863 F->getBasicBlockList().erase(DeadBB);
1864 }
1865 BlocksToErase.clear();
1866 }
1867
1868 // If we inferred constant or undef return values for a function, we replaced
1869 // all call uses with the inferred value. This means we don't need to bother
1870 // actually returning anything from the function. Replace all return
1871 // instructions with return undef.
Devang Pateld04d42b2008-03-11 17:32:05 +00001872 // TODO: Process multiple value ret instructions also.
Devang Pateladd320d2008-03-11 05:46:42 +00001873 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001874 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1875 E = RV.end(); I != E; ++I)
1876 if (!I->second.isOverdefined() &&
Chris Lattner82cdc062009-10-05 05:54:46 +00001877 !I->first->getReturnType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001878 Function *F = I->first;
1879 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1880 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1881 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +00001882 RI->setOperand(0, UndefValue::get(F->getReturnType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001883 }
1884
1885 // If we infered constant or undef values for globals variables, we can delete
1886 // the global and any stores that remain to it.
1887 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1888 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1889 E = TG.end(); I != E; ++I) {
1890 GlobalVariable *GV = I->first;
1891 assert(!I->second.isOverdefined() &&
1892 "Overdefined values should have been taken out of the map!");
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001893 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001894 while (!GV->use_empty()) {
1895 StoreInst *SI = cast<StoreInst>(GV->use_back());
1896 SI->eraseFromParent();
1897 }
1898 M.getGlobalList().erase(GV);
1899 ++IPNumGlobalConst;
1900 }
1901
1902 return MadeChanges;
1903}