blob: 46d90afc44ea410cd5de9da5869812a78113b283 [file] [log] [blame]
Misha Brukman373086d2003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +00009//
Misha Brukman373086d2003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner347389d2001-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 Lattnerdd6522e2002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner347389d2001-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 Lattnerb4cfa7f2002-05-07 20:03:00 +000024#include "llvm/Transforms/Scalar.h"
Chris Lattner0fe5b322004-01-12 17:43:40 +000025#include "llvm/Constants.h"
Chris Lattner57698e22002-03-26 18:01:55 +000026#include "llvm/Function.h"
Chris Lattner49f74522004-01-12 04:29:41 +000027#include "llvm/GlobalVariable.h"
Chris Lattnercccc5c72003-04-25 02:50:03 +000028#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000029#include "llvm/Pass.h"
Chris Lattner0fe5b322004-01-12 17:43:40 +000030#include "llvm/Type.h"
Chris Lattner6e560792002-04-18 15:13:15 +000031#include "llvm/Support/InstVisitor.h"
Chris Lattnerff9362a2004-04-13 19:43:54 +000032#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
34#include "llvm/ADT/hash_map"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/STLExtras.h"
Chris Lattner347389d2001-06-27 23:38:11 +000037#include <algorithm>
Chris Lattner347389d2001-06-27 23:38:11 +000038#include <set>
Chris Lattner49525f82004-01-09 06:02:20 +000039using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000040
Chris Lattner347389d2001-06-27 23:38:11 +000041// InstVal class - This class represents the different lattice values that an
Chris Lattnerc8e66542002-04-27 06:56:12 +000042// instruction may occupy. It is a simple class with value semantics.
Chris Lattner347389d2001-06-27 23:38:11 +000043//
Chris Lattner7d325382002-04-29 21:26:08 +000044namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000045 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
46
Chris Lattner347389d2001-06-27 23:38:11 +000047class InstVal {
48 enum {
Chris Lattner3462ae32001-12-03 22:26:30 +000049 undefined, // This instruction has no known value
50 constant, // This instruction has a constant value
Chris Lattner3462ae32001-12-03 22:26:30 +000051 overdefined // This instruction has an unknown value
52 } LatticeValue; // The current lattice position
53 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000054public:
Chris Lattner3462ae32001-12-03 22:26:30 +000055 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner347389d2001-06-27 23:38:11 +000056
57 // markOverdefined - Return true if this is a new status to be in...
58 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000059 if (LatticeValue != overdefined) {
60 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000061 return true;
62 }
63 return false;
64 }
65
66 // markConstant - Return true if this is a new status for us...
Chris Lattner3462ae32001-12-03 22:26:30 +000067 inline bool markConstant(Constant *V) {
68 if (LatticeValue != constant) {
69 LatticeValue = constant;
Chris Lattner347389d2001-06-27 23:38:11 +000070 ConstantVal = V;
71 return true;
72 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +000073 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +000074 }
75 return false;
76 }
77
Chris Lattner3462ae32001-12-03 22:26:30 +000078 inline bool isUndefined() const { return LatticeValue == undefined; }
79 inline bool isConstant() const { return LatticeValue == constant; }
80 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +000081
Chris Lattner05fe6842004-01-12 03:57:30 +000082 inline Constant *getConstant() const {
83 assert(isConstant() && "Cannot get the constant of a non-constant!");
84 return ConstantVal;
85 }
Chris Lattner347389d2001-06-27 23:38:11 +000086};
87
Chris Lattner7d325382002-04-29 21:26:08 +000088} // end anonymous namespace
Chris Lattner347389d2001-06-27 23:38:11 +000089
90
91//===----------------------------------------------------------------------===//
92// SCCP Class
93//
Misha Brukman373086d2003-05-20 21:01:22 +000094// This class does all of the work of Sparse Conditional Constant Propagation.
Chris Lattner347389d2001-06-27 23:38:11 +000095//
Chris Lattner7d325382002-04-29 21:26:08 +000096namespace {
97class SCCP : public FunctionPass, public InstVisitor<SCCP> {
Chris Lattner7f74a562002-01-20 22:54:45 +000098 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattnerd79334d2004-07-15 23:36:43 +000099 hash_map<Value*, InstVal> ValueState; // The state each value is in...
Chris Lattner347389d2001-06-27 23:38:11 +0000100
Chris Lattnerd79334d2004-07-15 23:36:43 +0000101 // The reason for two worklists is that overdefined is the lowest state
102 // on the lattice, and moving things to overdefined as fast as possible
103 // makes SCCP converge much faster.
104 // By having a separate worklist, we accomplish this because everything
105 // possibly overdefined will become overdefined at the soonest possible
106 // point.
107 std::vector<Instruction*> OverdefinedInstWorkList;// The overdefined
108 // instruction work list
Chris Lattnerd66a6e32002-05-07 04:29:32 +0000109 std::vector<Instruction*> InstWorkList;// The instruction work list
Chris Lattnerd79334d2004-07-15 23:36:43 +0000110
111
Chris Lattner7f74a562002-01-20 22:54:45 +0000112 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000113
Chris Lattner05fe6842004-01-12 03:57:30 +0000114 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
115 /// overdefined, despite the fact that the PHI node is overdefined.
116 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
117
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000118 /// KnownFeasibleEdges - Entries in this set are edges which have already had
119 /// PHI nodes retriggered.
120 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
121 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000122public:
123
Misha Brukman373086d2003-05-20 21:01:22 +0000124 // runOnFunction - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner7d325382002-04-29 21:26:08 +0000125 // and return true if the function was modified.
126 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000127 bool runOnFunction(Function &F);
Chris Lattner7d325382002-04-29 21:26:08 +0000128
129 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +0000130 AU.setPreservesCFG();
Chris Lattner7d325382002-04-29 21:26:08 +0000131 }
132
Chris Lattner347389d2001-06-27 23:38:11 +0000133
134 //===--------------------------------------------------------------------===//
135 // The implementation of this class
136 //
137private:
Chris Lattner6e560792002-04-18 15:13:15 +0000138 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
Chris Lattner347389d2001-06-27 23:38:11 +0000139
Chris Lattnerd79334d2004-07-15 23:36:43 +0000140 // markConstant - Make a value be marked as "constant". If the value
Chris Lattner347389d2001-06-27 23:38:11 +0000141 // is not already a constant, add it to the instruction work list so that
142 // the users of the instruction are updated later.
143 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000144 inline void markConstant(InstVal &IV, Instruction *I, Constant *C) {
145 if (IV.markConstant(C)) {
146 DEBUG(std::cerr << "markConstant: " << *C << ": " << *I);
Chris Lattnerd66a6e32002-05-07 04:29:32 +0000147 InstWorkList.push_back(I);
Chris Lattner347389d2001-06-27 23:38:11 +0000148 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000149 }
150 inline void markConstant(Instruction *I, Constant *C) {
151 markConstant(ValueState[I], I, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000152 }
153
Chris Lattnerd79334d2004-07-15 23:36:43 +0000154 // markOverdefined - Make a value be marked as "overdefined". If the
155 // value is not already overdefined, add it to the overdefined instruction
156 // work list so that the users of the instruction are updated later.
157
Chris Lattner7324f7c2003-10-08 16:21:03 +0000158 inline void markOverdefined(InstVal &IV, Instruction *I) {
159 if (IV.markOverdefined()) {
160 DEBUG(std::cerr << "markOverdefined: " << *I);
Chris Lattnerd79334d2004-07-15 23:36:43 +0000161 OverdefinedInstWorkList.push_back(I); // Only instructions go on the work list
Chris Lattner347389d2001-06-27 23:38:11 +0000162 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000163 }
164 inline void markOverdefined(Instruction *I) {
165 markOverdefined(ValueState[I], I);
Chris Lattner347389d2001-06-27 23:38:11 +0000166 }
167
168 // getValueState - Return the InstVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000169 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000170 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000171 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000172 // Instruction object, then use this accessor to get its value from the map.
173 //
174 inline InstVal &getValueState(Value *V) {
Chris Lattnerd79334d2004-07-15 23:36:43 +0000175 hash_map<Value*, InstVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000176 if (I != ValueState.end()) return I->second; // Common case, in the map
177
Reid Spencerf0a5bca2004-07-18 08:34:52 +0000178 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
Chris Lattner347389d2001-06-27 23:38:11 +0000179 ValueState[CPV].markConstant(CPV);
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000180 } else if (isa<Argument>(V)) { // Arguments are overdefined
Chris Lattner347389d2001-06-27 23:38:11 +0000181 ValueState[V].markOverdefined();
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000182 }
Chris Lattner347389d2001-06-27 23:38:11 +0000183 // All others are underdefined by default...
184 return ValueState[V];
185 }
186
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000187 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000188 // work list if it is not already executable...
189 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000190 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
191 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
192 return; // This edge is already known to be executable!
193
194 if (BBExecutable.count(Dest)) {
195 DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
196 << " -> " << Dest->getName() << "\n");
197
198 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000199 // feasible that wasn't before. Revisit the PHI nodes in the block
200 // because they have potentially new operands.
Reid Spencer66149462004-09-15 17:06:42 +0000201 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I) {
202 PHINode *PN = cast<PHINode>(I);
Chris Lattner3c982762003-04-25 03:35:10 +0000203 visitPHINode(*PN);
Reid Spencer66149462004-09-15 17:06:42 +0000204 }
Chris Lattnercccc5c72003-04-25 02:50:03 +0000205
206 } else {
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000207 DEBUG(std::cerr << "Marking Block Executable: " << Dest->getName()<<"\n");
208 BBExecutable.insert(Dest); // Basic block is executable!
209 BBWorkList.push_back(Dest); // Add the block to the work list!
Chris Lattnercccc5c72003-04-25 02:50:03 +0000210 }
Chris Lattner347389d2001-06-27 23:38:11 +0000211 }
212
Chris Lattner347389d2001-06-27 23:38:11 +0000213
Chris Lattner6e560792002-04-18 15:13:15 +0000214 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000215 // operand made a transition, or the instruction is newly executable. Change
216 // the value type of I to reflect these changes if appropriate.
217 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000218 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000219
220 // Terminators
Chris Lattner113f4f42002-06-25 16:13:24 +0000221 void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
222 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000223
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000224 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000225 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000226 void visitBinaryOperator(Instruction &I);
227 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000228
229 // Instructions that cannot be folded away...
Chris Lattner113f4f42002-06-25 16:13:24 +0000230 void visitStoreInst (Instruction &I) { /*returns void*/ }
Chris Lattner49f74522004-01-12 04:29:41 +0000231 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000232 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000233 void visitCallInst (CallInst &I);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000234 void visitInvokeInst (TerminatorInst &I) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000235 if (I.getType() != Type::VoidTy) markOverdefined(&I);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000236 visitTerminatorInst(I);
237 }
Chris Lattner9c58cf62003-09-08 18:54:55 +0000238 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000239 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000240 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
241 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000242 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000243
Chris Lattner113f4f42002-06-25 16:13:24 +0000244 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000245 // If a new instruction is added to LLVM that we don't handle...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000246 std::cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000247 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000248 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000249
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000250 // getFeasibleSuccessors - Return a vector of booleans to indicate which
251 // successors are reachable from a given terminator instruction.
252 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000253 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000254
Chris Lattner13b52e72002-05-02 21:18:01 +0000255 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
256 // block to the 'To' basic block is currently feasible...
257 //
258 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
259
Chris Lattner10b250e2001-06-29 23:56:23 +0000260 // OperandChangedState - This method is invoked on all of the users of an
261 // instruction that was just changed state somehow.... Based on this
262 // information, we need to update the specified user of this instruction.
263 //
Chris Lattner13b52e72002-05-02 21:18:01 +0000264 void OperandChangedState(User *U) {
265 // Only instructions use other variable values!
Chris Lattner113f4f42002-06-25 16:13:24 +0000266 Instruction &I = cast<Instruction>(*U);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000267 if (BBExecutable.count(I.getParent())) // Inst is executable?
268 visit(I);
Chris Lattner13b52e72002-05-02 21:18:01 +0000269 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000270};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000271
Chris Lattnercccc5c72003-04-25 02:50:03 +0000272 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner7d325382002-04-29 21:26:08 +0000273} // end anonymous namespace
274
275
276// createSCCPPass - This is the public interface to this file...
Chris Lattner3e860842004-09-20 04:43:15 +0000277FunctionPass *llvm::createSCCPPass() {
Chris Lattner7d325382002-04-29 21:26:08 +0000278 return new SCCP();
279}
280
Chris Lattner347389d2001-06-27 23:38:11 +0000281
Chris Lattner347389d2001-06-27 23:38:11 +0000282//===----------------------------------------------------------------------===//
283// SCCP Class Implementation
284
285
Misha Brukman373086d2003-05-20 21:01:22 +0000286// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner7d325382002-04-29 21:26:08 +0000287// and return true if the function was modified.
Chris Lattner347389d2001-06-27 23:38:11 +0000288//
Chris Lattner113f4f42002-06-25 16:13:24 +0000289bool SCCP::runOnFunction(Function &F) {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000290 // Mark the first block of the function as being executable...
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000291 BBExecutable.insert(F.begin()); // Basic block is executable!
292 BBWorkList.push_back(F.begin()); // Add the block to the work list!
Chris Lattner347389d2001-06-27 23:38:11 +0000293
Chris Lattnerd79334d2004-07-15 23:36:43 +0000294 // Process the work lists until they are empty!
295 while (!BBWorkList.empty() || !InstWorkList.empty() ||
296 !OverdefinedInstWorkList.empty()) {
297 // Process the instruction work list...
298 while (!OverdefinedInstWorkList.empty()) {
299 Instruction *I = OverdefinedInstWorkList.back();
300 OverdefinedInstWorkList.pop_back();
301
302 DEBUG(std::cerr << "\nPopped off OI-WL: " << I);
303
304 // "I" got into the work list because it either made the transition from
305 // bottom to constant
306 //
307 // Anything on this worklist that is overdefined need not be visited
308 // since all of its users will have already been marked as overdefined
309 // Update all of the users of this instruction's value...
310 //
311 for_each(I->use_begin(), I->use_end(),
312 bind_obj(this, &SCCP::OperandChangedState));
313 }
Chris Lattner347389d2001-06-27 23:38:11 +0000314 // Process the instruction work list...
315 while (!InstWorkList.empty()) {
Chris Lattnerd66a6e32002-05-07 04:29:32 +0000316 Instruction *I = InstWorkList.back();
317 InstWorkList.pop_back();
Chris Lattner347389d2001-06-27 23:38:11 +0000318
Chris Lattner9a63520b2004-07-15 01:50:47 +0000319 DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
Chris Lattner347389d2001-06-27 23:38:11 +0000320
321 // "I" got into the work list because it either made the transition from
Chris Lattnerd79334d2004-07-15 23:36:43 +0000322 // bottom to constant
Chris Lattner347389d2001-06-27 23:38:11 +0000323 //
Chris Lattnerd79334d2004-07-15 23:36:43 +0000324 // Anything on this worklist that is overdefined need not be visited
325 // since all of its users will have already been marked as overdefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000326 // Update all of the users of this instruction's value...
327 //
Chris Lattnerd79334d2004-07-15 23:36:43 +0000328 InstVal &Ival = getValueState (I);
329 if (!Ival.isOverdefined())
330 for_each(I->use_begin(), I->use_end(),
331 bind_obj(this, &SCCP::OperandChangedState));
Chris Lattner347389d2001-06-27 23:38:11 +0000332 }
333
334 // Process the basic block work list...
335 while (!BBWorkList.empty()) {
336 BasicBlock *BB = BBWorkList.back();
337 BBWorkList.pop_back();
338
Chris Lattner9a63520b2004-07-15 01:50:47 +0000339 DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
Chris Lattner347389d2001-06-27 23:38:11 +0000340
Chris Lattner6e560792002-04-18 15:13:15 +0000341 // Notify all instructions in this basic block that they are newly
342 // executable.
343 visit(BB);
Chris Lattner347389d2001-06-27 23:38:11 +0000344 }
345 }
346
Chris Lattner71cbd422002-05-22 17:17:27 +0000347 if (DebugFlag) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000348 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
349 if (!BBExecutable.count(I))
Chris Lattnercccc5c72003-04-25 02:50:03 +0000350 std::cerr << "BasicBlock Dead:" << *I;
Chris Lattner71cbd422002-05-22 17:17:27 +0000351 }
Chris Lattner347389d2001-06-27 23:38:11 +0000352
Chris Lattnerc8e66542002-04-27 06:56:12 +0000353 // Iterate over all of the instructions in a function, replacing them with
Chris Lattner347389d2001-06-27 23:38:11 +0000354 // constants if we have found them to be of constant values.
355 //
356 bool MadeChanges = false;
Chris Lattner113f4f42002-06-25 16:13:24 +0000357 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
Chris Lattner60a65912002-02-12 21:07:25 +0000358 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000359 Instruction &Inst = *BI;
360 InstVal &IV = ValueState[&Inst];
Chris Lattner60a65912002-02-12 21:07:25 +0000361 if (IV.isConstant()) {
362 Constant *Const = IV.getConstant();
Chris Lattner9a63520b2004-07-15 01:50:47 +0000363 DEBUG(std::cerr << "Constant: " << *Const << " = " << Inst);
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000364
Chris Lattner60a65912002-02-12 21:07:25 +0000365 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattner113f4f42002-06-25 16:13:24 +0000366 Inst.replaceAllUsesWith(Const);
Chris Lattner347389d2001-06-27 23:38:11 +0000367
Chris Lattner5364d1a2002-05-02 20:32:51 +0000368 // Remove the operator from the list of definitions... and delete it.
Chris Lattner113f4f42002-06-25 16:13:24 +0000369 BI = BB->getInstList().erase(BI);
Chris Lattner347389d2001-06-27 23:38:11 +0000370
Chris Lattner60a65912002-02-12 21:07:25 +0000371 // Hey, we just changed something!
372 MadeChanges = true;
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000373 ++NumInstRemoved;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000374 } else {
375 ++BI;
Chris Lattner60a65912002-02-12 21:07:25 +0000376 }
Chris Lattner347389d2001-06-27 23:38:11 +0000377 }
Chris Lattner347389d2001-06-27 23:38:11 +0000378
Chris Lattner13b52e72002-05-02 21:18:01 +0000379 // Reset state so that the next invocation will have empty data structures
Chris Lattner7d325382002-04-29 21:26:08 +0000380 BBExecutable.clear();
381 ValueState.clear();
Chris Lattnerd79334d2004-07-15 23:36:43 +0000382 std::vector<Instruction*>().swap(OverdefinedInstWorkList);
Chris Lattner669c6cf2002-11-04 02:54:22 +0000383 std::vector<Instruction*>().swap(InstWorkList);
384 std::vector<BasicBlock*>().swap(BBWorkList);
Chris Lattner7d325382002-04-29 21:26:08 +0000385
Chris Lattnerdae05dc2001-09-07 16:43:22 +0000386 return MadeChanges;
Chris Lattner347389d2001-06-27 23:38:11 +0000387}
388
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000389
390// getFeasibleSuccessors - Return a vector of booleans to indicate which
391// successors are reachable from a given terminator instruction.
392//
Chris Lattner113f4f42002-06-25 16:13:24 +0000393void SCCP::getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000394 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000395 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000396 if (BI->isUnconditional()) {
397 Succs[0] = true;
398 } else {
399 InstVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000400 if (BCValue.isOverdefined() ||
401 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
402 // Overdefined condition variables, and branches on unfoldable constant
403 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000404 Succs[0] = Succs[1] = true;
405 } else if (BCValue.isConstant()) {
406 // Constant condition variables mean the branch can only go a single way
407 Succs[BCValue.getConstant() == ConstantBool::False] = true;
408 }
409 }
Chris Lattner113f4f42002-06-25 16:13:24 +0000410 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000411 // Invoke instructions successors are always executable.
412 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000413 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000414 InstVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000415 if (SCValue.isOverdefined() || // Overdefined condition?
416 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000417 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000418 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000419 } else if (SCValue.isConstant()) {
420 Constant *CPV = SCValue.getConstant();
421 // Make sure to skip the "default value" which isn't a value
422 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
423 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
424 Succs[i] = true;
425 return;
426 }
427 }
428
429 // Constant value not equal to any of the branches... must execute
430 // default branch then...
431 Succs[0] = true;
432 }
433 } else {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000434 std::cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner113f4f42002-06-25 16:13:24 +0000435 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000436 }
437}
438
439
Chris Lattner13b52e72002-05-02 21:18:01 +0000440// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
441// block to the 'To' basic block is currently feasible...
442//
443bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
444 assert(BBExecutable.count(To) && "Dest should always be alive!");
445
446 // Make sure the source basic block is executable!!
447 if (!BBExecutable.count(From)) return false;
448
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000449 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000450 TerminatorInst *TI = From->getTerminator();
451 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
452 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000453 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000454 else {
455 InstVal &BCValue = getValueState(BI->getCondition());
456 if (BCValue.isOverdefined()) {
457 // Overdefined condition variables mean the branch could go either way.
458 return true;
459 } else if (BCValue.isConstant()) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000460 // Not branching on an evaluatable constant?
461 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
462
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000463 // Constant condition variables mean the branch can only go a single way
464 return BI->getSuccessor(BCValue.getConstant() ==
465 ConstantBool::False) == To;
466 }
467 return false;
468 }
469 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
470 // Invoke instructions successors are always executable.
471 return true;
472 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
473 InstVal &SCValue = getValueState(SI->getCondition());
474 if (SCValue.isOverdefined()) { // Overdefined condition?
475 // All destinations are executable!
476 return true;
477 } else if (SCValue.isConstant()) {
478 Constant *CPV = SCValue.getConstant();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000479 if (!isa<ConstantInt>(CPV))
480 return true; // not a foldable constant?
481
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000482 // Make sure to skip the "default value" which isn't a value
483 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
484 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
485 return SI->getSuccessor(i) == To;
486
487 // Constant value not equal to any of the branches... must execute
488 // default branch then...
489 return SI->getDefaultDest() == To;
490 }
491 return false;
492 } else {
493 std::cerr << "Unknown terminator instruction: " << *TI;
494 abort();
495 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000496}
Chris Lattner347389d2001-06-27 23:38:11 +0000497
Chris Lattner6e560792002-04-18 15:13:15 +0000498// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000499// operand made a transition, or the instruction is newly executable. Change
500// the value type of I to reflect these changes if appropriate. This method
501// makes sure to do the following actions:
502//
503// 1. If a phi node merges two constants in, and has conflicting value coming
504// from different branches, or if the PHI node merges in an overdefined
505// value, then the PHI node becomes overdefined.
506// 2. If a phi node merges only constants in, and they all agree on value, the
507// PHI node becomes a constant value equal to that.
508// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
509// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
510// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
511// 6. If a conditional branch has a value that is constant, make the selected
512// destination executable
513// 7. If a conditional branch has a value that is overdefined, make all
514// successors executable.
515//
Chris Lattner113f4f42002-06-25 16:13:24 +0000516void SCCP::visitPHINode(PHINode &PN) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000517 InstVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000518 if (PNIV.isOverdefined()) {
519 // There may be instructions using this PHI node that are not overdefined
520 // themselves. If so, make sure that they know that the PHI node operand
521 // changed.
522 std::multimap<PHINode*, Instruction*>::iterator I, E;
523 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
524 if (I != E) {
525 std::vector<Instruction*> Users;
526 Users.reserve(std::distance(I, E));
527 for (; I != E; ++I) Users.push_back(I->second);
528 while (!Users.empty()) {
529 visit(Users.back());
530 Users.pop_back();
531 }
532 }
533 return; // Quick exit
534 }
Chris Lattner347389d2001-06-27 23:38:11 +0000535
Chris Lattner7a7b1142004-03-16 19:49:59 +0000536 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
537 // and slow us down a lot. Just mark them overdefined.
538 if (PN.getNumIncomingValues() > 64) {
539 markOverdefined(PNIV, &PN);
540 return;
541 }
542
Chris Lattner6e560792002-04-18 15:13:15 +0000543 // Look at all of the executable operands of the PHI node. If any of them
544 // are overdefined, the PHI becomes overdefined as well. If they are all
545 // constant, and they agree with each other, the PHI becomes the identical
546 // constant. If they are constant and don't agree, the PHI is overdefined.
547 // If there are no executable operands, the PHI remains undefined.
548 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000549 Constant *OperandVal = 0;
550 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
551 InstVal &IV = getValueState(PN.getIncomingValue(i));
552 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000553
Chris Lattner113f4f42002-06-25 16:13:24 +0000554 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000555 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000556 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000557 return;
558 }
559
Chris Lattnercccc5c72003-04-25 02:50:03 +0000560 if (OperandVal == 0) { // Grab the first value...
561 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000562 } else { // Another value is being merged in!
563 // There is already a reachable operand. If we conflict with it,
564 // then the PHI node becomes overdefined. If we agree with it, we
565 // can continue on.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000566
Chris Lattner6e560792002-04-18 15:13:15 +0000567 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000568 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000569 // Yes there is. This means the PHI node is not constant.
570 // You must be overdefined poor PHI.
571 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000572 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000573 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000574 }
Chris Lattner347389d2001-06-27 23:38:11 +0000575 }
576 }
Chris Lattner347389d2001-06-27 23:38:11 +0000577 }
578
Chris Lattner6e560792002-04-18 15:13:15 +0000579 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000580 // arguments that agree with each other(and OperandVal is the constant) or
581 // OperandVal is null because there are no defined incoming arguments. If
582 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000583 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000584 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000585 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000586}
587
Chris Lattner113f4f42002-06-25 16:13:24 +0000588void SCCP::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000589 std::vector<bool> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000590 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000591
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000592 BasicBlock *BB = TI.getParent();
593
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000594 // Mark all feasible successors executable...
595 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000596 if (SuccFeasible[i])
597 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000598}
599
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000600void SCCP::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000601 Value *V = I.getOperand(0);
Chris Lattner6e560792002-04-18 15:13:15 +0000602 InstVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000603 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000604 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000605 else if (VState.isConstant()) // Propagate constant value
606 markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000607}
608
Chris Lattner59db22d2004-03-12 05:52:44 +0000609void SCCP::visitSelectInst(SelectInst &I) {
610 InstVal &CondValue = getValueState(I.getCondition());
611 if (CondValue.isOverdefined())
612 markOverdefined(&I);
613 else if (CondValue.isConstant()) {
614 if (CondValue.getConstant() == ConstantBool::True) {
615 InstVal &Val = getValueState(I.getTrueValue());
616 if (Val.isOverdefined())
617 markOverdefined(&I);
618 else if (Val.isConstant())
619 markConstant(&I, Val.getConstant());
620 } else if (CondValue.getConstant() == ConstantBool::False) {
621 InstVal &Val = getValueState(I.getFalseValue());
622 if (Val.isOverdefined())
623 markOverdefined(&I);
624 else if (Val.isConstant())
625 markConstant(&I, Val.getConstant());
626 } else
627 markOverdefined(&I);
628 }
629}
630
Chris Lattner6e560792002-04-18 15:13:15 +0000631// Handle BinaryOperators and Shift Instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000632void SCCP::visitBinaryOperator(Instruction &I) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000633 InstVal &IV = ValueState[&I];
634 if (IV.isOverdefined()) return;
635
Chris Lattner113f4f42002-06-25 16:13:24 +0000636 InstVal &V1State = getValueState(I.getOperand(0));
637 InstVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000638
Chris Lattner6e560792002-04-18 15:13:15 +0000639 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000640 // If both operands are PHI nodes, it is possible that this instruction has
641 // a constant value, despite the fact that the PHI node doesn't. Check for
642 // this condition now.
643 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
644 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
645 if (PN1->getParent() == PN2->getParent()) {
646 // Since the two PHI nodes are in the same basic block, they must have
647 // entries for the same predecessors. Walk the predecessor list, and
648 // if all of the incoming values are constants, and the result of
649 // evaluating this expression with all incoming value pairs is the
650 // same, then this expression is a constant even though the PHI node
651 // is not a constant!
652 InstVal Result;
653 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
654 InstVal &In1 = getValueState(PN1->getIncomingValue(i));
655 BasicBlock *InBlock = PN1->getIncomingBlock(i);
656 InstVal &In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
657
658 if (In1.isOverdefined() || In2.isOverdefined()) {
659 Result.markOverdefined();
660 break; // Cannot fold this operation over the PHI nodes!
661 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000662 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
663 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000664 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000665 Result.markConstant(V);
666 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000667 Result.markOverdefined();
668 break;
669 }
670 }
671 }
672
673 // If we found a constant value here, then we know the instruction is
674 // constant despite the fact that the PHI nodes are overdefined.
675 if (Result.isConstant()) {
676 markConstant(IV, &I, Result.getConstant());
677 // Remember that this instruction is virtually using the PHI node
678 // operands.
679 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
680 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
681 return;
682 } else if (Result.isUndefined()) {
683 return;
684 }
685
686 // Okay, this really is overdefined now. Since we might have
687 // speculatively thought that this was not overdefined before, and
688 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
689 // make sure to clean out any entries that we put there, for
690 // efficiency.
691 std::multimap<PHINode*, Instruction*>::iterator It, E;
692 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
693 while (It != E) {
694 if (It->second == &I) {
695 UsersOfOverdefinedPHIs.erase(It++);
696 } else
697 ++It;
698 }
699 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
700 while (It != E) {
701 if (It->second == &I) {
702 UsersOfOverdefinedPHIs.erase(It++);
703 } else
704 ++It;
705 }
706 }
707
708 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000709 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000710 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
711 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000712 }
713}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000714
715// Handle getelementptr instructions... if all operands are constants then we
716// can turn this into a getelementptr ConstantExpr.
717//
718void SCCP::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner49f74522004-01-12 04:29:41 +0000719 InstVal &IV = ValueState[&I];
720 if (IV.isOverdefined()) return;
721
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000722 std::vector<Constant*> Operands;
723 Operands.reserve(I.getNumOperands());
724
725 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
726 InstVal &State = getValueState(I.getOperand(i));
727 if (State.isUndefined())
728 return; // Operands are not resolved yet...
729 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +0000730 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000731 return;
732 }
733 assert(State.isConstant() && "Unknown state!");
734 Operands.push_back(State.getConstant());
735 }
736
737 Constant *Ptr = Operands[0];
738 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
739
Chris Lattner49f74522004-01-12 04:29:41 +0000740 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000741}
Brian Gaeke960707c2003-11-11 22:41:34 +0000742
Chris Lattner49f74522004-01-12 04:29:41 +0000743/// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
744/// return the constant value being addressed by the constant expression, or
745/// null if something is funny.
746///
747static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +0000748 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner49f74522004-01-12 04:29:41 +0000749 return 0; // Do not allow stepping over the value!
750
751 // Loop over all of the operands, tracking down which value we are
752 // addressing...
753 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
754 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +0000755 ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
756 if (CS == 0) return 0;
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000757 if (CU->getValue() >= CS->getNumOperands()) return 0;
758 C = CS->getOperand(CU->getValue());
Chris Lattner49f74522004-01-12 04:29:41 +0000759 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +0000760 ConstantArray *CA = dyn_cast<ConstantArray>(C);
761 if (CA == 0) return 0;
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000762 if ((uint64_t)CS->getValue() >= CA->getNumOperands()) return 0;
763 C = CA->getOperand(CS->getValue());
Chris Lattner76b2ff42004-02-15 05:55:15 +0000764 } else
Chris Lattner49f74522004-01-12 04:29:41 +0000765 return 0;
766 return C;
767}
768
769// Handle load instructions. If the operand is a constant pointer to a constant
770// global, we can replace the load with the loaded constant value!
771void SCCP::visitLoadInst(LoadInst &I) {
772 InstVal &IV = ValueState[&I];
773 if (IV.isOverdefined()) return;
774
775 InstVal &PtrVal = getValueState(I.getOperand(0));
776 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
777 if (PtrVal.isConstant() && !I.isVolatile()) {
778 Value *Ptr = PtrVal.getConstant();
Chris Lattner538fee72004-03-07 22:16:24 +0000779 if (isa<ConstantPointerNull>(Ptr)) {
780 // load null -> null
781 markConstant(IV, &I, Constant::getNullValue(I.getType()));
782 return;
783 }
784
Chris Lattner49f74522004-01-12 04:29:41 +0000785 // Transform load (constant global) into the value loaded.
786 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr))
787 if (GV->isConstant() && !GV->isExternal()) {
788 markConstant(IV, &I, GV->getInitializer());
789 return;
790 }
791
792 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
793 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
794 if (CE->getOpcode() == Instruction::GetElementPtr)
Reid Spencerc5afc952004-07-18 00:31:05 +0000795 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
796 if (GV->isConstant() && !GV->isExternal())
797 if (Constant *V =
798 GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
799 markConstant(IV, &I, V);
800 return;
801 }
Chris Lattner49f74522004-01-12 04:29:41 +0000802 }
803
804 // Otherwise we cannot say for certain what value this load will produce.
805 // Bail out.
806 markOverdefined(IV, &I);
807}
Chris Lattnerff9362a2004-04-13 19:43:54 +0000808
809void SCCP::visitCallInst(CallInst &I) {
810 InstVal &IV = ValueState[&I];
811 if (IV.isOverdefined()) return;
812
813 Function *F = I.getCalledFunction();
814 if (F == 0 || !canConstantFoldCallTo(F)) {
815 markOverdefined(IV, &I);
816 return;
817 }
818
819 std::vector<Constant*> Operands;
820 Operands.reserve(I.getNumOperands()-1);
821
822 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
823 InstVal &State = getValueState(I.getOperand(i));
824 if (State.isUndefined())
825 return; // Operands are not resolved yet...
826 else if (State.isOverdefined()) {
827 markOverdefined(IV, &I);
828 return;
829 }
830 assert(State.isConstant() && "Unknown state!");
831 Operands.push_back(State.getConstant());
832 }
833
834 if (Constant *C = ConstantFoldCall(F, Operands))
835 markConstant(IV, &I, C);
836 else
837 markOverdefined(IV, &I);
838}