blob: 4e5e5156bb76d6cf9830392be31ad7f8f5ad1b56 [file] [log] [blame]
Misha Brukman82c89b92003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
John Criswellb576c942003-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 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 Lattner022103b2002-05-07 20:03:00 +000024#include "llvm/Transforms/Scalar.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000025#include "llvm/Constants.h"
Chris Lattner79df7c02002-03-26 18:01:55 +000026#include "llvm/Function.h"
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +000027#include "llvm/GlobalVariable.h"
Chris Lattner9de28282003-04-25 02:50:03 +000028#include "llvm/Instructions.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000029#include "llvm/Pass.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000030#include "llvm/Type.h"
Chris Lattner2a632552002-04-18 15:13:15 +000031#include "llvm/Support/InstVisitor.h"
Chris Lattner6806f562003-08-01 22:15:03 +000032#include "Support/Debug.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000033#include "Support/Statistic.h"
Chris Lattner6806f562003-08-01 22:15:03 +000034#include "Support/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000035#include <algorithm>
Chris Lattner138a1242001-06-27 23:38:11 +000036#include <set>
Chris Lattnerd7456022004-01-09 06:02:20 +000037using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000038
Chris Lattner138a1242001-06-27 23:38:11 +000039// InstVal class - This class represents the different lattice values that an
Chris Lattnerf57b8452002-04-27 06:56:12 +000040// instruction may occupy. It is a simple class with value semantics.
Chris Lattner138a1242001-06-27 23:38:11 +000041//
Chris Lattner0dbfc052002-04-29 21:26:08 +000042namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000043 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
44
Chris Lattner138a1242001-06-27 23:38:11 +000045class InstVal {
46 enum {
Chris Lattnere9bb2df2001-12-03 22:26:30 +000047 undefined, // This instruction has no known value
48 constant, // This instruction has a constant value
Chris Lattnere9bb2df2001-12-03 22:26:30 +000049 overdefined // This instruction has an unknown value
50 } LatticeValue; // The current lattice position
51 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner138a1242001-06-27 23:38:11 +000052public:
Chris Lattnere9bb2df2001-12-03 22:26:30 +000053 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner138a1242001-06-27 23:38:11 +000054
55 // markOverdefined - Return true if this is a new status to be in...
56 inline bool markOverdefined() {
Chris Lattnere9bb2df2001-12-03 22:26:30 +000057 if (LatticeValue != overdefined) {
58 LatticeValue = overdefined;
Chris Lattner138a1242001-06-27 23:38:11 +000059 return true;
60 }
61 return false;
62 }
63
64 // markConstant - Return true if this is a new status for us...
Chris Lattnere9bb2df2001-12-03 22:26:30 +000065 inline bool markConstant(Constant *V) {
66 if (LatticeValue != constant) {
67 LatticeValue = constant;
Chris Lattner138a1242001-06-27 23:38:11 +000068 ConstantVal = V;
69 return true;
70 } else {
Chris Lattnerb70d82f2001-09-07 16:43:22 +000071 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner138a1242001-06-27 23:38:11 +000072 }
73 return false;
74 }
75
Chris Lattnere9bb2df2001-12-03 22:26:30 +000076 inline bool isUndefined() const { return LatticeValue == undefined; }
77 inline bool isConstant() const { return LatticeValue == constant; }
78 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner138a1242001-06-27 23:38:11 +000079
Chris Lattner1daee8b2004-01-12 03:57:30 +000080 inline Constant *getConstant() const {
81 assert(isConstant() && "Cannot get the constant of a non-constant!");
82 return ConstantVal;
83 }
Chris Lattner138a1242001-06-27 23:38:11 +000084};
85
Chris Lattner0dbfc052002-04-29 21:26:08 +000086} // end anonymous namespace
Chris Lattner138a1242001-06-27 23:38:11 +000087
88
89//===----------------------------------------------------------------------===//
90// SCCP Class
91//
Misha Brukman82c89b92003-05-20 21:01:22 +000092// This class does all of the work of Sparse Conditional Constant Propagation.
Chris Lattner138a1242001-06-27 23:38:11 +000093//
Chris Lattner0dbfc052002-04-29 21:26:08 +000094namespace {
95class SCCP : public FunctionPass, public InstVisitor<SCCP> {
Chris Lattner697954c2002-01-20 22:54:45 +000096 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
97 std::map<Value*, InstVal> ValueState; // The state each value is in...
Chris Lattner138a1242001-06-27 23:38:11 +000098
Chris Lattner071d0ad2002-05-07 04:29:32 +000099 std::vector<Instruction*> InstWorkList;// The instruction work list
Chris Lattner697954c2002-01-20 22:54:45 +0000100 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000101
Chris Lattner1daee8b2004-01-12 03:57:30 +0000102 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
103 /// overdefined, despite the fact that the PHI node is overdefined.
104 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
105
Chris Lattner16b18fd2003-10-08 16:55:34 +0000106 /// KnownFeasibleEdges - Entries in this set are edges which have already had
107 /// PHI nodes retriggered.
108 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
109 std::set<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000110public:
111
Misha Brukman82c89b92003-05-20 21:01:22 +0000112 // runOnFunction - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner0dbfc052002-04-29 21:26:08 +0000113 // and return true if the function was modified.
114 //
Chris Lattner7e708292002-06-25 16:13:24 +0000115 bool runOnFunction(Function &F);
Chris Lattner0dbfc052002-04-29 21:26:08 +0000116
117 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnercb2610e2002-10-21 20:00:28 +0000118 AU.setPreservesCFG();
Chris Lattner0dbfc052002-04-29 21:26:08 +0000119 }
120
Chris Lattner138a1242001-06-27 23:38:11 +0000121
122 //===--------------------------------------------------------------------===//
123 // The implementation of this class
124 //
125private:
Chris Lattner2a632552002-04-18 15:13:15 +0000126 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
Chris Lattner138a1242001-06-27 23:38:11 +0000127
128 // markValueOverdefined - Make a value be marked as "constant". If the value
129 // is not already a constant, add it to the instruction work list so that
130 // the users of the instruction are updated later.
131 //
Chris Lattner3d405b02003-10-08 16:21:03 +0000132 inline void markConstant(InstVal &IV, Instruction *I, Constant *C) {
133 if (IV.markConstant(C)) {
134 DEBUG(std::cerr << "markConstant: " << *C << ": " << *I);
Chris Lattner071d0ad2002-05-07 04:29:32 +0000135 InstWorkList.push_back(I);
Chris Lattner138a1242001-06-27 23:38:11 +0000136 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000137 }
138 inline void markConstant(Instruction *I, Constant *C) {
139 markConstant(ValueState[I], I, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000140 }
141
142 // markValueOverdefined - Make a value be marked as "overdefined". If the
143 // value is not already overdefined, add it to the instruction work list so
144 // that the users of the instruction are updated later.
145 //
Chris Lattner3d405b02003-10-08 16:21:03 +0000146 inline void markOverdefined(InstVal &IV, Instruction *I) {
147 if (IV.markOverdefined()) {
148 DEBUG(std::cerr << "markOverdefined: " << *I);
149 InstWorkList.push_back(I); // Only instructions go on the work list
Chris Lattner138a1242001-06-27 23:38:11 +0000150 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000151 }
152 inline void markOverdefined(Instruction *I) {
153 markOverdefined(ValueState[I], I);
Chris Lattner138a1242001-06-27 23:38:11 +0000154 }
155
156 // getValueState - Return the InstVal object that corresponds to the value.
Misha Brukman5560c9d2003-08-18 14:43:39 +0000157 // This function is necessary because not all values should start out in the
Chris Lattner73e21422002-04-09 19:48:49 +0000158 // underdefined state... Argument's should be overdefined, and
Chris Lattner79df7c02002-03-26 18:01:55 +0000159 // constants should be marked as constants. If a value is not known to be an
Chris Lattner138a1242001-06-27 23:38:11 +0000160 // Instruction object, then use this accessor to get its value from the map.
161 //
162 inline InstVal &getValueState(Value *V) {
Chris Lattner697954c2002-01-20 22:54:45 +0000163 std::map<Value*, InstVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000164 if (I != ValueState.end()) return I->second; // Common case, in the map
165
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000166 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
Chris Lattner138a1242001-06-27 23:38:11 +0000167 ValueState[CPV].markConstant(CPV);
Chris Lattner73e21422002-04-09 19:48:49 +0000168 } else if (isa<Argument>(V)) { // Arguments are overdefined
Chris Lattner138a1242001-06-27 23:38:11 +0000169 ValueState[V].markOverdefined();
Chris Lattner2a88bb72002-08-30 23:39:00 +0000170 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
171 // The address of a global is a constant...
172 ValueState[V].markConstant(ConstantPointerRef::get(GV));
173 }
Chris Lattner138a1242001-06-27 23:38:11 +0000174 // All others are underdefined by default...
175 return ValueState[V];
176 }
177
Chris Lattner16b18fd2003-10-08 16:55:34 +0000178 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner138a1242001-06-27 23:38:11 +0000179 // work list if it is not already executable...
180 //
Chris Lattner16b18fd2003-10-08 16:55:34 +0000181 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
182 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
183 return; // This edge is already known to be executable!
184
185 if (BBExecutable.count(Dest)) {
186 DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
187 << " -> " << Dest->getName() << "\n");
188
189 // The destination is already executable, but we just made an edge
Chris Lattner929c6fb2003-10-08 16:56:11 +0000190 // feasible that wasn't before. Revisit the PHI nodes in the block
191 // because they have potentially new operands.
Chris Lattner16b18fd2003-10-08 16:55:34 +0000192 for (BasicBlock::iterator I = Dest->begin();
Chris Lattner9de28282003-04-25 02:50:03 +0000193 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattnerbceb2b02003-04-25 03:35:10 +0000194 visitPHINode(*PN);
Chris Lattner9de28282003-04-25 02:50:03 +0000195
196 } else {
Chris Lattner16b18fd2003-10-08 16:55:34 +0000197 DEBUG(std::cerr << "Marking Block Executable: " << Dest->getName()<<"\n");
198 BBExecutable.insert(Dest); // Basic block is executable!
199 BBWorkList.push_back(Dest); // Add the block to the work list!
Chris Lattner9de28282003-04-25 02:50:03 +0000200 }
Chris Lattner138a1242001-06-27 23:38:11 +0000201 }
202
Chris Lattner138a1242001-06-27 23:38:11 +0000203
Chris Lattner2a632552002-04-18 15:13:15 +0000204 // visit implementations - Something changed in this instruction... Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000205 // operand made a transition, or the instruction is newly executable. Change
206 // the value type of I to reflect these changes if appropriate.
207 //
Chris Lattner7e708292002-06-25 16:13:24 +0000208 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000209
210 // Terminators
Chris Lattner7e708292002-06-25 16:13:24 +0000211 void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
212 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000213
Chris Lattnerb8047602002-08-14 17:53:45 +0000214 void visitCastInst(CastInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000215 void visitBinaryOperator(Instruction &I);
216 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000217
218 // Instructions that cannot be folded away...
Chris Lattner7e708292002-06-25 16:13:24 +0000219 void visitStoreInst (Instruction &I) { /*returns void*/ }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000220 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000221 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000222 void visitCallInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner99b28e62003-08-27 01:08:35 +0000223 void visitInvokeInst (TerminatorInst &I) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000224 if (I.getType() != Type::VoidTy) markOverdefined(&I);
Chris Lattner99b28e62003-08-27 01:08:35 +0000225 visitTerminatorInst(I);
226 }
Chris Lattner36143fc2003-09-08 18:54:55 +0000227 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner7e708292002-06-25 16:13:24 +0000228 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000229 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
230 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner7e708292002-06-25 16:13:24 +0000231 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner2a632552002-04-18 15:13:15 +0000232
Chris Lattner7e708292002-06-25 16:13:24 +0000233 void visitInstruction(Instruction &I) {
Chris Lattner2a632552002-04-18 15:13:15 +0000234 // If a new instruction is added to LLVM that we don't handle...
Chris Lattner9de28282003-04-25 02:50:03 +0000235 std::cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000236 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000237 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000238
Chris Lattnerb9a66342002-05-02 21:44:00 +0000239 // getFeasibleSuccessors - Return a vector of booleans to indicate which
240 // successors are reachable from a given terminator instruction.
241 //
Chris Lattner7e708292002-06-25 16:13:24 +0000242 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
Chris Lattnerb9a66342002-05-02 21:44:00 +0000243
Chris Lattner59f0ce22002-05-02 21:18:01 +0000244 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
245 // block to the 'To' basic block is currently feasible...
246 //
247 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
248
Chris Lattnercb056de2001-06-29 23:56:23 +0000249 // OperandChangedState - This method is invoked on all of the users of an
250 // instruction that was just changed state somehow.... Based on this
251 // information, we need to update the specified user of this instruction.
252 //
Chris Lattner59f0ce22002-05-02 21:18:01 +0000253 void OperandChangedState(User *U) {
254 // Only instructions use other variable values!
Chris Lattner7e708292002-06-25 16:13:24 +0000255 Instruction &I = cast<Instruction>(*U);
Chris Lattner9de28282003-04-25 02:50:03 +0000256 if (BBExecutable.count(I.getParent())) // Inst is executable?
257 visit(I);
Chris Lattner59f0ce22002-05-02 21:18:01 +0000258 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000259};
Chris Lattnerf6293092002-07-23 18:06:35 +0000260
Chris Lattner9de28282003-04-25 02:50:03 +0000261 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner0dbfc052002-04-29 21:26:08 +0000262} // end anonymous namespace
263
264
265// createSCCPPass - This is the public interface to this file...
Chris Lattnerd7456022004-01-09 06:02:20 +0000266Pass *llvm::createSCCPPass() {
Chris Lattner0dbfc052002-04-29 21:26:08 +0000267 return new SCCP();
268}
269
Chris Lattner138a1242001-06-27 23:38:11 +0000270
Chris Lattner138a1242001-06-27 23:38:11 +0000271//===----------------------------------------------------------------------===//
272// SCCP Class Implementation
273
274
Misha Brukman82c89b92003-05-20 21:01:22 +0000275// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner0dbfc052002-04-29 21:26:08 +0000276// and return true if the function was modified.
Chris Lattner138a1242001-06-27 23:38:11 +0000277//
Chris Lattner7e708292002-06-25 16:13:24 +0000278bool SCCP::runOnFunction(Function &F) {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000279 // Mark the first block of the function as being executable...
Chris Lattner16b18fd2003-10-08 16:55:34 +0000280 BBExecutable.insert(F.begin()); // Basic block is executable!
281 BBWorkList.push_back(F.begin()); // Add the block to the work list!
Chris Lattner138a1242001-06-27 23:38:11 +0000282
283 // Process the work lists until their are empty!
284 while (!BBWorkList.empty() || !InstWorkList.empty()) {
285 // Process the instruction work list...
286 while (!InstWorkList.empty()) {
Chris Lattner071d0ad2002-05-07 04:29:32 +0000287 Instruction *I = InstWorkList.back();
288 InstWorkList.pop_back();
Chris Lattner138a1242001-06-27 23:38:11 +0000289
Chris Lattner9de28282003-04-25 02:50:03 +0000290 DEBUG(std::cerr << "\nPopped off I-WL: " << I);
Chris Lattner138a1242001-06-27 23:38:11 +0000291
292 // "I" got into the work list because it either made the transition from
293 // bottom to constant, or to Overdefined.
294 //
295 // Update all of the users of this instruction's value...
296 //
297 for_each(I->use_begin(), I->use_end(),
298 bind_obj(this, &SCCP::OperandChangedState));
299 }
300
301 // Process the basic block work list...
302 while (!BBWorkList.empty()) {
303 BasicBlock *BB = BBWorkList.back();
304 BBWorkList.pop_back();
305
Chris Lattner9de28282003-04-25 02:50:03 +0000306 DEBUG(std::cerr << "\nPopped off BBWL: " << BB);
Chris Lattner138a1242001-06-27 23:38:11 +0000307
Chris Lattner2a632552002-04-18 15:13:15 +0000308 // Notify all instructions in this basic block that they are newly
309 // executable.
310 visit(BB);
Chris Lattner138a1242001-06-27 23:38:11 +0000311 }
312 }
313
Chris Lattnerf016ea42002-05-22 17:17:27 +0000314 if (DebugFlag) {
Chris Lattner7e708292002-06-25 16:13:24 +0000315 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
316 if (!BBExecutable.count(I))
Chris Lattner9de28282003-04-25 02:50:03 +0000317 std::cerr << "BasicBlock Dead:" << *I;
Chris Lattnerf016ea42002-05-22 17:17:27 +0000318 }
Chris Lattner138a1242001-06-27 23:38:11 +0000319
Chris Lattnerf57b8452002-04-27 06:56:12 +0000320 // Iterate over all of the instructions in a function, replacing them with
Chris Lattner138a1242001-06-27 23:38:11 +0000321 // constants if we have found them to be of constant values.
322 //
323 bool MadeChanges = false;
Chris Lattner7e708292002-06-25 16:13:24 +0000324 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
Chris Lattner221d6882002-02-12 21:07:25 +0000325 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattner7e708292002-06-25 16:13:24 +0000326 Instruction &Inst = *BI;
327 InstVal &IV = ValueState[&Inst];
Chris Lattner221d6882002-02-12 21:07:25 +0000328 if (IV.isConstant()) {
329 Constant *Const = IV.getConstant();
Chris Lattner9de28282003-04-25 02:50:03 +0000330 DEBUG(std::cerr << "Constant: " << Const << " = " << Inst);
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000331
Chris Lattner221d6882002-02-12 21:07:25 +0000332 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattner7e708292002-06-25 16:13:24 +0000333 Inst.replaceAllUsesWith(Const);
Chris Lattner138a1242001-06-27 23:38:11 +0000334
Chris Lattner0e9c5152002-05-02 20:32:51 +0000335 // Remove the operator from the list of definitions... and delete it.
Chris Lattner7e708292002-06-25 16:13:24 +0000336 BI = BB->getInstList().erase(BI);
Chris Lattner138a1242001-06-27 23:38:11 +0000337
Chris Lattner221d6882002-02-12 21:07:25 +0000338 // Hey, we just changed something!
339 MadeChanges = true;
Chris Lattner3dec1f22002-05-10 15:38:35 +0000340 ++NumInstRemoved;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000341 } else {
342 ++BI;
Chris Lattner221d6882002-02-12 21:07:25 +0000343 }
Chris Lattner138a1242001-06-27 23:38:11 +0000344 }
Chris Lattner138a1242001-06-27 23:38:11 +0000345
Chris Lattner59f0ce22002-05-02 21:18:01 +0000346 // Reset state so that the next invocation will have empty data structures
Chris Lattner0dbfc052002-04-29 21:26:08 +0000347 BBExecutable.clear();
348 ValueState.clear();
Chris Lattneraf663462002-11-04 02:54:22 +0000349 std::vector<Instruction*>().swap(InstWorkList);
350 std::vector<BasicBlock*>().swap(BBWorkList);
Chris Lattner0dbfc052002-04-29 21:26:08 +0000351
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000352 return MadeChanges;
Chris Lattner138a1242001-06-27 23:38:11 +0000353}
354
Chris Lattnerb9a66342002-05-02 21:44:00 +0000355
356// getFeasibleSuccessors - Return a vector of booleans to indicate which
357// successors are reachable from a given terminator instruction.
358//
Chris Lattner7e708292002-06-25 16:13:24 +0000359void SCCP::getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000360 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000361 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000362 if (BI->isUnconditional()) {
363 Succs[0] = true;
364 } else {
365 InstVal &BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000366 if (BCValue.isOverdefined() ||
367 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
368 // Overdefined condition variables, and branches on unfoldable constant
369 // conditions, mean the branch could go either way.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000370 Succs[0] = Succs[1] = true;
371 } else if (BCValue.isConstant()) {
372 // Constant condition variables mean the branch can only go a single way
373 Succs[BCValue.getConstant() == ConstantBool::False] = true;
374 }
375 }
Chris Lattner7e708292002-06-25 16:13:24 +0000376 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000377 // Invoke instructions successors are always executable.
378 Succs[0] = Succs[1] = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000379 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000380 InstVal &SCValue = getValueState(SI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000381 if (SCValue.isOverdefined() || // Overdefined condition?
382 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000383 // All destinations are executable!
Chris Lattner7e708292002-06-25 16:13:24 +0000384 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerb9a66342002-05-02 21:44:00 +0000385 } else if (SCValue.isConstant()) {
386 Constant *CPV = SCValue.getConstant();
387 // Make sure to skip the "default value" which isn't a value
388 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
389 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
390 Succs[i] = true;
391 return;
392 }
393 }
394
395 // Constant value not equal to any of the branches... must execute
396 // default branch then...
397 Succs[0] = true;
398 }
399 } else {
Chris Lattner9de28282003-04-25 02:50:03 +0000400 std::cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner7e708292002-06-25 16:13:24 +0000401 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerb9a66342002-05-02 21:44:00 +0000402 }
403}
404
405
Chris Lattner59f0ce22002-05-02 21:18:01 +0000406// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
407// block to the 'To' basic block is currently feasible...
408//
409bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
410 assert(BBExecutable.count(To) && "Dest should always be alive!");
411
412 // Make sure the source basic block is executable!!
413 if (!BBExecutable.count(From)) return false;
414
Chris Lattnerb9a66342002-05-02 21:44:00 +0000415 // Check to make sure this edge itself is actually feasible now...
Chris Lattner7d275f42003-10-08 15:47:41 +0000416 TerminatorInst *TI = From->getTerminator();
417 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
418 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000419 return true;
Chris Lattner7d275f42003-10-08 15:47:41 +0000420 else {
421 InstVal &BCValue = getValueState(BI->getCondition());
422 if (BCValue.isOverdefined()) {
423 // Overdefined condition variables mean the branch could go either way.
424 return true;
425 } else if (BCValue.isConstant()) {
Chris Lattner84831642004-01-12 17:40:36 +0000426 // Not branching on an evaluatable constant?
427 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
428
Chris Lattner7d275f42003-10-08 15:47:41 +0000429 // Constant condition variables mean the branch can only go a single way
430 return BI->getSuccessor(BCValue.getConstant() ==
431 ConstantBool::False) == To;
432 }
433 return false;
434 }
435 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
436 // Invoke instructions successors are always executable.
437 return true;
438 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
439 InstVal &SCValue = getValueState(SI->getCondition());
440 if (SCValue.isOverdefined()) { // Overdefined condition?
441 // All destinations are executable!
442 return true;
443 } else if (SCValue.isConstant()) {
444 Constant *CPV = SCValue.getConstant();
Chris Lattner84831642004-01-12 17:40:36 +0000445 if (!isa<ConstantInt>(CPV))
446 return true; // not a foldable constant?
447
Chris Lattner7d275f42003-10-08 15:47:41 +0000448 // Make sure to skip the "default value" which isn't a value
449 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
450 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
451 return SI->getSuccessor(i) == To;
452
453 // Constant value not equal to any of the branches... must execute
454 // default branch then...
455 return SI->getDefaultDest() == To;
456 }
457 return false;
458 } else {
459 std::cerr << "Unknown terminator instruction: " << *TI;
460 abort();
461 }
Chris Lattner59f0ce22002-05-02 21:18:01 +0000462}
Chris Lattner138a1242001-06-27 23:38:11 +0000463
Chris Lattner2a632552002-04-18 15:13:15 +0000464// visit Implementations - Something changed in this instruction... Either an
Chris Lattner138a1242001-06-27 23:38:11 +0000465// operand made a transition, or the instruction is newly executable. Change
466// the value type of I to reflect these changes if appropriate. This method
467// makes sure to do the following actions:
468//
469// 1. If a phi node merges two constants in, and has conflicting value coming
470// from different branches, or if the PHI node merges in an overdefined
471// value, then the PHI node becomes overdefined.
472// 2. If a phi node merges only constants in, and they all agree on value, the
473// PHI node becomes a constant value equal to that.
474// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
475// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
476// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
477// 6. If a conditional branch has a value that is constant, make the selected
478// destination executable
479// 7. If a conditional branch has a value that is overdefined, make all
480// successors executable.
481//
Chris Lattner7e708292002-06-25 16:13:24 +0000482void SCCP::visitPHINode(PHINode &PN) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000483 InstVal &PNIV = getValueState(&PN);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000484 if (PNIV.isOverdefined()) {
485 // There may be instructions using this PHI node that are not overdefined
486 // themselves. If so, make sure that they know that the PHI node operand
487 // changed.
488 std::multimap<PHINode*, Instruction*>::iterator I, E;
489 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
490 if (I != E) {
491 std::vector<Instruction*> Users;
492 Users.reserve(std::distance(I, E));
493 for (; I != E; ++I) Users.push_back(I->second);
494 while (!Users.empty()) {
495 visit(Users.back());
496 Users.pop_back();
497 }
498 }
499 return; // Quick exit
500 }
Chris Lattner138a1242001-06-27 23:38:11 +0000501
Chris Lattner2a632552002-04-18 15:13:15 +0000502 // Look at all of the executable operands of the PHI node. If any of them
503 // are overdefined, the PHI becomes overdefined as well. If they are all
504 // constant, and they agree with each other, the PHI becomes the identical
505 // constant. If they are constant and don't agree, the PHI is overdefined.
506 // If there are no executable operands, the PHI remains undefined.
507 //
Chris Lattner9de28282003-04-25 02:50:03 +0000508 Constant *OperandVal = 0;
509 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
510 InstVal &IV = getValueState(PN.getIncomingValue(i));
511 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Chris Lattner9de28282003-04-25 02:50:03 +0000512
Chris Lattner7e708292002-06-25 16:13:24 +0000513 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner38b5ae42003-06-24 20:29:52 +0000514 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner3d405b02003-10-08 16:21:03 +0000515 markOverdefined(PNIV, &PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000516 return;
517 }
518
Chris Lattner9de28282003-04-25 02:50:03 +0000519 if (OperandVal == 0) { // Grab the first value...
520 OperandVal = IV.getConstant();
Chris Lattner2a632552002-04-18 15:13:15 +0000521 } else { // Another value is being merged in!
522 // There is already a reachable operand. If we conflict with it,
523 // then the PHI node becomes overdefined. If we agree with it, we
524 // can continue on.
Chris Lattner9de28282003-04-25 02:50:03 +0000525
Chris Lattner2a632552002-04-18 15:13:15 +0000526 // Check to see if there are two different constants merging...
Chris Lattner9de28282003-04-25 02:50:03 +0000527 if (IV.getConstant() != OperandVal) {
Chris Lattner2a632552002-04-18 15:13:15 +0000528 // Yes there is. This means the PHI node is not constant.
529 // You must be overdefined poor PHI.
530 //
Chris Lattner3d405b02003-10-08 16:21:03 +0000531 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner2a632552002-04-18 15:13:15 +0000532 return; // I'm done analyzing you
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000533 }
Chris Lattner138a1242001-06-27 23:38:11 +0000534 }
535 }
Chris Lattner138a1242001-06-27 23:38:11 +0000536 }
537
Chris Lattner2a632552002-04-18 15:13:15 +0000538 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000539 // arguments that agree with each other(and OperandVal is the constant) or
540 // OperandVal is null because there are no defined incoming arguments. If
541 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000542 //
Chris Lattner9de28282003-04-25 02:50:03 +0000543 if (OperandVal)
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000544 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000545}
546
Chris Lattner7e708292002-06-25 16:13:24 +0000547void SCCP::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner9de28282003-04-25 02:50:03 +0000548 std::vector<bool> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000549 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000550
Chris Lattner16b18fd2003-10-08 16:55:34 +0000551 BasicBlock *BB = TI.getParent();
552
Chris Lattnerb9a66342002-05-02 21:44:00 +0000553 // Mark all feasible successors executable...
554 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000555 if (SuccFeasible[i])
556 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000557}
558
Chris Lattnerb8047602002-08-14 17:53:45 +0000559void SCCP::visitCastInst(CastInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000560 Value *V = I.getOperand(0);
Chris Lattner2a632552002-04-18 15:13:15 +0000561 InstVal &VState = getValueState(V);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000562 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000563 markOverdefined(&I);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000564 else if (VState.isConstant()) // Propagate constant value
565 markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000566}
567
568// Handle BinaryOperators and Shift Instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000569void SCCP::visitBinaryOperator(Instruction &I) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000570 InstVal &IV = ValueState[&I];
571 if (IV.isOverdefined()) return;
572
Chris Lattner7e708292002-06-25 16:13:24 +0000573 InstVal &V1State = getValueState(I.getOperand(0));
574 InstVal &V2State = getValueState(I.getOperand(1));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000575
Chris Lattner2a632552002-04-18 15:13:15 +0000576 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000577 // If both operands are PHI nodes, it is possible that this instruction has
578 // a constant value, despite the fact that the PHI node doesn't. Check for
579 // this condition now.
580 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
581 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
582 if (PN1->getParent() == PN2->getParent()) {
583 // Since the two PHI nodes are in the same basic block, they must have
584 // entries for the same predecessors. Walk the predecessor list, and
585 // if all of the incoming values are constants, and the result of
586 // evaluating this expression with all incoming value pairs is the
587 // same, then this expression is a constant even though the PHI node
588 // is not a constant!
589 InstVal Result;
590 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
591 InstVal &In1 = getValueState(PN1->getIncomingValue(i));
592 BasicBlock *InBlock = PN1->getIncomingBlock(i);
593 InstVal &In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
594
595 if (In1.isOverdefined() || In2.isOverdefined()) {
596 Result.markOverdefined();
597 break; // Cannot fold this operation over the PHI nodes!
598 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000599 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
600 In2.getConstant());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000601 if (Result.isUndefined())
Chris Lattnerb16689b2004-01-12 19:08:43 +0000602 Result.markConstant(V);
603 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000604 Result.markOverdefined();
605 break;
606 }
607 }
608 }
609
610 // If we found a constant value here, then we know the instruction is
611 // constant despite the fact that the PHI nodes are overdefined.
612 if (Result.isConstant()) {
613 markConstant(IV, &I, Result.getConstant());
614 // Remember that this instruction is virtually using the PHI node
615 // operands.
616 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
617 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
618 return;
619 } else if (Result.isUndefined()) {
620 return;
621 }
622
623 // Okay, this really is overdefined now. Since we might have
624 // speculatively thought that this was not overdefined before, and
625 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
626 // make sure to clean out any entries that we put there, for
627 // efficiency.
628 std::multimap<PHINode*, Instruction*>::iterator It, E;
629 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
630 while (It != E) {
631 if (It->second == &I) {
632 UsersOfOverdefinedPHIs.erase(It++);
633 } else
634 ++It;
635 }
636 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
637 while (It != E) {
638 if (It->second == &I) {
639 UsersOfOverdefinedPHIs.erase(It++);
640 } else
641 ++It;
642 }
643 }
644
645 markOverdefined(IV, &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000646 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000647 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
648 V2State.getConstant()));
Chris Lattner2a632552002-04-18 15:13:15 +0000649 }
650}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000651
652// Handle getelementptr instructions... if all operands are constants then we
653// can turn this into a getelementptr ConstantExpr.
654//
655void SCCP::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000656 InstVal &IV = ValueState[&I];
657 if (IV.isOverdefined()) return;
658
Chris Lattner2a88bb72002-08-30 23:39:00 +0000659 std::vector<Constant*> Operands;
660 Operands.reserve(I.getNumOperands());
661
662 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
663 InstVal &State = getValueState(I.getOperand(i));
664 if (State.isUndefined())
665 return; // Operands are not resolved yet...
666 else if (State.isOverdefined()) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000667 markOverdefined(IV, &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000668 return;
669 }
670 assert(State.isConstant() && "Unknown state!");
671 Operands.push_back(State.getConstant());
672 }
673
674 Constant *Ptr = Operands[0];
675 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
676
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000677 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattner2a88bb72002-08-30 23:39:00 +0000678}
Brian Gaeked0fde302003-11-11 22:41:34 +0000679
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000680/// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
681/// return the constant value being addressed by the constant expression, or
682/// null if something is funny.
683///
684static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
685 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
686 return 0; // Do not allow stepping over the value!
687
688 // Loop over all of the operands, tracking down which value we are
689 // addressing...
690 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
691 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
692 ConstantStruct *CS = cast<ConstantStruct>(C);
693 if (CU->getValue() >= CS->getValues().size()) return 0;
694 C = cast<Constant>(CS->getValues()[CU->getValue()]);
695 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
696 ConstantArray *CA = cast<ConstantArray>(C);
697 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
698 C = cast<Constant>(CA->getValues()[CS->getValue()]);
699 } else
700 return 0;
701 return C;
702}
703
704// Handle load instructions. If the operand is a constant pointer to a constant
705// global, we can replace the load with the loaded constant value!
706void SCCP::visitLoadInst(LoadInst &I) {
707 InstVal &IV = ValueState[&I];
708 if (IV.isOverdefined()) return;
709
710 InstVal &PtrVal = getValueState(I.getOperand(0));
711 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
712 if (PtrVal.isConstant() && !I.isVolatile()) {
713 Value *Ptr = PtrVal.getConstant();
714 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr))
715 Ptr = CPR->getValue();
716
717 // Transform load (constant global) into the value loaded.
718 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr))
719 if (GV->isConstant() && !GV->isExternal()) {
720 markConstant(IV, &I, GV->getInitializer());
721 return;
722 }
723
724 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
725 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
726 if (CE->getOpcode() == Instruction::GetElementPtr)
727 if (ConstantPointerRef *G
728 = dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
729 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
730 if (GV->isConstant() && !GV->isExternal())
731 if (Constant *V =
732 GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
733 markConstant(IV, &I, V);
734 return;
735 }
736 }
737
738 // Otherwise we cannot say for certain what value this load will produce.
739 // Bail out.
740 markOverdefined(IV, &I);
741}