blob: f0bc12734734abc731a09b4fafcb6626ace87bc4 [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//
18// Notice that:
19// * This pass has a habit of making definitions be dead. It is a good idea
20// to to run a DCE pass sometime after running this pass.
21//
22//===----------------------------------------------------------------------===//
23
24#define DEBUG_TYPE "sccp"
25#include "llvm/Transforms/Scalar.h"
26#include "llvm/Transforms/IPO.h"
27#include "llvm/Constants.h"
28#include "llvm/DerivedTypes.h"
29#include "llvm/Instructions.h"
Owen Andersonfa089ab2009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/Pass.h"
32#include "llvm/Analysis/ConstantFolding.h"
Dan Gohman856193b2008-06-20 01:15:44 +000033#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034#include "llvm/Transforms/Utils/Local.h"
35#include "llvm/Support/CallSite.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/InstVisitor.h"
39#include "llvm/ADT/DenseMap.h"
Chris Lattnerd3123a72008-08-23 23:36:38 +000040#include "llvm/ADT/DenseSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041#include "llvm/ADT/SmallSet.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/STLExtras.h"
45#include <algorithm>
Dan Gohman249ddbf2008-03-21 23:51:57 +000046#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047using namespace llvm;
48
49STATISTIC(NumInstRemoved, "Number of instructions removed");
50STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
51
Nick Lewyckybbdfc9c2008-03-08 07:48:41 +000052STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
54STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
55STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
56
57namespace {
58/// LatticeVal class - This class represents the different lattice values that
59/// an LLVM value may occupy. It is a simple class with value semantics.
60///
61class VISIBILITY_HIDDEN LatticeVal {
62 enum {
63 /// undefined - This LLVM Value has no known value yet.
64 undefined,
65
66 /// constant - This LLVM Value has a specific constant value.
67 constant,
68
69 /// forcedconstant - This LLVM Value was thought to be undef until
70 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
71 /// with another (different) constant, it goes to overdefined, instead of
72 /// asserting.
73 forcedconstant,
74
75 /// overdefined - This instruction is not known to be constant, and we know
76 /// it has a value.
77 overdefined
78 } LatticeValue; // The current lattice position
79
80 Constant *ConstantVal; // If Constant value, the current value
81public:
82 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
83
84 // markOverdefined - Return true if this is a new status to be in...
85 inline bool markOverdefined() {
86 if (LatticeValue != overdefined) {
87 LatticeValue = overdefined;
88 return true;
89 }
90 return false;
91 }
92
93 // markConstant - Return true if this is a new status for us.
94 inline bool markConstant(Constant *V) {
95 if (LatticeValue != constant) {
96 if (LatticeValue == undefined) {
97 LatticeValue = constant;
98 assert(V && "Marking constant with NULL");
99 ConstantVal = V;
100 } else {
101 assert(LatticeValue == forcedconstant &&
102 "Cannot move from overdefined to constant!");
103 // Stay at forcedconstant if the constant is the same.
104 if (V == ConstantVal) return false;
105
106 // Otherwise, we go to overdefined. Assumptions made based on the
107 // forced value are possibly wrong. Assuming this is another constant
108 // could expose a contradiction.
109 LatticeValue = overdefined;
110 }
111 return true;
112 } else {
113 assert(ConstantVal == V && "Marking constant with different value");
114 }
115 return false;
116 }
117
118 inline void markForcedConstant(Constant *V) {
119 assert(LatticeValue == undefined && "Can't force a defined value!");
120 LatticeValue = forcedconstant;
121 ConstantVal = V;
122 }
123
124 inline bool isUndefined() const { return LatticeValue == undefined; }
125 inline bool isConstant() const {
126 return LatticeValue == constant || LatticeValue == forcedconstant;
127 }
128 inline bool isOverdefined() const { return LatticeValue == overdefined; }
129
130 inline Constant *getConstant() const {
131 assert(isConstant() && "Cannot get the constant of a non-constant!");
132 return ConstantVal;
133 }
134};
135
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136//===----------------------------------------------------------------------===//
137//
138/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
139/// Constant Propagation.
140///
141class SCCPSolver : public InstVisitor<SCCPSolver> {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000142 LLVMContext* Context;
Chris Lattnerd3123a72008-08-23 23:36:38 +0000143 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Bill Wendling03488ae2008-08-14 23:05:24 +0000144 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145
146 /// GlobalValue - If we are tracking any values for the contents of a global
147 /// variable, we keep a mapping from the constant accessor to the element of
148 /// the global, to the currently known value. If the value becomes
149 /// overdefined, it's entry is simply removed from this map.
150 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
151
Devang Pateladd320d2008-03-11 05:46:42 +0000152 /// TrackedRetVals - If we are tracking arguments into and the return
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 /// value out of a function, it will have an entry in this map, indicating
154 /// what the known return value for the function is.
Devang Pateladd320d2008-03-11 05:46:42 +0000155 DenseMap<Function*, LatticeVal> TrackedRetVals;
156
157 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
158 /// that return multiple values.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000159 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160
161 // The reason for two worklists is that overdefined is the lowest state
162 // on the lattice, and moving things to overdefined as fast as possible
163 // makes SCCP converge much faster.
164 // By having a separate worklist, we accomplish this because everything
165 // possibly overdefined will become overdefined at the soonest possible
166 // point.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000167 SmallVector<Value*, 64> OverdefinedInstWorkList;
168 SmallVector<Value*, 64> InstWorkList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169
170
Chris Lattnerd3123a72008-08-23 23:36:38 +0000171 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172
173 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
174 /// overdefined, despite the fact that the PHI node is overdefined.
175 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
176
177 /// KnownFeasibleEdges - Entries in this set are edges which have already had
178 /// PHI nodes retriggered.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000179 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
180 DenseSet<Edge> KnownFeasibleEdges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181public:
Owen Andersonfa089ab2009-07-03 19:42:02 +0000182 void setContext(LLVMContext* C) { Context = C; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183
184 /// MarkBlockExecutable - This method can be used by clients to mark all of
185 /// the blocks that are known to be intrinsically live in the processed unit.
186 void MarkBlockExecutable(BasicBlock *BB) {
Chris Lattner56bf9a92008-05-11 01:55:59 +0000187 DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 BBExecutable.insert(BB); // Basic block is executable!
189 BBWorkList.push_back(BB); // Add the block to the work list!
190 }
191
192 /// TrackValueOfGlobalVariable - Clients can use this method to
193 /// inform the SCCPSolver that it should track loads and stores to the
194 /// specified global variable if it can. This is only legal to call if
195 /// performing Interprocedural SCCP.
196 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
197 const Type *ElTy = GV->getType()->getElementType();
198 if (ElTy->isFirstClassType()) {
199 LatticeVal &IV = TrackedGlobals[GV];
200 if (!isa<UndefValue>(GV->getInitializer()))
201 IV.markConstant(GV->getInitializer());
202 }
203 }
204
205 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
206 /// and out of the specified function (which cannot have its address taken),
207 /// this method must be called.
208 void AddTrackedFunction(Function *F) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000209 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 // Add an entry, F -> undef.
Devang Pateladd320d2008-03-11 05:46:42 +0000211 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
212 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnercd73be02008-04-23 05:38:20 +0000213 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
214 LatticeVal()));
215 } else
216 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 }
218
219 /// Solve - Solve for constants and executable blocks.
220 ///
221 void Solve();
222
223 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
224 /// that branches on undef values cannot reach any of their successors.
225 /// However, this is not a safe assumption. After we solve dataflow, this
226 /// method should be use to handle this. If this returns true, the solver
227 /// should be rerun.
228 bool ResolvedUndefsIn(Function &F);
229
Chris Lattner317e6b62008-08-23 23:39:31 +0000230 bool isBlockExecutable(BasicBlock *BB) const {
231 return BBExecutable.count(BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 }
233
234 /// getValueMapping - Once we have solved for constants, return the mapping of
235 /// LLVM values to LatticeVals.
Bill Wendling03488ae2008-08-14 23:05:24 +0000236 std::map<Value*, LatticeVal> &getValueMapping() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 return ValueState;
238 }
239
Devang Pateladd320d2008-03-11 05:46:42 +0000240 /// getTrackedRetVals - Get the inferred return value map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241 ///
Devang Pateladd320d2008-03-11 05:46:42 +0000242 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
243 return TrackedRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244 }
245
246 /// getTrackedGlobals - Get and return the set of inferred initializers for
247 /// global variables.
248 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
249 return TrackedGlobals;
250 }
251
252 inline void markOverdefined(Value *V) {
253 markOverdefined(ValueState[V], V);
254 }
255
256private:
257 // markConstant - Make a value be marked as "constant". If the value
258 // is not already a constant, add it to the instruction work list so that
259 // the users of the instruction are updated later.
260 //
261 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
262 if (IV.markConstant(C)) {
263 DOUT << "markConstant: " << *C << ": " << *V;
264 InstWorkList.push_back(V);
265 }
266 }
267
268 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
269 IV.markForcedConstant(C);
270 DOUT << "markForcedConstant: " << *C << ": " << *V;
271 InstWorkList.push_back(V);
272 }
273
274 inline void markConstant(Value *V, Constant *C) {
275 markConstant(ValueState[V], V, C);
276 }
277
278 // markOverdefined - Make a value be marked as "overdefined". If the
279 // value is not already overdefined, add it to the overdefined instruction
280 // work list so that the users of the instruction are updated later.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 inline void markOverdefined(LatticeVal &IV, Value *V) {
282 if (IV.markOverdefined()) {
283 DEBUG(DOUT << "markOverdefined: ";
284 if (Function *F = dyn_cast<Function>(V))
285 DOUT << "Function '" << F->getName() << "'\n";
286 else
287 DOUT << *V);
288 // Only instructions go on the work list
289 OverdefinedInstWorkList.push_back(V);
290 }
291 }
292
293 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
294 if (IV.isOverdefined() || MergeWithV.isUndefined())
295 return; // Noop.
296 if (MergeWithV.isOverdefined())
297 markOverdefined(IV, V);
298 else if (IV.isUndefined())
299 markConstant(IV, V, MergeWithV.getConstant());
300 else if (IV.getConstant() != MergeWithV.getConstant())
301 markOverdefined(IV, V);
302 }
303
304 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
305 return mergeInValue(ValueState[V], V, MergeWithV);
306 }
307
308
309 // getValueState - Return the LatticeVal object that corresponds to the value.
310 // This function is necessary because not all values should start out in the
311 // underdefined state... Argument's should be overdefined, and
312 // constants should be marked as constants. If a value is not known to be an
313 // Instruction object, then use this accessor to get its value from the map.
314 //
315 inline LatticeVal &getValueState(Value *V) {
Bill Wendling03488ae2008-08-14 23:05:24 +0000316 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 if (I != ValueState.end()) return I->second; // Common case, in the map
318
319 if (Constant *C = dyn_cast<Constant>(V)) {
320 if (isa<UndefValue>(V)) {
321 // Nothing to do, remain undefined.
322 } else {
323 LatticeVal &LV = ValueState[C];
324 LV.markConstant(C); // Constants are constant
325 return LV;
326 }
327 }
328 // All others are underdefined by default...
329 return ValueState[V];
330 }
331
332 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
333 // work list if it is not already executable...
334 //
335 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
336 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
337 return; // This edge is already known to be executable!
338
339 if (BBExecutable.count(Dest)) {
Chris Lattner56bf9a92008-05-11 01:55:59 +0000340 DOUT << "Marking Edge Executable: " << Source->getNameStart()
341 << " -> " << Dest->getNameStart() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342
343 // The destination is already executable, but we just made an edge
344 // feasible that wasn't before. Revisit the PHI nodes in the block
345 // because they have potentially new operands.
346 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
347 visitPHINode(*cast<PHINode>(I));
348
349 } else {
350 MarkBlockExecutable(Dest);
351 }
352 }
353
354 // getFeasibleSuccessors - Return a vector of booleans to indicate which
355 // successors are reachable from a given terminator instruction.
356 //
357 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
358
359 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
360 // block to the 'To' basic block is currently feasible...
361 //
362 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
363
364 // OperandChangedState - This method is invoked on all of the users of an
365 // instruction that was just changed state somehow.... Based on this
366 // information, we need to update the specified user of this instruction.
367 //
368 void OperandChangedState(User *U) {
369 // Only instructions use other variable values!
370 Instruction &I = cast<Instruction>(*U);
371 if (BBExecutable.count(I.getParent())) // Inst is executable?
372 visit(I);
373 }
374
375private:
376 friend class InstVisitor<SCCPSolver>;
377
378 // visit implementations - Something changed in this instruction... Either an
379 // operand made a transition, or the instruction is newly executable. Change
380 // the value type of I to reflect these changes if appropriate.
381 //
382 void visitPHINode(PHINode &I);
383
384 // Terminators
385 void visitReturnInst(ReturnInst &I);
386 void visitTerminatorInst(TerminatorInst &TI);
387
388 void visitCastInst(CastInst &I);
389 void visitSelectInst(SelectInst &I);
390 void visitBinaryOperator(Instruction &I);
391 void visitCmpInst(CmpInst &I);
392 void visitExtractElementInst(ExtractElementInst &I);
393 void visitInsertElementInst(InsertElementInst &I);
394 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman856193b2008-06-20 01:15:44 +0000395 void visitExtractValueInst(ExtractValueInst &EVI);
396 void visitInsertValueInst(InsertValueInst &IVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397
398 // Instructions that cannot be folded away...
399 void visitStoreInst (Instruction &I);
400 void visitLoadInst (LoadInst &I);
401 void visitGetElementPtrInst(GetElementPtrInst &I);
402 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
403 void visitInvokeInst (InvokeInst &II) {
404 visitCallSite(CallSite::get(&II));
405 visitTerminatorInst(II);
406 }
407 void visitCallSite (CallSite CS);
408 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
409 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
410 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
411 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
412 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
413 void visitFreeInst (Instruction &I) { /*returns void*/ }
414
415 void visitInstruction(Instruction &I) {
416 // If a new instruction is added to LLVM that we don't handle...
417 cerr << "SCCP: Don't know how to handle: " << I;
418 markOverdefined(&I); // Just in case
419 }
420};
421
Duncan Sands40f67972007-07-20 08:56:21 +0000422} // end anonymous namespace
423
424
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425// getFeasibleSuccessors - Return a vector of booleans to indicate which
426// successors are reachable from a given terminator instruction.
427//
428void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
429 SmallVector<bool, 16> &Succs) {
430 Succs.resize(TI.getNumSuccessors());
431 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
432 if (BI->isUnconditional()) {
433 Succs[0] = true;
434 } else {
435 LatticeVal &BCValue = getValueState(BI->getCondition());
436 if (BCValue.isOverdefined() ||
437 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
438 // Overdefined condition variables, and branches on unfoldable constant
439 // conditions, mean the branch could go either way.
440 Succs[0] = Succs[1] = true;
441 } else if (BCValue.isConstant()) {
442 // Constant condition variables mean the branch can only go a single way
Owen Andersonfa089ab2009-07-03 19:42:02 +0000443 Succs[BCValue.getConstant() == Context->getConstantIntFalse()] = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444 }
445 }
446 } else if (isa<InvokeInst>(&TI)) {
447 // Invoke instructions successors are always executable.
448 Succs[0] = Succs[1] = true;
449 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
450 LatticeVal &SCValue = getValueState(SI->getCondition());
451 if (SCValue.isOverdefined() || // Overdefined condition?
452 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
453 // All destinations are executable!
454 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner81335532008-05-10 23:56:54 +0000455 } else if (SCValue.isConstant())
456 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000457 } else {
458 assert(0 && "SCCP: Don't know how to handle this terminator!");
459 }
460}
461
462
463// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
464// block to the 'To' basic block is currently feasible...
465//
466bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
467 assert(BBExecutable.count(To) && "Dest should always be alive!");
468
469 // Make sure the source basic block is executable!!
470 if (!BBExecutable.count(From)) return false;
471
472 // Check to make sure this edge itself is actually feasible now...
473 TerminatorInst *TI = From->getTerminator();
474 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
475 if (BI->isUnconditional())
476 return true;
477 else {
478 LatticeVal &BCValue = getValueState(BI->getCondition());
479 if (BCValue.isOverdefined()) {
480 // Overdefined condition variables mean the branch could go either way.
481 return true;
482 } else if (BCValue.isConstant()) {
483 // Not branching on an evaluatable constant?
484 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
485
486 // Constant condition variables mean the branch can only go a single way
487 return BI->getSuccessor(BCValue.getConstant() ==
Owen Andersonfa089ab2009-07-03 19:42:02 +0000488 Context->getConstantIntFalse()) == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000489 }
490 return false;
491 }
492 } else if (isa<InvokeInst>(TI)) {
493 // Invoke instructions successors are always executable.
494 return true;
495 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
496 LatticeVal &SCValue = getValueState(SI->getCondition());
497 if (SCValue.isOverdefined()) { // Overdefined condition?
498 // All destinations are executable!
499 return true;
500 } else if (SCValue.isConstant()) {
501 Constant *CPV = SCValue.getConstant();
502 if (!isa<ConstantInt>(CPV))
503 return true; // not a foldable constant?
504
505 // Make sure to skip the "default value" which isn't a value
506 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
507 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
508 return SI->getSuccessor(i) == To;
509
510 // Constant value not equal to any of the branches... must execute
511 // default branch then...
512 return SI->getDefaultDest() == To;
513 }
514 return false;
515 } else {
516 cerr << "Unknown terminator instruction: " << *TI;
517 abort();
518 }
519}
520
521// visit Implementations - Something changed in this instruction... Either an
522// operand made a transition, or the instruction is newly executable. Change
523// the value type of I to reflect these changes if appropriate. This method
524// makes sure to do the following actions:
525//
526// 1. If a phi node merges two constants in, and has conflicting value coming
527// from different branches, or if the PHI node merges in an overdefined
528// value, then the PHI node becomes overdefined.
529// 2. If a phi node merges only constants in, and they all agree on value, the
530// PHI node becomes a constant value equal to that.
531// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
532// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
533// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
534// 6. If a conditional branch has a value that is constant, make the selected
535// destination executable
536// 7. If a conditional branch has a value that is overdefined, make all
537// successors executable.
538//
539void SCCPSolver::visitPHINode(PHINode &PN) {
540 LatticeVal &PNIV = getValueState(&PN);
541 if (PNIV.isOverdefined()) {
542 // There may be instructions using this PHI node that are not overdefined
543 // themselves. If so, make sure that they know that the PHI node operand
544 // changed.
545 std::multimap<PHINode*, Instruction*>::iterator I, E;
546 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
547 if (I != E) {
548 SmallVector<Instruction*, 16> Users;
549 for (; I != E; ++I) Users.push_back(I->second);
550 while (!Users.empty()) {
551 visit(Users.back());
552 Users.pop_back();
553 }
554 }
555 return; // Quick exit
556 }
557
558 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
559 // and slow us down a lot. Just mark them overdefined.
560 if (PN.getNumIncomingValues() > 64) {
561 markOverdefined(PNIV, &PN);
562 return;
563 }
564
565 // Look at all of the executable operands of the PHI node. If any of them
566 // are overdefined, the PHI becomes overdefined as well. If they are all
567 // constant, and they agree with each other, the PHI becomes the identical
568 // constant. If they are constant and don't agree, the PHI is overdefined.
569 // If there are no executable operands, the PHI remains undefined.
570 //
571 Constant *OperandVal = 0;
572 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
573 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
574 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
575
576 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
577 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattnerd3123a72008-08-23 23:36:38 +0000578 markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 return;
580 }
581
582 if (OperandVal == 0) { // Grab the first value...
583 OperandVal = IV.getConstant();
584 } else { // Another value is being merged in!
585 // There is already a reachable operand. If we conflict with it,
586 // then the PHI node becomes overdefined. If we agree with it, we
587 // can continue on.
588
589 // Check to see if there are two different constants merging...
590 if (IV.getConstant() != OperandVal) {
591 // Yes there is. This means the PHI node is not constant.
592 // You must be overdefined poor PHI.
593 //
Chris Lattnerd3123a72008-08-23 23:36:38 +0000594 markOverdefined(&PN); // The PHI node now becomes overdefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000595 return; // I'm done analyzing you
596 }
597 }
598 }
599 }
600
601 // If we exited the loop, this means that the PHI node only has constant
602 // arguments that agree with each other(and OperandVal is the constant) or
603 // OperandVal is null because there are no defined incoming arguments. If
604 // this is the case, the PHI remains undefined.
605 //
606 if (OperandVal)
Chris Lattnerd3123a72008-08-23 23:36:38 +0000607 markConstant(&PN, OperandVal); // Acquire operand value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000608}
609
610void SCCPSolver::visitReturnInst(ReturnInst &I) {
611 if (I.getNumOperands() == 0) return; // Ret void
612
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 Function *F = I.getParent()->getParent();
Devang Pateladd320d2008-03-11 05:46:42 +0000614 // If we are tracking the return value of this function, merge it in.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000615 if (!F->hasLocalLinkage())
Devang Pateladd320d2008-03-11 05:46:42 +0000616 return;
617
Chris Lattnercd73be02008-04-23 05:38:20 +0000618 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Pateladd320d2008-03-11 05:46:42 +0000620 TrackedRetVals.find(F);
621 if (TFRVI != TrackedRetVals.end() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622 !TFRVI->second.isOverdefined()) {
623 LatticeVal &IV = getValueState(I.getOperand(0));
624 mergeInValue(TFRVI->second, F, IV);
Devang Pateladd320d2008-03-11 05:46:42 +0000625 return;
626 }
627 }
628
Chris Lattnercd73be02008-04-23 05:38:20 +0000629 // Handle functions that return multiple values.
630 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
631 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000632 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnercd73be02008-04-23 05:38:20 +0000633 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
634 if (It == TrackedMultipleRetVals.end()) break;
635 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636 }
Dan Gohman856193b2008-06-20 01:15:44 +0000637 } else if (!TrackedMultipleRetVals.empty() &&
638 I.getNumOperands() == 1 &&
639 isa<StructType>(I.getOperand(0)->getType())) {
640 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
641 i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000642 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000643 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
644 if (It == TrackedMultipleRetVals.end()) break;
Nick Lewycky6ad29e02009-06-06 23:13:08 +0000645 if (Value *Val = FindInsertedValue(I.getOperand(0), i))
646 mergeInValue(It->second, F, getValueState(Val));
Dan Gohman856193b2008-06-20 01:15:44 +0000647 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 }
649}
650
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
652 SmallVector<bool, 16> SuccFeasible;
653 getFeasibleSuccessors(TI, SuccFeasible);
654
655 BasicBlock *BB = TI.getParent();
656
657 // Mark all feasible successors executable...
658 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
659 if (SuccFeasible[i])
660 markEdgeExecutable(BB, TI.getSuccessor(i));
661}
662
663void SCCPSolver::visitCastInst(CastInst &I) {
664 Value *V = I.getOperand(0);
665 LatticeVal &VState = getValueState(V);
666 if (VState.isOverdefined()) // Inherit overdefinedness of operand
667 markOverdefined(&I);
668 else if (VState.isConstant()) // Propagate constant value
Owen Andersonfa089ab2009-07-03 19:42:02 +0000669 markConstant(&I, Context->getConstantExprCast(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670 VState.getConstant(), I.getType()));
671}
672
Dan Gohman856193b2008-06-20 01:15:44 +0000673void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000674 Value *Aggr = EVI.getAggregateOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000675
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000676 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohman856193b2008-06-20 01:15:44 +0000677 if (isa<UndefValue>(Aggr))
678 return;
679
680 // Currently only handle single-index extractvalues.
681 if (EVI.getNumIndices() != 1) {
682 markOverdefined(&EVI);
683 return;
684 }
685
686 Function *F = 0;
687 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
688 F = CI->getCalledFunction();
689 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
690 F = II->getCalledFunction();
691
692 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
693 // result back!
694 if (F == 0 || TrackedMultipleRetVals.empty()) {
695 markOverdefined(&EVI);
696 return;
697 }
698
Chris Lattnerd3123a72008-08-23 23:36:38 +0000699 // See if we are tracking the result of the callee. If not tracking this
700 // function (for example, it is a declaration) just move to overdefined.
701 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
Dan Gohman856193b2008-06-20 01:15:44 +0000702 markOverdefined(&EVI);
703 return;
704 }
705
706 // Otherwise, the value will be merged in here as a result of CallSite
707 // handling.
708}
709
710void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000711 Value *Aggr = IVI.getAggregateOperand();
712 Value *Val = IVI.getInsertedValueOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000713
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000714 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohman78b2c392008-06-20 16:39:44 +0000715 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohman856193b2008-06-20 01:15:44 +0000716 return;
717
718 // Currently only handle single-index insertvalues.
719 if (IVI.getNumIndices() != 1) {
720 markOverdefined(&IVI);
721 return;
722 }
Dan Gohman78b2c392008-06-20 16:39:44 +0000723
724 // Currently only handle insertvalue instructions that are in a single-use
725 // chain that builds up a return value.
726 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
727 if (!TmpIVI->hasOneUse()) {
728 markOverdefined(&IVI);
729 return;
730 }
731 const Value *V = *TmpIVI->use_begin();
732 if (isa<ReturnInst>(V))
733 break;
734 TmpIVI = dyn_cast<InsertValueInst>(V);
735 if (!TmpIVI) {
736 markOverdefined(&IVI);
737 return;
738 }
739 }
Dan Gohman856193b2008-06-20 01:15:44 +0000740
741 // See if we are tracking the result of the callee.
742 Function *F = IVI.getParent()->getParent();
Chris Lattnerd3123a72008-08-23 23:36:38 +0000743 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000744 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
745
746 // Merge in the inserted member value.
747 if (It != TrackedMultipleRetVals.end())
748 mergeInValue(It->second, F, getValueState(Val));
749
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000750 // Mark the aggregate result of the IVI overdefined; any tracking that we do
751 // will be done on the individual member values.
Dan Gohman856193b2008-06-20 01:15:44 +0000752 markOverdefined(&IVI);
753}
754
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755void SCCPSolver::visitSelectInst(SelectInst &I) {
756 LatticeVal &CondValue = getValueState(I.getCondition());
757 if (CondValue.isUndefined())
758 return;
759 if (CondValue.isConstant()) {
760 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
761 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
762 : I.getFalseValue()));
763 return;
764 }
765 }
766
767 // Otherwise, the condition is overdefined or a constant we can't evaluate.
768 // See if we can produce something better than overdefined based on the T/F
769 // value.
770 LatticeVal &TVal = getValueState(I.getTrueValue());
771 LatticeVal &FVal = getValueState(I.getFalseValue());
772
773 // select ?, C, C -> C.
774 if (TVal.isConstant() && FVal.isConstant() &&
775 TVal.getConstant() == FVal.getConstant()) {
776 markConstant(&I, FVal.getConstant());
777 return;
778 }
779
780 if (TVal.isUndefined()) { // select ?, undef, X -> X.
781 mergeInValue(&I, FVal);
782 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
783 mergeInValue(&I, TVal);
784 } else {
785 markOverdefined(&I);
786 }
787}
788
789// Handle BinaryOperators and Shift Instructions...
790void SCCPSolver::visitBinaryOperator(Instruction &I) {
791 LatticeVal &IV = ValueState[&I];
792 if (IV.isOverdefined()) return;
793
794 LatticeVal &V1State = getValueState(I.getOperand(0));
795 LatticeVal &V2State = getValueState(I.getOperand(1));
796
797 if (V1State.isOverdefined() || V2State.isOverdefined()) {
798 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
799 // operand is overdefined.
800 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
801 LatticeVal *NonOverdefVal = 0;
802 if (!V1State.isOverdefined()) {
803 NonOverdefVal = &V1State;
804 } else if (!V2State.isOverdefined()) {
805 NonOverdefVal = &V2State;
806 }
807
808 if (NonOverdefVal) {
809 if (NonOverdefVal->isUndefined()) {
810 // Could annihilate value.
811 if (I.getOpcode() == Instruction::And)
Owen Andersonfa089ab2009-07-03 19:42:02 +0000812 markConstant(IV, &I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
Owen Andersonfa089ab2009-07-03 19:42:02 +0000814 markConstant(IV, &I, Context->getConstantVectorAllOnesValue(PT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000815 else
Owen Andersonfa089ab2009-07-03 19:42:02 +0000816 markConstant(IV, &I,
817 Context->getConstantIntAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818 return;
819 } else {
820 if (I.getOpcode() == Instruction::And) {
821 if (NonOverdefVal->getConstant()->isNullValue()) {
822 markConstant(IV, &I, NonOverdefVal->getConstant());
823 return; // X and 0 = 0
824 }
825 } else {
826 if (ConstantInt *CI =
827 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
828 if (CI->isAllOnesValue()) {
829 markConstant(IV, &I, NonOverdefVal->getConstant());
830 return; // X or -1 = -1
831 }
832 }
833 }
834 }
835 }
836
837
838 // If both operands are PHI nodes, it is possible that this instruction has
839 // a constant value, despite the fact that the PHI node doesn't. Check for
840 // this condition now.
841 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
842 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
843 if (PN1->getParent() == PN2->getParent()) {
844 // Since the two PHI nodes are in the same basic block, they must have
845 // entries for the same predecessors. Walk the predecessor list, and
846 // if all of the incoming values are constants, and the result of
847 // evaluating this expression with all incoming value pairs is the
848 // same, then this expression is a constant even though the PHI node
849 // is not a constant!
850 LatticeVal Result;
851 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
852 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
853 BasicBlock *InBlock = PN1->getIncomingBlock(i);
854 LatticeVal &In2 =
855 getValueState(PN2->getIncomingValueForBlock(InBlock));
856
857 if (In1.isOverdefined() || In2.isOverdefined()) {
858 Result.markOverdefined();
859 break; // Cannot fold this operation over the PHI nodes!
860 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000861 Constant *V =
862 Context->getConstantExpr(I.getOpcode(), In1.getConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000863 In2.getConstant());
864 if (Result.isUndefined())
865 Result.markConstant(V);
866 else if (Result.isConstant() && Result.getConstant() != V) {
867 Result.markOverdefined();
868 break;
869 }
870 }
871 }
872
873 // If we found a constant value here, then we know the instruction is
874 // constant despite the fact that the PHI nodes are overdefined.
875 if (Result.isConstant()) {
876 markConstant(IV, &I, Result.getConstant());
877 // Remember that this instruction is virtually using the PHI node
878 // operands.
879 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
880 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
881 return;
882 } else if (Result.isUndefined()) {
883 return;
884 }
885
886 // Okay, this really is overdefined now. Since we might have
887 // speculatively thought that this was not overdefined before, and
888 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
889 // make sure to clean out any entries that we put there, for
890 // efficiency.
891 std::multimap<PHINode*, Instruction*>::iterator It, E;
892 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
893 while (It != E) {
894 if (It->second == &I) {
895 UsersOfOverdefinedPHIs.erase(It++);
896 } else
897 ++It;
898 }
899 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
900 while (It != E) {
901 if (It->second == &I) {
902 UsersOfOverdefinedPHIs.erase(It++);
903 } else
904 ++It;
905 }
906 }
907
908 markOverdefined(IV, &I);
909 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000910 markConstant(IV, &I,
911 Context->getConstantExpr(I.getOpcode(), V1State.getConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 V2State.getConstant()));
913 }
914}
915
916// Handle ICmpInst instruction...
917void SCCPSolver::visitCmpInst(CmpInst &I) {
918 LatticeVal &IV = ValueState[&I];
919 if (IV.isOverdefined()) return;
920
921 LatticeVal &V1State = getValueState(I.getOperand(0));
922 LatticeVal &V2State = getValueState(I.getOperand(1));
923
924 if (V1State.isOverdefined() || V2State.isOverdefined()) {
925 // If both operands are PHI nodes, it is possible that this instruction has
926 // a constant value, despite the fact that the PHI node doesn't. Check for
927 // this condition now.
928 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
929 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
930 if (PN1->getParent() == PN2->getParent()) {
931 // Since the two PHI nodes are in the same basic block, they must have
932 // entries for the same predecessors. Walk the predecessor list, and
933 // if all of the incoming values are constants, and the result of
934 // evaluating this expression with all incoming value pairs is the
935 // same, then this expression is a constant even though the PHI node
936 // is not a constant!
937 LatticeVal Result;
938 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
939 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
940 BasicBlock *InBlock = PN1->getIncomingBlock(i);
941 LatticeVal &In2 =
942 getValueState(PN2->getIncomingValueForBlock(InBlock));
943
944 if (In1.isOverdefined() || In2.isOverdefined()) {
945 Result.markOverdefined();
946 break; // Cannot fold this operation over the PHI nodes!
947 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000948 Constant *V = Context->getConstantExprCompare(I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949 In1.getConstant(),
950 In2.getConstant());
951 if (Result.isUndefined())
952 Result.markConstant(V);
953 else if (Result.isConstant() && Result.getConstant() != V) {
954 Result.markOverdefined();
955 break;
956 }
957 }
958 }
959
960 // If we found a constant value here, then we know the instruction is
961 // constant despite the fact that the PHI nodes are overdefined.
962 if (Result.isConstant()) {
963 markConstant(IV, &I, Result.getConstant());
964 // Remember that this instruction is virtually using the PHI node
965 // operands.
966 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
967 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
968 return;
969 } else if (Result.isUndefined()) {
970 return;
971 }
972
973 // Okay, this really is overdefined now. Since we might have
974 // speculatively thought that this was not overdefined before, and
975 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
976 // make sure to clean out any entries that we put there, for
977 // efficiency.
978 std::multimap<PHINode*, Instruction*>::iterator It, E;
979 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
980 while (It != E) {
981 if (It->second == &I) {
982 UsersOfOverdefinedPHIs.erase(It++);
983 } else
984 ++It;
985 }
986 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
987 while (It != E) {
988 if (It->second == &I) {
989 UsersOfOverdefinedPHIs.erase(It++);
990 } else
991 ++It;
992 }
993 }
994
995 markOverdefined(IV, &I);
996 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000997 markConstant(IV, &I, Context->getConstantExprCompare(I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000998 V1State.getConstant(),
999 V2State.getConstant()));
1000 }
1001}
1002
1003void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1004 // FIXME : SCCP does not handle vectors properly.
1005 markOverdefined(&I);
1006 return;
1007
1008#if 0
1009 LatticeVal &ValState = getValueState(I.getOperand(0));
1010 LatticeVal &IdxState = getValueState(I.getOperand(1));
1011
1012 if (ValState.isOverdefined() || IdxState.isOverdefined())
1013 markOverdefined(&I);
1014 else if(ValState.isConstant() && IdxState.isConstant())
1015 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1016 IdxState.getConstant()));
1017#endif
1018}
1019
1020void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1021 // FIXME : SCCP does not handle vectors properly.
1022 markOverdefined(&I);
1023 return;
1024#if 0
1025 LatticeVal &ValState = getValueState(I.getOperand(0));
1026 LatticeVal &EltState = getValueState(I.getOperand(1));
1027 LatticeVal &IdxState = getValueState(I.getOperand(2));
1028
1029 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1030 IdxState.isOverdefined())
1031 markOverdefined(&I);
1032 else if(ValState.isConstant() && EltState.isConstant() &&
1033 IdxState.isConstant())
1034 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1035 EltState.getConstant(),
1036 IdxState.getConstant()));
1037 else if (ValState.isUndefined() && EltState.isConstant() &&
1038 IdxState.isConstant())
1039 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1040 EltState.getConstant(),
1041 IdxState.getConstant()));
1042#endif
1043}
1044
1045void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1046 // FIXME : SCCP does not handle vectors properly.
1047 markOverdefined(&I);
1048 return;
1049#if 0
1050 LatticeVal &V1State = getValueState(I.getOperand(0));
1051 LatticeVal &V2State = getValueState(I.getOperand(1));
1052 LatticeVal &MaskState = getValueState(I.getOperand(2));
1053
1054 if (MaskState.isUndefined() ||
1055 (V1State.isUndefined() && V2State.isUndefined()))
1056 return; // Undefined output if mask or both inputs undefined.
1057
1058 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1059 MaskState.isOverdefined()) {
1060 markOverdefined(&I);
1061 } else {
1062 // A mix of constant/undef inputs.
1063 Constant *V1 = V1State.isConstant() ?
1064 V1State.getConstant() : UndefValue::get(I.getType());
1065 Constant *V2 = V2State.isConstant() ?
1066 V2State.getConstant() : UndefValue::get(I.getType());
1067 Constant *Mask = MaskState.isConstant() ?
1068 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1069 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1070 }
1071#endif
1072}
1073
1074// Handle getelementptr instructions... if all operands are constants then we
1075// can turn this into a getelementptr ConstantExpr.
1076//
1077void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1078 LatticeVal &IV = ValueState[&I];
1079 if (IV.isOverdefined()) return;
1080
1081 SmallVector<Constant*, 8> Operands;
1082 Operands.reserve(I.getNumOperands());
1083
1084 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1085 LatticeVal &State = getValueState(I.getOperand(i));
1086 if (State.isUndefined())
1087 return; // Operands are not resolved yet...
1088 else if (State.isOverdefined()) {
1089 markOverdefined(IV, &I);
1090 return;
1091 }
1092 assert(State.isConstant() && "Unknown state!");
1093 Operands.push_back(State.getConstant());
1094 }
1095
1096 Constant *Ptr = Operands[0];
1097 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1098
Owen Andersonfa089ab2009-07-03 19:42:02 +00001099 markConstant(IV, &I, Context->getConstantExprGetElementPtr(Ptr, &Operands[0],
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100 Operands.size()));
1101}
1102
1103void SCCPSolver::visitStoreInst(Instruction &SI) {
1104 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1105 return;
1106 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1107 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1108 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1109
1110 // Get the value we are storing into the global.
1111 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1112
1113 mergeInValue(I->second, GV, PtrVal);
1114 if (I->second.isOverdefined())
1115 TrackedGlobals.erase(I); // No need to keep tracking this!
1116}
1117
1118
1119// Handle load instructions. If the operand is a constant pointer to a constant
1120// global, we can replace the load with the loaded constant value!
1121void SCCPSolver::visitLoadInst(LoadInst &I) {
1122 LatticeVal &IV = ValueState[&I];
1123 if (IV.isOverdefined()) return;
1124
1125 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1126 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1127 if (PtrVal.isConstant() && !I.isVolatile()) {
1128 Value *Ptr = PtrVal.getConstant();
Christopher Lamb2c175392007-12-29 07:56:53 +00001129 // TODO: Consider a target hook for valid address spaces for this xform.
1130 if (isa<ConstantPointerNull>(Ptr) &&
1131 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 // load null -> null
Owen Andersonfa089ab2009-07-03 19:42:02 +00001133 markConstant(IV, &I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 return;
1135 }
1136
1137 // Transform load (constant global) into the value loaded.
1138 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1139 if (GV->isConstant()) {
Duncan Sands54e70f62009-03-21 21:27:31 +00001140 if (GV->hasDefinitiveInitializer()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 markConstant(IV, &I, GV->getInitializer());
1142 return;
1143 }
1144 } else if (!TrackedGlobals.empty()) {
1145 // If we are tracking this global, merge in the known value for it.
1146 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1147 TrackedGlobals.find(GV);
1148 if (It != TrackedGlobals.end()) {
1149 mergeInValue(IV, &I, It->second);
1150 return;
1151 }
1152 }
1153 }
1154
1155 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1156 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1157 if (CE->getOpcode() == Instruction::GetElementPtr)
1158 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +00001159 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160 if (Constant *V =
1161 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
1162 markConstant(IV, &I, V);
1163 return;
1164 }
1165 }
1166
1167 // Otherwise we cannot say for certain what value this load will produce.
1168 // Bail out.
1169 markOverdefined(IV, &I);
1170}
1171
1172void SCCPSolver::visitCallSite(CallSite CS) {
1173 Function *F = CS.getCalledFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001174 Instruction *I = CS.getInstruction();
Chris Lattnercd73be02008-04-23 05:38:20 +00001175
1176 // The common case is that we aren't tracking the callee, either because we
1177 // are not doing interprocedural analysis or the callee is indirect, or is
1178 // external. Handle these cases first.
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001179 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001180CallOverdefined:
1181 // Void return and not tracking callee, just bail.
1182 if (I->getType() == Type::VoidTy) return;
1183
1184 // Otherwise, if we have a single return value case, and if the function is
1185 // a declaration, maybe we can constant fold it.
1186 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1187 canConstantFoldCallTo(F)) {
1188
1189 SmallVector<Constant*, 8> Operands;
1190 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1191 AI != E; ++AI) {
1192 LatticeVal &State = getValueState(*AI);
1193 if (State.isUndefined())
1194 return; // Operands are not resolved yet.
1195 else if (State.isOverdefined()) {
1196 markOverdefined(I);
1197 return;
1198 }
1199 assert(State.isConstant() && "Unknown state!");
1200 Operands.push_back(State.getConstant());
1201 }
1202
1203 // If we can constant fold this, mark the result of the call as a
1204 // constant.
Nick Lewyckye9279352009-05-28 04:08:10 +00001205 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001206 markConstant(I, C);
1207 return;
1208 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001209 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001210
1211 // Otherwise, we don't know anything about this call, mark it overdefined.
1212 markOverdefined(I);
1213 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 }
1215
Chris Lattnercd73be02008-04-23 05:38:20 +00001216 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohman856193b2008-06-20 01:15:44 +00001217 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1218 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001219 // If so, propagate the return value of the callee into this call result.
1220 mergeInValue(I, TFRVI->second);
Dan Gohman856193b2008-06-20 01:15:44 +00001221 } else if (isa<StructType>(I->getType())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001222 // Check to see if we're tracking this callee, if not, handle it in the
1223 // common path above.
Chris Lattnerd3123a72008-08-23 23:36:38 +00001224 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1225 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnercd73be02008-04-23 05:38:20 +00001226 if (TMRVI == TrackedMultipleRetVals.end())
1227 goto CallOverdefined;
1228
1229 // If we are tracking this callee, propagate the return values of the call
Dan Gohman856193b2008-06-20 01:15:44 +00001230 // into this call site. We do this by walking all the uses. Single-index
1231 // ExtractValueInst uses can be tracked; anything more complicated is
1232 // currently handled conservatively.
Chris Lattnercd73be02008-04-23 05:38:20 +00001233 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1234 UI != E; ++UI) {
Dan Gohman856193b2008-06-20 01:15:44 +00001235 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1236 if (EVI->getNumIndices() == 1) {
1237 mergeInValue(EVI,
Dan Gohmanaa7b7802008-06-20 16:41:17 +00001238 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohman856193b2008-06-20 01:15:44 +00001239 continue;
1240 }
1241 }
1242 // The aggregate value is used in a way not handled here. Assume nothing.
1243 markOverdefined(*UI);
Chris Lattnercd73be02008-04-23 05:38:20 +00001244 }
Dan Gohman856193b2008-06-20 01:15:44 +00001245 } else {
1246 // Otherwise we're not tracking this callee, so handle it in the
1247 // common path above.
1248 goto CallOverdefined;
Chris Lattnercd73be02008-04-23 05:38:20 +00001249 }
1250
1251 // Finally, if this is the first call to the function hit, mark its entry
1252 // block executable.
1253 if (!BBExecutable.count(F->begin()))
1254 MarkBlockExecutable(F->begin());
1255
1256 // Propagate information from this call site into the callee.
1257 CallSite::arg_iterator CAI = CS.arg_begin();
1258 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1259 AI != E; ++AI, ++CAI) {
1260 LatticeVal &IV = ValueState[AI];
1261 if (!IV.isOverdefined())
1262 mergeInValue(IV, AI, getValueState(*CAI));
1263 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264}
1265
1266
1267void SCCPSolver::Solve() {
1268 // Process the work lists until they are empty!
1269 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1270 !OverdefinedInstWorkList.empty()) {
1271 // Process the instruction work list...
1272 while (!OverdefinedInstWorkList.empty()) {
1273 Value *I = OverdefinedInstWorkList.back();
1274 OverdefinedInstWorkList.pop_back();
1275
1276 DOUT << "\nPopped off OI-WL: " << *I;
1277
1278 // "I" got into the work list because it either made the transition from
1279 // bottom to constant
1280 //
1281 // Anything on this worklist that is overdefined need not be visited
1282 // since all of its users will have already been marked as overdefined
1283 // Update all of the users of this instruction's value...
1284 //
1285 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1286 UI != E; ++UI)
1287 OperandChangedState(*UI);
1288 }
1289 // Process the instruction work list...
1290 while (!InstWorkList.empty()) {
1291 Value *I = InstWorkList.back();
1292 InstWorkList.pop_back();
1293
1294 DOUT << "\nPopped off I-WL: " << *I;
1295
1296 // "I" got into the work list because it either made the transition from
1297 // bottom to constant
1298 //
1299 // Anything on this worklist that is overdefined need not be visited
1300 // since all of its users will have already been marked as overdefined.
1301 // Update all of the users of this instruction's value...
1302 //
1303 if (!getValueState(I).isOverdefined())
1304 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1305 UI != E; ++UI)
1306 OperandChangedState(*UI);
1307 }
1308
1309 // Process the basic block work list...
1310 while (!BBWorkList.empty()) {
1311 BasicBlock *BB = BBWorkList.back();
1312 BBWorkList.pop_back();
1313
1314 DOUT << "\nPopped off BBWL: " << *BB;
1315
1316 // Notify all instructions in this basic block that they are newly
1317 // executable.
1318 visit(BB);
1319 }
1320 }
1321}
1322
1323/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1324/// that branches on undef values cannot reach any of their successors.
1325/// However, this is not a safe assumption. After we solve dataflow, this
1326/// method should be use to handle this. If this returns true, the solver
1327/// should be rerun.
1328///
1329/// This method handles this by finding an unresolved branch and marking it one
1330/// of the edges from the block as being feasible, even though the condition
1331/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1332/// CFG and only slightly pessimizes the analysis results (by marking one,
1333/// potentially infeasible, edge feasible). This cannot usefully modify the
1334/// constraints on the condition of the branch, as that would impact other users
1335/// of the value.
1336///
1337/// This scan also checks for values that use undefs, whose results are actually
1338/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1339/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1340/// even if X isn't defined.
1341bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1342 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1343 if (!BBExecutable.count(BB))
1344 continue;
1345
1346 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1347 // Look for instructions which produce undef values.
1348 if (I->getType() == Type::VoidTy) continue;
1349
1350 LatticeVal &LV = getValueState(I);
1351 if (!LV.isUndefined()) continue;
1352
1353 // Get the lattice values of the first two operands for use below.
1354 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1355 LatticeVal Op1LV;
1356 if (I->getNumOperands() == 2) {
1357 // If this is a two-operand instruction, and if both operands are
1358 // undefs, the result stays undef.
1359 Op1LV = getValueState(I->getOperand(1));
1360 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1361 continue;
1362 }
1363
1364 // If this is an instructions whose result is defined even if the input is
1365 // not fully defined, propagate the information.
1366 const Type *ITy = I->getType();
1367 switch (I->getOpcode()) {
1368 default: break; // Leave the instruction as an undef.
1369 case Instruction::ZExt:
1370 // After a zero extend, we know the top part is zero. SExt doesn't have
1371 // to be handled here, because we don't know whether the top part is 1's
1372 // or 0's.
1373 assert(Op0LV.isUndefined());
Owen Andersonfa089ab2009-07-03 19:42:02 +00001374 markForcedConstant(LV, I, Context->getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001375 return true;
1376 case Instruction::Mul:
1377 case Instruction::And:
1378 // undef * X -> 0. X could be zero.
1379 // undef & X -> 0. X could be zero.
Owen Andersonfa089ab2009-07-03 19:42:02 +00001380 markForcedConstant(LV, I, Context->getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001381 return true;
1382
1383 case Instruction::Or:
1384 // undef | X -> -1. X could be -1.
1385 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
Owen Andersonfa089ab2009-07-03 19:42:02 +00001386 markForcedConstant(LV, I,
1387 Context->getConstantVectorAllOnesValue(PTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 else
Owen Andersonfa089ab2009-07-03 19:42:02 +00001389 markForcedConstant(LV, I, Context->getConstantIntAllOnesValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390 return true;
1391
1392 case Instruction::SDiv:
1393 case Instruction::UDiv:
1394 case Instruction::SRem:
1395 case Instruction::URem:
1396 // X / undef -> undef. No change.
1397 // X % undef -> undef. No change.
1398 if (Op1LV.isUndefined()) break;
1399
1400 // undef / X -> 0. X could be maxint.
1401 // undef % X -> 0. X could be 1.
Owen Andersonfa089ab2009-07-03 19:42:02 +00001402 markForcedConstant(LV, I, Context->getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001403 return true;
1404
1405 case Instruction::AShr:
1406 // undef >>s X -> undef. No change.
1407 if (Op0LV.isUndefined()) break;
1408
1409 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1410 if (Op0LV.isConstant())
1411 markForcedConstant(LV, I, Op0LV.getConstant());
1412 else
1413 markOverdefined(LV, I);
1414 return true;
1415 case Instruction::LShr:
1416 case Instruction::Shl:
1417 // undef >> X -> undef. No change.
1418 // undef << X -> undef. No change.
1419 if (Op0LV.isUndefined()) break;
1420
1421 // X >> undef -> 0. X could be 0.
1422 // X << undef -> 0. X could be 0.
Owen Andersonfa089ab2009-07-03 19:42:02 +00001423 markForcedConstant(LV, I, Context->getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001424 return true;
1425 case Instruction::Select:
1426 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1427 if (Op0LV.isUndefined()) {
1428 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1429 Op1LV = getValueState(I->getOperand(2));
1430 } else if (Op1LV.isUndefined()) {
1431 // c ? undef : undef -> undef. No change.
1432 Op1LV = getValueState(I->getOperand(2));
1433 if (Op1LV.isUndefined())
1434 break;
1435 // Otherwise, c ? undef : x -> x.
1436 } else {
1437 // Leave Op1LV as Operand(1)'s LatticeValue.
1438 }
1439
1440 if (Op1LV.isConstant())
1441 markForcedConstant(LV, I, Op1LV.getConstant());
1442 else
1443 markOverdefined(LV, I);
1444 return true;
Chris Lattner9110ac92008-05-24 03:59:33 +00001445 case Instruction::Call:
1446 // If a call has an undef result, it is because it is constant foldable
1447 // but one of the inputs was undef. Just force the result to
1448 // overdefined.
1449 markOverdefined(LV, I);
1450 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001451 }
1452 }
1453
1454 TerminatorInst *TI = BB->getTerminator();
1455 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1456 if (!BI->isConditional()) continue;
1457 if (!getValueState(BI->getCondition()).isUndefined())
1458 continue;
1459 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Dale Johannesenfb06d0c2008-05-23 01:01:31 +00001460 if (SI->getNumSuccessors()<2) // no cases
1461 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001462 if (!getValueState(SI->getCondition()).isUndefined())
1463 continue;
1464 } else {
1465 continue;
1466 }
1467
Chris Lattner6186e8c2008-01-28 00:32:30 +00001468 // If the edge to the second successor isn't thought to be feasible yet,
1469 // mark it so now. We pick the second one so that this goes to some
1470 // enumerated value in a switch instead of going to the default destination.
1471 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472 continue;
1473
1474 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1475 // and return. This will make other blocks reachable, which will allow new
1476 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner6186e8c2008-01-28 00:32:30 +00001477 markEdgeExecutable(BB, TI->getSuccessor(1));
1478
1479 // This must be a conditional branch of switch on undef. At this point,
1480 // force the old terminator to branch to the first successor. This is
1481 // required because we are now influencing the dataflow of the function with
1482 // the assumption that this edge is taken. If we leave the branch condition
1483 // as undef, then further analysis could think the undef went another way
1484 // leading to an inconsistent set of conclusions.
1485 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Owen Andersonfa089ab2009-07-03 19:42:02 +00001486 BI->setCondition(Context->getConstantIntFalse());
Chris Lattner6186e8c2008-01-28 00:32:30 +00001487 } else {
1488 SwitchInst *SI = cast<SwitchInst>(TI);
1489 SI->setCondition(SI->getCaseValue(1));
1490 }
1491
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001492 return true;
1493 }
1494
1495 return false;
1496}
1497
1498
1499namespace {
1500 //===--------------------------------------------------------------------===//
1501 //
1502 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1503 /// Sparse Conditional Constant Propagator.
1504 ///
1505 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
1506 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +00001507 SCCP() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001508
1509 // runOnFunction - Run the Sparse Conditional Constant Propagation
1510 // algorithm, and return true if the function was modified.
1511 //
1512 bool runOnFunction(Function &F);
1513
1514 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1515 AU.setPreservesCFG();
1516 }
1517 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001518} // end anonymous namespace
1519
Dan Gohman089efff2008-05-13 00:00:25 +00001520char SCCP::ID = 0;
1521static RegisterPass<SCCP>
1522X("sccp", "Sparse Conditional Constant Propagation");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001523
1524// createSCCPPass - This is the public interface to this file...
1525FunctionPass *llvm::createSCCPPass() {
1526 return new SCCP();
1527}
1528
1529
1530// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1531// and return true if the function was modified.
1532//
1533bool SCCP::runOnFunction(Function &F) {
Chris Lattner56bf9a92008-05-11 01:55:59 +00001534 DOUT << "SCCP on function '" << F.getNameStart() << "'\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001535 SCCPSolver Solver;
Owen Andersonfa089ab2009-07-03 19:42:02 +00001536 Solver.setContext(Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001537
1538 // Mark the first block of the function as being executable.
1539 Solver.MarkBlockExecutable(F.begin());
1540
1541 // Mark all arguments to the function as being overdefined.
1542 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1543 Solver.markOverdefined(AI);
1544
1545 // Solve for constants.
1546 bool ResolvedUndefs = true;
1547 while (ResolvedUndefs) {
1548 Solver.Solve();
1549 DOUT << "RESOLVING UNDEFs\n";
1550 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1551 }
1552
1553 bool MadeChanges = false;
1554
1555 // If we decided that there are basic blocks that are dead in this function,
1556 // delete their contents now. Note that we cannot actually delete the blocks,
1557 // as we cannot modify the CFG of the function.
1558 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001559 SmallVector<Instruction*, 512> Insts;
Bill Wendling03488ae2008-08-14 23:05:24 +00001560 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001561
1562 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattner317e6b62008-08-23 23:39:31 +00001563 if (!Solver.isBlockExecutable(BB)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001564 DOUT << " BasicBlock Dead:" << *BB;
1565 ++NumDeadBlocks;
1566
1567 // Delete the instructions backwards, as it has a reduced likelihood of
1568 // having to update as many def-use and use-def chains.
1569 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1570 I != E; ++I)
1571 Insts.push_back(I);
1572 while (!Insts.empty()) {
1573 Instruction *I = Insts.back();
1574 Insts.pop_back();
1575 if (!I->use_empty())
Owen Andersonfa089ab2009-07-03 19:42:02 +00001576 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001577 BB->getInstList().erase(I);
1578 MadeChanges = true;
1579 ++NumInstRemoved;
1580 }
1581 } else {
1582 // Iterate over all of the instructions in a function, replacing them with
1583 // constants if we have found them to be of constant values.
1584 //
1585 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1586 Instruction *Inst = BI++;
Chris Lattner204cfde2008-04-24 00:19:54 +00001587 if (Inst->getType() == Type::VoidTy ||
Chris Lattnerb6f89362008-04-24 00:16:28 +00001588 isa<TerminatorInst>(Inst))
1589 continue;
1590
1591 LatticeVal &IV = Values[Inst];
1592 if (!IV.isConstant() && !IV.isUndefined())
1593 continue;
1594
1595 Constant *Const = IV.isConstant()
Owen Andersonfa089ab2009-07-03 19:42:02 +00001596 ? IV.getConstant() : Context->getUndef(Inst->getType());
Chris Lattnerb6f89362008-04-24 00:16:28 +00001597 DOUT << " Constant: " << *Const << " = " << *Inst;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001598
Chris Lattnerb6f89362008-04-24 00:16:28 +00001599 // Replaces all of the uses of a variable with uses of the constant.
1600 Inst->replaceAllUsesWith(Const);
1601
1602 // Delete the instruction.
1603 Inst->eraseFromParent();
1604
1605 // Hey, we just changed something!
1606 MadeChanges = true;
1607 ++NumInstRemoved;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001608 }
1609 }
1610
1611 return MadeChanges;
1612}
1613
1614namespace {
1615 //===--------------------------------------------------------------------===//
1616 //
1617 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1618 /// Constant Propagation.
1619 ///
1620 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
1621 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +00001622 IPSCCP() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001623 bool runOnModule(Module &M);
1624 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001625} // end anonymous namespace
1626
Dan Gohman089efff2008-05-13 00:00:25 +00001627char IPSCCP::ID = 0;
1628static RegisterPass<IPSCCP>
1629Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1630
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001631// createIPSCCPPass - This is the public interface to this file...
1632ModulePass *llvm::createIPSCCPPass() {
1633 return new IPSCCP();
1634}
1635
1636
1637static bool AddressIsTaken(GlobalValue *GV) {
1638 // Delete any dead constantexpr klingons.
1639 GV->removeDeadConstantUsers();
1640
1641 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1642 UI != E; ++UI)
1643 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1644 if (SI->getOperand(0) == GV || SI->isVolatile())
1645 return true; // Storing addr of GV.
1646 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1647 // Make sure we are calling the function, not passing the address.
1648 CallSite CS = CallSite::get(cast<Instruction>(*UI));
Nick Lewycky1cc2e102008-11-03 03:49:14 +00001649 if (CS.hasArgument(GV))
1650 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001651 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1652 if (LI->isVolatile())
1653 return true;
1654 } else {
1655 return true;
1656 }
1657 return false;
1658}
1659
1660bool IPSCCP::runOnModule(Module &M) {
1661 SCCPSolver Solver;
1662
1663 // Loop over all functions, marking arguments to those with their addresses
1664 // taken or that are external as overdefined.
1665 //
1666 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001667 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001668 if (!F->isDeclaration())
1669 Solver.MarkBlockExecutable(F->begin());
1670 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1671 AI != E; ++AI)
1672 Solver.markOverdefined(AI);
1673 } else {
1674 Solver.AddTrackedFunction(F);
1675 }
1676
1677 // Loop over global variables. We inform the solver about any internal global
1678 // variables that do not have their 'addresses taken'. If they don't have
1679 // their addresses taken, we can propagate constants through them.
1680 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1681 G != E; ++G)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001682 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001683 Solver.TrackValueOfGlobalVariable(G);
1684
1685 // Solve for constants.
1686 bool ResolvedUndefs = true;
1687 while (ResolvedUndefs) {
1688 Solver.Solve();
1689
1690 DOUT << "RESOLVING UNDEFS\n";
1691 ResolvedUndefs = false;
1692 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1693 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1694 }
1695
1696 bool MadeChanges = false;
1697
1698 // Iterate over all of the instructions in the module, replacing them with
1699 // constants if we have found them to be of constant values.
1700 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001701 SmallVector<Instruction*, 512> Insts;
1702 SmallVector<BasicBlock*, 512> BlocksToErase;
Bill Wendling03488ae2008-08-14 23:05:24 +00001703 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001704
1705 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1706 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1707 AI != E; ++AI)
1708 if (!AI->use_empty()) {
1709 LatticeVal &IV = Values[AI];
1710 if (IV.isConstant() || IV.isUndefined()) {
1711 Constant *CST = IV.isConstant() ?
Owen Andersonfa089ab2009-07-03 19:42:02 +00001712 IV.getConstant() : Context->getUndef(AI->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001713 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
1714
1715 // Replaces all of the uses of a variable with uses of the
1716 // constant.
1717 AI->replaceAllUsesWith(CST);
1718 ++IPNumArgsElimed;
1719 }
1720 }
1721
1722 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
Chris Lattner317e6b62008-08-23 23:39:31 +00001723 if (!Solver.isBlockExecutable(BB)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001724 DOUT << " BasicBlock Dead:" << *BB;
1725 ++IPNumDeadBlocks;
1726
1727 // Delete the instructions backwards, as it has a reduced likelihood of
1728 // having to update as many def-use and use-def chains.
1729 TerminatorInst *TI = BB->getTerminator();
1730 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1731 Insts.push_back(I);
1732
1733 while (!Insts.empty()) {
1734 Instruction *I = Insts.back();
1735 Insts.pop_back();
1736 if (!I->use_empty())
Owen Andersonfa089ab2009-07-03 19:42:02 +00001737 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738 BB->getInstList().erase(I);
1739 MadeChanges = true;
1740 ++IPNumInstRemoved;
1741 }
1742
1743 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1744 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohman3f7d94b2007-10-03 19:26:29 +00001745 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001746 TI->getSuccessor(i)->removePredecessor(BB);
1747 }
1748 if (!TI->use_empty())
Owen Andersonfa089ab2009-07-03 19:42:02 +00001749 TI->replaceAllUsesWith(Context->getUndef(TI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001750 BB->getInstList().erase(TI);
1751
1752 if (&*BB != &F->front())
1753 BlocksToErase.push_back(BB);
1754 else
1755 new UnreachableInst(BB);
1756
1757 } else {
1758 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1759 Instruction *Inst = BI++;
Chris Lattnerc27ce6d2009-01-14 21:01:16 +00001760 if (Inst->getType() == Type::VoidTy)
Chris Lattner50846cf2008-04-24 00:21:50 +00001761 continue;
1762
1763 LatticeVal &IV = Values[Inst];
1764 if (!IV.isConstant() && !IV.isUndefined())
1765 continue;
1766
1767 Constant *Const = IV.isConstant()
Owen Andersonfa089ab2009-07-03 19:42:02 +00001768 ? IV.getConstant() : Context->getUndef(Inst->getType());
Chris Lattner50846cf2008-04-24 00:21:50 +00001769 DOUT << " Constant: " << *Const << " = " << *Inst;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001770
Chris Lattner50846cf2008-04-24 00:21:50 +00001771 // Replaces all of the uses of a variable with uses of the
1772 // constant.
1773 Inst->replaceAllUsesWith(Const);
1774
1775 // Delete the instruction.
Chris Lattnerc27ce6d2009-01-14 21:01:16 +00001776 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
Chris Lattner50846cf2008-04-24 00:21:50 +00001777 Inst->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001778
Chris Lattner50846cf2008-04-24 00:21:50 +00001779 // Hey, we just changed something!
1780 MadeChanges = true;
1781 ++IPNumInstRemoved;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001782 }
1783 }
1784
1785 // Now that all instructions in the function are constant folded, erase dead
1786 // blocks, because we can now use ConstantFoldTerminator to get rid of
1787 // in-edges.
1788 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1789 // If there are any PHI nodes in this successor, drop entries for BB now.
1790 BasicBlock *DeadBB = BlocksToErase[i];
1791 while (!DeadBB->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001792 Instruction *I = cast<Instruction>(DeadBB->use_back());
1793 bool Folded = ConstantFoldTerminator(I->getParent());
1794 if (!Folded) {
1795 // The constant folder may not have been able to fold the terminator
1796 // if this is a branch or switch on undef. Fold it manually as a
1797 // branch to the first successor.
Devang Patele92c16d2008-11-21 01:52:59 +00001798#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001799 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1800 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1801 "Branch should be foldable!");
1802 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1803 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1804 } else {
1805 assert(0 && "Didn't fold away reference to block!");
1806 }
Devang Patele92c16d2008-11-21 01:52:59 +00001807#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001808
1809 // Make this an uncond branch to the first successor.
1810 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001811 BranchInst::Create(TI->getSuccessor(0), TI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001812
1813 // Remove entries in successor phi nodes to remove edges.
1814 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1815 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1816
1817 // Remove the old terminator.
1818 TI->eraseFromParent();
1819 }
1820 }
1821
1822 // Finally, delete the basic block.
1823 F->getBasicBlockList().erase(DeadBB);
1824 }
1825 BlocksToErase.clear();
1826 }
1827
1828 // If we inferred constant or undef return values for a function, we replaced
1829 // all call uses with the inferred value. This means we don't need to bother
1830 // actually returning anything from the function. Replace all return
1831 // instructions with return undef.
Devang Pateld04d42b2008-03-11 17:32:05 +00001832 // TODO: Process multiple value ret instructions also.
Devang Pateladd320d2008-03-11 05:46:42 +00001833 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001834 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1835 E = RV.end(); I != E; ++I)
1836 if (!I->second.isOverdefined() &&
1837 I->first->getReturnType() != Type::VoidTy) {
1838 Function *F = I->first;
1839 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1840 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1841 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Andersonfa089ab2009-07-03 19:42:02 +00001842 RI->setOperand(0, Context->getUndef(F->getReturnType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001843 }
1844
1845 // If we infered constant or undef values for globals variables, we can delete
1846 // the global and any stores that remain to it.
1847 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1848 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1849 E = TG.end(); I != E; ++I) {
1850 GlobalVariable *GV = I->first;
1851 assert(!I->second.isOverdefined() &&
1852 "Overdefined values should have been taken out of the map!");
Chris Lattner56bf9a92008-05-11 01:55:59 +00001853 DOUT << "Found that GV '" << GV->getNameStart() << "' is constant!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001854 while (!GV->use_empty()) {
1855 StoreInst *SI = cast<StoreInst>(GV->use_back());
1856 SI->eraseFromParent();
1857 }
1858 M.getGlobalList().erase(GV);
1859 ++IPNumGlobalConst;
1860 }
1861
1862 return MadeChanges;
1863}