blob: e849b2d876588893b87698b207a71a1be3240732 [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"
30#include "llvm/Pass.h"
31#include "llvm/Analysis/ConstantFolding.h"
32#include "llvm/Transforms/Utils/Local.h"
33#include "llvm/Support/CallSite.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/InstVisitor.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/SmallSet.h"
39#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///
58class VISIBILITY_HIDDEN LatticeVal {
59 enum {
60 /// 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
75 } LatticeValue; // The current lattice position
76
77 Constant *ConstantVal; // If Constant value, the current value
78public:
79 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
80
81 // markOverdefined - Return true if this is a new status to be in...
82 inline bool markOverdefined() {
83 if (LatticeValue != overdefined) {
84 LatticeValue = overdefined;
85 return true;
86 }
87 return false;
88 }
89
90 // markConstant - Return true if this is a new status for us.
91 inline bool markConstant(Constant *V) {
92 if (LatticeValue != constant) {
93 if (LatticeValue == undefined) {
94 LatticeValue = constant;
95 assert(V && "Marking constant with NULL");
96 ConstantVal = V;
97 } else {
98 assert(LatticeValue == forcedconstant &&
99 "Cannot move from overdefined to constant!");
100 // Stay at forcedconstant if the constant is the same.
101 if (V == ConstantVal) return false;
102
103 // Otherwise, we go to overdefined. Assumptions made based on the
104 // forced value are possibly wrong. Assuming this is another constant
105 // could expose a contradiction.
106 LatticeValue = overdefined;
107 }
108 return true;
109 } else {
110 assert(ConstantVal == V && "Marking constant with different value");
111 }
112 return false;
113 }
114
115 inline void markForcedConstant(Constant *V) {
116 assert(LatticeValue == undefined && "Can't force a defined value!");
117 LatticeValue = forcedconstant;
118 ConstantVal = V;
119 }
120
121 inline bool isUndefined() const { return LatticeValue == undefined; }
122 inline bool isConstant() const {
123 return LatticeValue == constant || LatticeValue == forcedconstant;
124 }
125 inline bool isOverdefined() const { return LatticeValue == overdefined; }
126
127 inline Constant *getConstant() const {
128 assert(isConstant() && "Cannot get the constant of a non-constant!");
129 return ConstantVal;
130 }
131};
132
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133//===----------------------------------------------------------------------===//
134//
135/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
136/// Constant Propagation.
137///
138class SCCPSolver : public InstVisitor<SCCPSolver> {
139 SmallSet<BasicBlock*, 16> BBExecutable;// The basic blocks that are executable
140 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
141
142 /// GlobalValue - If we are tracking any values for the contents of a global
143 /// variable, we keep a mapping from the constant accessor to the element of
144 /// the global, to the currently known value. If the value becomes
145 /// overdefined, it's entry is simply removed from this map.
146 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
147
Devang Pateladd320d2008-03-11 05:46:42 +0000148 /// TrackedRetVals - If we are tracking arguments into and the return
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149 /// value out of a function, it will have an entry in this map, indicating
150 /// what the known return value for the function is.
Devang Pateladd320d2008-03-11 05:46:42 +0000151 DenseMap<Function*, LatticeVal> TrackedRetVals;
152
153 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
154 /// that return multiple values.
Chris Lattnercd73be02008-04-23 05:38:20 +0000155 std::map<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156
157 // The reason for two worklists is that overdefined is the lowest state
158 // on the lattice, and moving things to overdefined as fast as possible
159 // makes SCCP converge much faster.
160 // By having a separate worklist, we accomplish this because everything
161 // possibly overdefined will become overdefined at the soonest possible
162 // point.
163 std::vector<Value*> OverdefinedInstWorkList;
164 std::vector<Value*> InstWorkList;
165
166
167 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
168
169 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
170 /// overdefined, despite the fact that the PHI node is overdefined.
171 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
172
173 /// KnownFeasibleEdges - Entries in this set are edges which have already had
174 /// PHI nodes retriggered.
175 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
176 std::set<Edge> KnownFeasibleEdges;
177public:
178
179 /// MarkBlockExecutable - This method can be used by clients to mark all of
180 /// the blocks that are known to be intrinsically live in the processed unit.
181 void MarkBlockExecutable(BasicBlock *BB) {
182 DOUT << "Marking Block Executable: " << BB->getName() << "\n";
183 BBExecutable.insert(BB); // Basic block is executable!
184 BBWorkList.push_back(BB); // Add the block to the work list!
185 }
186
187 /// TrackValueOfGlobalVariable - Clients can use this method to
188 /// inform the SCCPSolver that it should track loads and stores to the
189 /// specified global variable if it can. This is only legal to call if
190 /// performing Interprocedural SCCP.
191 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
192 const Type *ElTy = GV->getType()->getElementType();
193 if (ElTy->isFirstClassType()) {
194 LatticeVal &IV = TrackedGlobals[GV];
195 if (!isa<UndefValue>(GV->getInitializer()))
196 IV.markConstant(GV->getInitializer());
197 }
198 }
199
200 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
201 /// and out of the specified function (which cannot have its address taken),
202 /// this method must be called.
203 void AddTrackedFunction(Function *F) {
204 assert(F->hasInternalLinkage() && "Can only track internal functions!");
205 // Add an entry, F -> undef.
Devang Pateladd320d2008-03-11 05:46:42 +0000206 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
207 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnercd73be02008-04-23 05:38:20 +0000208 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
209 LatticeVal()));
210 } else
211 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 }
213
214 /// Solve - Solve for constants and executable blocks.
215 ///
216 void Solve();
217
218 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
219 /// that branches on undef values cannot reach any of their successors.
220 /// However, this is not a safe assumption. After we solve dataflow, this
221 /// method should be use to handle this. If this returns true, the solver
222 /// should be rerun.
223 bool ResolvedUndefsIn(Function &F);
224
225 /// getExecutableBlocks - Once we have solved for constants, return the set of
226 /// blocks that is known to be executable.
227 SmallSet<BasicBlock*, 16> &getExecutableBlocks() {
228 return BBExecutable;
229 }
230
231 /// getValueMapping - Once we have solved for constants, return the mapping of
232 /// LLVM values to LatticeVals.
233 std::map<Value*, LatticeVal> &getValueMapping() {
234 return ValueState;
235 }
236
Devang Pateladd320d2008-03-11 05:46:42 +0000237 /// getTrackedRetVals - Get the inferred return value map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 ///
Devang Pateladd320d2008-03-11 05:46:42 +0000239 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
240 return TrackedRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241 }
242
243 /// getTrackedGlobals - Get and return the set of inferred initializers for
244 /// global variables.
245 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
246 return TrackedGlobals;
247 }
248
249 inline void markOverdefined(Value *V) {
250 markOverdefined(ValueState[V], V);
251 }
252
253private:
254 // markConstant - Make a value be marked as "constant". If the value
255 // is not already a constant, add it to the instruction work list so that
256 // the users of the instruction are updated later.
257 //
258 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
259 if (IV.markConstant(C)) {
260 DOUT << "markConstant: " << *C << ": " << *V;
261 InstWorkList.push_back(V);
262 }
263 }
264
265 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
266 IV.markForcedConstant(C);
267 DOUT << "markForcedConstant: " << *C << ": " << *V;
268 InstWorkList.push_back(V);
269 }
270
271 inline void markConstant(Value *V, Constant *C) {
272 markConstant(ValueState[V], V, C);
273 }
274
275 // markOverdefined - Make a value be marked as "overdefined". If the
276 // value is not already overdefined, add it to the overdefined instruction
277 // work list so that the users of the instruction are updated later.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 inline void markOverdefined(LatticeVal &IV, Value *V) {
279 if (IV.markOverdefined()) {
280 DEBUG(DOUT << "markOverdefined: ";
281 if (Function *F = dyn_cast<Function>(V))
282 DOUT << "Function '" << F->getName() << "'\n";
283 else
284 DOUT << *V);
285 // Only instructions go on the work list
286 OverdefinedInstWorkList.push_back(V);
287 }
288 }
289
290 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
291 if (IV.isOverdefined() || MergeWithV.isUndefined())
292 return; // Noop.
293 if (MergeWithV.isOverdefined())
294 markOverdefined(IV, V);
295 else if (IV.isUndefined())
296 markConstant(IV, V, MergeWithV.getConstant());
297 else if (IV.getConstant() != MergeWithV.getConstant())
298 markOverdefined(IV, V);
299 }
300
301 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
302 return mergeInValue(ValueState[V], V, MergeWithV);
303 }
304
305
306 // getValueState - Return the LatticeVal object that corresponds to the value.
307 // This function is necessary because not all values should start out in the
308 // underdefined state... Argument's should be overdefined, and
309 // constants should be marked as constants. If a value is not known to be an
310 // Instruction object, then use this accessor to get its value from the map.
311 //
312 inline LatticeVal &getValueState(Value *V) {
313 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
314 if (I != ValueState.end()) return I->second; // Common case, in the map
315
316 if (Constant *C = dyn_cast<Constant>(V)) {
317 if (isa<UndefValue>(V)) {
318 // Nothing to do, remain undefined.
319 } else {
320 LatticeVal &LV = ValueState[C];
321 LV.markConstant(C); // Constants are constant
322 return LV;
323 }
324 }
325 // All others are underdefined by default...
326 return ValueState[V];
327 }
328
329 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
330 // work list if it is not already executable...
331 //
332 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
333 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
334 return; // This edge is already known to be executable!
335
336 if (BBExecutable.count(Dest)) {
337 DOUT << "Marking Edge Executable: " << Source->getName()
338 << " -> " << Dest->getName() << "\n";
339
340 // The destination is already executable, but we just made an edge
341 // feasible that wasn't before. Revisit the PHI nodes in the block
342 // because they have potentially new operands.
343 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
344 visitPHINode(*cast<PHINode>(I));
345
346 } else {
347 MarkBlockExecutable(Dest);
348 }
349 }
350
351 // getFeasibleSuccessors - Return a vector of booleans to indicate which
352 // successors are reachable from a given terminator instruction.
353 //
354 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
355
356 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
357 // block to the 'To' basic block is currently feasible...
358 //
359 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
360
361 // OperandChangedState - This method is invoked on all of the users of an
362 // instruction that was just changed state somehow.... Based on this
363 // information, we need to update the specified user of this instruction.
364 //
365 void OperandChangedState(User *U) {
366 // Only instructions use other variable values!
367 Instruction &I = cast<Instruction>(*U);
368 if (BBExecutable.count(I.getParent())) // Inst is executable?
369 visit(I);
370 }
371
372private:
373 friend class InstVisitor<SCCPSolver>;
374
375 // visit implementations - Something changed in this instruction... Either an
376 // operand made a transition, or the instruction is newly executable. Change
377 // the value type of I to reflect these changes if appropriate.
378 //
379 void visitPHINode(PHINode &I);
380
381 // Terminators
382 void visitReturnInst(ReturnInst &I);
383 void visitTerminatorInst(TerminatorInst &TI);
384
385 void visitCastInst(CastInst &I);
Devang Pateladd320d2008-03-11 05:46:42 +0000386 void visitGetResultInst(GetResultInst &GRI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000387 void visitSelectInst(SelectInst &I);
388 void visitBinaryOperator(Instruction &I);
389 void visitCmpInst(CmpInst &I);
390 void visitExtractElementInst(ExtractElementInst &I);
391 void visitInsertElementInst(InsertElementInst &I);
392 void visitShuffleVectorInst(ShuffleVectorInst &I);
393
394 // Instructions that cannot be folded away...
395 void visitStoreInst (Instruction &I);
396 void visitLoadInst (LoadInst &I);
397 void visitGetElementPtrInst(GetElementPtrInst &I);
398 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
399 void visitInvokeInst (InvokeInst &II) {
400 visitCallSite(CallSite::get(&II));
401 visitTerminatorInst(II);
402 }
403 void visitCallSite (CallSite CS);
404 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
405 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
406 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
407 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
408 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
409 void visitFreeInst (Instruction &I) { /*returns void*/ }
410
411 void visitInstruction(Instruction &I) {
412 // If a new instruction is added to LLVM that we don't handle...
413 cerr << "SCCP: Don't know how to handle: " << I;
414 markOverdefined(&I); // Just in case
415 }
416};
417
Duncan Sands40f67972007-07-20 08:56:21 +0000418} // end anonymous namespace
419
420
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421// getFeasibleSuccessors - Return a vector of booleans to indicate which
422// successors are reachable from a given terminator instruction.
423//
424void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
425 SmallVector<bool, 16> &Succs) {
426 Succs.resize(TI.getNumSuccessors());
427 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
428 if (BI->isUnconditional()) {
429 Succs[0] = true;
430 } else {
431 LatticeVal &BCValue = getValueState(BI->getCondition());
432 if (BCValue.isOverdefined() ||
433 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
434 // Overdefined condition variables, and branches on unfoldable constant
435 // conditions, mean the branch could go either way.
436 Succs[0] = Succs[1] = true;
437 } else if (BCValue.isConstant()) {
438 // Constant condition variables mean the branch can only go a single way
439 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
440 }
441 }
442 } else if (isa<InvokeInst>(&TI)) {
443 // Invoke instructions successors are always executable.
444 Succs[0] = Succs[1] = true;
445 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
446 LatticeVal &SCValue = getValueState(SI->getCondition());
447 if (SCValue.isOverdefined() || // Overdefined condition?
448 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
449 // All destinations are executable!
450 Succs.assign(TI.getNumSuccessors(), true);
451 } else if (SCValue.isConstant()) {
452 Constant *CPV = SCValue.getConstant();
453 // Make sure to skip the "default value" which isn't a value
454 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
455 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
456 Succs[i] = true;
457 return;
458 }
459 }
460
461 // Constant value not equal to any of the branches... must execute
462 // default branch then...
463 Succs[0] = true;
464 }
465 } else {
466 assert(0 && "SCCP: Don't know how to handle this terminator!");
467 }
468}
469
470
471// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
472// block to the 'To' basic block is currently feasible...
473//
474bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
475 assert(BBExecutable.count(To) && "Dest should always be alive!");
476
477 // Make sure the source basic block is executable!!
478 if (!BBExecutable.count(From)) return false;
479
480 // Check to make sure this edge itself is actually feasible now...
481 TerminatorInst *TI = From->getTerminator();
482 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
483 if (BI->isUnconditional())
484 return true;
485 else {
486 LatticeVal &BCValue = getValueState(BI->getCondition());
487 if (BCValue.isOverdefined()) {
488 // Overdefined condition variables mean the branch could go either way.
489 return true;
490 } else if (BCValue.isConstant()) {
491 // Not branching on an evaluatable constant?
492 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
493
494 // Constant condition variables mean the branch can only go a single way
495 return BI->getSuccessor(BCValue.getConstant() ==
496 ConstantInt::getFalse()) == To;
497 }
498 return false;
499 }
500 } else if (isa<InvokeInst>(TI)) {
501 // Invoke instructions successors are always executable.
502 return true;
503 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
504 LatticeVal &SCValue = getValueState(SI->getCondition());
505 if (SCValue.isOverdefined()) { // Overdefined condition?
506 // All destinations are executable!
507 return true;
508 } else if (SCValue.isConstant()) {
509 Constant *CPV = SCValue.getConstant();
510 if (!isa<ConstantInt>(CPV))
511 return true; // not a foldable constant?
512
513 // Make sure to skip the "default value" which isn't a value
514 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
515 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
516 return SI->getSuccessor(i) == To;
517
518 // Constant value not equal to any of the branches... must execute
519 // default branch then...
520 return SI->getDefaultDest() == To;
521 }
522 return false;
523 } else {
524 cerr << "Unknown terminator instruction: " << *TI;
525 abort();
526 }
527}
528
529// visit Implementations - Something changed in this instruction... Either an
530// operand made a transition, or the instruction is newly executable. Change
531// the value type of I to reflect these changes if appropriate. This method
532// makes sure to do the following actions:
533//
534// 1. If a phi node merges two constants in, and has conflicting value coming
535// from different branches, or if the PHI node merges in an overdefined
536// value, then the PHI node becomes overdefined.
537// 2. If a phi node merges only constants in, and they all agree on value, the
538// PHI node becomes a constant value equal to that.
539// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
540// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
541// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
542// 6. If a conditional branch has a value that is constant, make the selected
543// destination executable
544// 7. If a conditional branch has a value that is overdefined, make all
545// successors executable.
546//
547void SCCPSolver::visitPHINode(PHINode &PN) {
548 LatticeVal &PNIV = getValueState(&PN);
549 if (PNIV.isOverdefined()) {
550 // There may be instructions using this PHI node that are not overdefined
551 // themselves. If so, make sure that they know that the PHI node operand
552 // changed.
553 std::multimap<PHINode*, Instruction*>::iterator I, E;
554 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
555 if (I != E) {
556 SmallVector<Instruction*, 16> Users;
557 for (; I != E; ++I) Users.push_back(I->second);
558 while (!Users.empty()) {
559 visit(Users.back());
560 Users.pop_back();
561 }
562 }
563 return; // Quick exit
564 }
565
566 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
567 // and slow us down a lot. Just mark them overdefined.
568 if (PN.getNumIncomingValues() > 64) {
569 markOverdefined(PNIV, &PN);
570 return;
571 }
572
573 // Look at all of the executable operands of the PHI node. If any of them
574 // are overdefined, the PHI becomes overdefined as well. If they are all
575 // constant, and they agree with each other, the PHI becomes the identical
576 // constant. If they are constant and don't agree, the PHI is overdefined.
577 // If there are no executable operands, the PHI remains undefined.
578 //
579 Constant *OperandVal = 0;
580 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
581 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
582 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
583
584 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
585 if (IV.isOverdefined()) { // PHI node becomes overdefined!
586 markOverdefined(PNIV, &PN);
587 return;
588 }
589
590 if (OperandVal == 0) { // Grab the first value...
591 OperandVal = IV.getConstant();
592 } else { // Another value is being merged in!
593 // There is already a reachable operand. If we conflict with it,
594 // then the PHI node becomes overdefined. If we agree with it, we
595 // can continue on.
596
597 // Check to see if there are two different constants merging...
598 if (IV.getConstant() != OperandVal) {
599 // Yes there is. This means the PHI node is not constant.
600 // You must be overdefined poor PHI.
601 //
602 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
603 return; // I'm done analyzing you
604 }
605 }
606 }
607 }
608
609 // If we exited the loop, this means that the PHI node only has constant
610 // arguments that agree with each other(and OperandVal is the constant) or
611 // OperandVal is null because there are no defined incoming arguments. If
612 // this is the case, the PHI remains undefined.
613 //
614 if (OperandVal)
615 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
616}
617
618void SCCPSolver::visitReturnInst(ReturnInst &I) {
619 if (I.getNumOperands() == 0) return; // Ret void
620
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621 Function *F = I.getParent()->getParent();
Devang Pateladd320d2008-03-11 05:46:42 +0000622 // If we are tracking the return value of this function, merge it in.
623 if (!F->hasInternalLinkage())
624 return;
625
Chris Lattnercd73be02008-04-23 05:38:20 +0000626 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Pateladd320d2008-03-11 05:46:42 +0000628 TrackedRetVals.find(F);
629 if (TFRVI != TrackedRetVals.end() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 !TFRVI->second.isOverdefined()) {
631 LatticeVal &IV = getValueState(I.getOperand(0));
632 mergeInValue(TFRVI->second, F, IV);
Devang Pateladd320d2008-03-11 05:46:42 +0000633 return;
634 }
635 }
636
Chris Lattnercd73be02008-04-23 05:38:20 +0000637 // Handle functions that return multiple values.
638 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
639 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
640 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
641 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
642 if (It == TrackedMultipleRetVals.end()) break;
643 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644 }
645 }
646}
647
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
649 SmallVector<bool, 16> SuccFeasible;
650 getFeasibleSuccessors(TI, SuccFeasible);
651
652 BasicBlock *BB = TI.getParent();
653
654 // Mark all feasible successors executable...
655 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
656 if (SuccFeasible[i])
657 markEdgeExecutable(BB, TI.getSuccessor(i));
658}
659
660void SCCPSolver::visitCastInst(CastInst &I) {
661 Value *V = I.getOperand(0);
662 LatticeVal &VState = getValueState(V);
663 if (VState.isOverdefined()) // Inherit overdefinedness of operand
664 markOverdefined(&I);
665 else if (VState.isConstant()) // Propagate constant value
666 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
667 VState.getConstant(), I.getType()));
668}
669
Devang Pateladd320d2008-03-11 05:46:42 +0000670void SCCPSolver::visitGetResultInst(GetResultInst &GRI) {
Devang Pateladd320d2008-03-11 05:46:42 +0000671 Value *Aggr = GRI.getOperand(0);
Chris Lattnercd73be02008-04-23 05:38:20 +0000672
673 // If the operand to the getresult is an undef, the result is undef.
674 if (isa<UndefValue>(Aggr))
675 return;
676
677 Function *F;
Devang Patelfbb201d2008-04-09 15:58:24 +0000678 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
Devang Pateladd320d2008-03-11 05:46:42 +0000679 F = CI->getCalledFunction();
Chris Lattnercd73be02008-04-23 05:38:20 +0000680 else
681 F = cast<InvokeInst>(Aggr)->getCalledFunction();
Devang Pateladd320d2008-03-11 05:46:42 +0000682
Chris Lattnercd73be02008-04-23 05:38:20 +0000683 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
684 // result back!
685 if (F == 0 || TrackedMultipleRetVals.empty()) {
686 markOverdefined(&GRI);
Devang Patelfbb201d2008-04-09 15:58:24 +0000687 return;
Devang Pateladd320d2008-03-11 05:46:42 +0000688 }
Chris Lattnercd73be02008-04-23 05:38:20 +0000689
690 // See if we are tracking the result of the callee.
691 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
692 It = TrackedMultipleRetVals.find(std::make_pair(F, GRI.getIndex()));
693
694 // If not tracking this function (for example, it is a declaration) just move
695 // to overdefined.
696 if (It == TrackedMultipleRetVals.end()) {
697 markOverdefined(&GRI);
698 return;
699 }
700
701 // Otherwise, the value will be merged in here as a result of CallSite
702 // handling.
Devang Pateladd320d2008-03-11 05:46:42 +0000703}
704
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705void SCCPSolver::visitSelectInst(SelectInst &I) {
706 LatticeVal &CondValue = getValueState(I.getCondition());
707 if (CondValue.isUndefined())
708 return;
709 if (CondValue.isConstant()) {
710 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
711 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
712 : I.getFalseValue()));
713 return;
714 }
715 }
716
717 // Otherwise, the condition is overdefined or a constant we can't evaluate.
718 // See if we can produce something better than overdefined based on the T/F
719 // value.
720 LatticeVal &TVal = getValueState(I.getTrueValue());
721 LatticeVal &FVal = getValueState(I.getFalseValue());
722
723 // select ?, C, C -> C.
724 if (TVal.isConstant() && FVal.isConstant() &&
725 TVal.getConstant() == FVal.getConstant()) {
726 markConstant(&I, FVal.getConstant());
727 return;
728 }
729
730 if (TVal.isUndefined()) { // select ?, undef, X -> X.
731 mergeInValue(&I, FVal);
732 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
733 mergeInValue(&I, TVal);
734 } else {
735 markOverdefined(&I);
736 }
737}
738
739// Handle BinaryOperators and Shift Instructions...
740void SCCPSolver::visitBinaryOperator(Instruction &I) {
741 LatticeVal &IV = ValueState[&I];
742 if (IV.isOverdefined()) return;
743
744 LatticeVal &V1State = getValueState(I.getOperand(0));
745 LatticeVal &V2State = getValueState(I.getOperand(1));
746
747 if (V1State.isOverdefined() || V2State.isOverdefined()) {
748 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
749 // operand is overdefined.
750 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
751 LatticeVal *NonOverdefVal = 0;
752 if (!V1State.isOverdefined()) {
753 NonOverdefVal = &V1State;
754 } else if (!V2State.isOverdefined()) {
755 NonOverdefVal = &V2State;
756 }
757
758 if (NonOverdefVal) {
759 if (NonOverdefVal->isUndefined()) {
760 // Could annihilate value.
761 if (I.getOpcode() == Instruction::And)
762 markConstant(IV, &I, Constant::getNullValue(I.getType()));
763 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
764 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
765 else
766 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
767 return;
768 } else {
769 if (I.getOpcode() == Instruction::And) {
770 if (NonOverdefVal->getConstant()->isNullValue()) {
771 markConstant(IV, &I, NonOverdefVal->getConstant());
772 return; // X and 0 = 0
773 }
774 } else {
775 if (ConstantInt *CI =
776 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
777 if (CI->isAllOnesValue()) {
778 markConstant(IV, &I, NonOverdefVal->getConstant());
779 return; // X or -1 = -1
780 }
781 }
782 }
783 }
784 }
785
786
787 // If both operands are PHI nodes, it is possible that this instruction has
788 // a constant value, despite the fact that the PHI node doesn't. Check for
789 // this condition now.
790 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
791 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
792 if (PN1->getParent() == PN2->getParent()) {
793 // Since the two PHI nodes are in the same basic block, they must have
794 // entries for the same predecessors. Walk the predecessor list, and
795 // if all of the incoming values are constants, and the result of
796 // evaluating this expression with all incoming value pairs is the
797 // same, then this expression is a constant even though the PHI node
798 // is not a constant!
799 LatticeVal Result;
800 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
801 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
802 BasicBlock *InBlock = PN1->getIncomingBlock(i);
803 LatticeVal &In2 =
804 getValueState(PN2->getIncomingValueForBlock(InBlock));
805
806 if (In1.isOverdefined() || In2.isOverdefined()) {
807 Result.markOverdefined();
808 break; // Cannot fold this operation over the PHI nodes!
809 } else if (In1.isConstant() && In2.isConstant()) {
810 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
811 In2.getConstant());
812 if (Result.isUndefined())
813 Result.markConstant(V);
814 else if (Result.isConstant() && Result.getConstant() != V) {
815 Result.markOverdefined();
816 break;
817 }
818 }
819 }
820
821 // If we found a constant value here, then we know the instruction is
822 // constant despite the fact that the PHI nodes are overdefined.
823 if (Result.isConstant()) {
824 markConstant(IV, &I, Result.getConstant());
825 // Remember that this instruction is virtually using the PHI node
826 // operands.
827 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
828 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
829 return;
830 } else if (Result.isUndefined()) {
831 return;
832 }
833
834 // Okay, this really is overdefined now. Since we might have
835 // speculatively thought that this was not overdefined before, and
836 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
837 // make sure to clean out any entries that we put there, for
838 // efficiency.
839 std::multimap<PHINode*, Instruction*>::iterator It, E;
840 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
841 while (It != E) {
842 if (It->second == &I) {
843 UsersOfOverdefinedPHIs.erase(It++);
844 } else
845 ++It;
846 }
847 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
848 while (It != E) {
849 if (It->second == &I) {
850 UsersOfOverdefinedPHIs.erase(It++);
851 } else
852 ++It;
853 }
854 }
855
856 markOverdefined(IV, &I);
857 } else if (V1State.isConstant() && V2State.isConstant()) {
858 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
859 V2State.getConstant()));
860 }
861}
862
863// Handle ICmpInst instruction...
864void SCCPSolver::visitCmpInst(CmpInst &I) {
865 LatticeVal &IV = ValueState[&I];
866 if (IV.isOverdefined()) return;
867
868 LatticeVal &V1State = getValueState(I.getOperand(0));
869 LatticeVal &V2State = getValueState(I.getOperand(1));
870
871 if (V1State.isOverdefined() || V2State.isOverdefined()) {
872 // If both operands are PHI nodes, it is possible that this instruction has
873 // a constant value, despite the fact that the PHI node doesn't. Check for
874 // this condition now.
875 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
876 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
877 if (PN1->getParent() == PN2->getParent()) {
878 // Since the two PHI nodes are in the same basic block, they must have
879 // entries for the same predecessors. Walk the predecessor list, and
880 // if all of the incoming values are constants, and the result of
881 // evaluating this expression with all incoming value pairs is the
882 // same, then this expression is a constant even though the PHI node
883 // is not a constant!
884 LatticeVal Result;
885 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
886 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
887 BasicBlock *InBlock = PN1->getIncomingBlock(i);
888 LatticeVal &In2 =
889 getValueState(PN2->getIncomingValueForBlock(InBlock));
890
891 if (In1.isOverdefined() || In2.isOverdefined()) {
892 Result.markOverdefined();
893 break; // Cannot fold this operation over the PHI nodes!
894 } else if (In1.isConstant() && In2.isConstant()) {
895 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
896 In1.getConstant(),
897 In2.getConstant());
898 if (Result.isUndefined())
899 Result.markConstant(V);
900 else if (Result.isConstant() && Result.getConstant() != V) {
901 Result.markOverdefined();
902 break;
903 }
904 }
905 }
906
907 // If we found a constant value here, then we know the instruction is
908 // constant despite the fact that the PHI nodes are overdefined.
909 if (Result.isConstant()) {
910 markConstant(IV, &I, Result.getConstant());
911 // Remember that this instruction is virtually using the PHI node
912 // operands.
913 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
914 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
915 return;
916 } else if (Result.isUndefined()) {
917 return;
918 }
919
920 // Okay, this really is overdefined now. Since we might have
921 // speculatively thought that this was not overdefined before, and
922 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
923 // make sure to clean out any entries that we put there, for
924 // efficiency.
925 std::multimap<PHINode*, Instruction*>::iterator It, E;
926 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
927 while (It != E) {
928 if (It->second == &I) {
929 UsersOfOverdefinedPHIs.erase(It++);
930 } else
931 ++It;
932 }
933 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
934 while (It != E) {
935 if (It->second == &I) {
936 UsersOfOverdefinedPHIs.erase(It++);
937 } else
938 ++It;
939 }
940 }
941
942 markOverdefined(IV, &I);
943 } else if (V1State.isConstant() && V2State.isConstant()) {
944 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
945 V1State.getConstant(),
946 V2State.getConstant()));
947 }
948}
949
950void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
951 // FIXME : SCCP does not handle vectors properly.
952 markOverdefined(&I);
953 return;
954
955#if 0
956 LatticeVal &ValState = getValueState(I.getOperand(0));
957 LatticeVal &IdxState = getValueState(I.getOperand(1));
958
959 if (ValState.isOverdefined() || IdxState.isOverdefined())
960 markOverdefined(&I);
961 else if(ValState.isConstant() && IdxState.isConstant())
962 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
963 IdxState.getConstant()));
964#endif
965}
966
967void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
968 // FIXME : SCCP does not handle vectors properly.
969 markOverdefined(&I);
970 return;
971#if 0
972 LatticeVal &ValState = getValueState(I.getOperand(0));
973 LatticeVal &EltState = getValueState(I.getOperand(1));
974 LatticeVal &IdxState = getValueState(I.getOperand(2));
975
976 if (ValState.isOverdefined() || EltState.isOverdefined() ||
977 IdxState.isOverdefined())
978 markOverdefined(&I);
979 else if(ValState.isConstant() && EltState.isConstant() &&
980 IdxState.isConstant())
981 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
982 EltState.getConstant(),
983 IdxState.getConstant()));
984 else if (ValState.isUndefined() && EltState.isConstant() &&
985 IdxState.isConstant())
986 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
987 EltState.getConstant(),
988 IdxState.getConstant()));
989#endif
990}
991
992void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
993 // FIXME : SCCP does not handle vectors properly.
994 markOverdefined(&I);
995 return;
996#if 0
997 LatticeVal &V1State = getValueState(I.getOperand(0));
998 LatticeVal &V2State = getValueState(I.getOperand(1));
999 LatticeVal &MaskState = getValueState(I.getOperand(2));
1000
1001 if (MaskState.isUndefined() ||
1002 (V1State.isUndefined() && V2State.isUndefined()))
1003 return; // Undefined output if mask or both inputs undefined.
1004
1005 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1006 MaskState.isOverdefined()) {
1007 markOverdefined(&I);
1008 } else {
1009 // A mix of constant/undef inputs.
1010 Constant *V1 = V1State.isConstant() ?
1011 V1State.getConstant() : UndefValue::get(I.getType());
1012 Constant *V2 = V2State.isConstant() ?
1013 V2State.getConstant() : UndefValue::get(I.getType());
1014 Constant *Mask = MaskState.isConstant() ?
1015 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1016 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1017 }
1018#endif
1019}
1020
1021// Handle getelementptr instructions... if all operands are constants then we
1022// can turn this into a getelementptr ConstantExpr.
1023//
1024void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1025 LatticeVal &IV = ValueState[&I];
1026 if (IV.isOverdefined()) return;
1027
1028 SmallVector<Constant*, 8> Operands;
1029 Operands.reserve(I.getNumOperands());
1030
1031 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1032 LatticeVal &State = getValueState(I.getOperand(i));
1033 if (State.isUndefined())
1034 return; // Operands are not resolved yet...
1035 else if (State.isOverdefined()) {
1036 markOverdefined(IV, &I);
1037 return;
1038 }
1039 assert(State.isConstant() && "Unknown state!");
1040 Operands.push_back(State.getConstant());
1041 }
1042
1043 Constant *Ptr = Operands[0];
1044 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1045
1046 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1047 Operands.size()));
1048}
1049
1050void SCCPSolver::visitStoreInst(Instruction &SI) {
1051 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1052 return;
1053 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1054 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1055 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1056
1057 // Get the value we are storing into the global.
1058 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1059
1060 mergeInValue(I->second, GV, PtrVal);
1061 if (I->second.isOverdefined())
1062 TrackedGlobals.erase(I); // No need to keep tracking this!
1063}
1064
1065
1066// Handle load instructions. If the operand is a constant pointer to a constant
1067// global, we can replace the load with the loaded constant value!
1068void SCCPSolver::visitLoadInst(LoadInst &I) {
1069 LatticeVal &IV = ValueState[&I];
1070 if (IV.isOverdefined()) return;
1071
1072 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1073 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1074 if (PtrVal.isConstant() && !I.isVolatile()) {
1075 Value *Ptr = PtrVal.getConstant();
Christopher Lamb2c175392007-12-29 07:56:53 +00001076 // TODO: Consider a target hook for valid address spaces for this xform.
1077 if (isa<ConstantPointerNull>(Ptr) &&
1078 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 // load null -> null
1080 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1081 return;
1082 }
1083
1084 // Transform load (constant global) into the value loaded.
1085 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1086 if (GV->isConstant()) {
1087 if (!GV->isDeclaration()) {
1088 markConstant(IV, &I, GV->getInitializer());
1089 return;
1090 }
1091 } else if (!TrackedGlobals.empty()) {
1092 // If we are tracking this global, merge in the known value for it.
1093 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1094 TrackedGlobals.find(GV);
1095 if (It != TrackedGlobals.end()) {
1096 mergeInValue(IV, &I, It->second);
1097 return;
1098 }
1099 }
1100 }
1101
1102 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1103 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1104 if (CE->getOpcode() == Instruction::GetElementPtr)
1105 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
1106 if (GV->isConstant() && !GV->isDeclaration())
1107 if (Constant *V =
1108 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
1109 markConstant(IV, &I, V);
1110 return;
1111 }
1112 }
1113
1114 // Otherwise we cannot say for certain what value this load will produce.
1115 // Bail out.
1116 markOverdefined(IV, &I);
1117}
1118
1119void SCCPSolver::visitCallSite(CallSite CS) {
1120 Function *F = CS.getCalledFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121 Instruction *I = CS.getInstruction();
Chris Lattnercd73be02008-04-23 05:38:20 +00001122
1123 // The common case is that we aren't tracking the callee, either because we
1124 // are not doing interprocedural analysis or the callee is indirect, or is
1125 // external. Handle these cases first.
1126 if (F == 0 || !F->hasInternalLinkage()) {
1127CallOverdefined:
1128 // Void return and not tracking callee, just bail.
1129 if (I->getType() == Type::VoidTy) return;
1130
1131 // Otherwise, if we have a single return value case, and if the function is
1132 // a declaration, maybe we can constant fold it.
1133 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1134 canConstantFoldCallTo(F)) {
1135
1136 SmallVector<Constant*, 8> Operands;
1137 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1138 AI != E; ++AI) {
1139 LatticeVal &State = getValueState(*AI);
1140 if (State.isUndefined())
1141 return; // Operands are not resolved yet.
1142 else if (State.isOverdefined()) {
1143 markOverdefined(I);
1144 return;
1145 }
1146 assert(State.isConstant() && "Unknown state!");
1147 Operands.push_back(State.getConstant());
1148 }
1149
1150 // If we can constant fold this, mark the result of the call as a
1151 // constant.
1152 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size())) {
1153 markConstant(I, C);
1154 return;
1155 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001157
1158 // Otherwise, we don't know anything about this call, mark it overdefined.
1159 markOverdefined(I);
1160 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161 }
1162
Chris Lattnercd73be02008-04-23 05:38:20 +00001163 // If this is a single/zero retval case, see if we're tracking the function.
1164 const StructType *RetSTy = dyn_cast<StructType>(I->getType());
1165 if (RetSTy == 0) {
1166 // Check to see if we're tracking this callee, if not, handle it in the
1167 // common path above.
1168 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1169 if (TFRVI == TrackedRetVals.end())
1170 goto CallOverdefined;
1171
1172 // If so, propagate the return value of the callee into this call result.
1173 mergeInValue(I, TFRVI->second);
1174 } else {
1175 // Check to see if we're tracking this callee, if not, handle it in the
1176 // common path above.
1177 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
1178 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
1179 if (TMRVI == TrackedMultipleRetVals.end())
1180 goto CallOverdefined;
1181
1182 // If we are tracking this callee, propagate the return values of the call
1183 // into this call site. We do this by walking all the getresult uses.
1184 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1185 UI != E; ++UI) {
1186 GetResultInst *GRI = cast<GetResultInst>(*UI);
1187 mergeInValue(GRI,
1188 TrackedMultipleRetVals[std::make_pair(F, GRI->getIndex())]);
1189 }
1190 }
1191
1192 // Finally, if this is the first call to the function hit, mark its entry
1193 // block executable.
1194 if (!BBExecutable.count(F->begin()))
1195 MarkBlockExecutable(F->begin());
1196
1197 // Propagate information from this call site into the callee.
1198 CallSite::arg_iterator CAI = CS.arg_begin();
1199 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1200 AI != E; ++AI, ++CAI) {
1201 LatticeVal &IV = ValueState[AI];
1202 if (!IV.isOverdefined())
1203 mergeInValue(IV, AI, getValueState(*CAI));
1204 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001205}
1206
1207
1208void SCCPSolver::Solve() {
1209 // Process the work lists until they are empty!
1210 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1211 !OverdefinedInstWorkList.empty()) {
1212 // Process the instruction work list...
1213 while (!OverdefinedInstWorkList.empty()) {
1214 Value *I = OverdefinedInstWorkList.back();
1215 OverdefinedInstWorkList.pop_back();
1216
1217 DOUT << "\nPopped off OI-WL: " << *I;
1218
1219 // "I" got into the work list because it either made the transition from
1220 // bottom to constant
1221 //
1222 // Anything on this worklist that is overdefined need not be visited
1223 // since all of its users will have already been marked as overdefined
1224 // Update all of the users of this instruction's value...
1225 //
1226 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1227 UI != E; ++UI)
1228 OperandChangedState(*UI);
1229 }
1230 // Process the instruction work list...
1231 while (!InstWorkList.empty()) {
1232 Value *I = InstWorkList.back();
1233 InstWorkList.pop_back();
1234
1235 DOUT << "\nPopped off I-WL: " << *I;
1236
1237 // "I" got into the work list because it either made the transition from
1238 // bottom to constant
1239 //
1240 // Anything on this worklist that is overdefined need not be visited
1241 // since all of its users will have already been marked as overdefined.
1242 // Update all of the users of this instruction's value...
1243 //
1244 if (!getValueState(I).isOverdefined())
1245 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1246 UI != E; ++UI)
1247 OperandChangedState(*UI);
1248 }
1249
1250 // Process the basic block work list...
1251 while (!BBWorkList.empty()) {
1252 BasicBlock *BB = BBWorkList.back();
1253 BBWorkList.pop_back();
1254
1255 DOUT << "\nPopped off BBWL: " << *BB;
1256
1257 // Notify all instructions in this basic block that they are newly
1258 // executable.
1259 visit(BB);
1260 }
1261 }
1262}
1263
1264/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1265/// that branches on undef values cannot reach any of their successors.
1266/// However, this is not a safe assumption. After we solve dataflow, this
1267/// method should be use to handle this. If this returns true, the solver
1268/// should be rerun.
1269///
1270/// This method handles this by finding an unresolved branch and marking it one
1271/// of the edges from the block as being feasible, even though the condition
1272/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1273/// CFG and only slightly pessimizes the analysis results (by marking one,
1274/// potentially infeasible, edge feasible). This cannot usefully modify the
1275/// constraints on the condition of the branch, as that would impact other users
1276/// of the value.
1277///
1278/// This scan also checks for values that use undefs, whose results are actually
1279/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1280/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1281/// even if X isn't defined.
1282bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1283 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1284 if (!BBExecutable.count(BB))
1285 continue;
1286
1287 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1288 // Look for instructions which produce undef values.
1289 if (I->getType() == Type::VoidTy) continue;
1290
1291 LatticeVal &LV = getValueState(I);
1292 if (!LV.isUndefined()) continue;
1293
1294 // Get the lattice values of the first two operands for use below.
1295 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1296 LatticeVal Op1LV;
1297 if (I->getNumOperands() == 2) {
1298 // If this is a two-operand instruction, and if both operands are
1299 // undefs, the result stays undef.
1300 Op1LV = getValueState(I->getOperand(1));
1301 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1302 continue;
1303 }
1304
1305 // If this is an instructions whose result is defined even if the input is
1306 // not fully defined, propagate the information.
1307 const Type *ITy = I->getType();
1308 switch (I->getOpcode()) {
1309 default: break; // Leave the instruction as an undef.
1310 case Instruction::ZExt:
1311 // After a zero extend, we know the top part is zero. SExt doesn't have
1312 // to be handled here, because we don't know whether the top part is 1's
1313 // or 0's.
1314 assert(Op0LV.isUndefined());
1315 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1316 return true;
1317 case Instruction::Mul:
1318 case Instruction::And:
1319 // undef * X -> 0. X could be zero.
1320 // undef & X -> 0. X could be zero.
1321 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1322 return true;
1323
1324 case Instruction::Or:
1325 // undef | X -> -1. X could be -1.
1326 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1327 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
1328 else
1329 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1330 return true;
1331
1332 case Instruction::SDiv:
1333 case Instruction::UDiv:
1334 case Instruction::SRem:
1335 case Instruction::URem:
1336 // X / undef -> undef. No change.
1337 // X % undef -> undef. No change.
1338 if (Op1LV.isUndefined()) break;
1339
1340 // undef / X -> 0. X could be maxint.
1341 // undef % X -> 0. X could be 1.
1342 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1343 return true;
1344
1345 case Instruction::AShr:
1346 // undef >>s X -> undef. No change.
1347 if (Op0LV.isUndefined()) break;
1348
1349 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1350 if (Op0LV.isConstant())
1351 markForcedConstant(LV, I, Op0LV.getConstant());
1352 else
1353 markOverdefined(LV, I);
1354 return true;
1355 case Instruction::LShr:
1356 case Instruction::Shl:
1357 // undef >> X -> undef. No change.
1358 // undef << X -> undef. No change.
1359 if (Op0LV.isUndefined()) break;
1360
1361 // X >> undef -> 0. X could be 0.
1362 // X << undef -> 0. X could be 0.
1363 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1364 return true;
1365 case Instruction::Select:
1366 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1367 if (Op0LV.isUndefined()) {
1368 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1369 Op1LV = getValueState(I->getOperand(2));
1370 } else if (Op1LV.isUndefined()) {
1371 // c ? undef : undef -> undef. No change.
1372 Op1LV = getValueState(I->getOperand(2));
1373 if (Op1LV.isUndefined())
1374 break;
1375 // Otherwise, c ? undef : x -> x.
1376 } else {
1377 // Leave Op1LV as Operand(1)'s LatticeValue.
1378 }
1379
1380 if (Op1LV.isConstant())
1381 markForcedConstant(LV, I, Op1LV.getConstant());
1382 else
1383 markOverdefined(LV, I);
1384 return true;
1385 }
1386 }
1387
1388 TerminatorInst *TI = BB->getTerminator();
1389 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1390 if (!BI->isConditional()) continue;
1391 if (!getValueState(BI->getCondition()).isUndefined())
1392 continue;
1393 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1394 if (!getValueState(SI->getCondition()).isUndefined())
1395 continue;
1396 } else {
1397 continue;
1398 }
1399
Chris Lattner6186e8c2008-01-28 00:32:30 +00001400 // If the edge to the second successor isn't thought to be feasible yet,
1401 // mark it so now. We pick the second one so that this goes to some
1402 // enumerated value in a switch instead of going to the default destination.
1403 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001404 continue;
1405
1406 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1407 // and return. This will make other blocks reachable, which will allow new
1408 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner6186e8c2008-01-28 00:32:30 +00001409 markEdgeExecutable(BB, TI->getSuccessor(1));
1410
1411 // This must be a conditional branch of switch on undef. At this point,
1412 // force the old terminator to branch to the first successor. This is
1413 // required because we are now influencing the dataflow of the function with
1414 // the assumption that this edge is taken. If we leave the branch condition
1415 // as undef, then further analysis could think the undef went another way
1416 // leading to an inconsistent set of conclusions.
1417 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1418 BI->setCondition(ConstantInt::getFalse());
1419 } else {
1420 SwitchInst *SI = cast<SwitchInst>(TI);
1421 SI->setCondition(SI->getCaseValue(1));
1422 }
1423
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001424 return true;
1425 }
1426
1427 return false;
1428}
1429
1430
1431namespace {
1432 //===--------------------------------------------------------------------===//
1433 //
1434 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1435 /// Sparse Conditional Constant Propagator.
1436 ///
1437 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
1438 static char ID; // Pass identification, replacement for typeid
1439 SCCP() : FunctionPass((intptr_t)&ID) {}
1440
1441 // runOnFunction - Run the Sparse Conditional Constant Propagation
1442 // algorithm, and return true if the function was modified.
1443 //
1444 bool runOnFunction(Function &F);
1445
1446 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1447 AU.setPreservesCFG();
1448 }
1449 };
1450
1451 char SCCP::ID = 0;
1452 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
1453} // end anonymous namespace
1454
1455
1456// createSCCPPass - This is the public interface to this file...
1457FunctionPass *llvm::createSCCPPass() {
1458 return new SCCP();
1459}
1460
1461
1462// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1463// and return true if the function was modified.
1464//
1465bool SCCP::runOnFunction(Function &F) {
1466 DOUT << "SCCP on function '" << F.getName() << "'\n";
1467 SCCPSolver Solver;
1468
1469 // Mark the first block of the function as being executable.
1470 Solver.MarkBlockExecutable(F.begin());
1471
1472 // Mark all arguments to the function as being overdefined.
1473 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1474 Solver.markOverdefined(AI);
1475
1476 // Solve for constants.
1477 bool ResolvedUndefs = true;
1478 while (ResolvedUndefs) {
1479 Solver.Solve();
1480 DOUT << "RESOLVING UNDEFs\n";
1481 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1482 }
1483
1484 bool MadeChanges = false;
1485
1486 // If we decided that there are basic blocks that are dead in this function,
1487 // delete their contents now. Note that we cannot actually delete the blocks,
1488 // as we cannot modify the CFG of the function.
1489 //
1490 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
1491 SmallVector<Instruction*, 32> Insts;
1492 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1493
1494 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1495 if (!ExecutableBBs.count(BB)) {
1496 DOUT << " BasicBlock Dead:" << *BB;
1497 ++NumDeadBlocks;
1498
1499 // Delete the instructions backwards, as it has a reduced likelihood of
1500 // having to update as many def-use and use-def chains.
1501 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1502 I != E; ++I)
1503 Insts.push_back(I);
1504 while (!Insts.empty()) {
1505 Instruction *I = Insts.back();
1506 Insts.pop_back();
1507 if (!I->use_empty())
1508 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1509 BB->getInstList().erase(I);
1510 MadeChanges = true;
1511 ++NumInstRemoved;
1512 }
1513 } else {
1514 // Iterate over all of the instructions in a function, replacing them with
1515 // constants if we have found them to be of constant values.
1516 //
1517 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1518 Instruction *Inst = BI++;
Chris Lattner204cfde2008-04-24 00:19:54 +00001519 if (Inst->getType() == Type::VoidTy ||
1520 isa<StructType>(Inst->getType()) ||
Chris Lattnerb6f89362008-04-24 00:16:28 +00001521 isa<TerminatorInst>(Inst))
1522 continue;
1523
1524 LatticeVal &IV = Values[Inst];
1525 if (!IV.isConstant() && !IV.isUndefined())
1526 continue;
1527
1528 Constant *Const = IV.isConstant()
1529 ? IV.getConstant() : UndefValue::get(Inst->getType());
1530 DOUT << " Constant: " << *Const << " = " << *Inst;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001531
Chris Lattnerb6f89362008-04-24 00:16:28 +00001532 // Replaces all of the uses of a variable with uses of the constant.
1533 Inst->replaceAllUsesWith(Const);
1534
1535 // Delete the instruction.
1536 Inst->eraseFromParent();
1537
1538 // Hey, we just changed something!
1539 MadeChanges = true;
1540 ++NumInstRemoved;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001541 }
1542 }
1543
1544 return MadeChanges;
1545}
1546
1547namespace {
1548 //===--------------------------------------------------------------------===//
1549 //
1550 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1551 /// Constant Propagation.
1552 ///
1553 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
1554 static char ID;
1555 IPSCCP() : ModulePass((intptr_t)&ID) {}
1556 bool runOnModule(Module &M);
1557 };
1558
1559 char IPSCCP::ID = 0;
1560 RegisterPass<IPSCCP>
1561 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1562} // end anonymous namespace
1563
1564// createIPSCCPPass - This is the public interface to this file...
1565ModulePass *llvm::createIPSCCPPass() {
1566 return new IPSCCP();
1567}
1568
1569
1570static bool AddressIsTaken(GlobalValue *GV) {
1571 // Delete any dead constantexpr klingons.
1572 GV->removeDeadConstantUsers();
1573
1574 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1575 UI != E; ++UI)
1576 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1577 if (SI->getOperand(0) == GV || SI->isVolatile())
1578 return true; // Storing addr of GV.
1579 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1580 // Make sure we are calling the function, not passing the address.
1581 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1582 for (CallSite::arg_iterator AI = CS.arg_begin(),
1583 E = CS.arg_end(); AI != E; ++AI)
1584 if (*AI == GV)
1585 return true;
1586 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1587 if (LI->isVolatile())
1588 return true;
1589 } else {
1590 return true;
1591 }
1592 return false;
1593}
1594
1595bool IPSCCP::runOnModule(Module &M) {
1596 SCCPSolver Solver;
1597
1598 // Loop over all functions, marking arguments to those with their addresses
1599 // taken or that are external as overdefined.
1600 //
1601 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1602 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1603 if (!F->isDeclaration())
1604 Solver.MarkBlockExecutable(F->begin());
1605 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1606 AI != E; ++AI)
1607 Solver.markOverdefined(AI);
1608 } else {
1609 Solver.AddTrackedFunction(F);
1610 }
1611
1612 // Loop over global variables. We inform the solver about any internal global
1613 // variables that do not have their 'addresses taken'. If they don't have
1614 // their addresses taken, we can propagate constants through them.
1615 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1616 G != E; ++G)
1617 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1618 Solver.TrackValueOfGlobalVariable(G);
1619
1620 // Solve for constants.
1621 bool ResolvedUndefs = true;
1622 while (ResolvedUndefs) {
1623 Solver.Solve();
1624
1625 DOUT << "RESOLVING UNDEFS\n";
1626 ResolvedUndefs = false;
1627 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1628 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1629 }
1630
1631 bool MadeChanges = false;
1632
1633 // Iterate over all of the instructions in the module, replacing them with
1634 // constants if we have found them to be of constant values.
1635 //
1636 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
1637 SmallVector<Instruction*, 32> Insts;
1638 SmallVector<BasicBlock*, 32> BlocksToErase;
1639 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1640
1641 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1642 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1643 AI != E; ++AI)
1644 if (!AI->use_empty()) {
1645 LatticeVal &IV = Values[AI];
1646 if (IV.isConstant() || IV.isUndefined()) {
1647 Constant *CST = IV.isConstant() ?
1648 IV.getConstant() : UndefValue::get(AI->getType());
1649 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
1650
1651 // Replaces all of the uses of a variable with uses of the
1652 // constant.
1653 AI->replaceAllUsesWith(CST);
1654 ++IPNumArgsElimed;
1655 }
1656 }
1657
1658 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1659 if (!ExecutableBBs.count(BB)) {
1660 DOUT << " BasicBlock Dead:" << *BB;
1661 ++IPNumDeadBlocks;
1662
1663 // Delete the instructions backwards, as it has a reduced likelihood of
1664 // having to update as many def-use and use-def chains.
1665 TerminatorInst *TI = BB->getTerminator();
1666 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1667 Insts.push_back(I);
1668
1669 while (!Insts.empty()) {
1670 Instruction *I = Insts.back();
1671 Insts.pop_back();
1672 if (!I->use_empty())
1673 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1674 BB->getInstList().erase(I);
1675 MadeChanges = true;
1676 ++IPNumInstRemoved;
1677 }
1678
1679 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1680 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohman3f7d94b2007-10-03 19:26:29 +00001681 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001682 TI->getSuccessor(i)->removePredecessor(BB);
1683 }
1684 if (!TI->use_empty())
1685 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1686 BB->getInstList().erase(TI);
1687
1688 if (&*BB != &F->front())
1689 BlocksToErase.push_back(BB);
1690 else
1691 new UnreachableInst(BB);
1692
1693 } else {
1694 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1695 Instruction *Inst = BI++;
Chris Lattner204cfde2008-04-24 00:19:54 +00001696 if (Inst->getType() != Type::VoidTy &&
1697 !isa<StructType>(Inst->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001698 LatticeVal &IV = Values[Inst];
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00001699 if (IV.isConstant() ||
1700 (IV.isUndefined() && !isa<TerminatorInst>(Inst))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001701 Constant *Const = IV.isConstant()
1702 ? IV.getConstant() : UndefValue::get(Inst->getType());
1703 DOUT << " Constant: " << *Const << " = " << *Inst;
1704
1705 // Replaces all of the uses of a variable with uses of the
1706 // constant.
1707 Inst->replaceAllUsesWith(Const);
1708
1709 // Delete the instruction.
1710 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1711 BB->getInstList().erase(Inst);
1712
1713 // Hey, we just changed something!
1714 MadeChanges = true;
1715 ++IPNumInstRemoved;
1716 }
1717 }
1718 }
1719 }
1720
1721 // Now that all instructions in the function are constant folded, erase dead
1722 // blocks, because we can now use ConstantFoldTerminator to get rid of
1723 // in-edges.
1724 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1725 // If there are any PHI nodes in this successor, drop entries for BB now.
1726 BasicBlock *DeadBB = BlocksToErase[i];
1727 while (!DeadBB->use_empty()) {
Nick Lewyckybbdfc9c2008-03-08 07:48:41 +00001728 if (BasicBlock *PredBB = dyn_cast<BasicBlock>(DeadBB->use_back())) {
1729 PredBB->setUnwindDest(NULL);
1730 continue;
1731 }
1732
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001733 Instruction *I = cast<Instruction>(DeadBB->use_back());
1734 bool Folded = ConstantFoldTerminator(I->getParent());
1735 if (!Folded) {
1736 // The constant folder may not have been able to fold the terminator
1737 // if this is a branch or switch on undef. Fold it manually as a
1738 // branch to the first successor.
1739 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1740 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1741 "Branch should be foldable!");
1742 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1743 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1744 } else {
1745 assert(0 && "Didn't fold away reference to block!");
1746 }
1747
1748 // Make this an uncond branch to the first successor.
1749 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001750 BranchInst::Create(TI->getSuccessor(0), TI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001751
1752 // Remove entries in successor phi nodes to remove edges.
1753 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1754 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1755
1756 // Remove the old terminator.
1757 TI->eraseFromParent();
1758 }
1759 }
1760
1761 // Finally, delete the basic block.
1762 F->getBasicBlockList().erase(DeadBB);
1763 }
1764 BlocksToErase.clear();
1765 }
1766
1767 // If we inferred constant or undef return values for a function, we replaced
1768 // all call uses with the inferred value. This means we don't need to bother
1769 // actually returning anything from the function. Replace all return
1770 // instructions with return undef.
Devang Pateld04d42b2008-03-11 17:32:05 +00001771 // TODO: Process multiple value ret instructions also.
Devang Pateladd320d2008-03-11 05:46:42 +00001772 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001773 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1774 E = RV.end(); I != E; ++I)
1775 if (!I->second.isOverdefined() &&
1776 I->first->getReturnType() != Type::VoidTy) {
1777 Function *F = I->first;
1778 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1779 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1780 if (!isa<UndefValue>(RI->getOperand(0)))
1781 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1782 }
1783
1784 // If we infered constant or undef values for globals variables, we can delete
1785 // the global and any stores that remain to it.
1786 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1787 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1788 E = TG.end(); I != E; ++I) {
1789 GlobalVariable *GV = I->first;
1790 assert(!I->second.isOverdefined() &&
1791 "Overdefined values should have been taken out of the map!");
1792 DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
1793 while (!GV->use_empty()) {
1794 StoreInst *SI = cast<StoreInst>(GV->use_back());
1795 SI->eraseFromParent();
1796 }
1797 M.getGlobalList().erase(GV);
1798 ++IPNumGlobalConst;
1799 }
1800
1801 return MadeChanges;
1802}