blob: 3c92afe8cf504679864147e10582cb2ecf0eb45f [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 Lattner65b529f2002-04-08 20:18:09 +000025#include "llvm/ConstantHandling.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 Lattner6e560792002-04-18 15:13:15 +000030#include "llvm/Support/InstVisitor.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000031#include "Support/Debug.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000032#include "Support/Statistic.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000033#include "Support/STLExtras.h"
Chris Lattner347389d2001-06-27 23:38:11 +000034#include <algorithm>
Chris Lattner347389d2001-06-27 23:38:11 +000035#include <set>
Chris Lattner49525f82004-01-09 06:02:20 +000036using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000037
Chris Lattner347389d2001-06-27 23:38:11 +000038// InstVal class - This class represents the different lattice values that an
Chris Lattnerc8e66542002-04-27 06:56:12 +000039// instruction may occupy. It is a simple class with value semantics.
Chris Lattner347389d2001-06-27 23:38:11 +000040//
Chris Lattner7d325382002-04-29 21:26:08 +000041namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000042 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
43
Chris Lattner347389d2001-06-27 23:38:11 +000044class InstVal {
45 enum {
Chris Lattner3462ae32001-12-03 22:26:30 +000046 undefined, // This instruction has no known value
47 constant, // This instruction has a constant value
Chris Lattner3462ae32001-12-03 22:26:30 +000048 overdefined // This instruction has an unknown value
49 } LatticeValue; // The current lattice position
50 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000051public:
Chris Lattner3462ae32001-12-03 22:26:30 +000052 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner347389d2001-06-27 23:38:11 +000053
54 // markOverdefined - Return true if this is a new status to be in...
55 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000056 if (LatticeValue != overdefined) {
57 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000058 return true;
59 }
60 return false;
61 }
62
63 // markConstant - Return true if this is a new status for us...
Chris Lattner3462ae32001-12-03 22:26:30 +000064 inline bool markConstant(Constant *V) {
65 if (LatticeValue != constant) {
66 LatticeValue = constant;
Chris Lattner347389d2001-06-27 23:38:11 +000067 ConstantVal = V;
68 return true;
69 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +000070 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +000071 }
72 return false;
73 }
74
Chris Lattner3462ae32001-12-03 22:26:30 +000075 inline bool isUndefined() const { return LatticeValue == undefined; }
76 inline bool isConstant() const { return LatticeValue == constant; }
77 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +000078
Chris Lattner05fe6842004-01-12 03:57:30 +000079 inline Constant *getConstant() const {
80 assert(isConstant() && "Cannot get the constant of a non-constant!");
81 return ConstantVal;
82 }
Chris Lattner347389d2001-06-27 23:38:11 +000083};
84
Chris Lattner7d325382002-04-29 21:26:08 +000085} // end anonymous namespace
Chris Lattner347389d2001-06-27 23:38:11 +000086
87
88//===----------------------------------------------------------------------===//
89// SCCP Class
90//
Misha Brukman373086d2003-05-20 21:01:22 +000091// This class does all of the work of Sparse Conditional Constant Propagation.
Chris Lattner347389d2001-06-27 23:38:11 +000092//
Chris Lattner7d325382002-04-29 21:26:08 +000093namespace {
94class SCCP : public FunctionPass, public InstVisitor<SCCP> {
Chris Lattner7f74a562002-01-20 22:54:45 +000095 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
96 std::map<Value*, InstVal> ValueState; // The state each value is in...
Chris Lattner347389d2001-06-27 23:38:11 +000097
Chris Lattnerd66a6e32002-05-07 04:29:32 +000098 std::vector<Instruction*> InstWorkList;// The instruction work list
Chris Lattner7f74a562002-01-20 22:54:45 +000099 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000100
Chris Lattner05fe6842004-01-12 03:57:30 +0000101 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
102 /// overdefined, despite the fact that the PHI node is overdefined.
103 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
104
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000105 /// KnownFeasibleEdges - Entries in this set are edges which have already had
106 /// PHI nodes retriggered.
107 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
108 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000109public:
110
Misha Brukman373086d2003-05-20 21:01:22 +0000111 // runOnFunction - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner7d325382002-04-29 21:26:08 +0000112 // and return true if the function was modified.
113 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000114 bool runOnFunction(Function &F);
Chris Lattner7d325382002-04-29 21:26:08 +0000115
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +0000117 AU.setPreservesCFG();
Chris Lattner7d325382002-04-29 21:26:08 +0000118 }
119
Chris Lattner347389d2001-06-27 23:38:11 +0000120
121 //===--------------------------------------------------------------------===//
122 // The implementation of this class
123 //
124private:
Chris Lattner6e560792002-04-18 15:13:15 +0000125 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
Chris Lattner347389d2001-06-27 23:38:11 +0000126
127 // markValueOverdefined - Make a value be marked as "constant". If the value
128 // is not already a constant, add it to the instruction work list so that
129 // the users of the instruction are updated later.
130 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000131 inline void markConstant(InstVal &IV, Instruction *I, Constant *C) {
132 if (IV.markConstant(C)) {
133 DEBUG(std::cerr << "markConstant: " << *C << ": " << *I);
Chris Lattnerd66a6e32002-05-07 04:29:32 +0000134 InstWorkList.push_back(I);
Chris Lattner347389d2001-06-27 23:38:11 +0000135 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000136 }
137 inline void markConstant(Instruction *I, Constant *C) {
138 markConstant(ValueState[I], I, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000139 }
140
141 // markValueOverdefined - Make a value be marked as "overdefined". If the
142 // value is not already overdefined, add it to the instruction work list so
143 // that the users of the instruction are updated later.
144 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000145 inline void markOverdefined(InstVal &IV, Instruction *I) {
146 if (IV.markOverdefined()) {
147 DEBUG(std::cerr << "markOverdefined: " << *I);
148 InstWorkList.push_back(I); // Only instructions go on the work list
Chris Lattner347389d2001-06-27 23:38:11 +0000149 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000150 }
151 inline void markOverdefined(Instruction *I) {
152 markOverdefined(ValueState[I], I);
Chris Lattner347389d2001-06-27 23:38:11 +0000153 }
154
155 // getValueState - Return the InstVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000156 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000157 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000158 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000159 // Instruction object, then use this accessor to get its value from the map.
160 //
161 inline InstVal &getValueState(Value *V) {
Chris Lattner7f74a562002-01-20 22:54:45 +0000162 std::map<Value*, InstVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000163 if (I != ValueState.end()) return I->second; // Common case, in the map
164
Chris Lattner3462ae32001-12-03 22:26:30 +0000165 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
Chris Lattner347389d2001-06-27 23:38:11 +0000166 ValueState[CPV].markConstant(CPV);
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000167 } else if (isa<Argument>(V)) { // Arguments are overdefined
Chris Lattner347389d2001-06-27 23:38:11 +0000168 ValueState[V].markOverdefined();
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000169 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
170 // The address of a global is a constant...
171 ValueState[V].markConstant(ConstantPointerRef::get(GV));
172 }
Chris Lattner347389d2001-06-27 23:38:11 +0000173 // All others are underdefined by default...
174 return ValueState[V];
175 }
176
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000177 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000178 // work list if it is not already executable...
179 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000180 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
181 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
182 return; // This edge is already known to be executable!
183
184 if (BBExecutable.count(Dest)) {
185 DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
186 << " -> " << Dest->getName() << "\n");
187
188 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000189 // feasible that wasn't before. Revisit the PHI nodes in the block
190 // because they have potentially new operands.
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000191 for (BasicBlock::iterator I = Dest->begin();
Chris Lattnercccc5c72003-04-25 02:50:03 +0000192 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattner3c982762003-04-25 03:35:10 +0000193 visitPHINode(*PN);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000194
195 } else {
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000196 DEBUG(std::cerr << "Marking Block Executable: " << Dest->getName()<<"\n");
197 BBExecutable.insert(Dest); // Basic block is executable!
198 BBWorkList.push_back(Dest); // Add the block to the work list!
Chris Lattnercccc5c72003-04-25 02:50:03 +0000199 }
Chris Lattner347389d2001-06-27 23:38:11 +0000200 }
201
Chris Lattner347389d2001-06-27 23:38:11 +0000202
Chris Lattner6e560792002-04-18 15:13:15 +0000203 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000204 // operand made a transition, or the instruction is newly executable. Change
205 // the value type of I to reflect these changes if appropriate.
206 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000207 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000208
209 // Terminators
Chris Lattner113f4f42002-06-25 16:13:24 +0000210 void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
211 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000212
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000213 void visitCastInst(CastInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000214 void visitBinaryOperator(Instruction &I);
215 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000216
217 // Instructions that cannot be folded away...
Chris Lattner113f4f42002-06-25 16:13:24 +0000218 void visitStoreInst (Instruction &I) { /*returns void*/ }
Chris Lattner49f74522004-01-12 04:29:41 +0000219 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000220 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000221 void visitCallInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnerdf741d62003-08-27 01:08:35 +0000222 void visitInvokeInst (TerminatorInst &I) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000223 if (I.getType() != Type::VoidTy) markOverdefined(&I);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000224 visitTerminatorInst(I);
225 }
Chris Lattner9c58cf62003-09-08 18:54:55 +0000226 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000227 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000228 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
229 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000230 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000231
Chris Lattner113f4f42002-06-25 16:13:24 +0000232 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000233 // If a new instruction is added to LLVM that we don't handle...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000234 std::cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000235 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000236 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000237
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000238 // getFeasibleSuccessors - Return a vector of booleans to indicate which
239 // successors are reachable from a given terminator instruction.
240 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000241 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000242
Chris Lattner13b52e72002-05-02 21:18:01 +0000243 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
244 // block to the 'To' basic block is currently feasible...
245 //
246 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
247
Chris Lattner10b250e2001-06-29 23:56:23 +0000248 // OperandChangedState - This method is invoked on all of the users of an
249 // instruction that was just changed state somehow.... Based on this
250 // information, we need to update the specified user of this instruction.
251 //
Chris Lattner13b52e72002-05-02 21:18:01 +0000252 void OperandChangedState(User *U) {
253 // Only instructions use other variable values!
Chris Lattner113f4f42002-06-25 16:13:24 +0000254 Instruction &I = cast<Instruction>(*U);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000255 if (BBExecutable.count(I.getParent())) // Inst is executable?
256 visit(I);
Chris Lattner13b52e72002-05-02 21:18:01 +0000257 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000258};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000259
Chris Lattnercccc5c72003-04-25 02:50:03 +0000260 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner7d325382002-04-29 21:26:08 +0000261} // end anonymous namespace
262
263
264// createSCCPPass - This is the public interface to this file...
Chris Lattner49525f82004-01-09 06:02:20 +0000265Pass *llvm::createSCCPPass() {
Chris Lattner7d325382002-04-29 21:26:08 +0000266 return new SCCP();
267}
268
Chris Lattner347389d2001-06-27 23:38:11 +0000269
Chris Lattner347389d2001-06-27 23:38:11 +0000270//===----------------------------------------------------------------------===//
271// SCCP Class Implementation
272
273
Misha Brukman373086d2003-05-20 21:01:22 +0000274// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner7d325382002-04-29 21:26:08 +0000275// and return true if the function was modified.
Chris Lattner347389d2001-06-27 23:38:11 +0000276//
Chris Lattner113f4f42002-06-25 16:13:24 +0000277bool SCCP::runOnFunction(Function &F) {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000278 // Mark the first block of the function as being executable...
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000279 BBExecutable.insert(F.begin()); // Basic block is executable!
280 BBWorkList.push_back(F.begin()); // Add the block to the work list!
Chris Lattner347389d2001-06-27 23:38:11 +0000281
282 // Process the work lists until their are empty!
283 while (!BBWorkList.empty() || !InstWorkList.empty()) {
284 // Process the instruction work list...
285 while (!InstWorkList.empty()) {
Chris Lattnerd66a6e32002-05-07 04:29:32 +0000286 Instruction *I = InstWorkList.back();
287 InstWorkList.pop_back();
Chris Lattner347389d2001-06-27 23:38:11 +0000288
Chris Lattnercccc5c72003-04-25 02:50:03 +0000289 DEBUG(std::cerr << "\nPopped off I-WL: " << I);
Chris Lattner347389d2001-06-27 23:38:11 +0000290
291 // "I" got into the work list because it either made the transition from
292 // bottom to constant, or to Overdefined.
293 //
294 // Update all of the users of this instruction's value...
295 //
296 for_each(I->use_begin(), I->use_end(),
297 bind_obj(this, &SCCP::OperandChangedState));
298 }
299
300 // Process the basic block work list...
301 while (!BBWorkList.empty()) {
302 BasicBlock *BB = BBWorkList.back();
303 BBWorkList.pop_back();
304
Chris Lattnercccc5c72003-04-25 02:50:03 +0000305 DEBUG(std::cerr << "\nPopped off BBWL: " << BB);
Chris Lattner347389d2001-06-27 23:38:11 +0000306
Chris Lattner6e560792002-04-18 15:13:15 +0000307 // Notify all instructions in this basic block that they are newly
308 // executable.
309 visit(BB);
Chris Lattner347389d2001-06-27 23:38:11 +0000310 }
311 }
312
Chris Lattner71cbd422002-05-22 17:17:27 +0000313 if (DebugFlag) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000314 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
315 if (!BBExecutable.count(I))
Chris Lattnercccc5c72003-04-25 02:50:03 +0000316 std::cerr << "BasicBlock Dead:" << *I;
Chris Lattner71cbd422002-05-22 17:17:27 +0000317 }
Chris Lattner347389d2001-06-27 23:38:11 +0000318
Chris Lattnerc8e66542002-04-27 06:56:12 +0000319 // Iterate over all of the instructions in a function, replacing them with
Chris Lattner347389d2001-06-27 23:38:11 +0000320 // constants if we have found them to be of constant values.
321 //
322 bool MadeChanges = false;
Chris Lattner113f4f42002-06-25 16:13:24 +0000323 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
Chris Lattner60a65912002-02-12 21:07:25 +0000324 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000325 Instruction &Inst = *BI;
326 InstVal &IV = ValueState[&Inst];
Chris Lattner60a65912002-02-12 21:07:25 +0000327 if (IV.isConstant()) {
328 Constant *Const = IV.getConstant();
Chris Lattnercccc5c72003-04-25 02:50:03 +0000329 DEBUG(std::cerr << "Constant: " << Const << " = " << Inst);
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000330
Chris Lattner60a65912002-02-12 21:07:25 +0000331 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattner113f4f42002-06-25 16:13:24 +0000332 Inst.replaceAllUsesWith(Const);
Chris Lattner347389d2001-06-27 23:38:11 +0000333
Chris Lattner5364d1a2002-05-02 20:32:51 +0000334 // Remove the operator from the list of definitions... and delete it.
Chris Lattner113f4f42002-06-25 16:13:24 +0000335 BI = BB->getInstList().erase(BI);
Chris Lattner347389d2001-06-27 23:38:11 +0000336
Chris Lattner60a65912002-02-12 21:07:25 +0000337 // Hey, we just changed something!
338 MadeChanges = true;
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000339 ++NumInstRemoved;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000340 } else {
341 ++BI;
Chris Lattner60a65912002-02-12 21:07:25 +0000342 }
Chris Lattner347389d2001-06-27 23:38:11 +0000343 }
Chris Lattner347389d2001-06-27 23:38:11 +0000344
Chris Lattner13b52e72002-05-02 21:18:01 +0000345 // Reset state so that the next invocation will have empty data structures
Chris Lattner7d325382002-04-29 21:26:08 +0000346 BBExecutable.clear();
347 ValueState.clear();
Chris Lattner669c6cf2002-11-04 02:54:22 +0000348 std::vector<Instruction*>().swap(InstWorkList);
349 std::vector<BasicBlock*>().swap(BBWorkList);
Chris Lattner7d325382002-04-29 21:26:08 +0000350
Chris Lattnerdae05dc2001-09-07 16:43:22 +0000351 return MadeChanges;
Chris Lattner347389d2001-06-27 23:38:11 +0000352}
353
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000354
355// getFeasibleSuccessors - Return a vector of booleans to indicate which
356// successors are reachable from a given terminator instruction.
357//
Chris Lattner113f4f42002-06-25 16:13:24 +0000358void SCCP::getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000359 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000360 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000361 if (BI->isUnconditional()) {
362 Succs[0] = true;
363 } else {
364 InstVal &BCValue = getValueState(BI->getCondition());
365 if (BCValue.isOverdefined()) {
366 // Overdefined condition variables mean the branch could go either way.
367 Succs[0] = Succs[1] = true;
368 } else if (BCValue.isConstant()) {
369 // Constant condition variables mean the branch can only go a single way
370 Succs[BCValue.getConstant() == ConstantBool::False] = true;
371 }
372 }
Chris Lattner113f4f42002-06-25 16:13:24 +0000373 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000374 // Invoke instructions successors are always executable.
375 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000376 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000377 InstVal &SCValue = getValueState(SI->getCondition());
378 if (SCValue.isOverdefined()) { // Overdefined condition?
379 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000380 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000381 } else if (SCValue.isConstant()) {
382 Constant *CPV = SCValue.getConstant();
383 // Make sure to skip the "default value" which isn't a value
384 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
385 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
386 Succs[i] = true;
387 return;
388 }
389 }
390
391 // Constant value not equal to any of the branches... must execute
392 // default branch then...
393 Succs[0] = true;
394 }
395 } else {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000396 std::cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner113f4f42002-06-25 16:13:24 +0000397 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000398 }
399}
400
401
Chris Lattner13b52e72002-05-02 21:18:01 +0000402// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
403// block to the 'To' basic block is currently feasible...
404//
405bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
406 assert(BBExecutable.count(To) && "Dest should always be alive!");
407
408 // Make sure the source basic block is executable!!
409 if (!BBExecutable.count(From)) return false;
410
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000411 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000412 TerminatorInst *TI = From->getTerminator();
413 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
414 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000415 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000416 else {
417 InstVal &BCValue = getValueState(BI->getCondition());
418 if (BCValue.isOverdefined()) {
419 // Overdefined condition variables mean the branch could go either way.
420 return true;
421 } else if (BCValue.isConstant()) {
422 // Constant condition variables mean the branch can only go a single way
423 return BI->getSuccessor(BCValue.getConstant() ==
424 ConstantBool::False) == To;
425 }
426 return false;
427 }
428 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
429 // Invoke instructions successors are always executable.
430 return true;
431 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
432 InstVal &SCValue = getValueState(SI->getCondition());
433 if (SCValue.isOverdefined()) { // Overdefined condition?
434 // All destinations are executable!
435 return true;
436 } else if (SCValue.isConstant()) {
437 Constant *CPV = SCValue.getConstant();
438 // Make sure to skip the "default value" which isn't a value
439 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
440 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
441 return SI->getSuccessor(i) == To;
442
443 // Constant value not equal to any of the branches... must execute
444 // default branch then...
445 return SI->getDefaultDest() == To;
446 }
447 return false;
448 } else {
449 std::cerr << "Unknown terminator instruction: " << *TI;
450 abort();
451 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000452}
Chris Lattner347389d2001-06-27 23:38:11 +0000453
Chris Lattner6e560792002-04-18 15:13:15 +0000454// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000455// operand made a transition, or the instruction is newly executable. Change
456// the value type of I to reflect these changes if appropriate. This method
457// makes sure to do the following actions:
458//
459// 1. If a phi node merges two constants in, and has conflicting value coming
460// from different branches, or if the PHI node merges in an overdefined
461// value, then the PHI node becomes overdefined.
462// 2. If a phi node merges only constants in, and they all agree on value, the
463// PHI node becomes a constant value equal to that.
464// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
465// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
466// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
467// 6. If a conditional branch has a value that is constant, make the selected
468// destination executable
469// 7. If a conditional branch has a value that is overdefined, make all
470// successors executable.
471//
Chris Lattner113f4f42002-06-25 16:13:24 +0000472void SCCP::visitPHINode(PHINode &PN) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000473 InstVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000474 if (PNIV.isOverdefined()) {
475 // There may be instructions using this PHI node that are not overdefined
476 // themselves. If so, make sure that they know that the PHI node operand
477 // changed.
478 std::multimap<PHINode*, Instruction*>::iterator I, E;
479 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
480 if (I != E) {
481 std::vector<Instruction*> Users;
482 Users.reserve(std::distance(I, E));
483 for (; I != E; ++I) Users.push_back(I->second);
484 while (!Users.empty()) {
485 visit(Users.back());
486 Users.pop_back();
487 }
488 }
489 return; // Quick exit
490 }
Chris Lattner347389d2001-06-27 23:38:11 +0000491
Chris Lattner6e560792002-04-18 15:13:15 +0000492 // Look at all of the executable operands of the PHI node. If any of them
493 // are overdefined, the PHI becomes overdefined as well. If they are all
494 // constant, and they agree with each other, the PHI becomes the identical
495 // constant. If they are constant and don't agree, the PHI is overdefined.
496 // If there are no executable operands, the PHI remains undefined.
497 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000498 Constant *OperandVal = 0;
499 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
500 InstVal &IV = getValueState(PN.getIncomingValue(i));
501 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000502
Chris Lattner113f4f42002-06-25 16:13:24 +0000503 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000504 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000505 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000506 return;
507 }
508
Chris Lattnercccc5c72003-04-25 02:50:03 +0000509 if (OperandVal == 0) { // Grab the first value...
510 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000511 } else { // Another value is being merged in!
512 // There is already a reachable operand. If we conflict with it,
513 // then the PHI node becomes overdefined. If we agree with it, we
514 // can continue on.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000515
Chris Lattner6e560792002-04-18 15:13:15 +0000516 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000517 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000518 // Yes there is. This means the PHI node is not constant.
519 // You must be overdefined poor PHI.
520 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000521 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000522 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000523 }
Chris Lattner347389d2001-06-27 23:38:11 +0000524 }
525 }
Chris Lattner347389d2001-06-27 23:38:11 +0000526 }
527
Chris Lattner6e560792002-04-18 15:13:15 +0000528 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000529 // arguments that agree with each other(and OperandVal is the constant) or
530 // OperandVal is null because there are no defined incoming arguments. If
531 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000532 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000533 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000534 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000535}
536
Chris Lattner113f4f42002-06-25 16:13:24 +0000537void SCCP::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000538 std::vector<bool> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000539 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000540
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000541 BasicBlock *BB = TI.getParent();
542
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000543 // Mark all feasible successors executable...
544 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000545 if (SuccFeasible[i])
546 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000547}
548
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000549void SCCP::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000550 Value *V = I.getOperand(0);
Chris Lattner6e560792002-04-18 15:13:15 +0000551 InstVal &VState = getValueState(V);
552 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000553 markOverdefined(&I);
Misha Brukman632df282002-10-29 23:06:16 +0000554 } else if (VState.isConstant()) { // Propagate constant value
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000555 Constant *Result =
556 ConstantFoldCastInstruction(VState.getConstant(), I.getType());
Chris Lattner6e560792002-04-18 15:13:15 +0000557
Chris Lattner7324f7c2003-10-08 16:21:03 +0000558 if (Result) // If this instruction constant folds!
Chris Lattner113f4f42002-06-25 16:13:24 +0000559 markConstant(&I, Result);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000560 else
Chris Lattner113f4f42002-06-25 16:13:24 +0000561 markOverdefined(&I); // Don't know how to fold this instruction. :(
Chris Lattner6e560792002-04-18 15:13:15 +0000562 }
563}
564
565// Handle BinaryOperators and Shift Instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000566void SCCP::visitBinaryOperator(Instruction &I) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000567 InstVal &IV = ValueState[&I];
568 if (IV.isOverdefined()) return;
569
Chris Lattner113f4f42002-06-25 16:13:24 +0000570 InstVal &V1State = getValueState(I.getOperand(0));
571 InstVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000572
Chris Lattner6e560792002-04-18 15:13:15 +0000573 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000574 // If both operands are PHI nodes, it is possible that this instruction has
575 // a constant value, despite the fact that the PHI node doesn't. Check for
576 // this condition now.
577 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
578 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
579 if (PN1->getParent() == PN2->getParent()) {
580 // Since the two PHI nodes are in the same basic block, they must have
581 // entries for the same predecessors. Walk the predecessor list, and
582 // if all of the incoming values are constants, and the result of
583 // evaluating this expression with all incoming value pairs is the
584 // same, then this expression is a constant even though the PHI node
585 // is not a constant!
586 InstVal Result;
587 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
588 InstVal &In1 = getValueState(PN1->getIncomingValue(i));
589 BasicBlock *InBlock = PN1->getIncomingBlock(i);
590 InstVal &In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
591
592 if (In1.isOverdefined() || In2.isOverdefined()) {
593 Result.markOverdefined();
594 break; // Cannot fold this operation over the PHI nodes!
595 } else if (In1.isConstant() && In2.isConstant()) {
596 Constant *Val = 0;
597 if (isa<BinaryOperator>(I))
598 Val = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
599 In2.getConstant());
600 else {
601 assert(isa<ShiftInst>(I) &&
602 "Can only handle binops and shifts here!");
603 Val = ConstantExpr::getShift(I.getOpcode(), In1.getConstant(),
604 In2.getConstant());
605 }
606 if (Result.isUndefined())
607 Result.markConstant(Val);
608 else if (Result.isConstant() && Result.getConstant() != Val) {
609 Result.markOverdefined();
610 break;
611 }
612 }
613 }
614
615 // If we found a constant value here, then we know the instruction is
616 // constant despite the fact that the PHI nodes are overdefined.
617 if (Result.isConstant()) {
618 markConstant(IV, &I, Result.getConstant());
619 // Remember that this instruction is virtually using the PHI node
620 // operands.
621 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
622 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
623 return;
624 } else if (Result.isUndefined()) {
625 return;
626 }
627
628 // Okay, this really is overdefined now. Since we might have
629 // speculatively thought that this was not overdefined before, and
630 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
631 // make sure to clean out any entries that we put there, for
632 // efficiency.
633 std::multimap<PHINode*, Instruction*>::iterator It, E;
634 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
635 while (It != E) {
636 if (It->second == &I) {
637 UsersOfOverdefinedPHIs.erase(It++);
638 } else
639 ++It;
640 }
641 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
642 while (It != E) {
643 if (It->second == &I) {
644 UsersOfOverdefinedPHIs.erase(It++);
645 } else
646 ++It;
647 }
648 }
649
650 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000651 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner940daed2002-05-06 03:01:37 +0000652 Constant *Result = 0;
653 if (isa<BinaryOperator>(I))
Chris Lattner05fe6842004-01-12 03:57:30 +0000654 Result = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
655 V2State.getConstant());
656 else {
657 assert (isa<ShiftInst>(I) && "Can only handle binops and shifts here!");
658 Result = ConstantExpr::getShift(I.getOpcode(), V1State.getConstant(),
659 V2State.getConstant());
660 }
661
662 markConstant(IV, &I, Result); // This instruction constant folds!
Chris Lattner6e560792002-04-18 15:13:15 +0000663 }
664}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000665
666// Handle getelementptr instructions... if all operands are constants then we
667// can turn this into a getelementptr ConstantExpr.
668//
669void SCCP::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner49f74522004-01-12 04:29:41 +0000670 InstVal &IV = ValueState[&I];
671 if (IV.isOverdefined()) return;
672
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000673 std::vector<Constant*> Operands;
674 Operands.reserve(I.getNumOperands());
675
676 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
677 InstVal &State = getValueState(I.getOperand(i));
678 if (State.isUndefined())
679 return; // Operands are not resolved yet...
680 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +0000681 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000682 return;
683 }
684 assert(State.isConstant() && "Unknown state!");
685 Operands.push_back(State.getConstant());
686 }
687
688 Constant *Ptr = Operands[0];
689 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
690
Chris Lattner49f74522004-01-12 04:29:41 +0000691 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000692}
Brian Gaeke960707c2003-11-11 22:41:34 +0000693
Chris Lattner49f74522004-01-12 04:29:41 +0000694/// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
695/// return the constant value being addressed by the constant expression, or
696/// null if something is funny.
697///
698static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
699 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
700 return 0; // Do not allow stepping over the value!
701
702 // Loop over all of the operands, tracking down which value we are
703 // addressing...
704 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
705 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
706 ConstantStruct *CS = cast<ConstantStruct>(C);
707 if (CU->getValue() >= CS->getValues().size()) return 0;
708 C = cast<Constant>(CS->getValues()[CU->getValue()]);
709 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
710 ConstantArray *CA = cast<ConstantArray>(C);
711 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
712 C = cast<Constant>(CA->getValues()[CS->getValue()]);
713 } else
714 return 0;
715 return C;
716}
717
718// Handle load instructions. If the operand is a constant pointer to a constant
719// global, we can replace the load with the loaded constant value!
720void SCCP::visitLoadInst(LoadInst &I) {
721 InstVal &IV = ValueState[&I];
722 if (IV.isOverdefined()) return;
723
724 InstVal &PtrVal = getValueState(I.getOperand(0));
725 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
726 if (PtrVal.isConstant() && !I.isVolatile()) {
727 Value *Ptr = PtrVal.getConstant();
728 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr))
729 Ptr = CPR->getValue();
730
731 // Transform load (constant global) into the value loaded.
732 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr))
733 if (GV->isConstant() && !GV->isExternal()) {
734 markConstant(IV, &I, GV->getInitializer());
735 return;
736 }
737
738 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
739 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
740 if (CE->getOpcode() == Instruction::GetElementPtr)
741 if (ConstantPointerRef *G
742 = dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
743 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
744 if (GV->isConstant() && !GV->isExternal())
745 if (Constant *V =
746 GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
747 markConstant(IV, &I, V);
748 return;
749 }
750 }
751
752 // Otherwise we cannot say for certain what value this load will produce.
753 // Bail out.
754 markOverdefined(IV, &I);
755}