blob: 3972282a01cf17160459e871eca4cf5a0e6e7b01 [file] [log] [blame]
Misha Brukman82c89b92003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +00009//
Misha Brukman82c89b92003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner138a1242001-06-27 23:38:11 +000011//
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
Chris Lattner2a88bb72002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner138a1242001-06-27 23:38:11 +000017//
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
Chris Lattneref36dfd2004-11-15 05:03:30 +000024#define DEBUG_TYPE "sccp"
Chris Lattner022103b2002-05-07 20:03:00 +000025#include "llvm/Transforms/Scalar.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000026#include "llvm/Transforms/IPO.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000027#include "llvm/Constants.h"
Chris Lattnerdd336d12004-12-11 05:15:59 +000028#include "llvm/DerivedTypes.h"
Chris Lattner9de28282003-04-25 02:50:03 +000029#include "llvm/Instructions.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000030#include "llvm/Pass.h"
Chris Lattner2a632552002-04-18 15:13:15 +000031#include "llvm/Support/InstVisitor.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000032#include "llvm/Transforms/Utils/Local.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000033#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000034#include "llvm/Support/Debug.h"
35#include "llvm/ADT/hash_map"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000038#include <algorithm>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000039#include <iostream>
Chris Lattner138a1242001-06-27 23:38:11 +000040#include <set>
Chris Lattnerd7456022004-01-09 06:02:20 +000041using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000042
Chris Lattneref36dfd2004-11-15 05:03:30 +000043// LatticeVal class - This class represents the different lattice values that an
Chris Lattnerf57b8452002-04-27 06:56:12 +000044// instruction may occupy. It is a simple class with value semantics.
Chris Lattner138a1242001-06-27 23:38:11 +000045//
Chris Lattner0dbfc052002-04-29 21:26:08 +000046namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000047
Chris Lattneref36dfd2004-11-15 05:03:30 +000048class LatticeVal {
Misha Brukmanfd939082005-04-21 23:48:37 +000049 enum {
Chris Lattnere9bb2df2001-12-03 22:26:30 +000050 undefined, // This instruction has no known value
51 constant, // This instruction has a constant value
Chris Lattnere9bb2df2001-12-03 22:26:30 +000052 overdefined // This instruction has an unknown value
53 } LatticeValue; // The current lattice position
54 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner138a1242001-06-27 23:38:11 +000055public:
Chris Lattneref36dfd2004-11-15 05:03:30 +000056 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner138a1242001-06-27 23:38:11 +000057
58 // markOverdefined - Return true if this is a new status to be in...
59 inline bool markOverdefined() {
Chris Lattnere9bb2df2001-12-03 22:26:30 +000060 if (LatticeValue != overdefined) {
61 LatticeValue = overdefined;
Chris Lattner138a1242001-06-27 23:38:11 +000062 return true;
63 }
64 return false;
65 }
66
67 // markConstant - Return true if this is a new status for us...
Chris Lattnere9bb2df2001-12-03 22:26:30 +000068 inline bool markConstant(Constant *V) {
69 if (LatticeValue != constant) {
70 LatticeValue = constant;
Chris Lattner138a1242001-06-27 23:38:11 +000071 ConstantVal = V;
72 return true;
73 } else {
Chris Lattnerb70d82f2001-09-07 16:43:22 +000074 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner138a1242001-06-27 23:38:11 +000075 }
76 return false;
77 }
78
Chris Lattnere9bb2df2001-12-03 22:26:30 +000079 inline bool isUndefined() const { return LatticeValue == undefined; }
80 inline bool isConstant() const { return LatticeValue == constant; }
81 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner138a1242001-06-27 23:38:11 +000082
Chris Lattner1daee8b2004-01-12 03:57:30 +000083 inline Constant *getConstant() const {
84 assert(isConstant() && "Cannot get the constant of a non-constant!");
85 return ConstantVal;
86 }
Chris Lattner138a1242001-06-27 23:38:11 +000087};
88
Chris Lattner0dbfc052002-04-29 21:26:08 +000089} // end anonymous namespace
Chris Lattner138a1242001-06-27 23:38:11 +000090
91
92//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +000093//
Chris Lattner82bec2c2004-11-15 04:44:20 +000094/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
95/// Constant Propagation.
96///
97class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner697954c2002-01-20 22:54:45 +000098 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattneref36dfd2004-11-15 05:03:30 +000099 hash_map<Value*, LatticeVal> ValueState; // The state each value is in...
Chris Lattner138a1242001-06-27 23:38:11 +0000100
Chris Lattnerdd336d12004-12-11 05:15:59 +0000101 /// GlobalValue - If we are tracking any values for the contents of a global
102 /// variable, we keep a mapping from the constant accessor to the element of
103 /// the global, to the currently known value. If the value becomes
104 /// overdefined, it's entry is simply removed from this map.
105 hash_map<GlobalVariable*, LatticeVal> TrackedGlobals;
106
Chris Lattner59acc7d2004-12-10 08:02:06 +0000107 /// TrackedFunctionRetVals - If we are tracking arguments into and the return
108 /// value out of a function, it will have an entry in this map, indicating
109 /// what the known return value for the function is.
110 hash_map<Function*, LatticeVal> TrackedFunctionRetVals;
111
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000112 // The reason for two worklists is that overdefined is the lowest state
113 // on the lattice, and moving things to overdefined as fast as possible
114 // makes SCCP converge much faster.
115 // By having a separate worklist, we accomplish this because everything
116 // possibly overdefined will become overdefined at the soonest possible
117 // point.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000118 std::vector<Value*> OverdefinedInstWorkList;
119 std::vector<Value*> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000120
121
Chris Lattner697954c2002-01-20 22:54:45 +0000122 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000123
Chris Lattner1daee8b2004-01-12 03:57:30 +0000124 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
125 /// overdefined, despite the fact that the PHI node is overdefined.
126 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
127
Chris Lattner16b18fd2003-10-08 16:55:34 +0000128 /// KnownFeasibleEdges - Entries in this set are edges which have already had
129 /// PHI nodes retriggered.
130 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
131 std::set<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000132public:
133
Chris Lattner82bec2c2004-11-15 04:44:20 +0000134 /// MarkBlockExecutable - This method can be used by clients to mark all of
135 /// the blocks that are known to be intrinsically live in the processed unit.
136 void MarkBlockExecutable(BasicBlock *BB) {
137 DEBUG(std::cerr << "Marking Block Executable: " << BB->getName() << "\n");
138 BBExecutable.insert(BB); // Basic block is executable!
139 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner0dbfc052002-04-29 21:26:08 +0000140 }
141
Chris Lattnerdd336d12004-12-11 05:15:59 +0000142 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000143 /// inform the SCCPSolver that it should track loads and stores to the
144 /// specified global variable if it can. This is only legal to call if
145 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000146 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
147 const Type *ElTy = GV->getType()->getElementType();
148 if (ElTy->isFirstClassType()) {
149 LatticeVal &IV = TrackedGlobals[GV];
150 if (!isa<UndefValue>(GV->getInitializer()))
151 IV.markConstant(GV->getInitializer());
152 }
153 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000154
155 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
156 /// and out of the specified function (which cannot have its address taken),
157 /// this method must be called.
158 void AddTrackedFunction(Function *F) {
159 assert(F->hasInternalLinkage() && "Can only track internal functions!");
160 // Add an entry, F -> undef.
161 TrackedFunctionRetVals[F];
162 }
163
Chris Lattner82bec2c2004-11-15 04:44:20 +0000164 /// Solve - Solve for constants and executable blocks.
165 ///
166 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000167
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000168 /// ResolveBranchesIn - While solving the dataflow for a function, we assume
169 /// that branches on undef values cannot reach any of their successors.
170 /// However, this is not a safe assumption. After we solve dataflow, this
171 /// method should be use to handle this. If this returns true, the solver
172 /// should be rerun.
173 bool ResolveBranchesIn(Function &F);
174
Chris Lattner82bec2c2004-11-15 04:44:20 +0000175 /// getExecutableBlocks - Once we have solved for constants, return the set of
176 /// blocks that is known to be executable.
177 std::set<BasicBlock*> &getExecutableBlocks() {
178 return BBExecutable;
179 }
180
181 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattneref36dfd2004-11-15 05:03:30 +0000182 /// LLVM values to LatticeVals.
183 hash_map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000184 return ValueState;
185 }
186
Chris Lattner0417feb2004-12-11 02:53:57 +0000187 /// getTrackedFunctionRetVals - Get the inferred return value map.
188 ///
189 const hash_map<Function*, LatticeVal> &getTrackedFunctionRetVals() {
190 return TrackedFunctionRetVals;
191 }
192
Chris Lattnerdd336d12004-12-11 05:15:59 +0000193 /// getTrackedGlobals - Get and return the set of inferred initializers for
194 /// global variables.
195 const hash_map<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
196 return TrackedGlobals;
197 }
198
Chris Lattner0417feb2004-12-11 02:53:57 +0000199
Chris Lattner138a1242001-06-27 23:38:11 +0000200private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000201 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000202 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000203 // the users of the instruction are updated later.
204 //
Chris Lattner59acc7d2004-12-10 08:02:06 +0000205 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000206 if (IV.markConstant(C)) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000207 DEBUG(std::cerr << "markConstant: " << *C << ": " << *V);
208 InstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000209 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000210 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000211 inline void markConstant(Value *V, Constant *C) {
212 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000213 }
214
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000215 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000216 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000217 // work list so that the users of the instruction are updated later.
Misha Brukmanfd939082005-04-21 23:48:37 +0000218
Chris Lattner59acc7d2004-12-10 08:02:06 +0000219 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000220 if (IV.markOverdefined()) {
Chris Lattnerdade2d22004-12-11 06:05:53 +0000221 DEBUG(std::cerr << "markOverdefined: ";
222 if (Function *F = dyn_cast<Function>(V))
223 std::cerr << "Function '" << F->getName() << "'\n";
224 else
225 std::cerr << *V);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000226 // Only instructions go on the work list
Chris Lattner59acc7d2004-12-10 08:02:06 +0000227 OverdefinedInstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000228 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000229 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000230 inline void markOverdefined(Value *V) {
231 markOverdefined(ValueState[V], V);
232 }
233
234 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
235 if (IV.isOverdefined() || MergeWithV.isUndefined())
236 return; // Noop.
237 if (MergeWithV.isOverdefined())
238 markOverdefined(IV, V);
239 else if (IV.isUndefined())
240 markConstant(IV, V, MergeWithV.getConstant());
241 else if (IV.getConstant() != MergeWithV.getConstant())
242 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000243 }
244
Chris Lattneref36dfd2004-11-15 05:03:30 +0000245 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman5560c9d2003-08-18 14:43:39 +0000246 // This function is necessary because not all values should start out in the
Chris Lattner73e21422002-04-09 19:48:49 +0000247 // underdefined state... Argument's should be overdefined, and
Chris Lattner79df7c02002-03-26 18:01:55 +0000248 // constants should be marked as constants. If a value is not known to be an
Chris Lattner138a1242001-06-27 23:38:11 +0000249 // Instruction object, then use this accessor to get its value from the map.
250 //
Chris Lattneref36dfd2004-11-15 05:03:30 +0000251 inline LatticeVal &getValueState(Value *V) {
252 hash_map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000253 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000254
Chris Lattner7e529e42004-11-15 05:45:33 +0000255 if (Constant *CPV = dyn_cast<Constant>(V)) {
256 if (isa<UndefValue>(V)) {
257 // Nothing to do, remain undefined.
258 } else {
259 ValueState[CPV].markConstant(CPV); // Constants are constant
260 }
Chris Lattner2a88bb72002-08-30 23:39:00 +0000261 }
Chris Lattner138a1242001-06-27 23:38:11 +0000262 // All others are underdefined by default...
263 return ValueState[V];
264 }
265
Misha Brukmanfd939082005-04-21 23:48:37 +0000266 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner138a1242001-06-27 23:38:11 +0000267 // work list if it is not already executable...
Misha Brukmanfd939082005-04-21 23:48:37 +0000268 //
Chris Lattner16b18fd2003-10-08 16:55:34 +0000269 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
270 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
271 return; // This edge is already known to be executable!
272
273 if (BBExecutable.count(Dest)) {
274 DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
275 << " -> " << Dest->getName() << "\n");
276
277 // The destination is already executable, but we just made an edge
Chris Lattner929c6fb2003-10-08 16:56:11 +0000278 // feasible that wasn't before. Revisit the PHI nodes in the block
279 // because they have potentially new operands.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000280 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
281 visitPHINode(*cast<PHINode>(I));
Chris Lattner9de28282003-04-25 02:50:03 +0000282
283 } else {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000284 MarkBlockExecutable(Dest);
Chris Lattner9de28282003-04-25 02:50:03 +0000285 }
Chris Lattner138a1242001-06-27 23:38:11 +0000286 }
287
Chris Lattner82bec2c2004-11-15 04:44:20 +0000288 // getFeasibleSuccessors - Return a vector of booleans to indicate which
289 // successors are reachable from a given terminator instruction.
290 //
291 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
292
293 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
294 // block to the 'To' basic block is currently feasible...
295 //
296 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
297
298 // OperandChangedState - This method is invoked on all of the users of an
299 // instruction that was just changed state somehow.... Based on this
300 // information, we need to update the specified user of this instruction.
301 //
302 void OperandChangedState(User *U) {
303 // Only instructions use other variable values!
304 Instruction &I = cast<Instruction>(*U);
305 if (BBExecutable.count(I.getParent())) // Inst is executable?
306 visit(I);
307 }
308
309private:
310 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000311
Misha Brukmanfd939082005-04-21 23:48:37 +0000312 // visit implementations - Something changed in this instruction... Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000313 // operand made a transition, or the instruction is newly executable. Change
314 // the value type of I to reflect these changes if appropriate.
315 //
Chris Lattner7e708292002-06-25 16:13:24 +0000316 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000317
318 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000319 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000320 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000321
Chris Lattnerb8047602002-08-14 17:53:45 +0000322 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000323 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000324 void visitBinaryOperator(Instruction &I);
325 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Robert Bocchino56107e22006-01-10 19:05:05 +0000326 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000327 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000328
329 // Instructions that cannot be folded away...
Chris Lattnerdd336d12004-12-11 05:15:59 +0000330 void visitStoreInst (Instruction &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000331 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000332 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner59acc7d2004-12-10 08:02:06 +0000333 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
334 void visitInvokeInst (InvokeInst &II) {
335 visitCallSite(CallSite::get(&II));
336 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000337 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000338 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000339 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000340 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner7e708292002-06-25 16:13:24 +0000341 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000342 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
343 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner7e708292002-06-25 16:13:24 +0000344 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner2a632552002-04-18 15:13:15 +0000345
Chris Lattner7e708292002-06-25 16:13:24 +0000346 void visitInstruction(Instruction &I) {
Chris Lattner2a632552002-04-18 15:13:15 +0000347 // If a new instruction is added to LLVM that we don't handle...
Chris Lattner9de28282003-04-25 02:50:03 +0000348 std::cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000349 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000350 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000351};
Chris Lattnerf6293092002-07-23 18:06:35 +0000352
Chris Lattnerb9a66342002-05-02 21:44:00 +0000353// getFeasibleSuccessors - Return a vector of booleans to indicate which
354// successors are reachable from a given terminator instruction.
355//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000356void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
357 std::vector<bool> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000358 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000359 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000360 if (BI->isUnconditional()) {
361 Succs[0] = true;
362 } else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000363 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000364 if (BCValue.isOverdefined() ||
365 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
366 // Overdefined condition variables, and branches on unfoldable constant
367 // conditions, mean the branch could go either way.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000368 Succs[0] = Succs[1] = true;
369 } else if (BCValue.isConstant()) {
370 // Constant condition variables mean the branch can only go a single way
371 Succs[BCValue.getConstant() == ConstantBool::False] = true;
372 }
373 }
Chris Lattner7e708292002-06-25 16:13:24 +0000374 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000375 // Invoke instructions successors are always executable.
376 Succs[0] = Succs[1] = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000377 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000378 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000379 if (SCValue.isOverdefined() || // Overdefined condition?
380 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000381 // All destinations are executable!
Chris Lattner7e708292002-06-25 16:13:24 +0000382 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerb9a66342002-05-02 21:44:00 +0000383 } else if (SCValue.isConstant()) {
384 Constant *CPV = SCValue.getConstant();
385 // Make sure to skip the "default value" which isn't a value
386 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
387 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
388 Succs[i] = true;
389 return;
390 }
391 }
392
393 // Constant value not equal to any of the branches... must execute
394 // default branch then...
395 Succs[0] = true;
396 }
397 } else {
Chris Lattner9de28282003-04-25 02:50:03 +0000398 std::cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner7e708292002-06-25 16:13:24 +0000399 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerb9a66342002-05-02 21:44:00 +0000400 }
401}
402
403
Chris Lattner59f0ce22002-05-02 21:18:01 +0000404// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
405// block to the 'To' basic block is currently feasible...
406//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000407bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000408 assert(BBExecutable.count(To) && "Dest should always be alive!");
409
410 // Make sure the source basic block is executable!!
411 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000412
Chris Lattnerb9a66342002-05-02 21:44:00 +0000413 // Check to make sure this edge itself is actually feasible now...
Chris Lattner7d275f42003-10-08 15:47:41 +0000414 TerminatorInst *TI = From->getTerminator();
415 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
416 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000417 return true;
Chris Lattner7d275f42003-10-08 15:47:41 +0000418 else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000419 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000420 if (BCValue.isOverdefined()) {
421 // Overdefined condition variables mean the branch could go either way.
422 return true;
423 } else if (BCValue.isConstant()) {
Chris Lattner84831642004-01-12 17:40:36 +0000424 // Not branching on an evaluatable constant?
425 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
426
Chris Lattner7d275f42003-10-08 15:47:41 +0000427 // Constant condition variables mean the branch can only go a single way
Misha Brukmanfd939082005-04-21 23:48:37 +0000428 return BI->getSuccessor(BCValue.getConstant() ==
Chris Lattner7d275f42003-10-08 15:47:41 +0000429 ConstantBool::False) == To;
430 }
431 return false;
432 }
433 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
434 // Invoke instructions successors are always executable.
435 return true;
436 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000437 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000438 if (SCValue.isOverdefined()) { // Overdefined condition?
439 // All destinations are executable!
440 return true;
441 } else if (SCValue.isConstant()) {
442 Constant *CPV = SCValue.getConstant();
Chris Lattner84831642004-01-12 17:40:36 +0000443 if (!isa<ConstantInt>(CPV))
444 return true; // not a foldable constant?
445
Chris Lattner7d275f42003-10-08 15:47:41 +0000446 // Make sure to skip the "default value" which isn't a value
447 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
448 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
449 return SI->getSuccessor(i) == To;
450
451 // Constant value not equal to any of the branches... must execute
452 // default branch then...
453 return SI->getDefaultDest() == To;
454 }
455 return false;
456 } else {
457 std::cerr << "Unknown terminator instruction: " << *TI;
458 abort();
459 }
Chris Lattner59f0ce22002-05-02 21:18:01 +0000460}
Chris Lattner138a1242001-06-27 23:38:11 +0000461
Chris Lattner2a632552002-04-18 15:13:15 +0000462// visit Implementations - Something changed in this instruction... Either an
Chris Lattner138a1242001-06-27 23:38:11 +0000463// operand made a transition, or the instruction is newly executable. Change
464// the value type of I to reflect these changes if appropriate. This method
465// makes sure to do the following actions:
466//
467// 1. If a phi node merges two constants in, and has conflicting value coming
468// from different branches, or if the PHI node merges in an overdefined
469// value, then the PHI node becomes overdefined.
470// 2. If a phi node merges only constants in, and they all agree on value, the
471// PHI node becomes a constant value equal to that.
472// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
473// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
474// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
475// 6. If a conditional branch has a value that is constant, make the selected
476// destination executable
477// 7. If a conditional branch has a value that is overdefined, make all
478// successors executable.
479//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000480void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000481 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000482 if (PNIV.isOverdefined()) {
483 // There may be instructions using this PHI node that are not overdefined
484 // themselves. If so, make sure that they know that the PHI node operand
485 // changed.
486 std::multimap<PHINode*, Instruction*>::iterator I, E;
487 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
488 if (I != E) {
489 std::vector<Instruction*> Users;
490 Users.reserve(std::distance(I, E));
491 for (; I != E; ++I) Users.push_back(I->second);
492 while (!Users.empty()) {
493 visit(Users.back());
494 Users.pop_back();
495 }
496 }
497 return; // Quick exit
498 }
Chris Lattner138a1242001-06-27 23:38:11 +0000499
Chris Lattnera2f652d2004-03-16 19:49:59 +0000500 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
501 // and slow us down a lot. Just mark them overdefined.
502 if (PN.getNumIncomingValues() > 64) {
503 markOverdefined(PNIV, &PN);
504 return;
505 }
506
Chris Lattner2a632552002-04-18 15:13:15 +0000507 // Look at all of the executable operands of the PHI node. If any of them
508 // are overdefined, the PHI becomes overdefined as well. If they are all
509 // constant, and they agree with each other, the PHI becomes the identical
510 // constant. If they are constant and don't agree, the PHI is overdefined.
511 // If there are no executable operands, the PHI remains undefined.
512 //
Chris Lattner9de28282003-04-25 02:50:03 +0000513 Constant *OperandVal = 0;
514 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000515 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000516 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000517
Chris Lattner7e708292002-06-25 16:13:24 +0000518 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner38b5ae42003-06-24 20:29:52 +0000519 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner3d405b02003-10-08 16:21:03 +0000520 markOverdefined(PNIV, &PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000521 return;
522 }
523
Chris Lattner9de28282003-04-25 02:50:03 +0000524 if (OperandVal == 0) { // Grab the first value...
525 OperandVal = IV.getConstant();
Chris Lattner2a632552002-04-18 15:13:15 +0000526 } else { // Another value is being merged in!
527 // There is already a reachable operand. If we conflict with it,
528 // then the PHI node becomes overdefined. If we agree with it, we
529 // can continue on.
Misha Brukmanfd939082005-04-21 23:48:37 +0000530
Chris Lattner2a632552002-04-18 15:13:15 +0000531 // Check to see if there are two different constants merging...
Chris Lattner9de28282003-04-25 02:50:03 +0000532 if (IV.getConstant() != OperandVal) {
Chris Lattner2a632552002-04-18 15:13:15 +0000533 // Yes there is. This means the PHI node is not constant.
534 // You must be overdefined poor PHI.
535 //
Chris Lattner3d405b02003-10-08 16:21:03 +0000536 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner2a632552002-04-18 15:13:15 +0000537 return; // I'm done analyzing you
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000538 }
Chris Lattner138a1242001-06-27 23:38:11 +0000539 }
540 }
Chris Lattner138a1242001-06-27 23:38:11 +0000541 }
542
Chris Lattner2a632552002-04-18 15:13:15 +0000543 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000544 // arguments that agree with each other(and OperandVal is the constant) or
545 // OperandVal is null because there are no defined incoming arguments. If
546 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000547 //
Chris Lattner9de28282003-04-25 02:50:03 +0000548 if (OperandVal)
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000549 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000550}
551
Chris Lattner59acc7d2004-12-10 08:02:06 +0000552void SCCPSolver::visitReturnInst(ReturnInst &I) {
553 if (I.getNumOperands() == 0) return; // Ret void
554
555 // If we are tracking the return value of this function, merge it in.
556 Function *F = I.getParent()->getParent();
557 if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
558 hash_map<Function*, LatticeVal>::iterator TFRVI =
559 TrackedFunctionRetVals.find(F);
560 if (TFRVI != TrackedFunctionRetVals.end() &&
561 !TFRVI->second.isOverdefined()) {
562 LatticeVal &IV = getValueState(I.getOperand(0));
563 mergeInValue(TFRVI->second, F, IV);
564 }
565 }
566}
567
568
Chris Lattner82bec2c2004-11-15 04:44:20 +0000569void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner9de28282003-04-25 02:50:03 +0000570 std::vector<bool> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000571 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000572
Chris Lattner16b18fd2003-10-08 16:55:34 +0000573 BasicBlock *BB = TI.getParent();
574
Chris Lattnerb9a66342002-05-02 21:44:00 +0000575 // Mark all feasible successors executable...
576 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000577 if (SuccFeasible[i])
578 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000579}
580
Chris Lattner82bec2c2004-11-15 04:44:20 +0000581void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000582 Value *V = I.getOperand(0);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000583 LatticeVal &VState = getValueState(V);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000584 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000585 markOverdefined(&I);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000586 else if (VState.isConstant()) // Propagate constant value
587 markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000588}
589
Chris Lattner82bec2c2004-11-15 04:44:20 +0000590void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000591 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattner6e323722004-03-12 05:52:44 +0000592 if (CondValue.isOverdefined())
593 markOverdefined(&I);
594 else if (CondValue.isConstant()) {
595 if (CondValue.getConstant() == ConstantBool::True) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000596 LatticeVal &Val = getValueState(I.getTrueValue());
Chris Lattner6e323722004-03-12 05:52:44 +0000597 if (Val.isOverdefined())
598 markOverdefined(&I);
599 else if (Val.isConstant())
600 markConstant(&I, Val.getConstant());
601 } else if (CondValue.getConstant() == ConstantBool::False) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000602 LatticeVal &Val = getValueState(I.getFalseValue());
Chris Lattner6e323722004-03-12 05:52:44 +0000603 if (Val.isOverdefined())
604 markOverdefined(&I);
605 else if (Val.isConstant())
606 markConstant(&I, Val.getConstant());
607 } else
608 markOverdefined(&I);
609 }
610}
611
Chris Lattner2a632552002-04-18 15:13:15 +0000612// Handle BinaryOperators and Shift Instructions...
Chris Lattner82bec2c2004-11-15 04:44:20 +0000613void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000614 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000615 if (IV.isOverdefined()) return;
616
Chris Lattneref36dfd2004-11-15 05:03:30 +0000617 LatticeVal &V1State = getValueState(I.getOperand(0));
618 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000619
Chris Lattner2a632552002-04-18 15:13:15 +0000620 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnera177c672004-12-11 23:15:19 +0000621 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
622 // operand is overdefined.
623 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
624 LatticeVal *NonOverdefVal = 0;
625 if (!V1State.isOverdefined()) {
626 NonOverdefVal = &V1State;
627 } else if (!V2State.isOverdefined()) {
628 NonOverdefVal = &V2State;
629 }
630
631 if (NonOverdefVal) {
632 if (NonOverdefVal->isUndefined()) {
633 // Could annihilate value.
634 if (I.getOpcode() == Instruction::And)
635 markConstant(IV, &I, Constant::getNullValue(I.getType()));
636 else
637 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
638 return;
639 } else {
640 if (I.getOpcode() == Instruction::And) {
641 if (NonOverdefVal->getConstant()->isNullValue()) {
642 markConstant(IV, &I, NonOverdefVal->getConstant());
643 return; // X or 0 = -1
644 }
645 } else {
646 if (ConstantIntegral *CI =
647 dyn_cast<ConstantIntegral>(NonOverdefVal->getConstant()))
648 if (CI->isAllOnesValue()) {
649 markConstant(IV, &I, NonOverdefVal->getConstant());
650 return; // X or -1 = -1
651 }
652 }
653 }
654 }
655 }
656
657
Chris Lattner1daee8b2004-01-12 03:57:30 +0000658 // If both operands are PHI nodes, it is possible that this instruction has
659 // a constant value, despite the fact that the PHI node doesn't. Check for
660 // this condition now.
661 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
662 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
663 if (PN1->getParent() == PN2->getParent()) {
664 // Since the two PHI nodes are in the same basic block, they must have
665 // entries for the same predecessors. Walk the predecessor list, and
666 // if all of the incoming values are constants, and the result of
667 // evaluating this expression with all incoming value pairs is the
668 // same, then this expression is a constant even though the PHI node
669 // is not a constant!
Chris Lattneref36dfd2004-11-15 05:03:30 +0000670 LatticeVal Result;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000671 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000672 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000673 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000674 LatticeVal &In2 =
675 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000676
677 if (In1.isOverdefined() || In2.isOverdefined()) {
678 Result.markOverdefined();
679 break; // Cannot fold this operation over the PHI nodes!
680 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000681 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
682 In2.getConstant());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000683 if (Result.isUndefined())
Chris Lattnerb16689b2004-01-12 19:08:43 +0000684 Result.markConstant(V);
685 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000686 Result.markOverdefined();
687 break;
688 }
689 }
690 }
691
692 // If we found a constant value here, then we know the instruction is
693 // constant despite the fact that the PHI nodes are overdefined.
694 if (Result.isConstant()) {
695 markConstant(IV, &I, Result.getConstant());
696 // Remember that this instruction is virtually using the PHI node
697 // operands.
698 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
699 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
700 return;
701 } else if (Result.isUndefined()) {
702 return;
703 }
704
705 // Okay, this really is overdefined now. Since we might have
706 // speculatively thought that this was not overdefined before, and
707 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
708 // make sure to clean out any entries that we put there, for
709 // efficiency.
710 std::multimap<PHINode*, Instruction*>::iterator It, E;
711 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
712 while (It != E) {
713 if (It->second == &I) {
714 UsersOfOverdefinedPHIs.erase(It++);
715 } else
716 ++It;
717 }
718 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
719 while (It != E) {
720 if (It->second == &I) {
721 UsersOfOverdefinedPHIs.erase(It++);
722 } else
723 ++It;
724 }
725 }
726
727 markOverdefined(IV, &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000728 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000729 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
730 V2State.getConstant()));
Chris Lattner2a632552002-04-18 15:13:15 +0000731 }
732}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000733
Robert Bocchino56107e22006-01-10 19:05:05 +0000734void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
735 LatticeVal &ValState = getValueState(I.getOperand(0));
736 LatticeVal &IdxState = getValueState(I.getOperand(1));
737
738 if (ValState.isOverdefined() || IdxState.isOverdefined())
739 markOverdefined(&I);
740 else if(ValState.isConstant() && IdxState.isConstant())
741 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
742 IdxState.getConstant()));
743}
744
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000745void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
746 LatticeVal &ValState = getValueState(I.getOperand(0));
747 LatticeVal &EltState = getValueState(I.getOperand(1));
748 LatticeVal &IdxState = getValueState(I.getOperand(2));
749
750 if (ValState.isOverdefined() || EltState.isOverdefined() ||
751 IdxState.isOverdefined())
752 markOverdefined(&I);
753 else if(ValState.isConstant() && EltState.isConstant() &&
754 IdxState.isConstant())
755 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
756 EltState.getConstant(),
757 IdxState.getConstant()));
758 else if (ValState.isUndefined() && EltState.isConstant() &&
759 IdxState.isConstant())
760 markConstant(&I, ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
761 EltState.getConstant(),
762 IdxState.getConstant()));
763}
764
Chris Lattner2a88bb72002-08-30 23:39:00 +0000765// Handle getelementptr instructions... if all operands are constants then we
766// can turn this into a getelementptr ConstantExpr.
767//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000768void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000769 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000770 if (IV.isOverdefined()) return;
771
Chris Lattner2a88bb72002-08-30 23:39:00 +0000772 std::vector<Constant*> Operands;
773 Operands.reserve(I.getNumOperands());
774
775 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000776 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +0000777 if (State.isUndefined())
778 return; // Operands are not resolved yet...
779 else if (State.isOverdefined()) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000780 markOverdefined(IV, &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000781 return;
782 }
783 assert(State.isConstant() && "Unknown state!");
784 Operands.push_back(State.getConstant());
785 }
786
787 Constant *Ptr = Operands[0];
788 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
789
Misha Brukmanfd939082005-04-21 23:48:37 +0000790 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattner2a88bb72002-08-30 23:39:00 +0000791}
Brian Gaeked0fde302003-11-11 22:41:34 +0000792
Chris Lattnerdd336d12004-12-11 05:15:59 +0000793void SCCPSolver::visitStoreInst(Instruction &SI) {
794 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
795 return;
796 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
797 hash_map<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
798 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
799
800 // Get the value we are storing into the global.
801 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
802
803 mergeInValue(I->second, GV, PtrVal);
804 if (I->second.isOverdefined())
805 TrackedGlobals.erase(I); // No need to keep tracking this!
806}
807
808
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000809// Handle load instructions. If the operand is a constant pointer to a constant
810// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +0000811void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000812 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000813 if (IV.isOverdefined()) return;
814
Chris Lattneref36dfd2004-11-15 05:03:30 +0000815 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000816 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
817 if (PtrVal.isConstant() && !I.isVolatile()) {
818 Value *Ptr = PtrVal.getConstant();
Chris Lattnerc76d8032004-03-07 22:16:24 +0000819 if (isa<ConstantPointerNull>(Ptr)) {
820 // load null -> null
821 markConstant(IV, &I, Constant::getNullValue(I.getType()));
822 return;
823 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000824
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000825 // Transform load (constant global) into the value loaded.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000826 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
827 if (GV->isConstant()) {
828 if (!GV->isExternal()) {
829 markConstant(IV, &I, GV->getInitializer());
830 return;
831 }
832 } else if (!TrackedGlobals.empty()) {
833 // If we are tracking this global, merge in the known value for it.
834 hash_map<GlobalVariable*, LatticeVal>::iterator It =
835 TrackedGlobals.find(GV);
836 if (It != TrackedGlobals.end()) {
837 mergeInValue(IV, &I, It->second);
838 return;
839 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000840 }
Chris Lattnerdd336d12004-12-11 05:15:59 +0000841 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000842
843 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
844 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
845 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen9d809302005-04-23 21:38:35 +0000846 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
847 if (GV->isConstant() && !GV->isExternal())
848 if (Constant *V =
Chris Lattnerebe61202005-09-26 05:28:52 +0000849 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen9d809302005-04-23 21:38:35 +0000850 markConstant(IV, &I, V);
851 return;
852 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000853 }
854
855 // Otherwise we cannot say for certain what value this load will produce.
856 // Bail out.
857 markOverdefined(IV, &I);
858}
Chris Lattner58b7b082004-04-13 19:43:54 +0000859
Chris Lattner59acc7d2004-12-10 08:02:06 +0000860void SCCPSolver::visitCallSite(CallSite CS) {
861 Function *F = CS.getCalledFunction();
862
863 // If we are tracking this function, we must make sure to bind arguments as
864 // appropriate.
865 hash_map<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
866 if (F && F->hasInternalLinkage())
867 TFRVI = TrackedFunctionRetVals.find(F);
Misha Brukmanfd939082005-04-21 23:48:37 +0000868
Chris Lattner59acc7d2004-12-10 08:02:06 +0000869 if (TFRVI != TrackedFunctionRetVals.end()) {
870 // If this is the first call to the function hit, mark its entry block
871 // executable.
872 if (!BBExecutable.count(F->begin()))
873 MarkBlockExecutable(F->begin());
874
875 CallSite::arg_iterator CAI = CS.arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000876 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
Chris Lattner59acc7d2004-12-10 08:02:06 +0000877 AI != E; ++AI, ++CAI) {
878 LatticeVal &IV = ValueState[AI];
879 if (!IV.isOverdefined())
880 mergeInValue(IV, AI, getValueState(*CAI));
881 }
882 }
883 Instruction *I = CS.getInstruction();
884 if (I->getType() == Type::VoidTy) return;
885
886 LatticeVal &IV = ValueState[I];
Chris Lattner58b7b082004-04-13 19:43:54 +0000887 if (IV.isOverdefined()) return;
888
Chris Lattner59acc7d2004-12-10 08:02:06 +0000889 // Propagate the return value of the function to the value of the instruction.
890 if (TFRVI != TrackedFunctionRetVals.end()) {
891 mergeInValue(IV, I, TFRVI->second);
892 return;
893 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000894
Chris Lattner59acc7d2004-12-10 08:02:06 +0000895 if (F == 0 || !F->isExternal() || !canConstantFoldCallTo(F)) {
896 markOverdefined(IV, I);
Chris Lattner58b7b082004-04-13 19:43:54 +0000897 return;
898 }
899
900 std::vector<Constant*> Operands;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000901 Operands.reserve(I->getNumOperands()-1);
Chris Lattner58b7b082004-04-13 19:43:54 +0000902
Chris Lattner59acc7d2004-12-10 08:02:06 +0000903 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
904 AI != E; ++AI) {
905 LatticeVal &State = getValueState(*AI);
Chris Lattner58b7b082004-04-13 19:43:54 +0000906 if (State.isUndefined())
907 return; // Operands are not resolved yet...
908 else if (State.isOverdefined()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000909 markOverdefined(IV, I);
Chris Lattner58b7b082004-04-13 19:43:54 +0000910 return;
911 }
912 assert(State.isConstant() && "Unknown state!");
913 Operands.push_back(State.getConstant());
914 }
915
916 if (Constant *C = ConstantFoldCall(F, Operands))
Chris Lattner59acc7d2004-12-10 08:02:06 +0000917 markConstant(IV, I, C);
Chris Lattner58b7b082004-04-13 19:43:54 +0000918 else
Chris Lattner59acc7d2004-12-10 08:02:06 +0000919 markOverdefined(IV, I);
Chris Lattner58b7b082004-04-13 19:43:54 +0000920}
Chris Lattner82bec2c2004-11-15 04:44:20 +0000921
922
923void SCCPSolver::Solve() {
924 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +0000925 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +0000926 !OverdefinedInstWorkList.empty()) {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000927 // Process the instruction work list...
928 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000929 Value *I = OverdefinedInstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +0000930 OverdefinedInstWorkList.pop_back();
931
Chris Lattner59acc7d2004-12-10 08:02:06 +0000932 DEBUG(std::cerr << "\nPopped off OI-WL: " << *I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000933
Chris Lattner82bec2c2004-11-15 04:44:20 +0000934 // "I" got into the work list because it either made the transition from
935 // bottom to constant
936 //
937 // Anything on this worklist that is overdefined need not be visited
938 // since all of its users will have already been marked as overdefined
939 // Update all of the users of this instruction's value...
940 //
941 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
942 UI != E; ++UI)
943 OperandChangedState(*UI);
944 }
945 // Process the instruction work list...
946 while (!InstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000947 Value *I = InstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +0000948 InstWorkList.pop_back();
949
950 DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000951
Chris Lattner82bec2c2004-11-15 04:44:20 +0000952 // "I" got into the work list because it either made the transition from
953 // bottom to constant
954 //
955 // Anything on this worklist that is overdefined need not be visited
956 // since all of its users will have already been marked as overdefined.
957 // Update all of the users of this instruction's value...
958 //
959 if (!getValueState(I).isOverdefined())
960 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
961 UI != E; ++UI)
962 OperandChangedState(*UI);
963 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000964
Chris Lattner82bec2c2004-11-15 04:44:20 +0000965 // Process the basic block work list...
966 while (!BBWorkList.empty()) {
967 BasicBlock *BB = BBWorkList.back();
968 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +0000969
Chris Lattner82bec2c2004-11-15 04:44:20 +0000970 DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
Misha Brukmanfd939082005-04-21 23:48:37 +0000971
Chris Lattner82bec2c2004-11-15 04:44:20 +0000972 // Notify all instructions in this basic block that they are newly
973 // executable.
974 visit(BB);
975 }
976 }
977}
978
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000979/// ResolveBranchesIn - While solving the dataflow for a function, we assume
980/// that branches on undef values cannot reach any of their successors.
981/// However, this is not a safe assumption. After we solve dataflow, this
982/// method should be use to handle this. If this returns true, the solver
983/// should be rerun.
984bool SCCPSolver::ResolveBranchesIn(Function &F) {
985 bool BranchesResolved = false;
Chris Lattnerdade2d22004-12-11 06:05:53 +0000986 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
987 if (BBExecutable.count(BB)) {
988 TerminatorInst *TI = BB->getTerminator();
989 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
990 if (BI->isConditional()) {
991 LatticeVal &BCValue = getValueState(BI->getCondition());
992 if (BCValue.isUndefined()) {
993 BI->setCondition(ConstantBool::True);
994 BranchesResolved = true;
995 visit(BI);
996 }
997 }
998 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
999 LatticeVal &SCValue = getValueState(SI->getCondition());
1000 if (SCValue.isUndefined()) {
1001 const Type *CondTy = SI->getCondition()->getType();
1002 SI->setCondition(Constant::getNullValue(CondTy));
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001003 BranchesResolved = true;
Chris Lattnerdade2d22004-12-11 06:05:53 +00001004 visit(SI);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001005 }
1006 }
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001007 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001008
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001009 return BranchesResolved;
1010}
1011
Chris Lattner82bec2c2004-11-15 04:44:20 +00001012
1013namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001014 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
1015 Statistic<> NumDeadBlocks ("sccp", "Number of basic blocks unreachable");
1016
Chris Lattner14051812004-11-15 07:15:04 +00001017 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001018 //
Chris Lattner14051812004-11-15 07:15:04 +00001019 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1020 /// Sparse Conditional COnstant Propagator.
1021 ///
1022 struct SCCP : public FunctionPass {
1023 // runOnFunction - Run the Sparse Conditional Constant Propagation
1024 // algorithm, and return true if the function was modified.
1025 //
1026 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001027
Chris Lattner14051812004-11-15 07:15:04 +00001028 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1029 AU.setPreservesCFG();
1030 }
1031 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001032
1033 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
1034} // end anonymous namespace
1035
1036
1037// createSCCPPass - This is the public interface to this file...
1038FunctionPass *llvm::createSCCPPass() {
1039 return new SCCP();
1040}
1041
1042
Chris Lattner82bec2c2004-11-15 04:44:20 +00001043// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1044// and return true if the function was modified.
1045//
1046bool SCCP::runOnFunction(Function &F) {
Chris Lattner7e529e42004-11-15 05:45:33 +00001047 DEBUG(std::cerr << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001048 SCCPSolver Solver;
1049
1050 // Mark the first block of the function as being executable.
1051 Solver.MarkBlockExecutable(F.begin());
1052
Chris Lattner7e529e42004-11-15 05:45:33 +00001053 // Mark all arguments to the function as being overdefined.
1054 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattnere4d5c442005-03-15 04:54:21 +00001055 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; ++AI)
Chris Lattner7e529e42004-11-15 05:45:33 +00001056 Values[AI].markOverdefined();
1057
Chris Lattner82bec2c2004-11-15 04:44:20 +00001058 // Solve for constants.
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001059 bool ResolvedBranches = true;
1060 while (ResolvedBranches) {
1061 Solver.Solve();
Chris Lattnerdade2d22004-12-11 06:05:53 +00001062 DEBUG(std::cerr << "RESOLVING UNDEF BRANCHES\n");
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001063 ResolvedBranches = Solver.ResolveBranchesIn(F);
1064 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001065
Chris Lattner7e529e42004-11-15 05:45:33 +00001066 bool MadeChanges = false;
1067
1068 // If we decided that there are basic blocks that are dead in this function,
1069 // delete their contents now. Note that we cannot actually delete the blocks,
1070 // as we cannot modify the CFG of the function.
1071 //
1072 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1073 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1074 if (!ExecutableBBs.count(BB)) {
1075 DEBUG(std::cerr << " BasicBlock Dead:" << *BB);
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001076 ++NumDeadBlocks;
1077
Chris Lattner7e529e42004-11-15 05:45:33 +00001078 // Delete the instructions backwards, as it has a reduced likelihood of
1079 // having to update as many def-use and use-def chains.
1080 std::vector<Instruction*> Insts;
1081 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1082 I != E; ++I)
1083 Insts.push_back(I);
1084 while (!Insts.empty()) {
1085 Instruction *I = Insts.back();
1086 Insts.pop_back();
1087 if (!I->use_empty())
1088 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1089 BB->getInstList().erase(I);
1090 MadeChanges = true;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001091 ++NumInstRemoved;
Chris Lattner7e529e42004-11-15 05:45:33 +00001092 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001093 } else {
1094 // Iterate over all of the instructions in a function, replacing them with
1095 // constants if we have found them to be of constant values.
1096 //
1097 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1098 Instruction *Inst = BI++;
1099 if (Inst->getType() != Type::VoidTy) {
1100 LatticeVal &IV = Values[Inst];
1101 if (IV.isConstant() || IV.isUndefined() &&
1102 !isa<TerminatorInst>(Inst)) {
1103 Constant *Const = IV.isConstant()
1104 ? IV.getConstant() : UndefValue::get(Inst->getType());
Chris Lattner82bec2c2004-11-15 04:44:20 +00001105 DEBUG(std::cerr << " Constant: " << *Const << " = " << *Inst);
Misha Brukmanfd939082005-04-21 23:48:37 +00001106
Chris Lattner59acc7d2004-12-10 08:02:06 +00001107 // Replaces all of the uses of a variable with uses of the constant.
1108 Inst->replaceAllUsesWith(Const);
Misha Brukmanfd939082005-04-21 23:48:37 +00001109
Chris Lattner59acc7d2004-12-10 08:02:06 +00001110 // Delete the instruction.
1111 BB->getInstList().erase(Inst);
Misha Brukmanfd939082005-04-21 23:48:37 +00001112
Chris Lattner59acc7d2004-12-10 08:02:06 +00001113 // Hey, we just changed something!
1114 MadeChanges = true;
1115 ++NumInstRemoved;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001116 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001117 }
1118 }
1119 }
1120
1121 return MadeChanges;
1122}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001123
1124namespace {
1125 Statistic<> IPNumInstRemoved("ipsccp", "Number of instructions removed");
1126 Statistic<> IPNumDeadBlocks ("ipsccp", "Number of basic blocks unreachable");
1127 Statistic<> IPNumArgsElimed ("ipsccp",
1128 "Number of arguments constant propagated");
Chris Lattnerdd336d12004-12-11 05:15:59 +00001129 Statistic<> IPNumGlobalConst("ipsccp",
1130 "Number of globals found to be constant");
Chris Lattner59acc7d2004-12-10 08:02:06 +00001131
1132 //===--------------------------------------------------------------------===//
1133 //
1134 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1135 /// Constant Propagation.
1136 ///
1137 struct IPSCCP : public ModulePass {
1138 bool runOnModule(Module &M);
1139 };
1140
1141 RegisterOpt<IPSCCP>
1142 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1143} // end anonymous namespace
1144
1145// createIPSCCPPass - This is the public interface to this file...
1146ModulePass *llvm::createIPSCCPPass() {
1147 return new IPSCCP();
1148}
1149
1150
1151static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001152 // Delete any dead constantexpr klingons.
1153 GV->removeDeadConstantUsers();
1154
Chris Lattner59acc7d2004-12-10 08:02:06 +00001155 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1156 UI != E; ++UI)
1157 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001158 if (SI->getOperand(0) == GV || SI->isVolatile())
1159 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001160 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1161 // Make sure we are calling the function, not passing the address.
1162 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1163 for (CallSite::arg_iterator AI = CS.arg_begin(),
1164 E = CS.arg_end(); AI != E; ++AI)
1165 if (*AI == GV)
1166 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001167 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1168 if (LI->isVolatile())
1169 return true;
1170 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001171 return true;
1172 }
1173 return false;
1174}
1175
1176bool IPSCCP::runOnModule(Module &M) {
1177 SCCPSolver Solver;
1178
1179 // Loop over all functions, marking arguments to those with their addresses
1180 // taken or that are external as overdefined.
1181 //
1182 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1183 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1184 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1185 if (!F->isExternal())
1186 Solver.MarkBlockExecutable(F->begin());
Chris Lattner7d27fc02005-04-19 19:16:19 +00001187 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1188 AI != E; ++AI)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001189 Values[AI].markOverdefined();
1190 } else {
1191 Solver.AddTrackedFunction(F);
1192 }
1193
Chris Lattnerdd336d12004-12-11 05:15:59 +00001194 // Loop over global variables. We inform the solver about any internal global
1195 // variables that do not have their 'addresses taken'. If they don't have
1196 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001197 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1198 G != E; ++G)
Chris Lattnerdd336d12004-12-11 05:15:59 +00001199 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1200 Solver.TrackValueOfGlobalVariable(G);
1201
Chris Lattner59acc7d2004-12-10 08:02:06 +00001202 // Solve for constants.
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001203 bool ResolvedBranches = true;
1204 while (ResolvedBranches) {
1205 Solver.Solve();
1206
Chris Lattnerdade2d22004-12-11 06:05:53 +00001207 DEBUG(std::cerr << "RESOLVING UNDEF BRANCHES\n");
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001208 ResolvedBranches = false;
1209 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1210 ResolvedBranches |= Solver.ResolveBranchesIn(*F);
1211 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001212
1213 bool MadeChanges = false;
1214
1215 // Iterate over all of the instructions in the module, replacing them with
1216 // constants if we have found them to be of constant values.
1217 //
1218 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1219 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001220 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1221 AI != E; ++AI)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001222 if (!AI->use_empty()) {
1223 LatticeVal &IV = Values[AI];
1224 if (IV.isConstant() || IV.isUndefined()) {
1225 Constant *CST = IV.isConstant() ?
1226 IV.getConstant() : UndefValue::get(AI->getType());
1227 DEBUG(std::cerr << "*** Arg " << *AI << " = " << *CST <<"\n");
Misha Brukmanfd939082005-04-21 23:48:37 +00001228
Chris Lattner59acc7d2004-12-10 08:02:06 +00001229 // Replaces all of the uses of a variable with uses of the
1230 // constant.
1231 AI->replaceAllUsesWith(CST);
1232 ++IPNumArgsElimed;
1233 }
1234 }
1235
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001236 std::vector<BasicBlock*> BlocksToErase;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001237 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1238 if (!ExecutableBBs.count(BB)) {
1239 DEBUG(std::cerr << " BasicBlock Dead:" << *BB);
1240 ++IPNumDeadBlocks;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001241
Chris Lattner59acc7d2004-12-10 08:02:06 +00001242 // Delete the instructions backwards, as it has a reduced likelihood of
1243 // having to update as many def-use and use-def chains.
1244 std::vector<Instruction*> Insts;
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001245 TerminatorInst *TI = BB->getTerminator();
1246 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001247 Insts.push_back(I);
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001248
Chris Lattner59acc7d2004-12-10 08:02:06 +00001249 while (!Insts.empty()) {
1250 Instruction *I = Insts.back();
1251 Insts.pop_back();
1252 if (!I->use_empty())
1253 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1254 BB->getInstList().erase(I);
1255 MadeChanges = true;
1256 ++IPNumInstRemoved;
1257 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001258
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001259 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1260 BasicBlock *Succ = TI->getSuccessor(i);
1261 if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1262 TI->getSuccessor(i)->removePredecessor(BB);
1263 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001264 if (!TI->use_empty())
1265 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001266 BB->getInstList().erase(TI);
1267
Chris Lattner864737b2004-12-11 05:32:19 +00001268 if (&*BB != &F->front())
1269 BlocksToErase.push_back(BB);
1270 else
1271 new UnreachableInst(BB);
1272
Chris Lattner59acc7d2004-12-10 08:02:06 +00001273 } else {
1274 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1275 Instruction *Inst = BI++;
1276 if (Inst->getType() != Type::VoidTy) {
1277 LatticeVal &IV = Values[Inst];
1278 if (IV.isConstant() || IV.isUndefined() &&
1279 !isa<TerminatorInst>(Inst)) {
1280 Constant *Const = IV.isConstant()
1281 ? IV.getConstant() : UndefValue::get(Inst->getType());
1282 DEBUG(std::cerr << " Constant: " << *Const << " = " << *Inst);
Misha Brukmanfd939082005-04-21 23:48:37 +00001283
Chris Lattner59acc7d2004-12-10 08:02:06 +00001284 // Replaces all of the uses of a variable with uses of the
1285 // constant.
1286 Inst->replaceAllUsesWith(Const);
Misha Brukmanfd939082005-04-21 23:48:37 +00001287
Chris Lattner59acc7d2004-12-10 08:02:06 +00001288 // Delete the instruction.
1289 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1290 BB->getInstList().erase(Inst);
1291
1292 // Hey, we just changed something!
1293 MadeChanges = true;
1294 ++IPNumInstRemoved;
1295 }
1296 }
1297 }
1298 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001299
1300 // Now that all instructions in the function are constant folded, erase dead
1301 // blocks, because we can now use ConstantFoldTerminator to get rid of
1302 // in-edges.
1303 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1304 // If there are any PHI nodes in this successor, drop entries for BB now.
1305 BasicBlock *DeadBB = BlocksToErase[i];
1306 while (!DeadBB->use_empty()) {
1307 Instruction *I = cast<Instruction>(DeadBB->use_back());
1308 bool Folded = ConstantFoldTerminator(I->getParent());
1309 assert(Folded && "Didn't fold away reference to block!");
1310 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001311
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001312 // Finally, delete the basic block.
1313 F->getBasicBlockList().erase(DeadBB);
1314 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001315 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001316
1317 // If we inferred constant or undef return values for a function, we replaced
1318 // all call uses with the inferred value. This means we don't need to bother
1319 // actually returning anything from the function. Replace all return
1320 // instructions with return undef.
1321 const hash_map<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals();
1322 for (hash_map<Function*, LatticeVal>::const_iterator I = RV.begin(),
1323 E = RV.end(); I != E; ++I)
1324 if (!I->second.isOverdefined() &&
1325 I->first->getReturnType() != Type::VoidTy) {
1326 Function *F = I->first;
1327 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1328 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1329 if (!isa<UndefValue>(RI->getOperand(0)))
1330 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1331 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001332
1333 // If we infered constant or undef values for globals variables, we can delete
1334 // the global and any stores that remain to it.
1335 const hash_map<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1336 for (hash_map<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1337 E = TG.end(); I != E; ++I) {
1338 GlobalVariable *GV = I->first;
1339 assert(!I->second.isOverdefined() &&
1340 "Overdefined values should have been taken out of the map!");
1341 DEBUG(std::cerr << "Found that GV '" << GV->getName()<< "' is constant!\n");
1342 while (!GV->use_empty()) {
1343 StoreInst *SI = cast<StoreInst>(GV->use_back());
1344 SI->eraseFromParent();
1345 }
1346 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001347 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001348 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001349
Chris Lattner59acc7d2004-12-10 08:02:06 +00001350 return MadeChanges;
1351}