blob: ec2d368d72c0fd191daea1c264b7023478b28f6d [file] [log] [blame]
Misha Brukman82c89b92003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +00009//
Misha Brukman82c89b92003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner138a1242001-06-27 23:38:11 +000011//
12// Specifically, this:
13// * Assumes values are constant unless proven otherwise
14// * Assumes BasicBlocks are dead unless proven otherwise
15// * Proves values to be constant, and replaces them with constants
Chris Lattner2a88bb72002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner138a1242001-06-27 23:38:11 +000017//
18// Notice that:
19// * This pass has a habit of making definitions be dead. It is a good idea
20// to to run a DCE pass sometime after running this pass.
21//
22//===----------------------------------------------------------------------===//
23
Chris Lattneref36dfd2004-11-15 05:03:30 +000024#define DEBUG_TYPE "sccp"
Chris Lattner022103b2002-05-07 20:03:00 +000025#include "llvm/Transforms/Scalar.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000026#include "llvm/Transforms/IPO.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000027#include "llvm/Constants.h"
Chris Lattnerdd336d12004-12-11 05:15:59 +000028#include "llvm/DerivedTypes.h"
Chris Lattner9de28282003-04-25 02:50:03 +000029#include "llvm/Instructions.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000030#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000031#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000032#include "llvm/Transforms/Utils/Local.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000033#include "llvm/Support/CallSite.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000034#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/Support/Debug.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000036#include "llvm/Support/InstVisitor.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000037#include "llvm/ADT/DenseMap.h"
Chris Lattnercc56aad2007-02-02 20:57:39 +000038#include "llvm/ADT/SmallSet.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000039#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000040#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000042#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000043#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner0e5f4992006-12-19 21:40:18 +000046STATISTIC(NumInstRemoved, "Number of instructions removed");
47STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
48
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000049STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000050STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
51STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
53
Chris Lattner0dbfc052002-04-29 21:26:08 +000054namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000055/// LatticeVal class - This class represents the different lattice values that
56/// an LLVM value may occupy. It is a simple class with value semantics.
57///
Reid Spencer9133fe22007-02-05 23:32:05 +000058class VISIBILITY_HIDDEN LatticeVal {
Misha Brukmanfd939082005-04-21 23:48:37 +000059 enum {
Chris Lattner3bad2532006-12-20 06:21:33 +000060 /// undefined - This LLVM Value has no known value yet.
61 undefined,
62
63 /// constant - This LLVM Value has a specific constant value.
64 constant,
65
66 /// forcedconstant - This LLVM Value was thought to be undef until
67 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
68 /// with another (different) constant, it goes to overdefined, instead of
69 /// asserting.
70 forcedconstant,
71
72 /// overdefined - This instruction is not known to be constant, and we know
73 /// it has a value.
74 overdefined
75 } LatticeValue; // The current lattice position
76
Chris Lattnere9bb2df2001-12-03 22:26:30 +000077 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner138a1242001-06-27 23:38:11 +000078public:
Chris Lattneref36dfd2004-11-15 05:03:30 +000079 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000080
Chris Lattner138a1242001-06-27 23:38:11 +000081 // markOverdefined - Return true if this is a new status to be in...
82 inline bool markOverdefined() {
Chris Lattnere9bb2df2001-12-03 22:26:30 +000083 if (LatticeValue != overdefined) {
84 LatticeValue = overdefined;
Chris Lattner138a1242001-06-27 23:38:11 +000085 return true;
86 }
87 return false;
88 }
89
Chris Lattner3bad2532006-12-20 06:21:33 +000090 // markConstant - Return true if this is a new status for us.
Chris Lattnere9bb2df2001-12-03 22:26:30 +000091 inline bool markConstant(Constant *V) {
92 if (LatticeValue != constant) {
Chris Lattner3bad2532006-12-20 06:21:33 +000093 if (LatticeValue == undefined) {
94 LatticeValue = constant;
Jim Laskey52ab9042007-01-03 00:11:03 +000095 assert(V && "Marking constant with NULL");
Chris Lattner3bad2532006-12-20 06:21:33 +000096 ConstantVal = V;
97 } else {
98 assert(LatticeValue == forcedconstant &&
99 "Cannot move from overdefined to constant!");
100 // Stay at forcedconstant if the constant is the same.
101 if (V == ConstantVal) return false;
102
103 // Otherwise, we go to overdefined. Assumptions made based on the
104 // forced value are possibly wrong. Assuming this is another constant
105 // could expose a contradiction.
106 LatticeValue = overdefined;
107 }
Chris Lattner138a1242001-06-27 23:38:11 +0000108 return true;
109 } else {
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000110 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner138a1242001-06-27 23:38:11 +0000111 }
112 return false;
113 }
114
Chris Lattner3bad2532006-12-20 06:21:33 +0000115 inline void markForcedConstant(Constant *V) {
116 assert(LatticeValue == undefined && "Can't force a defined value!");
117 LatticeValue = forcedconstant;
118 ConstantVal = V;
119 }
120
121 inline bool isUndefined() const { return LatticeValue == undefined; }
122 inline bool isConstant() const {
123 return LatticeValue == constant || LatticeValue == forcedconstant;
124 }
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000125 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner138a1242001-06-27 23:38:11 +0000126
Chris Lattner1daee8b2004-01-12 03:57:30 +0000127 inline Constant *getConstant() const {
128 assert(isConstant() && "Cannot get the constant of a non-constant!");
129 return ConstantVal;
130 }
Chris Lattner138a1242001-06-27 23:38:11 +0000131};
132
Devang Patel7c490d42008-03-11 05:46:42 +0000133/// LatticeValIndex - LatticeVal and associated Index. This is used
134/// to track individual operand Lattice values for multi value ret instructions.
135class VISIBILITY_HIDDEN LatticeValIndexed {
136 public:
137 LatticeValIndexed(unsigned I = 0) { Index = I; }
138 LatticeVal &getLatticeVal() { return LV; }
139 unsigned getIndex() const { return Index; }
140
141 void setLatticeVal(LatticeVal &L) { LV = L; }
142 void setIndex(unsigned I) { Index = I; }
143
144 private:
145 LatticeVal LV;
146 unsigned Index;
147};
Chris Lattner138a1242001-06-27 23:38:11 +0000148//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000149//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000150/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
151/// Constant Propagation.
152///
153class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattnercc56aad2007-02-02 20:57:39 +0000154 SmallSet<BasicBlock*, 16> BBExecutable;// The basic blocks that are executable
Chris Lattnerc1ec7802007-02-02 22:36:16 +0000155 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000156
Chris Lattnerdd336d12004-12-11 05:15:59 +0000157 /// GlobalValue - If we are tracking any values for the contents of a global
158 /// variable, we keep a mapping from the constant accessor to the element of
159 /// the global, to the currently known value. If the value becomes
160 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000161 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000162
Devang Patel7c490d42008-03-11 05:46:42 +0000163 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000164 /// value out of a function, it will have an entry in this map, indicating
165 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000166 DenseMap<Function*, LatticeVal> TrackedRetVals;
167
168 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
169 /// that return multiple values.
170 std::multimap<Function*, LatticeValIndexed> TrackedMultipleRetVals;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000171
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000172 // The reason for two worklists is that overdefined is the lowest state
173 // on the lattice, and moving things to overdefined as fast as possible
174 // makes SCCP converge much faster.
175 // By having a separate worklist, we accomplish this because everything
176 // possibly overdefined will become overdefined at the soonest possible
177 // point.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000178 std::vector<Value*> OverdefinedInstWorkList;
179 std::vector<Value*> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000180
181
Chris Lattner697954c2002-01-20 22:54:45 +0000182 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000183
Chris Lattner1daee8b2004-01-12 03:57:30 +0000184 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
185 /// overdefined, despite the fact that the PHI node is overdefined.
186 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
187
Chris Lattner16b18fd2003-10-08 16:55:34 +0000188 /// KnownFeasibleEdges - Entries in this set are edges which have already had
189 /// PHI nodes retriggered.
190 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
191 std::set<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000192public:
193
Chris Lattner82bec2c2004-11-15 04:44:20 +0000194 /// MarkBlockExecutable - This method can be used by clients to mark all of
195 /// the blocks that are known to be intrinsically live in the processed unit.
196 void MarkBlockExecutable(BasicBlock *BB) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000197 DOUT << "Marking Block Executable: " << BB->getName() << "\n";
Chris Lattner82bec2c2004-11-15 04:44:20 +0000198 BBExecutable.insert(BB); // Basic block is executable!
199 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner0dbfc052002-04-29 21:26:08 +0000200 }
201
Chris Lattnerdd336d12004-12-11 05:15:59 +0000202 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000203 /// inform the SCCPSolver that it should track loads and stores to the
204 /// specified global variable if it can. This is only legal to call if
205 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000206 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
207 const Type *ElTy = GV->getType()->getElementType();
208 if (ElTy->isFirstClassType()) {
209 LatticeVal &IV = TrackedGlobals[GV];
210 if (!isa<UndefValue>(GV->getInitializer()))
211 IV.markConstant(GV->getInitializer());
212 }
213 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000214
215 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
216 /// and out of the specified function (which cannot have its address taken),
217 /// this method must be called.
218 void AddTrackedFunction(Function *F) {
219 assert(F->hasInternalLinkage() && "Can only track internal functions!");
220 // Add an entry, F -> undef.
Devang Patel7c490d42008-03-11 05:46:42 +0000221 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
222 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
223 TrackedMultipleRetVals.insert(std::pair<Function *, LatticeValIndexed>
224 (F, LatticeValIndexed(i)));
225 }
226 else
227 TrackedRetVals[F];
Chris Lattner59acc7d2004-12-10 08:02:06 +0000228 }
229
Chris Lattner82bec2c2004-11-15 04:44:20 +0000230 /// Solve - Solve for constants and executable blocks.
231 ///
232 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000233
Chris Lattner3bad2532006-12-20 06:21:33 +0000234 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000235 /// that branches on undef values cannot reach any of their successors.
236 /// However, this is not a safe assumption. After we solve dataflow, this
237 /// method should be use to handle this. If this returns true, the solver
238 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000239 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000240
Chris Lattner82bec2c2004-11-15 04:44:20 +0000241 /// getExecutableBlocks - Once we have solved for constants, return the set of
242 /// blocks that is known to be executable.
Chris Lattnercc56aad2007-02-02 20:57:39 +0000243 SmallSet<BasicBlock*, 16> &getExecutableBlocks() {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000244 return BBExecutable;
245 }
246
247 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattneref36dfd2004-11-15 05:03:30 +0000248 /// LLVM values to LatticeVals.
Chris Lattnerc1ec7802007-02-02 22:36:16 +0000249 std::map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000250 return ValueState;
251 }
252
Devang Patel7c490d42008-03-11 05:46:42 +0000253 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000254 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000255 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
256 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000257 }
258
Chris Lattnerdd336d12004-12-11 05:15:59 +0000259 /// getTrackedGlobals - Get and return the set of inferred initializers for
260 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000261 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000262 return TrackedGlobals;
263 }
264
Chris Lattner57939df2007-03-04 04:50:21 +0000265 inline void markOverdefined(Value *V) {
266 markOverdefined(ValueState[V], V);
267 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000268
Chris Lattner138a1242001-06-27 23:38:11 +0000269private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000270 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000271 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000272 // the users of the instruction are updated later.
273 //
Chris Lattner59acc7d2004-12-10 08:02:06 +0000274 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000275 if (IV.markConstant(C)) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000276 DOUT << "markConstant: " << *C << ": " << *V;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000277 InstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000278 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000279 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000280
281 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
282 IV.markForcedConstant(C);
283 DOUT << "markForcedConstant: " << *C << ": " << *V;
284 InstWorkList.push_back(V);
285 }
286
Chris Lattner59acc7d2004-12-10 08:02:06 +0000287 inline void markConstant(Value *V, Constant *C) {
288 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000289 }
290
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000291 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000292 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000293 // work list so that the users of the instruction are updated later.
Misha Brukmanfd939082005-04-21 23:48:37 +0000294
Chris Lattner59acc7d2004-12-10 08:02:06 +0000295 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000296 if (IV.markOverdefined()) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000297 DEBUG(DOUT << "markOverdefined: ";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000298 if (Function *F = dyn_cast<Function>(V))
Bill Wendlingb7427032006-11-26 09:46:52 +0000299 DOUT << "Function '" << F->getName() << "'\n";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000300 else
Bill Wendlingb7427032006-11-26 09:46:52 +0000301 DOUT << *V);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000302 // Only instructions go on the work list
Chris Lattner59acc7d2004-12-10 08:02:06 +0000303 OverdefinedInstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000304 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000305 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000306
307 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
308 if (IV.isOverdefined() || MergeWithV.isUndefined())
309 return; // Noop.
310 if (MergeWithV.isOverdefined())
311 markOverdefined(IV, V);
312 else if (IV.isUndefined())
313 markConstant(IV, V, MergeWithV.getConstant());
314 else if (IV.getConstant() != MergeWithV.getConstant())
315 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000316 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000317
318 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
319 return mergeInValue(ValueState[V], V, MergeWithV);
320 }
321
Chris Lattner138a1242001-06-27 23:38:11 +0000322
Chris Lattneref36dfd2004-11-15 05:03:30 +0000323 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman5560c9d2003-08-18 14:43:39 +0000324 // This function is necessary because not all values should start out in the
Chris Lattner73e21422002-04-09 19:48:49 +0000325 // underdefined state... Argument's should be overdefined, and
Chris Lattner79df7c02002-03-26 18:01:55 +0000326 // constants should be marked as constants. If a value is not known to be an
Chris Lattner138a1242001-06-27 23:38:11 +0000327 // Instruction object, then use this accessor to get its value from the map.
328 //
Chris Lattneref36dfd2004-11-15 05:03:30 +0000329 inline LatticeVal &getValueState(Value *V) {
Chris Lattnerc1ec7802007-02-02 22:36:16 +0000330 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000331 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000332
Chris Lattner3bad2532006-12-20 06:21:33 +0000333 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner7e529e42004-11-15 05:45:33 +0000334 if (isa<UndefValue>(V)) {
335 // Nothing to do, remain undefined.
336 } else {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000337 LatticeVal &LV = ValueState[C];
338 LV.markConstant(C); // Constants are constant
339 return LV;
Chris Lattner7e529e42004-11-15 05:45:33 +0000340 }
Chris Lattner2a88bb72002-08-30 23:39:00 +0000341 }
Chris Lattner138a1242001-06-27 23:38:11 +0000342 // All others are underdefined by default...
343 return ValueState[V];
344 }
345
Misha Brukmanfd939082005-04-21 23:48:37 +0000346 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner138a1242001-06-27 23:38:11 +0000347 // work list if it is not already executable...
Misha Brukmanfd939082005-04-21 23:48:37 +0000348 //
Chris Lattner16b18fd2003-10-08 16:55:34 +0000349 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
350 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
351 return; // This edge is already known to be executable!
352
353 if (BBExecutable.count(Dest)) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000354 DOUT << "Marking Edge Executable: " << Source->getName()
355 << " -> " << Dest->getName() << "\n";
Chris Lattner16b18fd2003-10-08 16:55:34 +0000356
357 // The destination is already executable, but we just made an edge
Chris Lattner929c6fb2003-10-08 16:56:11 +0000358 // feasible that wasn't before. Revisit the PHI nodes in the block
359 // because they have potentially new operands.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000360 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
361 visitPHINode(*cast<PHINode>(I));
Chris Lattner9de28282003-04-25 02:50:03 +0000362
363 } else {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000364 MarkBlockExecutable(Dest);
Chris Lattner9de28282003-04-25 02:50:03 +0000365 }
Chris Lattner138a1242001-06-27 23:38:11 +0000366 }
367
Chris Lattner82bec2c2004-11-15 04:44:20 +0000368 // getFeasibleSuccessors - Return a vector of booleans to indicate which
369 // successors are reachable from a given terminator instruction.
370 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000371 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000372
373 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
374 // block to the 'To' basic block is currently feasible...
375 //
376 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
377
378 // OperandChangedState - This method is invoked on all of the users of an
379 // instruction that was just changed state somehow.... Based on this
380 // information, we need to update the specified user of this instruction.
381 //
382 void OperandChangedState(User *U) {
383 // Only instructions use other variable values!
384 Instruction &I = cast<Instruction>(*U);
385 if (BBExecutable.count(I.getParent())) // Inst is executable?
386 visit(I);
387 }
388
389private:
390 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000391
Misha Brukmanfd939082005-04-21 23:48:37 +0000392 // visit implementations - Something changed in this instruction... Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000393 // operand made a transition, or the instruction is newly executable. Change
394 // the value type of I to reflect these changes if appropriate.
395 //
Chris Lattner7e708292002-06-25 16:13:24 +0000396 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000397
398 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000399 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000400 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000401
Chris Lattnerb8047602002-08-14 17:53:45 +0000402 void visitCastInst(CastInst &I);
Devang Patel7c490d42008-03-11 05:46:42 +0000403 void visitGetResultInst(GetResultInst &GRI);
Chris Lattner6e323722004-03-12 05:52:44 +0000404 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000405 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000406 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000407 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000408 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000409 void visitShuffleVectorInst(ShuffleVectorInst &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000410
411 // Instructions that cannot be folded away...
Chris Lattnerdd336d12004-12-11 05:15:59 +0000412 void visitStoreInst (Instruction &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000413 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000414 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner59acc7d2004-12-10 08:02:06 +0000415 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
416 void visitInvokeInst (InvokeInst &II) {
417 visitCallSite(CallSite::get(&II));
418 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000419 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000420 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000421 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000422 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner7e708292002-06-25 16:13:24 +0000423 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000424 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
425 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner7e708292002-06-25 16:13:24 +0000426 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner2a632552002-04-18 15:13:15 +0000427
Chris Lattner7e708292002-06-25 16:13:24 +0000428 void visitInstruction(Instruction &I) {
Chris Lattner2a632552002-04-18 15:13:15 +0000429 // If a new instruction is added to LLVM that we don't handle...
Bill Wendlinge8156192006-12-07 01:30:32 +0000430 cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000431 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000432 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000433};
Chris Lattnerf6293092002-07-23 18:06:35 +0000434
Duncan Sandse2abf122007-07-20 08:56:21 +0000435} // end anonymous namespace
436
437
Chris Lattnerb9a66342002-05-02 21:44:00 +0000438// getFeasibleSuccessors - Return a vector of booleans to indicate which
439// successors are reachable from a given terminator instruction.
440//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000441void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000442 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000443 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000444 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000445 if (BI->isUnconditional()) {
446 Succs[0] = true;
447 } else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000448 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000449 if (BCValue.isOverdefined() ||
Reid Spencer579dca12007-01-12 04:24:46 +0000450 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
Chris Lattner84831642004-01-12 17:40:36 +0000451 // Overdefined condition variables, and branches on unfoldable constant
452 // conditions, mean the branch could go either way.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000453 Succs[0] = Succs[1] = true;
454 } else if (BCValue.isConstant()) {
455 // Constant condition variables mean the branch can only go a single way
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000456 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000457 }
458 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000459 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000460 // Invoke instructions successors are always executable.
461 Succs[0] = Succs[1] = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000462 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000463 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000464 if (SCValue.isOverdefined() || // Overdefined condition?
465 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000466 // All destinations are executable!
Chris Lattner7e708292002-06-25 16:13:24 +0000467 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerb9a66342002-05-02 21:44:00 +0000468 } else if (SCValue.isConstant()) {
469 Constant *CPV = SCValue.getConstant();
470 // Make sure to skip the "default value" which isn't a value
471 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
472 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
473 Succs[i] = true;
474 return;
475 }
476 }
477
478 // Constant value not equal to any of the branches... must execute
479 // default branch then...
480 Succs[0] = true;
481 }
482 } else {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000483 assert(0 && "SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000484 }
485}
486
487
Chris Lattner59f0ce22002-05-02 21:18:01 +0000488// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
489// block to the 'To' basic block is currently feasible...
490//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000491bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000492 assert(BBExecutable.count(To) && "Dest should always be alive!");
493
494 // Make sure the source basic block is executable!!
495 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000496
Chris Lattnerb9a66342002-05-02 21:44:00 +0000497 // Check to make sure this edge itself is actually feasible now...
Chris Lattner7d275f42003-10-08 15:47:41 +0000498 TerminatorInst *TI = From->getTerminator();
499 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
500 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000501 return true;
Chris Lattner7d275f42003-10-08 15:47:41 +0000502 else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000503 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000504 if (BCValue.isOverdefined()) {
505 // Overdefined condition variables mean the branch could go either way.
506 return true;
507 } else if (BCValue.isConstant()) {
Chris Lattner84831642004-01-12 17:40:36 +0000508 // Not branching on an evaluatable constant?
Chris Lattner54a525d2007-01-13 00:42:58 +0000509 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
Chris Lattner84831642004-01-12 17:40:36 +0000510
Chris Lattner7d275f42003-10-08 15:47:41 +0000511 // Constant condition variables mean the branch can only go a single way
Misha Brukmanfd939082005-04-21 23:48:37 +0000512 return BI->getSuccessor(BCValue.getConstant() ==
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000513 ConstantInt::getFalse()) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000514 }
515 return false;
516 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000517 } else if (isa<InvokeInst>(TI)) {
Chris Lattner7d275f42003-10-08 15:47:41 +0000518 // Invoke instructions successors are always executable.
519 return true;
520 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000521 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000522 if (SCValue.isOverdefined()) { // Overdefined condition?
523 // All destinations are executable!
524 return true;
525 } else if (SCValue.isConstant()) {
526 Constant *CPV = SCValue.getConstant();
Chris Lattner84831642004-01-12 17:40:36 +0000527 if (!isa<ConstantInt>(CPV))
528 return true; // not a foldable constant?
529
Chris Lattner7d275f42003-10-08 15:47:41 +0000530 // Make sure to skip the "default value" which isn't a value
531 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
532 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
533 return SI->getSuccessor(i) == To;
534
535 // Constant value not equal to any of the branches... must execute
536 // default branch then...
537 return SI->getDefaultDest() == To;
538 }
539 return false;
540 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000541 cerr << "Unknown terminator instruction: " << *TI;
Chris Lattner7d275f42003-10-08 15:47:41 +0000542 abort();
543 }
Chris Lattner59f0ce22002-05-02 21:18:01 +0000544}
Chris Lattner138a1242001-06-27 23:38:11 +0000545
Chris Lattner2a632552002-04-18 15:13:15 +0000546// visit Implementations - Something changed in this instruction... Either an
Chris Lattner138a1242001-06-27 23:38:11 +0000547// operand made a transition, or the instruction is newly executable. Change
548// the value type of I to reflect these changes if appropriate. This method
549// makes sure to do the following actions:
550//
551// 1. If a phi node merges two constants in, and has conflicting value coming
552// from different branches, or if the PHI node merges in an overdefined
553// value, then the PHI node becomes overdefined.
554// 2. If a phi node merges only constants in, and they all agree on value, the
555// PHI node becomes a constant value equal to that.
556// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
557// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
558// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
559// 6. If a conditional branch has a value that is constant, make the selected
560// destination executable
561// 7. If a conditional branch has a value that is overdefined, make all
562// successors executable.
563//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000564void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000565 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000566 if (PNIV.isOverdefined()) {
567 // There may be instructions using this PHI node that are not overdefined
568 // themselves. If so, make sure that they know that the PHI node operand
569 // changed.
570 std::multimap<PHINode*, Instruction*>::iterator I, E;
571 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
572 if (I != E) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000573 SmallVector<Instruction*, 16> Users;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000574 for (; I != E; ++I) Users.push_back(I->second);
575 while (!Users.empty()) {
576 visit(Users.back());
577 Users.pop_back();
578 }
579 }
580 return; // Quick exit
581 }
Chris Lattner138a1242001-06-27 23:38:11 +0000582
Chris Lattnera2f652d2004-03-16 19:49:59 +0000583 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
584 // and slow us down a lot. Just mark them overdefined.
585 if (PN.getNumIncomingValues() > 64) {
586 markOverdefined(PNIV, &PN);
587 return;
588 }
589
Chris Lattner2a632552002-04-18 15:13:15 +0000590 // Look at all of the executable operands of the PHI node. If any of them
591 // are overdefined, the PHI becomes overdefined as well. If they are all
592 // constant, and they agree with each other, the PHI becomes the identical
593 // constant. If they are constant and don't agree, the PHI is overdefined.
594 // If there are no executable operands, the PHI remains undefined.
595 //
Chris Lattner9de28282003-04-25 02:50:03 +0000596 Constant *OperandVal = 0;
597 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000598 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000599 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000600
Chris Lattner7e708292002-06-25 16:13:24 +0000601 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner38b5ae42003-06-24 20:29:52 +0000602 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner3d405b02003-10-08 16:21:03 +0000603 markOverdefined(PNIV, &PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000604 return;
605 }
606
Chris Lattner9de28282003-04-25 02:50:03 +0000607 if (OperandVal == 0) { // Grab the first value...
608 OperandVal = IV.getConstant();
Chris Lattner2a632552002-04-18 15:13:15 +0000609 } else { // Another value is being merged in!
610 // There is already a reachable operand. If we conflict with it,
611 // then the PHI node becomes overdefined. If we agree with it, we
612 // can continue on.
Misha Brukmanfd939082005-04-21 23:48:37 +0000613
Chris Lattner2a632552002-04-18 15:13:15 +0000614 // Check to see if there are two different constants merging...
Chris Lattner9de28282003-04-25 02:50:03 +0000615 if (IV.getConstant() != OperandVal) {
Chris Lattner2a632552002-04-18 15:13:15 +0000616 // Yes there is. This means the PHI node is not constant.
617 // You must be overdefined poor PHI.
618 //
Chris Lattner3d405b02003-10-08 16:21:03 +0000619 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner2a632552002-04-18 15:13:15 +0000620 return; // I'm done analyzing you
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000621 }
Chris Lattner138a1242001-06-27 23:38:11 +0000622 }
623 }
Chris Lattner138a1242001-06-27 23:38:11 +0000624 }
625
Chris Lattner2a632552002-04-18 15:13:15 +0000626 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000627 // arguments that agree with each other(and OperandVal is the constant) or
628 // OperandVal is null because there are no defined incoming arguments. If
629 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000630 //
Chris Lattner9de28282003-04-25 02:50:03 +0000631 if (OperandVal)
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000632 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000633}
634
Chris Lattner59acc7d2004-12-10 08:02:06 +0000635void SCCPSolver::visitReturnInst(ReturnInst &I) {
636 if (I.getNumOperands() == 0) return; // Ret void
637
Chris Lattner59acc7d2004-12-10 08:02:06 +0000638 Function *F = I.getParent()->getParent();
Devang Patel7c490d42008-03-11 05:46:42 +0000639 // If we are tracking the return value of this function, merge it in.
640 if (!F->hasInternalLinkage())
641 return;
642
643 if (!TrackedRetVals.empty()) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000644 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000645 TrackedRetVals.find(F);
646 if (TFRVI != TrackedRetVals.end() &&
Chris Lattner59acc7d2004-12-10 08:02:06 +0000647 !TFRVI->second.isOverdefined()) {
648 LatticeVal &IV = getValueState(I.getOperand(0));
649 mergeInValue(TFRVI->second, F, IV);
Devang Patel7c490d42008-03-11 05:46:42 +0000650 return;
651 }
652 }
653
654 // Handle function that returns multiple values.
655 std::multimap<Function*, LatticeValIndexed>::iterator It, E;
656 tie(It, E) = TrackedMultipleRetVals.equal_range(F);
657 if (It != E) {
658 for (; It != E; ++It) {
659 LatticeValIndexed &LV = It->second;
660 unsigned Idx = LV.getIndex();
661 Value *V = I.getOperand(Idx);
662 mergeInValue(LV.getLatticeVal(), V, getValueState(V));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000663 }
664 }
665}
666
Chris Lattner82bec2c2004-11-15 04:44:20 +0000667void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000668 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000669 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000670
Chris Lattner16b18fd2003-10-08 16:55:34 +0000671 BasicBlock *BB = TI.getParent();
672
Chris Lattnerb9a66342002-05-02 21:44:00 +0000673 // Mark all feasible successors executable...
674 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000675 if (SuccFeasible[i])
676 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000677}
678
Chris Lattner82bec2c2004-11-15 04:44:20 +0000679void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000680 Value *V = I.getOperand(0);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000681 LatticeVal &VState = getValueState(V);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000682 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000683 markOverdefined(&I);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000684 else if (VState.isConstant()) // Propagate constant value
Reid Spencer4da49122006-12-12 05:05:00 +0000685 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
686 VState.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000687}
688
Devang Patel7c490d42008-03-11 05:46:42 +0000689void SCCPSolver::visitGetResultInst(GetResultInst &GRI) {
690 unsigned Idx = GRI.getIndex();
691 Value *Aggr = GRI.getOperand(0);
692 Function *F = NULL;
Devang Pateld4e0af92008-04-09 15:58:24 +0000693 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
Devang Patel7c490d42008-03-11 05:46:42 +0000694 F = CI->getCalledFunction();
695 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
696 F = II->getCalledFunction();
697
Devang Pateld4e0af92008-04-09 15:58:24 +0000698 if (!F)
699 return;
Devang Patel7c490d42008-03-11 05:46:42 +0000700
701 std::multimap<Function*, LatticeValIndexed>::iterator It, E;
702 tie(It, E) = TrackedMultipleRetVals.equal_range(F);
703 if (It == E)
704 return;
705
706 for (; It != E; ++It) {
707 LatticeValIndexed &LIV = It->second;
708 if (LIV.getIndex() == Idx) {
709 mergeInValue(&GRI, LIV.getLatticeVal());
710 }
711 }
712}
713
Chris Lattner82bec2c2004-11-15 04:44:20 +0000714void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000715 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000716 if (CondValue.isUndefined())
717 return;
Reid Spencer579dca12007-01-12 04:24:46 +0000718 if (CondValue.isConstant()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000719 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencer579dca12007-01-12 04:24:46 +0000720 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000721 : I.getFalseValue()));
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000722 return;
723 }
724 }
725
726 // Otherwise, the condition is overdefined or a constant we can't evaluate.
727 // See if we can produce something better than overdefined based on the T/F
728 // value.
729 LatticeVal &TVal = getValueState(I.getTrueValue());
730 LatticeVal &FVal = getValueState(I.getFalseValue());
731
732 // select ?, C, C -> C.
733 if (TVal.isConstant() && FVal.isConstant() &&
734 TVal.getConstant() == FVal.getConstant()) {
735 markConstant(&I, FVal.getConstant());
736 return;
737 }
738
739 if (TVal.isUndefined()) { // select ?, undef, X -> X.
740 mergeInValue(&I, FVal);
741 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
742 mergeInValue(&I, TVal);
743 } else {
744 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000745 }
746}
747
Chris Lattner2a632552002-04-18 15:13:15 +0000748// Handle BinaryOperators and Shift Instructions...
Chris Lattner82bec2c2004-11-15 04:44:20 +0000749void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000750 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000751 if (IV.isOverdefined()) return;
752
Chris Lattneref36dfd2004-11-15 05:03:30 +0000753 LatticeVal &V1State = getValueState(I.getOperand(0));
754 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000755
Chris Lattner2a632552002-04-18 15:13:15 +0000756 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnera177c672004-12-11 23:15:19 +0000757 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
758 // operand is overdefined.
759 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
760 LatticeVal *NonOverdefVal = 0;
761 if (!V1State.isOverdefined()) {
762 NonOverdefVal = &V1State;
763 } else if (!V2State.isOverdefined()) {
764 NonOverdefVal = &V2State;
765 }
766
767 if (NonOverdefVal) {
768 if (NonOverdefVal->isUndefined()) {
769 // Could annihilate value.
770 if (I.getOpcode() == Instruction::And)
771 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +0000772 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
773 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +0000774 else
775 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera177c672004-12-11 23:15:19 +0000776 return;
777 } else {
778 if (I.getOpcode() == Instruction::And) {
779 if (NonOverdefVal->getConstant()->isNullValue()) {
780 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskey52ab9042007-01-03 00:11:03 +0000781 return; // X and 0 = 0
Chris Lattnera177c672004-12-11 23:15:19 +0000782 }
783 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000784 if (ConstantInt *CI =
785 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnera177c672004-12-11 23:15:19 +0000786 if (CI->isAllOnesValue()) {
787 markConstant(IV, &I, NonOverdefVal->getConstant());
788 return; // X or -1 = -1
789 }
790 }
791 }
792 }
793 }
794
795
Chris Lattner1daee8b2004-01-12 03:57:30 +0000796 // If both operands are PHI nodes, it is possible that this instruction has
797 // a constant value, despite the fact that the PHI node doesn't. Check for
798 // this condition now.
799 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
800 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
801 if (PN1->getParent() == PN2->getParent()) {
802 // Since the two PHI nodes are in the same basic block, they must have
803 // entries for the same predecessors. Walk the predecessor list, and
804 // if all of the incoming values are constants, and the result of
805 // evaluating this expression with all incoming value pairs is the
806 // same, then this expression is a constant even though the PHI node
807 // is not a constant!
Chris Lattneref36dfd2004-11-15 05:03:30 +0000808 LatticeVal Result;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000809 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000810 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000811 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000812 LatticeVal &In2 =
813 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000814
815 if (In1.isOverdefined() || In2.isOverdefined()) {
816 Result.markOverdefined();
817 break; // Cannot fold this operation over the PHI nodes!
818 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000819 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
820 In2.getConstant());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000821 if (Result.isUndefined())
Chris Lattnerb16689b2004-01-12 19:08:43 +0000822 Result.markConstant(V);
823 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000824 Result.markOverdefined();
825 break;
826 }
827 }
828 }
829
830 // If we found a constant value here, then we know the instruction is
831 // constant despite the fact that the PHI nodes are overdefined.
832 if (Result.isConstant()) {
833 markConstant(IV, &I, Result.getConstant());
834 // Remember that this instruction is virtually using the PHI node
835 // operands.
836 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
837 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
838 return;
839 } else if (Result.isUndefined()) {
840 return;
841 }
842
843 // Okay, this really is overdefined now. Since we might have
844 // speculatively thought that this was not overdefined before, and
845 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
846 // make sure to clean out any entries that we put there, for
847 // efficiency.
848 std::multimap<PHINode*, Instruction*>::iterator It, E;
849 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
850 while (It != E) {
851 if (It->second == &I) {
852 UsersOfOverdefinedPHIs.erase(It++);
853 } else
854 ++It;
855 }
856 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
857 while (It != E) {
858 if (It->second == &I) {
859 UsersOfOverdefinedPHIs.erase(It++);
860 } else
861 ++It;
862 }
863 }
864
865 markOverdefined(IV, &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000866 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000867 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
868 V2State.getConstant()));
Chris Lattner2a632552002-04-18 15:13:15 +0000869 }
870}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000871
Reid Spencere4d87aa2006-12-23 06:05:41 +0000872// Handle ICmpInst instruction...
873void SCCPSolver::visitCmpInst(CmpInst &I) {
874 LatticeVal &IV = ValueState[&I];
875 if (IV.isOverdefined()) return;
876
877 LatticeVal &V1State = getValueState(I.getOperand(0));
878 LatticeVal &V2State = getValueState(I.getOperand(1));
879
880 if (V1State.isOverdefined() || V2State.isOverdefined()) {
881 // If both operands are PHI nodes, it is possible that this instruction has
882 // a constant value, despite the fact that the PHI node doesn't. Check for
883 // this condition now.
884 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
885 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
886 if (PN1->getParent() == PN2->getParent()) {
887 // Since the two PHI nodes are in the same basic block, they must have
888 // entries for the same predecessors. Walk the predecessor list, and
889 // if all of the incoming values are constants, and the result of
890 // evaluating this expression with all incoming value pairs is the
891 // same, then this expression is a constant even though the PHI node
892 // is not a constant!
893 LatticeVal Result;
894 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
895 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
896 BasicBlock *InBlock = PN1->getIncomingBlock(i);
897 LatticeVal &In2 =
898 getValueState(PN2->getIncomingValueForBlock(InBlock));
899
900 if (In1.isOverdefined() || In2.isOverdefined()) {
901 Result.markOverdefined();
902 break; // Cannot fold this operation over the PHI nodes!
903 } else if (In1.isConstant() && In2.isConstant()) {
904 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
905 In1.getConstant(),
906 In2.getConstant());
907 if (Result.isUndefined())
908 Result.markConstant(V);
909 else if (Result.isConstant() && Result.getConstant() != V) {
910 Result.markOverdefined();
911 break;
912 }
913 }
914 }
915
916 // If we found a constant value here, then we know the instruction is
917 // constant despite the fact that the PHI nodes are overdefined.
918 if (Result.isConstant()) {
919 markConstant(IV, &I, Result.getConstant());
920 // Remember that this instruction is virtually using the PHI node
921 // operands.
922 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
923 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
924 return;
925 } else if (Result.isUndefined()) {
926 return;
927 }
928
929 // Okay, this really is overdefined now. Since we might have
930 // speculatively thought that this was not overdefined before, and
931 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
932 // make sure to clean out any entries that we put there, for
933 // efficiency.
934 std::multimap<PHINode*, Instruction*>::iterator It, E;
935 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
936 while (It != E) {
937 if (It->second == &I) {
938 UsersOfOverdefinedPHIs.erase(It++);
939 } else
940 ++It;
941 }
942 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
943 while (It != E) {
944 if (It->second == &I) {
945 UsersOfOverdefinedPHIs.erase(It++);
946 } else
947 ++It;
948 }
949 }
950
951 markOverdefined(IV, &I);
952 } else if (V1State.isConstant() && V2State.isConstant()) {
953 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
954 V1State.getConstant(),
955 V2State.getConstant()));
956 }
957}
958
Robert Bocchino56107e22006-01-10 19:05:05 +0000959void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +0000960 // FIXME : SCCP does not handle vectors properly.
961 markOverdefined(&I);
962 return;
963
964#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +0000965 LatticeVal &ValState = getValueState(I.getOperand(0));
966 LatticeVal &IdxState = getValueState(I.getOperand(1));
967
968 if (ValState.isOverdefined() || IdxState.isOverdefined())
969 markOverdefined(&I);
970 else if(ValState.isConstant() && IdxState.isConstant())
971 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
972 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +0000973#endif
Robert Bocchino56107e22006-01-10 19:05:05 +0000974}
975
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000976void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +0000977 // FIXME : SCCP does not handle vectors properly.
978 markOverdefined(&I);
979 return;
980#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000981 LatticeVal &ValState = getValueState(I.getOperand(0));
982 LatticeVal &EltState = getValueState(I.getOperand(1));
983 LatticeVal &IdxState = getValueState(I.getOperand(2));
984
985 if (ValState.isOverdefined() || EltState.isOverdefined() ||
986 IdxState.isOverdefined())
987 markOverdefined(&I);
988 else if(ValState.isConstant() && EltState.isConstant() &&
989 IdxState.isConstant())
990 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
991 EltState.getConstant(),
992 IdxState.getConstant()));
993 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +0000994 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +0000995 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
996 EltState.getConstant(),
997 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +0000998#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000999}
1000
Chris Lattner543abdf2006-04-08 01:19:12 +00001001void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001002 // FIXME : SCCP does not handle vectors properly.
1003 markOverdefined(&I);
1004 return;
1005#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +00001006 LatticeVal &V1State = getValueState(I.getOperand(0));
1007 LatticeVal &V2State = getValueState(I.getOperand(1));
1008 LatticeVal &MaskState = getValueState(I.getOperand(2));
1009
1010 if (MaskState.isUndefined() ||
1011 (V1State.isUndefined() && V2State.isUndefined()))
1012 return; // Undefined output if mask or both inputs undefined.
1013
1014 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1015 MaskState.isOverdefined()) {
1016 markOverdefined(&I);
1017 } else {
1018 // A mix of constant/undef inputs.
1019 Constant *V1 = V1State.isConstant() ?
1020 V1State.getConstant() : UndefValue::get(I.getType());
1021 Constant *V2 = V2State.isConstant() ?
1022 V2State.getConstant() : UndefValue::get(I.getType());
1023 Constant *Mask = MaskState.isConstant() ?
1024 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1025 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1026 }
Devang Patel67a821d2006-12-04 23:54:59 +00001027#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001028}
1029
Chris Lattner2a88bb72002-08-30 23:39:00 +00001030// Handle getelementptr instructions... if all operands are constants then we
1031// can turn this into a getelementptr ConstantExpr.
1032//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001033void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001034 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001035 if (IV.isOverdefined()) return;
1036
Chris Lattnere777ff22007-02-02 20:51:48 +00001037 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001038 Operands.reserve(I.getNumOperands());
1039
1040 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001041 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001042 if (State.isUndefined())
1043 return; // Operands are not resolved yet...
1044 else if (State.isOverdefined()) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001045 markOverdefined(IV, &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +00001046 return;
1047 }
1048 assert(State.isConstant() && "Unknown state!");
1049 Operands.push_back(State.getConstant());
1050 }
1051
1052 Constant *Ptr = Operands[0];
1053 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1054
Chris Lattnere777ff22007-02-02 20:51:48 +00001055 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1056 Operands.size()));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001057}
Brian Gaeked0fde302003-11-11 22:41:34 +00001058
Chris Lattnerdd336d12004-12-11 05:15:59 +00001059void SCCPSolver::visitStoreInst(Instruction &SI) {
1060 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1061 return;
1062 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001063 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001064 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1065
1066 // Get the value we are storing into the global.
1067 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1068
1069 mergeInValue(I->second, GV, PtrVal);
1070 if (I->second.isOverdefined())
1071 TrackedGlobals.erase(I); // No need to keep tracking this!
1072}
1073
1074
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001075// Handle load instructions. If the operand is a constant pointer to a constant
1076// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001077void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001078 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001079 if (IV.isOverdefined()) return;
1080
Chris Lattneref36dfd2004-11-15 05:03:30 +00001081 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001082 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1083 if (PtrVal.isConstant() && !I.isVolatile()) {
1084 Value *Ptr = PtrVal.getConstant();
Christopher Lambb15147e2007-12-29 07:56:53 +00001085 // TODO: Consider a target hook for valid address spaces for this xform.
1086 if (isa<ConstantPointerNull>(Ptr) &&
1087 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattnerc76d8032004-03-07 22:16:24 +00001088 // load null -> null
1089 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1090 return;
1091 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001092
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001093 // Transform load (constant global) into the value loaded.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001094 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1095 if (GV->isConstant()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001096 if (!GV->isDeclaration()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001097 markConstant(IV, &I, GV->getInitializer());
1098 return;
1099 }
1100 } else if (!TrackedGlobals.empty()) {
1101 // If we are tracking this global, merge in the known value for it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001102 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
Chris Lattnerdd336d12004-12-11 05:15:59 +00001103 TrackedGlobals.find(GV);
1104 if (It != TrackedGlobals.end()) {
1105 mergeInValue(IV, &I, It->second);
1106 return;
1107 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001108 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001109 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001110
1111 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1112 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1113 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen9d809302005-04-23 21:38:35 +00001114 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00001115 if (GV->isConstant() && !GV->isDeclaration())
Jeff Cohen9d809302005-04-23 21:38:35 +00001116 if (Constant *V =
Chris Lattnerebe61202005-09-26 05:28:52 +00001117 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen9d809302005-04-23 21:38:35 +00001118 markConstant(IV, &I, V);
1119 return;
1120 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001121 }
1122
1123 // Otherwise we cannot say for certain what value this load will produce.
1124 // Bail out.
1125 markOverdefined(IV, &I);
1126}
Chris Lattner58b7b082004-04-13 19:43:54 +00001127
Chris Lattner59acc7d2004-12-10 08:02:06 +00001128void SCCPSolver::visitCallSite(CallSite CS) {
1129 Function *F = CS.getCalledFunction();
1130
Devang Patel7c490d42008-03-11 05:46:42 +00001131 DenseMap<Function*, LatticeVal>::iterator TFRVI =TrackedRetVals.end();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001132 // If we are tracking this function, we must make sure to bind arguments as
1133 // appropriate.
Devang Patel7c490d42008-03-11 05:46:42 +00001134 bool FirstCall = false;
1135 if (F && F->hasInternalLinkage()) {
1136 TFRVI = TrackedRetVals.find(F);
1137 if (TFRVI != TrackedRetVals.end())
1138 FirstCall = true;
1139 else {
1140 std::multimap<Function*, LatticeValIndexed>::iterator It, E;
1141 tie(It, E) = TrackedMultipleRetVals.equal_range(F);
1142 if (It != E)
1143 FirstCall = true;
1144 }
1145 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001146
Devang Patel7c490d42008-03-11 05:46:42 +00001147 if (FirstCall) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001148 // If this is the first call to the function hit, mark its entry block
1149 // executable.
1150 if (!BBExecutable.count(F->begin()))
1151 MarkBlockExecutable(F->begin());
Devang Patel7c490d42008-03-11 05:46:42 +00001152
Chris Lattner59acc7d2004-12-10 08:02:06 +00001153 CallSite::arg_iterator CAI = CS.arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +00001154 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001155 AI != E; ++AI, ++CAI) {
1156 LatticeVal &IV = ValueState[AI];
1157 if (!IV.isOverdefined())
1158 mergeInValue(IV, AI, getValueState(*CAI));
1159 }
1160 }
1161 Instruction *I = CS.getInstruction();
Nick Lewyckya66696e2008-03-09 09:44:38 +00001162
1163 if (!CS.doesNotThrow() && I->getParent()->getUnwindDest())
1164 markEdgeExecutable(I->getParent(), I->getParent()->getUnwindDest());
1165
Chris Lattner59acc7d2004-12-10 08:02:06 +00001166 if (I->getType() == Type::VoidTy) return;
1167
1168 LatticeVal &IV = ValueState[I];
Chris Lattner58b7b082004-04-13 19:43:54 +00001169 if (IV.isOverdefined()) return;
1170
Devang Patel7c490d42008-03-11 05:46:42 +00001171 // Propagate the single return value of the function to the value of the
1172 // instruction.
1173 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001174 mergeInValue(IV, I, TFRVI->second);
1175 return;
1176 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001177
Reid Spencer5cbf9852007-01-30 20:08:39 +00001178 if (F == 0 || !F->isDeclaration() || !canConstantFoldCallTo(F)) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001179 markOverdefined(IV, I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001180 return;
1181 }
1182
Chris Lattnercd2492e2007-01-30 23:15:19 +00001183 SmallVector<Constant*, 8> Operands;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001184 Operands.reserve(I->getNumOperands()-1);
Chris Lattner58b7b082004-04-13 19:43:54 +00001185
Chris Lattner59acc7d2004-12-10 08:02:06 +00001186 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1187 AI != E; ++AI) {
1188 LatticeVal &State = getValueState(*AI);
Chris Lattner58b7b082004-04-13 19:43:54 +00001189 if (State.isUndefined())
1190 return; // Operands are not resolved yet...
1191 else if (State.isOverdefined()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001192 markOverdefined(IV, I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001193 return;
1194 }
1195 assert(State.isConstant() && "Unknown state!");
1196 Operands.push_back(State.getConstant());
1197 }
1198
Chris Lattnercd2492e2007-01-30 23:15:19 +00001199 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size()))
Chris Lattner59acc7d2004-12-10 08:02:06 +00001200 markConstant(IV, I, C);
Chris Lattner58b7b082004-04-13 19:43:54 +00001201 else
Chris Lattner59acc7d2004-12-10 08:02:06 +00001202 markOverdefined(IV, I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001203}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001204
1205
1206void SCCPSolver::Solve() {
1207 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001208 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001209 !OverdefinedInstWorkList.empty()) {
Chris Lattner82bec2c2004-11-15 04:44:20 +00001210 // Process the instruction work list...
1211 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001212 Value *I = OverdefinedInstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001213 OverdefinedInstWorkList.pop_back();
1214
Bill Wendlingb7427032006-11-26 09:46:52 +00001215 DOUT << "\nPopped off OI-WL: " << *I;
Misha Brukmanfd939082005-04-21 23:48:37 +00001216
Chris Lattner82bec2c2004-11-15 04:44:20 +00001217 // "I" got into the work list because it either made the transition from
1218 // bottom to constant
1219 //
1220 // Anything on this worklist that is overdefined need not be visited
1221 // since all of its users will have already been marked as overdefined
1222 // Update all of the users of this instruction's value...
1223 //
1224 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1225 UI != E; ++UI)
1226 OperandChangedState(*UI);
1227 }
1228 // Process the instruction work list...
1229 while (!InstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001230 Value *I = InstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001231 InstWorkList.pop_back();
1232
Bill Wendlingb7427032006-11-26 09:46:52 +00001233 DOUT << "\nPopped off I-WL: " << *I;
Misha Brukmanfd939082005-04-21 23:48:37 +00001234
Chris Lattner82bec2c2004-11-15 04:44:20 +00001235 // "I" got into the work list because it either made the transition from
1236 // bottom to constant
1237 //
1238 // Anything on this worklist that is overdefined need not be visited
1239 // since all of its users will have already been marked as overdefined.
1240 // Update all of the users of this instruction's value...
1241 //
1242 if (!getValueState(I).isOverdefined())
1243 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1244 UI != E; ++UI)
1245 OperandChangedState(*UI);
1246 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001247
Chris Lattner82bec2c2004-11-15 04:44:20 +00001248 // Process the basic block work list...
1249 while (!BBWorkList.empty()) {
1250 BasicBlock *BB = BBWorkList.back();
1251 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001252
Bill Wendlingb7427032006-11-26 09:46:52 +00001253 DOUT << "\nPopped off BBWL: " << *BB;
Misha Brukmanfd939082005-04-21 23:48:37 +00001254
Chris Lattner82bec2c2004-11-15 04:44:20 +00001255 // Notify all instructions in this basic block that they are newly
1256 // executable.
1257 visit(BB);
1258 }
1259 }
1260}
1261
Chris Lattner3bad2532006-12-20 06:21:33 +00001262/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001263/// that branches on undef values cannot reach any of their successors.
1264/// However, this is not a safe assumption. After we solve dataflow, this
1265/// method should be use to handle this. If this returns true, the solver
1266/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001267///
1268/// This method handles this by finding an unresolved branch and marking it one
1269/// of the edges from the block as being feasible, even though the condition
1270/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1271/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001272/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001273/// constraints on the condition of the branch, as that would impact other users
1274/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001275///
1276/// This scan also checks for values that use undefs, whose results are actually
1277/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1278/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1279/// even if X isn't defined.
1280bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001281 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1282 if (!BBExecutable.count(BB))
1283 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001284
1285 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1286 // Look for instructions which produce undef values.
1287 if (I->getType() == Type::VoidTy) continue;
1288
1289 LatticeVal &LV = getValueState(I);
1290 if (!LV.isUndefined()) continue;
1291
1292 // Get the lattice values of the first two operands for use below.
1293 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1294 LatticeVal Op1LV;
1295 if (I->getNumOperands() == 2) {
1296 // If this is a two-operand instruction, and if both operands are
1297 // undefs, the result stays undef.
1298 Op1LV = getValueState(I->getOperand(1));
1299 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1300 continue;
1301 }
1302
1303 // If this is an instructions whose result is defined even if the input is
1304 // not fully defined, propagate the information.
1305 const Type *ITy = I->getType();
1306 switch (I->getOpcode()) {
1307 default: break; // Leave the instruction as an undef.
1308 case Instruction::ZExt:
1309 // After a zero extend, we know the top part is zero. SExt doesn't have
1310 // to be handled here, because we don't know whether the top part is 1's
1311 // or 0's.
1312 assert(Op0LV.isUndefined());
1313 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1314 return true;
1315 case Instruction::Mul:
1316 case Instruction::And:
1317 // undef * X -> 0. X could be zero.
1318 // undef & X -> 0. X could be zero.
1319 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1320 return true;
1321
1322 case Instruction::Or:
1323 // undef | X -> -1. X could be -1.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001324 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1325 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001326 else
1327 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1328 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001329
1330 case Instruction::SDiv:
1331 case Instruction::UDiv:
1332 case Instruction::SRem:
1333 case Instruction::URem:
1334 // X / undef -> undef. No change.
1335 // X % undef -> undef. No change.
1336 if (Op1LV.isUndefined()) break;
1337
1338 // undef / X -> 0. X could be maxint.
1339 // undef % X -> 0. X could be 1.
1340 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1341 return true;
1342
1343 case Instruction::AShr:
1344 // undef >>s X -> undef. No change.
1345 if (Op0LV.isUndefined()) break;
1346
1347 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1348 if (Op0LV.isConstant())
1349 markForcedConstant(LV, I, Op0LV.getConstant());
1350 else
1351 markOverdefined(LV, I);
1352 return true;
1353 case Instruction::LShr:
1354 case Instruction::Shl:
1355 // undef >> X -> undef. No change.
1356 // undef << X -> undef. No change.
1357 if (Op0LV.isUndefined()) break;
1358
1359 // X >> undef -> 0. X could be 0.
1360 // X << undef -> 0. X could be 0.
1361 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1362 return true;
1363 case Instruction::Select:
1364 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1365 if (Op0LV.isUndefined()) {
1366 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1367 Op1LV = getValueState(I->getOperand(2));
1368 } else if (Op1LV.isUndefined()) {
1369 // c ? undef : undef -> undef. No change.
1370 Op1LV = getValueState(I->getOperand(2));
1371 if (Op1LV.isUndefined())
1372 break;
1373 // Otherwise, c ? undef : x -> x.
1374 } else {
1375 // Leave Op1LV as Operand(1)'s LatticeValue.
1376 }
1377
1378 if (Op1LV.isConstant())
1379 markForcedConstant(LV, I, Op1LV.getConstant());
1380 else
1381 markOverdefined(LV, I);
1382 return true;
1383 }
1384 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001385
1386 TerminatorInst *TI = BB->getTerminator();
1387 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1388 if (!BI->isConditional()) continue;
1389 if (!getValueState(BI->getCondition()).isUndefined())
1390 continue;
1391 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1392 if (!getValueState(SI->getCondition()).isUndefined())
1393 continue;
1394 } else {
1395 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001396 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001397
Chris Lattner05bb7892008-01-28 00:32:30 +00001398 // If the edge to the second successor isn't thought to be feasible yet,
1399 // mark it so now. We pick the second one so that this goes to some
1400 // enumerated value in a switch instead of going to the default destination.
1401 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001402 continue;
1403
1404 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1405 // and return. This will make other blocks reachable, which will allow new
1406 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001407 markEdgeExecutable(BB, TI->getSuccessor(1));
1408
1409 // This must be a conditional branch of switch on undef. At this point,
1410 // force the old terminator to branch to the first successor. This is
1411 // required because we are now influencing the dataflow of the function with
1412 // the assumption that this edge is taken. If we leave the branch condition
1413 // as undef, then further analysis could think the undef went another way
1414 // leading to an inconsistent set of conclusions.
1415 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1416 BI->setCondition(ConstantInt::getFalse());
1417 } else {
1418 SwitchInst *SI = cast<SwitchInst>(TI);
1419 SI->setCondition(SI->getCaseValue(1));
1420 }
1421
Chris Lattnerd2d86702006-10-22 05:59:17 +00001422 return true;
1423 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001424
Chris Lattnerd2d86702006-10-22 05:59:17 +00001425 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001426}
1427
Chris Lattner82bec2c2004-11-15 04:44:20 +00001428
1429namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001430 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001431 //
Chris Lattner14051812004-11-15 07:15:04 +00001432 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001433 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001434 ///
Reid Spencer9133fe22007-02-05 23:32:05 +00001435 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001436 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +00001437 SCCP() : FunctionPass((intptr_t)&ID) {}
1438
Chris Lattner14051812004-11-15 07:15:04 +00001439 // runOnFunction - Run the Sparse Conditional Constant Propagation
1440 // algorithm, and return true if the function was modified.
1441 //
1442 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001443
Chris Lattner14051812004-11-15 07:15:04 +00001444 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1445 AU.setPreservesCFG();
1446 }
1447 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001448
Devang Patel19974732007-05-03 01:11:54 +00001449 char SCCP::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +00001450 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001451} // end anonymous namespace
1452
1453
1454// createSCCPPass - This is the public interface to this file...
1455FunctionPass *llvm::createSCCPPass() {
1456 return new SCCP();
1457}
1458
1459
Chris Lattner82bec2c2004-11-15 04:44:20 +00001460// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1461// and return true if the function was modified.
1462//
1463bool SCCP::runOnFunction(Function &F) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001464 DOUT << "SCCP on function '" << F.getName() << "'\n";
Chris Lattner82bec2c2004-11-15 04:44:20 +00001465 SCCPSolver Solver;
1466
1467 // Mark the first block of the function as being executable.
1468 Solver.MarkBlockExecutable(F.begin());
1469
Chris Lattner7e529e42004-11-15 05:45:33 +00001470 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001471 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001472 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001473
Chris Lattner82bec2c2004-11-15 04:44:20 +00001474 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001475 bool ResolvedUndefs = true;
1476 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001477 Solver.Solve();
Chris Lattner3bad2532006-12-20 06:21:33 +00001478 DOUT << "RESOLVING UNDEFs\n";
1479 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001480 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001481
Chris Lattner7e529e42004-11-15 05:45:33 +00001482 bool MadeChanges = false;
1483
1484 // If we decided that there are basic blocks that are dead in this function,
1485 // delete their contents now. Note that we cannot actually delete the blocks,
1486 // as we cannot modify the CFG of the function.
1487 //
Chris Lattnercc56aad2007-02-02 20:57:39 +00001488 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001489 SmallVector<Instruction*, 32> Insts;
Chris Lattner57939df2007-03-04 04:50:21 +00001490 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1491
Chris Lattner7e529e42004-11-15 05:45:33 +00001492 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1493 if (!ExecutableBBs.count(BB)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001494 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001495 ++NumDeadBlocks;
1496
Chris Lattner7e529e42004-11-15 05:45:33 +00001497 // Delete the instructions backwards, as it has a reduced likelihood of
1498 // having to update as many def-use and use-def chains.
Chris Lattner7e529e42004-11-15 05:45:33 +00001499 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1500 I != E; ++I)
1501 Insts.push_back(I);
1502 while (!Insts.empty()) {
1503 Instruction *I = Insts.back();
1504 Insts.pop_back();
1505 if (!I->use_empty())
1506 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1507 BB->getInstList().erase(I);
1508 MadeChanges = true;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001509 ++NumInstRemoved;
Chris Lattner7e529e42004-11-15 05:45:33 +00001510 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001511 } else {
1512 // Iterate over all of the instructions in a function, replacing them with
1513 // constants if we have found them to be of constant values.
1514 //
1515 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1516 Instruction *Inst = BI++;
1517 if (Inst->getType() != Type::VoidTy) {
1518 LatticeVal &IV = Values[Inst];
Devang Patel9f26f732007-05-17 22:10:15 +00001519 if ((IV.isConstant() || IV.isUndefined()) &&
Chris Lattner59acc7d2004-12-10 08:02:06 +00001520 !isa<TerminatorInst>(Inst)) {
1521 Constant *Const = IV.isConstant()
1522 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendlingb7427032006-11-26 09:46:52 +00001523 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanfd939082005-04-21 23:48:37 +00001524
Chris Lattner59acc7d2004-12-10 08:02:06 +00001525 // Replaces all of the uses of a variable with uses of the constant.
1526 Inst->replaceAllUsesWith(Const);
Misha Brukmanfd939082005-04-21 23:48:37 +00001527
Chris Lattner59acc7d2004-12-10 08:02:06 +00001528 // Delete the instruction.
1529 BB->getInstList().erase(Inst);
Misha Brukmanfd939082005-04-21 23:48:37 +00001530
Chris Lattner59acc7d2004-12-10 08:02:06 +00001531 // Hey, we just changed something!
1532 MadeChanges = true;
1533 ++NumInstRemoved;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001534 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001535 }
1536 }
1537 }
1538
1539 return MadeChanges;
1540}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001541
1542namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001543 //===--------------------------------------------------------------------===//
1544 //
1545 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1546 /// Constant Propagation.
1547 ///
Reid Spencer9133fe22007-02-05 23:32:05 +00001548 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001549 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +00001550 IPSCCP() : ModulePass((intptr_t)&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001551 bool runOnModule(Module &M);
1552 };
1553
Devang Patel19974732007-05-03 01:11:54 +00001554 char IPSCCP::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +00001555 RegisterPass<IPSCCP>
Chris Lattner59acc7d2004-12-10 08:02:06 +00001556 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1557} // end anonymous namespace
1558
1559// createIPSCCPPass - This is the public interface to this file...
1560ModulePass *llvm::createIPSCCPPass() {
1561 return new IPSCCP();
1562}
1563
1564
1565static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001566 // Delete any dead constantexpr klingons.
1567 GV->removeDeadConstantUsers();
1568
Chris Lattner59acc7d2004-12-10 08:02:06 +00001569 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1570 UI != E; ++UI)
1571 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001572 if (SI->getOperand(0) == GV || SI->isVolatile())
1573 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001574 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1575 // Make sure we are calling the function, not passing the address.
1576 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1577 for (CallSite::arg_iterator AI = CS.arg_begin(),
1578 E = CS.arg_end(); AI != E; ++AI)
1579 if (*AI == GV)
1580 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001581 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1582 if (LI->isVolatile())
1583 return true;
1584 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001585 return true;
1586 }
1587 return false;
1588}
1589
1590bool IPSCCP::runOnModule(Module &M) {
1591 SCCPSolver Solver;
1592
1593 // Loop over all functions, marking arguments to those with their addresses
1594 // taken or that are external as overdefined.
1595 //
Chris Lattner59acc7d2004-12-10 08:02:06 +00001596 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1597 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001598 if (!F->isDeclaration())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001599 Solver.MarkBlockExecutable(F->begin());
Chris Lattner7d27fc02005-04-19 19:16:19 +00001600 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1601 AI != E; ++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001602 Solver.markOverdefined(AI);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001603 } else {
1604 Solver.AddTrackedFunction(F);
1605 }
1606
Chris Lattnerdd336d12004-12-11 05:15:59 +00001607 // Loop over global variables. We inform the solver about any internal global
1608 // variables that do not have their 'addresses taken'. If they don't have
1609 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001610 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1611 G != E; ++G)
Chris Lattnerdd336d12004-12-11 05:15:59 +00001612 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1613 Solver.TrackValueOfGlobalVariable(G);
1614
Chris Lattner59acc7d2004-12-10 08:02:06 +00001615 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001616 bool ResolvedUndefs = true;
1617 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001618 Solver.Solve();
1619
Chris Lattner3bad2532006-12-20 06:21:33 +00001620 DOUT << "RESOLVING UNDEFS\n";
1621 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001622 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001623 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001624 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001625
1626 bool MadeChanges = false;
1627
1628 // Iterate over all of the instructions in the module, replacing them with
1629 // constants if we have found them to be of constant values.
1630 //
Chris Lattnercc56aad2007-02-02 20:57:39 +00001631 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001632 SmallVector<Instruction*, 32> Insts;
1633 SmallVector<BasicBlock*, 32> BlocksToErase;
Chris Lattner57939df2007-03-04 04:50:21 +00001634 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001635
Chris Lattner59acc7d2004-12-10 08:02:06 +00001636 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001637 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1638 AI != E; ++AI)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001639 if (!AI->use_empty()) {
1640 LatticeVal &IV = Values[AI];
1641 if (IV.isConstant() || IV.isUndefined()) {
1642 Constant *CST = IV.isConstant() ?
1643 IV.getConstant() : UndefValue::get(AI->getType());
Bill Wendlingb7427032006-11-26 09:46:52 +00001644 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
Misha Brukmanfd939082005-04-21 23:48:37 +00001645
Chris Lattner59acc7d2004-12-10 08:02:06 +00001646 // Replaces all of the uses of a variable with uses of the
1647 // constant.
1648 AI->replaceAllUsesWith(CST);
1649 ++IPNumArgsElimed;
1650 }
1651 }
1652
1653 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1654 if (!ExecutableBBs.count(BB)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001655 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001656 ++IPNumDeadBlocks;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001657
Chris Lattner59acc7d2004-12-10 08:02:06 +00001658 // Delete the instructions backwards, as it has a reduced likelihood of
1659 // having to update as many def-use and use-def chains.
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001660 TerminatorInst *TI = BB->getTerminator();
1661 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001662 Insts.push_back(I);
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001663
Chris Lattner59acc7d2004-12-10 08:02:06 +00001664 while (!Insts.empty()) {
1665 Instruction *I = Insts.back();
1666 Insts.pop_back();
1667 if (!I->use_empty())
1668 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1669 BB->getInstList().erase(I);
1670 MadeChanges = true;
1671 ++IPNumInstRemoved;
1672 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001673
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001674 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1675 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001676 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001677 TI->getSuccessor(i)->removePredecessor(BB);
1678 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001679 if (!TI->use_empty())
1680 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001681 BB->getInstList().erase(TI);
1682
Chris Lattner864737b2004-12-11 05:32:19 +00001683 if (&*BB != &F->front())
1684 BlocksToErase.push_back(BB);
1685 else
1686 new UnreachableInst(BB);
1687
Chris Lattner59acc7d2004-12-10 08:02:06 +00001688 } else {
1689 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1690 Instruction *Inst = BI++;
1691 if (Inst->getType() != Type::VoidTy) {
1692 LatticeVal &IV = Values[Inst];
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001693 if (IV.isConstant() ||
1694 (IV.isUndefined() && !isa<TerminatorInst>(Inst))) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001695 Constant *Const = IV.isConstant()
1696 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendlingb7427032006-11-26 09:46:52 +00001697 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanfd939082005-04-21 23:48:37 +00001698
Chris Lattner59acc7d2004-12-10 08:02:06 +00001699 // Replaces all of the uses of a variable with uses of the
1700 // constant.
1701 Inst->replaceAllUsesWith(Const);
Misha Brukmanfd939082005-04-21 23:48:37 +00001702
Chris Lattner59acc7d2004-12-10 08:02:06 +00001703 // Delete the instruction.
1704 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1705 BB->getInstList().erase(Inst);
1706
1707 // Hey, we just changed something!
1708 MadeChanges = true;
1709 ++IPNumInstRemoved;
1710 }
1711 }
1712 }
1713 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001714
1715 // Now that all instructions in the function are constant folded, erase dead
1716 // blocks, because we can now use ConstantFoldTerminator to get rid of
1717 // in-edges.
1718 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1719 // If there are any PHI nodes in this successor, drop entries for BB now.
1720 BasicBlock *DeadBB = BlocksToErase[i];
1721 while (!DeadBB->use_empty()) {
Nick Lewycky6c36a0f2008-03-08 07:48:41 +00001722 if (BasicBlock *PredBB = dyn_cast<BasicBlock>(DeadBB->use_back())) {
1723 PredBB->setUnwindDest(NULL);
1724 continue;
1725 }
1726
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001727 Instruction *I = cast<Instruction>(DeadBB->use_back());
1728 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001729 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001730 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001731 // if this is a branch or switch on undef. Fold it manually as a
1732 // branch to the first successor.
1733 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1734 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1735 "Branch should be foldable!");
1736 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1737 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1738 } else {
1739 assert(0 && "Didn't fold away reference to block!");
1740 }
1741
1742 // Make this an uncond branch to the first successor.
1743 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001744 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001745
1746 // Remove entries in successor phi nodes to remove edges.
1747 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1748 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1749
1750 // Remove the old terminator.
1751 TI->eraseFromParent();
1752 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001753 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001754
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001755 // Finally, delete the basic block.
1756 F->getBasicBlockList().erase(DeadBB);
1757 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001758 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001759 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001760
1761 // If we inferred constant or undef return values for a function, we replaced
1762 // all call uses with the inferred value. This means we don't need to bother
1763 // actually returning anything from the function. Replace all return
1764 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001765 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001766 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001767 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner0417feb2004-12-11 02:53:57 +00001768 E = RV.end(); I != E; ++I)
1769 if (!I->second.isOverdefined() &&
1770 I->first->getReturnType() != Type::VoidTy) {
1771 Function *F = I->first;
1772 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1773 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1774 if (!isa<UndefValue>(RI->getOperand(0)))
1775 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1776 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001777
1778 // If we infered constant or undef values for globals variables, we can delete
1779 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001780 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1781 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001782 E = TG.end(); I != E; ++I) {
1783 GlobalVariable *GV = I->first;
1784 assert(!I->second.isOverdefined() &&
1785 "Overdefined values should have been taken out of the map!");
Bill Wendlingb7427032006-11-26 09:46:52 +00001786 DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
Chris Lattnerdd336d12004-12-11 05:15:59 +00001787 while (!GV->use_empty()) {
1788 StoreInst *SI = cast<StoreInst>(GV->use_back());
1789 SI->eraseFromParent();
1790 }
1791 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001792 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001793 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001794
Chris Lattner59acc7d2004-12-10 08:02:06 +00001795 return MadeChanges;
1796}