blob: a49bcc84547b7ba2a74aa0fb1864509359f3f3fe [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"
Dan Gohmanc4b65ea2008-06-20 01:15:44 +000032#include "llvm/Analysis/ValueTracking.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000033#include "llvm/Transforms/Utils/Local.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000034#include "llvm/Support/CallSite.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000035#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000036#include "llvm/Support/Debug.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000037#include "llvm/Support/InstVisitor.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000038#include "llvm/ADT/DenseMap.h"
Chris Lattnercf712de2008-08-23 23:36:38 +000039#include "llvm/ADT/DenseSet.h"
Chris Lattnercc56aad2007-02-02 20:57:39 +000040#include "llvm/ADT/SmallSet.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000041#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000042#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000044#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000045#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000046using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000047
Chris Lattner0e5f4992006-12-19 21:40:18 +000048STATISTIC(NumInstRemoved, "Number of instructions removed");
49STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
50
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000051STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000052STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
53STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
54STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
55
Chris Lattner0dbfc052002-04-29 21:26:08 +000056namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000057/// LatticeVal class - This class represents the different lattice values that
58/// an LLVM value may occupy. It is a simple class with value semantics.
59///
Reid Spencer9133fe22007-02-05 23:32:05 +000060class VISIBILITY_HIDDEN LatticeVal {
Misha Brukmanfd939082005-04-21 23:48:37 +000061 enum {
Chris Lattner3bad2532006-12-20 06:21:33 +000062 /// undefined - This LLVM Value has no known value yet.
63 undefined,
64
65 /// constant - This LLVM Value has a specific constant value.
66 constant,
67
68 /// forcedconstant - This LLVM Value was thought to be undef until
69 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
70 /// with another (different) constant, it goes to overdefined, instead of
71 /// asserting.
72 forcedconstant,
73
74 /// overdefined - This instruction is not known to be constant, and we know
75 /// it has a value.
76 overdefined
77 } LatticeValue; // The current lattice position
78
Chris Lattnere9bb2df2001-12-03 22:26:30 +000079 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner138a1242001-06-27 23:38:11 +000080public:
Chris Lattneref36dfd2004-11-15 05:03:30 +000081 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000082
Chris Lattner138a1242001-06-27 23:38:11 +000083 // markOverdefined - Return true if this is a new status to be in...
84 inline bool markOverdefined() {
Chris Lattnere9bb2df2001-12-03 22:26:30 +000085 if (LatticeValue != overdefined) {
86 LatticeValue = overdefined;
Chris Lattner138a1242001-06-27 23:38:11 +000087 return true;
88 }
89 return false;
90 }
91
Chris Lattner3bad2532006-12-20 06:21:33 +000092 // markConstant - Return true if this is a new status for us.
Chris Lattnere9bb2df2001-12-03 22:26:30 +000093 inline bool markConstant(Constant *V) {
94 if (LatticeValue != constant) {
Chris Lattner3bad2532006-12-20 06:21:33 +000095 if (LatticeValue == undefined) {
96 LatticeValue = constant;
Jim Laskey52ab9042007-01-03 00:11:03 +000097 assert(V && "Marking constant with NULL");
Chris Lattner3bad2532006-12-20 06:21:33 +000098 ConstantVal = V;
99 } else {
100 assert(LatticeValue == forcedconstant &&
101 "Cannot move from overdefined to constant!");
102 // Stay at forcedconstant if the constant is the same.
103 if (V == ConstantVal) return false;
104
105 // Otherwise, we go to overdefined. Assumptions made based on the
106 // forced value are possibly wrong. Assuming this is another constant
107 // could expose a contradiction.
108 LatticeValue = overdefined;
109 }
Chris Lattner138a1242001-06-27 23:38:11 +0000110 return true;
111 } else {
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000112 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner138a1242001-06-27 23:38:11 +0000113 }
114 return false;
115 }
116
Chris Lattner3bad2532006-12-20 06:21:33 +0000117 inline void markForcedConstant(Constant *V) {
118 assert(LatticeValue == undefined && "Can't force a defined value!");
119 LatticeValue = forcedconstant;
120 ConstantVal = V;
121 }
122
123 inline bool isUndefined() const { return LatticeValue == undefined; }
124 inline bool isConstant() const {
125 return LatticeValue == constant || LatticeValue == forcedconstant;
126 }
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000127 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner138a1242001-06-27 23:38:11 +0000128
Chris Lattner1daee8b2004-01-12 03:57:30 +0000129 inline Constant *getConstant() const {
130 assert(isConstant() && "Cannot get the constant of a non-constant!");
131 return ConstantVal;
132 }
Chris Lattner138a1242001-06-27 23:38:11 +0000133};
134
Chris Lattner138a1242001-06-27 23:38:11 +0000135//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000136//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000137/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
138/// Constant Propagation.
139///
140class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattnercf712de2008-08-23 23:36:38 +0000141 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000142 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000143
Chris Lattnerdd336d12004-12-11 05:15:59 +0000144 /// GlobalValue - If we are tracking any values for the contents of a global
145 /// variable, we keep a mapping from the constant accessor to the element of
146 /// the global, to the currently known value. If the value becomes
147 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000148 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000149
Devang Patel7c490d42008-03-11 05:46:42 +0000150 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000151 /// value out of a function, it will have an entry in this map, indicating
152 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000153 DenseMap<Function*, LatticeVal> TrackedRetVals;
154
155 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
156 /// that return multiple values.
Chris Lattnercf712de2008-08-23 23:36:38 +0000157 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000158
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000159 // The reason for two worklists is that overdefined is the lowest state
160 // on the lattice, and moving things to overdefined as fast as possible
161 // makes SCCP converge much faster.
162 // By having a separate worklist, we accomplish this because everything
163 // possibly overdefined will become overdefined at the soonest possible
164 // point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000165 SmallVector<Value*, 64> OverdefinedInstWorkList;
166 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000167
168
Chris Lattnercf712de2008-08-23 23:36:38 +0000169 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000170
Chris Lattner1daee8b2004-01-12 03:57:30 +0000171 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
172 /// overdefined, despite the fact that the PHI node is overdefined.
173 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
174
Chris Lattner16b18fd2003-10-08 16:55:34 +0000175 /// KnownFeasibleEdges - Entries in this set are edges which have already had
176 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000177 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
178 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000179public:
180
Chris Lattner82bec2c2004-11-15 04:44:20 +0000181 /// MarkBlockExecutable - This method can be used by clients to mark all of
182 /// the blocks that are known to be intrinsically live in the processed unit.
183 void MarkBlockExecutable(BasicBlock *BB) {
Chris Lattner5c8e8d72008-05-11 01:55:59 +0000184 DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n";
Chris Lattner82bec2c2004-11-15 04:44:20 +0000185 BBExecutable.insert(BB); // Basic block is executable!
186 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner0dbfc052002-04-29 21:26:08 +0000187 }
188
Chris Lattnerdd336d12004-12-11 05:15:59 +0000189 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000190 /// inform the SCCPSolver that it should track loads and stores to the
191 /// specified global variable if it can. This is only legal to call if
192 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000193 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
194 const Type *ElTy = GV->getType()->getElementType();
195 if (ElTy->isFirstClassType()) {
196 LatticeVal &IV = TrackedGlobals[GV];
197 if (!isa<UndefValue>(GV->getInitializer()))
198 IV.markConstant(GV->getInitializer());
199 }
200 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000201
202 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
203 /// and out of the specified function (which cannot have its address taken),
204 /// this method must be called.
205 void AddTrackedFunction(Function *F) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000206 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Chris Lattner59acc7d2004-12-10 08:02:06 +0000207 // Add an entry, F -> undef.
Devang Patel7c490d42008-03-11 05:46:42 +0000208 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
209 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000210 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
211 LatticeVal()));
212 } else
213 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000214 }
215
Chris Lattner82bec2c2004-11-15 04:44:20 +0000216 /// Solve - Solve for constants and executable blocks.
217 ///
218 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000219
Chris Lattner3bad2532006-12-20 06:21:33 +0000220 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000221 /// that branches on undef values cannot reach any of their successors.
222 /// However, this is not a safe assumption. After we solve dataflow, this
223 /// method should be use to handle this. If this returns true, the solver
224 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000225 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000226
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000227 bool isBlockExecutable(BasicBlock *BB) const {
228 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000229 }
230
231 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattneref36dfd2004-11-15 05:03:30 +0000232 /// LLVM values to LatticeVals.
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000233 std::map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000234 return ValueState;
235 }
236
Devang Patel7c490d42008-03-11 05:46:42 +0000237 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000238 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000239 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
240 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000241 }
242
Chris Lattnerdd336d12004-12-11 05:15:59 +0000243 /// getTrackedGlobals - Get and return the set of inferred initializers for
244 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000245 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000246 return TrackedGlobals;
247 }
248
Chris Lattner57939df2007-03-04 04:50:21 +0000249 inline void markOverdefined(Value *V) {
250 markOverdefined(ValueState[V], V);
251 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000252
Chris Lattner138a1242001-06-27 23:38:11 +0000253private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000254 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000255 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000256 // the users of the instruction are updated later.
257 //
Chris Lattner59acc7d2004-12-10 08:02:06 +0000258 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000259 if (IV.markConstant(C)) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000260 DOUT << "markConstant: " << *C << ": " << *V;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000261 InstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000262 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000263 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000264
265 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
266 IV.markForcedConstant(C);
267 DOUT << "markForcedConstant: " << *C << ": " << *V;
268 InstWorkList.push_back(V);
269 }
270
Chris Lattner59acc7d2004-12-10 08:02:06 +0000271 inline void markConstant(Value *V, Constant *C) {
272 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000273 }
274
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000275 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000276 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000277 // work list so that the users of the instruction are updated later.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000278 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000279 if (IV.markOverdefined()) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000280 DEBUG(DOUT << "markOverdefined: ";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000281 if (Function *F = dyn_cast<Function>(V))
Bill Wendlingb7427032006-11-26 09:46:52 +0000282 DOUT << "Function '" << F->getName() << "'\n";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000283 else
Bill Wendlingb7427032006-11-26 09:46:52 +0000284 DOUT << *V);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000285 // Only instructions go on the work list
Chris Lattner59acc7d2004-12-10 08:02:06 +0000286 OverdefinedInstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000287 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000288 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000289
290 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
291 if (IV.isOverdefined() || MergeWithV.isUndefined())
292 return; // Noop.
293 if (MergeWithV.isOverdefined())
294 markOverdefined(IV, V);
295 else if (IV.isUndefined())
296 markConstant(IV, V, MergeWithV.getConstant());
297 else if (IV.getConstant() != MergeWithV.getConstant())
298 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000299 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000300
301 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
302 return mergeInValue(ValueState[V], V, MergeWithV);
303 }
304
Chris Lattner138a1242001-06-27 23:38:11 +0000305
Chris Lattneref36dfd2004-11-15 05:03:30 +0000306 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman5560c9d2003-08-18 14:43:39 +0000307 // This function is necessary because not all values should start out in the
Chris Lattner73e21422002-04-09 19:48:49 +0000308 // underdefined state... Argument's should be overdefined, and
Chris Lattner79df7c02002-03-26 18:01:55 +0000309 // constants should be marked as constants. If a value is not known to be an
Chris Lattner138a1242001-06-27 23:38:11 +0000310 // Instruction object, then use this accessor to get its value from the map.
311 //
Chris Lattneref36dfd2004-11-15 05:03:30 +0000312 inline LatticeVal &getValueState(Value *V) {
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000313 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000314 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000315
Chris Lattner3bad2532006-12-20 06:21:33 +0000316 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner7e529e42004-11-15 05:45:33 +0000317 if (isa<UndefValue>(V)) {
318 // Nothing to do, remain undefined.
319 } else {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000320 LatticeVal &LV = ValueState[C];
321 LV.markConstant(C); // Constants are constant
322 return LV;
Chris Lattner7e529e42004-11-15 05:45:33 +0000323 }
Chris Lattner2a88bb72002-08-30 23:39:00 +0000324 }
Chris Lattner138a1242001-06-27 23:38:11 +0000325 // All others are underdefined by default...
326 return ValueState[V];
327 }
328
Misha Brukmanfd939082005-04-21 23:48:37 +0000329 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner138a1242001-06-27 23:38:11 +0000330 // work list if it is not already executable...
Misha Brukmanfd939082005-04-21 23:48:37 +0000331 //
Chris Lattner16b18fd2003-10-08 16:55:34 +0000332 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
333 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
334 return; // This edge is already known to be executable!
335
336 if (BBExecutable.count(Dest)) {
Chris Lattner5c8e8d72008-05-11 01:55:59 +0000337 DOUT << "Marking Edge Executable: " << Source->getNameStart()
338 << " -> " << Dest->getNameStart() << "\n";
Chris Lattner16b18fd2003-10-08 16:55:34 +0000339
340 // The destination is already executable, but we just made an edge
Chris Lattner929c6fb2003-10-08 16:56:11 +0000341 // feasible that wasn't before. Revisit the PHI nodes in the block
342 // because they have potentially new operands.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000343 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
344 visitPHINode(*cast<PHINode>(I));
Chris Lattner9de28282003-04-25 02:50:03 +0000345
346 } else {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000347 MarkBlockExecutable(Dest);
Chris Lattner9de28282003-04-25 02:50:03 +0000348 }
Chris Lattner138a1242001-06-27 23:38:11 +0000349 }
350
Chris Lattner82bec2c2004-11-15 04:44:20 +0000351 // getFeasibleSuccessors - Return a vector of booleans to indicate which
352 // successors are reachable from a given terminator instruction.
353 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000354 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000355
356 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
357 // block to the 'To' basic block is currently feasible...
358 //
359 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
360
361 // OperandChangedState - This method is invoked on all of the users of an
362 // instruction that was just changed state somehow.... Based on this
363 // information, we need to update the specified user of this instruction.
364 //
365 void OperandChangedState(User *U) {
366 // Only instructions use other variable values!
367 Instruction &I = cast<Instruction>(*U);
368 if (BBExecutable.count(I.getParent())) // Inst is executable?
369 visit(I);
370 }
371
372private:
373 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000374
Misha Brukmanfd939082005-04-21 23:48:37 +0000375 // visit implementations - Something changed in this instruction... Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000376 // operand made a transition, or the instruction is newly executable. Change
377 // the value type of I to reflect these changes if appropriate.
378 //
Chris Lattner7e708292002-06-25 16:13:24 +0000379 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000380
381 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000382 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000383 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000384
Chris Lattnerb8047602002-08-14 17:53:45 +0000385 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000386 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000387 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000388 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000389 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000390 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000391 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000392 void visitExtractValueInst(ExtractValueInst &EVI);
393 void visitInsertValueInst(InsertValueInst &IVI);
Chris Lattner2a632552002-04-18 15:13:15 +0000394
395 // Instructions that cannot be folded away...
Chris Lattnerdd336d12004-12-11 05:15:59 +0000396 void visitStoreInst (Instruction &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000397 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000398 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner59acc7d2004-12-10 08:02:06 +0000399 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
400 void visitInvokeInst (InvokeInst &II) {
401 visitCallSite(CallSite::get(&II));
402 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000403 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000404 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000405 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000406 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner7e708292002-06-25 16:13:24 +0000407 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000408 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
409 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner7e708292002-06-25 16:13:24 +0000410 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner2a632552002-04-18 15:13:15 +0000411
Chris Lattner7e708292002-06-25 16:13:24 +0000412 void visitInstruction(Instruction &I) {
Chris Lattner2a632552002-04-18 15:13:15 +0000413 // If a new instruction is added to LLVM that we don't handle...
Bill Wendlinge8156192006-12-07 01:30:32 +0000414 cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000415 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000416 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000417};
Chris Lattnerf6293092002-07-23 18:06:35 +0000418
Duncan Sandse2abf122007-07-20 08:56:21 +0000419} // end anonymous namespace
420
421
Chris Lattnerb9a66342002-05-02 21:44:00 +0000422// getFeasibleSuccessors - Return a vector of booleans to indicate which
423// successors are reachable from a given terminator instruction.
424//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000425void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000426 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000427 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000428 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000429 if (BI->isUnconditional()) {
430 Succs[0] = true;
431 } else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000432 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000433 if (BCValue.isOverdefined() ||
Reid Spencer579dca12007-01-12 04:24:46 +0000434 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
Chris Lattner84831642004-01-12 17:40:36 +0000435 // Overdefined condition variables, and branches on unfoldable constant
436 // conditions, mean the branch could go either way.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000437 Succs[0] = Succs[1] = true;
438 } else if (BCValue.isConstant()) {
439 // Constant condition variables mean the branch can only go a single way
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000440 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000441 }
442 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000443 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000444 // Invoke instructions successors are always executable.
445 Succs[0] = Succs[1] = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000446 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000447 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000448 if (SCValue.isOverdefined() || // Overdefined condition?
449 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000450 // All destinations are executable!
Chris Lattner7e708292002-06-25 16:13:24 +0000451 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner3a73c9e2008-05-10 23:56:54 +0000452 } else if (SCValue.isConstant())
453 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000454 } else {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000455 assert(0 && "SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000456 }
457}
458
459
Chris Lattner59f0ce22002-05-02 21:18:01 +0000460// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
461// block to the 'To' basic block is currently feasible...
462//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000463bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000464 assert(BBExecutable.count(To) && "Dest should always be alive!");
465
466 // Make sure the source basic block is executable!!
467 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000468
Chris Lattnerb9a66342002-05-02 21:44:00 +0000469 // Check to make sure this edge itself is actually feasible now...
Chris Lattner7d275f42003-10-08 15:47:41 +0000470 TerminatorInst *TI = From->getTerminator();
471 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
472 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000473 return true;
Chris Lattner7d275f42003-10-08 15:47:41 +0000474 else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000475 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000476 if (BCValue.isOverdefined()) {
477 // Overdefined condition variables mean the branch could go either way.
478 return true;
479 } else if (BCValue.isConstant()) {
Chris Lattner84831642004-01-12 17:40:36 +0000480 // Not branching on an evaluatable constant?
Chris Lattner54a525d2007-01-13 00:42:58 +0000481 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
Chris Lattner84831642004-01-12 17:40:36 +0000482
Chris Lattner7d275f42003-10-08 15:47:41 +0000483 // Constant condition variables mean the branch can only go a single way
Misha Brukmanfd939082005-04-21 23:48:37 +0000484 return BI->getSuccessor(BCValue.getConstant() ==
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000485 ConstantInt::getFalse()) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000486 }
487 return false;
488 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000489 } else if (isa<InvokeInst>(TI)) {
Chris Lattner7d275f42003-10-08 15:47:41 +0000490 // Invoke instructions successors are always executable.
491 return true;
492 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000493 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000494 if (SCValue.isOverdefined()) { // Overdefined condition?
495 // All destinations are executable!
496 return true;
497 } else if (SCValue.isConstant()) {
498 Constant *CPV = SCValue.getConstant();
Chris Lattner84831642004-01-12 17:40:36 +0000499 if (!isa<ConstantInt>(CPV))
500 return true; // not a foldable constant?
501
Chris Lattner7d275f42003-10-08 15:47:41 +0000502 // Make sure to skip the "default value" which isn't a value
503 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
504 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
505 return SI->getSuccessor(i) == To;
506
507 // Constant value not equal to any of the branches... must execute
508 // default branch then...
509 return SI->getDefaultDest() == To;
510 }
511 return false;
512 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000513 cerr << "Unknown terminator instruction: " << *TI;
Chris Lattner7d275f42003-10-08 15:47:41 +0000514 abort();
515 }
Chris Lattner59f0ce22002-05-02 21:18:01 +0000516}
Chris Lattner138a1242001-06-27 23:38:11 +0000517
Chris Lattner2a632552002-04-18 15:13:15 +0000518// visit Implementations - Something changed in this instruction... Either an
Chris Lattner138a1242001-06-27 23:38:11 +0000519// operand made a transition, or the instruction is newly executable. Change
520// the value type of I to reflect these changes if appropriate. This method
521// makes sure to do the following actions:
522//
523// 1. If a phi node merges two constants in, and has conflicting value coming
524// from different branches, or if the PHI node merges in an overdefined
525// value, then the PHI node becomes overdefined.
526// 2. If a phi node merges only constants in, and they all agree on value, the
527// PHI node becomes a constant value equal to that.
528// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
529// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
530// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
531// 6. If a conditional branch has a value that is constant, make the selected
532// destination executable
533// 7. If a conditional branch has a value that is overdefined, make all
534// successors executable.
535//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000536void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000537 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000538 if (PNIV.isOverdefined()) {
539 // There may be instructions using this PHI node that are not overdefined
540 // themselves. If so, make sure that they know that the PHI node operand
541 // changed.
542 std::multimap<PHINode*, Instruction*>::iterator I, E;
543 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
544 if (I != E) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000545 SmallVector<Instruction*, 16> Users;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000546 for (; I != E; ++I) Users.push_back(I->second);
547 while (!Users.empty()) {
548 visit(Users.back());
549 Users.pop_back();
550 }
551 }
552 return; // Quick exit
553 }
Chris Lattner138a1242001-06-27 23:38:11 +0000554
Chris Lattnera2f652d2004-03-16 19:49:59 +0000555 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
556 // and slow us down a lot. Just mark them overdefined.
557 if (PN.getNumIncomingValues() > 64) {
558 markOverdefined(PNIV, &PN);
559 return;
560 }
561
Chris Lattner2a632552002-04-18 15:13:15 +0000562 // Look at all of the executable operands of the PHI node. If any of them
563 // are overdefined, the PHI becomes overdefined as well. If they are all
564 // constant, and they agree with each other, the PHI becomes the identical
565 // constant. If they are constant and don't agree, the PHI is overdefined.
566 // If there are no executable operands, the PHI remains undefined.
567 //
Chris Lattner9de28282003-04-25 02:50:03 +0000568 Constant *OperandVal = 0;
569 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000570 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000571 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000572
Chris Lattner7e708292002-06-25 16:13:24 +0000573 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner38b5ae42003-06-24 20:29:52 +0000574 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattnercf712de2008-08-23 23:36:38 +0000575 markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000576 return;
577 }
578
Chris Lattner9de28282003-04-25 02:50:03 +0000579 if (OperandVal == 0) { // Grab the first value...
580 OperandVal = IV.getConstant();
Chris Lattner2a632552002-04-18 15:13:15 +0000581 } else { // Another value is being merged in!
582 // There is already a reachable operand. If we conflict with it,
583 // then the PHI node becomes overdefined. If we agree with it, we
584 // can continue on.
Misha Brukmanfd939082005-04-21 23:48:37 +0000585
Chris Lattner2a632552002-04-18 15:13:15 +0000586 // Check to see if there are two different constants merging...
Chris Lattner9de28282003-04-25 02:50:03 +0000587 if (IV.getConstant() != OperandVal) {
Chris Lattner2a632552002-04-18 15:13:15 +0000588 // Yes there is. This means the PHI node is not constant.
589 // You must be overdefined poor PHI.
590 //
Chris Lattnercf712de2008-08-23 23:36:38 +0000591 markOverdefined(&PN); // The PHI node now becomes overdefined
Chris Lattner2a632552002-04-18 15:13:15 +0000592 return; // I'm done analyzing you
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000593 }
Chris Lattner138a1242001-06-27 23:38:11 +0000594 }
595 }
Chris Lattner138a1242001-06-27 23:38:11 +0000596 }
597
Chris Lattner2a632552002-04-18 15:13:15 +0000598 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000599 // arguments that agree with each other(and OperandVal is the constant) or
600 // OperandVal is null because there are no defined incoming arguments. If
601 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000602 //
Chris Lattner9de28282003-04-25 02:50:03 +0000603 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000604 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000605}
606
Chris Lattner59acc7d2004-12-10 08:02:06 +0000607void SCCPSolver::visitReturnInst(ReturnInst &I) {
608 if (I.getNumOperands() == 0) return; // Ret void
609
Chris Lattner59acc7d2004-12-10 08:02:06 +0000610 Function *F = I.getParent()->getParent();
Devang Patel7c490d42008-03-11 05:46:42 +0000611 // If we are tracking the return value of this function, merge it in.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000612 if (!F->hasLocalLinkage())
Devang Patel7c490d42008-03-11 05:46:42 +0000613 return;
614
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000615 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000616 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000617 TrackedRetVals.find(F);
618 if (TFRVI != TrackedRetVals.end() &&
Chris Lattner59acc7d2004-12-10 08:02:06 +0000619 !TFRVI->second.isOverdefined()) {
620 LatticeVal &IV = getValueState(I.getOperand(0));
621 mergeInValue(TFRVI->second, F, IV);
Devang Patel7c490d42008-03-11 05:46:42 +0000622 return;
623 }
624 }
625
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000626 // Handle functions that return multiple values.
627 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
628 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000629 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000630 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
631 if (It == TrackedMultipleRetVals.end()) break;
632 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000633 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000634 } else if (!TrackedMultipleRetVals.empty() &&
635 I.getNumOperands() == 1 &&
636 isa<StructType>(I.getOperand(0)->getType())) {
637 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
638 i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000639 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000640 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
641 if (It == TrackedMultipleRetVals.end()) break;
642 Value *Val = FindInsertedValue(I.getOperand(0), i);
643 mergeInValue(It->second, F, getValueState(Val));
644 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000645 }
646}
647
Chris Lattner82bec2c2004-11-15 04:44:20 +0000648void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000649 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000650 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000651
Chris Lattner16b18fd2003-10-08 16:55:34 +0000652 BasicBlock *BB = TI.getParent();
653
Chris Lattnerb9a66342002-05-02 21:44:00 +0000654 // Mark all feasible successors executable...
655 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000656 if (SuccFeasible[i])
657 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000658}
659
Chris Lattner82bec2c2004-11-15 04:44:20 +0000660void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000661 Value *V = I.getOperand(0);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000662 LatticeVal &VState = getValueState(V);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000663 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000664 markOverdefined(&I);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000665 else if (VState.isConstant()) // Propagate constant value
Reid Spencer4da49122006-12-12 05:05:00 +0000666 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
667 VState.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000668}
669
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000670void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000671 Value *Aggr = EVI.getAggregateOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000672
Dan Gohman60ea2682008-06-20 16:41:17 +0000673 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000674 if (isa<UndefValue>(Aggr))
675 return;
676
677 // Currently only handle single-index extractvalues.
678 if (EVI.getNumIndices() != 1) {
679 markOverdefined(&EVI);
680 return;
681 }
682
683 Function *F = 0;
684 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
685 F = CI->getCalledFunction();
686 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
687 F = II->getCalledFunction();
688
689 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
690 // result back!
691 if (F == 0 || TrackedMultipleRetVals.empty()) {
692 markOverdefined(&EVI);
693 return;
694 }
695
Chris Lattnercf712de2008-08-23 23:36:38 +0000696 // See if we are tracking the result of the callee. If not tracking this
697 // function (for example, it is a declaration) just move to overdefined.
698 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000699 markOverdefined(&EVI);
700 return;
701 }
702
703 // Otherwise, the value will be merged in here as a result of CallSite
704 // handling.
705}
706
707void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000708 Value *Aggr = IVI.getAggregateOperand();
709 Value *Val = IVI.getInsertedValueOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000710
Dan Gohman60ea2682008-06-20 16:41:17 +0000711 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohmandfaceb42008-06-20 16:39:44 +0000712 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000713 return;
714
715 // Currently only handle single-index insertvalues.
716 if (IVI.getNumIndices() != 1) {
717 markOverdefined(&IVI);
718 return;
719 }
Dan Gohmandfaceb42008-06-20 16:39:44 +0000720
721 // Currently only handle insertvalue instructions that are in a single-use
722 // chain that builds up a return value.
723 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
724 if (!TmpIVI->hasOneUse()) {
725 markOverdefined(&IVI);
726 return;
727 }
728 const Value *V = *TmpIVI->use_begin();
729 if (isa<ReturnInst>(V))
730 break;
731 TmpIVI = dyn_cast<InsertValueInst>(V);
732 if (!TmpIVI) {
733 markOverdefined(&IVI);
734 return;
735 }
736 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000737
738 // See if we are tracking the result of the callee.
739 Function *F = IVI.getParent()->getParent();
Chris Lattnercf712de2008-08-23 23:36:38 +0000740 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000741 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
742
743 // Merge in the inserted member value.
744 if (It != TrackedMultipleRetVals.end())
745 mergeInValue(It->second, F, getValueState(Val));
746
Dan Gohman60ea2682008-06-20 16:41:17 +0000747 // Mark the aggregate result of the IVI overdefined; any tracking that we do
748 // will be done on the individual member values.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000749 markOverdefined(&IVI);
750}
751
Chris Lattner82bec2c2004-11-15 04:44:20 +0000752void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000753 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000754 if (CondValue.isUndefined())
755 return;
Reid Spencer579dca12007-01-12 04:24:46 +0000756 if (CondValue.isConstant()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000757 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencer579dca12007-01-12 04:24:46 +0000758 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000759 : I.getFalseValue()));
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000760 return;
761 }
762 }
763
764 // Otherwise, the condition is overdefined or a constant we can't evaluate.
765 // See if we can produce something better than overdefined based on the T/F
766 // value.
767 LatticeVal &TVal = getValueState(I.getTrueValue());
768 LatticeVal &FVal = getValueState(I.getFalseValue());
769
770 // select ?, C, C -> C.
771 if (TVal.isConstant() && FVal.isConstant() &&
772 TVal.getConstant() == FVal.getConstant()) {
773 markConstant(&I, FVal.getConstant());
774 return;
775 }
776
777 if (TVal.isUndefined()) { // select ?, undef, X -> X.
778 mergeInValue(&I, FVal);
779 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
780 mergeInValue(&I, TVal);
781 } else {
782 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000783 }
784}
785
Chris Lattner2a632552002-04-18 15:13:15 +0000786// Handle BinaryOperators and Shift Instructions...
Chris Lattner82bec2c2004-11-15 04:44:20 +0000787void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000788 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000789 if (IV.isOverdefined()) return;
790
Chris Lattneref36dfd2004-11-15 05:03:30 +0000791 LatticeVal &V1State = getValueState(I.getOperand(0));
792 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000793
Chris Lattner2a632552002-04-18 15:13:15 +0000794 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnera177c672004-12-11 23:15:19 +0000795 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
796 // operand is overdefined.
797 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
798 LatticeVal *NonOverdefVal = 0;
799 if (!V1State.isOverdefined()) {
800 NonOverdefVal = &V1State;
801 } else if (!V2State.isOverdefined()) {
802 NonOverdefVal = &V2State;
803 }
804
805 if (NonOverdefVal) {
806 if (NonOverdefVal->isUndefined()) {
807 // Could annihilate value.
808 if (I.getOpcode() == Instruction::And)
809 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +0000810 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
811 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +0000812 else
813 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera177c672004-12-11 23:15:19 +0000814 return;
815 } else {
816 if (I.getOpcode() == Instruction::And) {
817 if (NonOverdefVal->getConstant()->isNullValue()) {
818 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskey52ab9042007-01-03 00:11:03 +0000819 return; // X and 0 = 0
Chris Lattnera177c672004-12-11 23:15:19 +0000820 }
821 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000822 if (ConstantInt *CI =
823 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnera177c672004-12-11 23:15:19 +0000824 if (CI->isAllOnesValue()) {
825 markConstant(IV, &I, NonOverdefVal->getConstant());
826 return; // X or -1 = -1
827 }
828 }
829 }
830 }
831 }
832
833
Chris Lattner1daee8b2004-01-12 03:57:30 +0000834 // If both operands are PHI nodes, it is possible that this instruction has
835 // a constant value, despite the fact that the PHI node doesn't. Check for
836 // this condition now.
837 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
838 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
839 if (PN1->getParent() == PN2->getParent()) {
840 // Since the two PHI nodes are in the same basic block, they must have
841 // entries for the same predecessors. Walk the predecessor list, and
842 // if all of the incoming values are constants, and the result of
843 // evaluating this expression with all incoming value pairs is the
844 // same, then this expression is a constant even though the PHI node
845 // is not a constant!
Chris Lattneref36dfd2004-11-15 05:03:30 +0000846 LatticeVal Result;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000847 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000848 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000849 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000850 LatticeVal &In2 =
851 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000852
853 if (In1.isOverdefined() || In2.isOverdefined()) {
854 Result.markOverdefined();
855 break; // Cannot fold this operation over the PHI nodes!
856 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000857 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
858 In2.getConstant());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000859 if (Result.isUndefined())
Chris Lattnerb16689b2004-01-12 19:08:43 +0000860 Result.markConstant(V);
861 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000862 Result.markOverdefined();
863 break;
864 }
865 }
866 }
867
868 // If we found a constant value here, then we know the instruction is
869 // constant despite the fact that the PHI nodes are overdefined.
870 if (Result.isConstant()) {
871 markConstant(IV, &I, Result.getConstant());
872 // Remember that this instruction is virtually using the PHI node
873 // operands.
874 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
875 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
876 return;
877 } else if (Result.isUndefined()) {
878 return;
879 }
880
881 // Okay, this really is overdefined now. Since we might have
882 // speculatively thought that this was not overdefined before, and
883 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
884 // make sure to clean out any entries that we put there, for
885 // efficiency.
886 std::multimap<PHINode*, Instruction*>::iterator It, E;
887 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
888 while (It != E) {
889 if (It->second == &I) {
890 UsersOfOverdefinedPHIs.erase(It++);
891 } else
892 ++It;
893 }
894 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
895 while (It != E) {
896 if (It->second == &I) {
897 UsersOfOverdefinedPHIs.erase(It++);
898 } else
899 ++It;
900 }
901 }
902
903 markOverdefined(IV, &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000904 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000905 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
906 V2State.getConstant()));
Chris Lattner2a632552002-04-18 15:13:15 +0000907 }
908}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000909
Reid Spencere4d87aa2006-12-23 06:05:41 +0000910// Handle ICmpInst instruction...
911void SCCPSolver::visitCmpInst(CmpInst &I) {
912 LatticeVal &IV = ValueState[&I];
913 if (IV.isOverdefined()) return;
914
915 LatticeVal &V1State = getValueState(I.getOperand(0));
916 LatticeVal &V2State = getValueState(I.getOperand(1));
917
918 if (V1State.isOverdefined() || V2State.isOverdefined()) {
919 // If both operands are PHI nodes, it is possible that this instruction has
920 // a constant value, despite the fact that the PHI node doesn't. Check for
921 // this condition now.
922 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
923 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
924 if (PN1->getParent() == PN2->getParent()) {
925 // Since the two PHI nodes are in the same basic block, they must have
926 // entries for the same predecessors. Walk the predecessor list, and
927 // if all of the incoming values are constants, and the result of
928 // evaluating this expression with all incoming value pairs is the
929 // same, then this expression is a constant even though the PHI node
930 // is not a constant!
931 LatticeVal Result;
932 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
933 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
934 BasicBlock *InBlock = PN1->getIncomingBlock(i);
935 LatticeVal &In2 =
936 getValueState(PN2->getIncomingValueForBlock(InBlock));
937
938 if (In1.isOverdefined() || In2.isOverdefined()) {
939 Result.markOverdefined();
940 break; // Cannot fold this operation over the PHI nodes!
941 } else if (In1.isConstant() && In2.isConstant()) {
942 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
943 In1.getConstant(),
944 In2.getConstant());
945 if (Result.isUndefined())
946 Result.markConstant(V);
947 else if (Result.isConstant() && Result.getConstant() != V) {
948 Result.markOverdefined();
949 break;
950 }
951 }
952 }
953
954 // If we found a constant value here, then we know the instruction is
955 // constant despite the fact that the PHI nodes are overdefined.
956 if (Result.isConstant()) {
957 markConstant(IV, &I, Result.getConstant());
958 // Remember that this instruction is virtually using the PHI node
959 // operands.
960 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
961 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
962 return;
963 } else if (Result.isUndefined()) {
964 return;
965 }
966
967 // Okay, this really is overdefined now. Since we might have
968 // speculatively thought that this was not overdefined before, and
969 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
970 // make sure to clean out any entries that we put there, for
971 // efficiency.
972 std::multimap<PHINode*, Instruction*>::iterator It, E;
973 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
974 while (It != E) {
975 if (It->second == &I) {
976 UsersOfOverdefinedPHIs.erase(It++);
977 } else
978 ++It;
979 }
980 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
981 while (It != E) {
982 if (It->second == &I) {
983 UsersOfOverdefinedPHIs.erase(It++);
984 } else
985 ++It;
986 }
987 }
988
989 markOverdefined(IV, &I);
990 } else if (V1State.isConstant() && V2State.isConstant()) {
991 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
992 V1State.getConstant(),
993 V2State.getConstant()));
994 }
995}
996
Robert Bocchino56107e22006-01-10 19:05:05 +0000997void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +0000998 // FIXME : SCCP does not handle vectors properly.
999 markOverdefined(&I);
1000 return;
1001
1002#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +00001003 LatticeVal &ValState = getValueState(I.getOperand(0));
1004 LatticeVal &IdxState = getValueState(I.getOperand(1));
1005
1006 if (ValState.isOverdefined() || IdxState.isOverdefined())
1007 markOverdefined(&I);
1008 else if(ValState.isConstant() && IdxState.isConstant())
1009 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1010 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001011#endif
Robert Bocchino56107e22006-01-10 19:05:05 +00001012}
1013
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001014void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001015 // FIXME : SCCP does not handle vectors properly.
1016 markOverdefined(&I);
1017 return;
1018#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001019 LatticeVal &ValState = getValueState(I.getOperand(0));
1020 LatticeVal &EltState = getValueState(I.getOperand(1));
1021 LatticeVal &IdxState = getValueState(I.getOperand(2));
1022
1023 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1024 IdxState.isOverdefined())
1025 markOverdefined(&I);
1026 else if(ValState.isConstant() && EltState.isConstant() &&
1027 IdxState.isConstant())
1028 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1029 EltState.getConstant(),
1030 IdxState.getConstant()));
1031 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +00001032 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +00001033 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1034 EltState.getConstant(),
1035 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001036#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001037}
1038
Chris Lattner543abdf2006-04-08 01:19:12 +00001039void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001040 // FIXME : SCCP does not handle vectors properly.
1041 markOverdefined(&I);
1042 return;
1043#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +00001044 LatticeVal &V1State = getValueState(I.getOperand(0));
1045 LatticeVal &V2State = getValueState(I.getOperand(1));
1046 LatticeVal &MaskState = getValueState(I.getOperand(2));
1047
1048 if (MaskState.isUndefined() ||
1049 (V1State.isUndefined() && V2State.isUndefined()))
1050 return; // Undefined output if mask or both inputs undefined.
1051
1052 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1053 MaskState.isOverdefined()) {
1054 markOverdefined(&I);
1055 } else {
1056 // A mix of constant/undef inputs.
1057 Constant *V1 = V1State.isConstant() ?
1058 V1State.getConstant() : UndefValue::get(I.getType());
1059 Constant *V2 = V2State.isConstant() ?
1060 V2State.getConstant() : UndefValue::get(I.getType());
1061 Constant *Mask = MaskState.isConstant() ?
1062 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1063 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1064 }
Devang Patel67a821d2006-12-04 23:54:59 +00001065#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001066}
1067
Chris Lattner2a88bb72002-08-30 23:39:00 +00001068// Handle getelementptr instructions... if all operands are constants then we
1069// can turn this into a getelementptr ConstantExpr.
1070//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001071void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001072 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001073 if (IV.isOverdefined()) return;
1074
Chris Lattnere777ff22007-02-02 20:51:48 +00001075 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001076 Operands.reserve(I.getNumOperands());
1077
1078 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001079 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001080 if (State.isUndefined())
1081 return; // Operands are not resolved yet...
1082 else if (State.isOverdefined()) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001083 markOverdefined(IV, &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +00001084 return;
1085 }
1086 assert(State.isConstant() && "Unknown state!");
1087 Operands.push_back(State.getConstant());
1088 }
1089
1090 Constant *Ptr = Operands[0];
1091 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1092
Chris Lattnere777ff22007-02-02 20:51:48 +00001093 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1094 Operands.size()));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001095}
Brian Gaeked0fde302003-11-11 22:41:34 +00001096
Chris Lattnerdd336d12004-12-11 05:15:59 +00001097void SCCPSolver::visitStoreInst(Instruction &SI) {
1098 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1099 return;
1100 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001101 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001102 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1103
1104 // Get the value we are storing into the global.
1105 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1106
1107 mergeInValue(I->second, GV, PtrVal);
1108 if (I->second.isOverdefined())
1109 TrackedGlobals.erase(I); // No need to keep tracking this!
1110}
1111
1112
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001113// Handle load instructions. If the operand is a constant pointer to a constant
1114// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001115void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001116 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001117 if (IV.isOverdefined()) return;
1118
Chris Lattneref36dfd2004-11-15 05:03:30 +00001119 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001120 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1121 if (PtrVal.isConstant() && !I.isVolatile()) {
1122 Value *Ptr = PtrVal.getConstant();
Christopher Lambb15147e2007-12-29 07:56:53 +00001123 // TODO: Consider a target hook for valid address spaces for this xform.
1124 if (isa<ConstantPointerNull>(Ptr) &&
1125 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattnerc76d8032004-03-07 22:16:24 +00001126 // load null -> null
1127 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1128 return;
1129 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001130
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001131 // Transform load (constant global) into the value loaded.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001132 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1133 if (GV->isConstant()) {
Duncan Sandsab6b2262009-03-20 21:53:29 +00001134 if (!GV->isDeclaration() && !GV->mayBeOverridden()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001135 markConstant(IV, &I, GV->getInitializer());
1136 return;
1137 }
1138 } else if (!TrackedGlobals.empty()) {
1139 // If we are tracking this global, merge in the known value for it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001140 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
Chris Lattnerdd336d12004-12-11 05:15:59 +00001141 TrackedGlobals.find(GV);
1142 if (It != TrackedGlobals.end()) {
1143 mergeInValue(IV, &I, It->second);
1144 return;
1145 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001146 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001147 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001148
1149 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1150 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1151 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen9d809302005-04-23 21:38:35 +00001152 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sandsab6b2262009-03-20 21:53:29 +00001153 if (GV->isConstant() && !GV->isDeclaration() && !GV->mayBeOverridden())
Jeff Cohen9d809302005-04-23 21:38:35 +00001154 if (Constant *V =
Chris Lattnerebe61202005-09-26 05:28:52 +00001155 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen9d809302005-04-23 21:38:35 +00001156 markConstant(IV, &I, V);
1157 return;
1158 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001159 }
1160
1161 // Otherwise we cannot say for certain what value this load will produce.
1162 // Bail out.
1163 markOverdefined(IV, &I);
1164}
Chris Lattner58b7b082004-04-13 19:43:54 +00001165
Chris Lattner59acc7d2004-12-10 08:02:06 +00001166void SCCPSolver::visitCallSite(CallSite CS) {
1167 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001168 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001169
1170 // The common case is that we aren't tracking the callee, either because we
1171 // are not doing interprocedural analysis or the callee is indirect, or is
1172 // external. Handle these cases first.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001173 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001174CallOverdefined:
1175 // Void return and not tracking callee, just bail.
1176 if (I->getType() == Type::VoidTy) return;
1177
1178 // Otherwise, if we have a single return value case, and if the function is
1179 // a declaration, maybe we can constant fold it.
1180 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1181 canConstantFoldCallTo(F)) {
1182
1183 SmallVector<Constant*, 8> Operands;
1184 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1185 AI != E; ++AI) {
1186 LatticeVal &State = getValueState(*AI);
1187 if (State.isUndefined())
1188 return; // Operands are not resolved yet.
1189 else if (State.isOverdefined()) {
1190 markOverdefined(I);
1191 return;
1192 }
1193 assert(State.isConstant() && "Unknown state!");
1194 Operands.push_back(State.getConstant());
1195 }
1196
1197 // If we can constant fold this, mark the result of the call as a
1198 // constant.
1199 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size())) {
1200 markConstant(I, C);
1201 return;
1202 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001203 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001204
1205 // Otherwise, we don't know anything about this call, mark it overdefined.
1206 markOverdefined(I);
1207 return;
Chris Lattner58b7b082004-04-13 19:43:54 +00001208 }
1209
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001210 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001211 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1212 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001213 // If so, propagate the return value of the callee into this call result.
1214 mergeInValue(I, TFRVI->second);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001215 } else if (isa<StructType>(I->getType())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001216 // Check to see if we're tracking this callee, if not, handle it in the
1217 // common path above.
Chris Lattnercf712de2008-08-23 23:36:38 +00001218 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1219 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001220 if (TMRVI == TrackedMultipleRetVals.end())
1221 goto CallOverdefined;
1222
1223 // If we are tracking this callee, propagate the return values of the call
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001224 // into this call site. We do this by walking all the uses. Single-index
1225 // ExtractValueInst uses can be tracked; anything more complicated is
1226 // currently handled conservatively.
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001227 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1228 UI != E; ++UI) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001229 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1230 if (EVI->getNumIndices() == 1) {
1231 mergeInValue(EVI,
Dan Gohman60ea2682008-06-20 16:41:17 +00001232 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001233 continue;
1234 }
1235 }
1236 // The aggregate value is used in a way not handled here. Assume nothing.
1237 markOverdefined(*UI);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001238 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001239 } else {
1240 // Otherwise we're not tracking this callee, so handle it in the
1241 // common path above.
1242 goto CallOverdefined;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001243 }
1244
1245 // Finally, if this is the first call to the function hit, mark its entry
1246 // block executable.
1247 if (!BBExecutable.count(F->begin()))
1248 MarkBlockExecutable(F->begin());
1249
1250 // Propagate information from this call site into the callee.
1251 CallSite::arg_iterator CAI = CS.arg_begin();
1252 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1253 AI != E; ++AI, ++CAI) {
1254 LatticeVal &IV = ValueState[AI];
1255 if (!IV.isOverdefined())
1256 mergeInValue(IV, AI, getValueState(*CAI));
1257 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001258}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001259
1260
1261void SCCPSolver::Solve() {
1262 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001263 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001264 !OverdefinedInstWorkList.empty()) {
Chris Lattner82bec2c2004-11-15 04:44:20 +00001265 // Process the instruction work list...
1266 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001267 Value *I = OverdefinedInstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001268 OverdefinedInstWorkList.pop_back();
1269
Bill Wendlingb7427032006-11-26 09:46:52 +00001270 DOUT << "\nPopped off OI-WL: " << *I;
Misha Brukmanfd939082005-04-21 23:48:37 +00001271
Chris Lattner82bec2c2004-11-15 04:44:20 +00001272 // "I" got into the work list because it either made the transition from
1273 // bottom to constant
1274 //
1275 // Anything on this worklist that is overdefined need not be visited
1276 // since all of its users will have already been marked as overdefined
1277 // Update all of the users of this instruction's value...
1278 //
1279 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1280 UI != E; ++UI)
1281 OperandChangedState(*UI);
1282 }
1283 // Process the instruction work list...
1284 while (!InstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001285 Value *I = InstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001286 InstWorkList.pop_back();
1287
Bill Wendlingb7427032006-11-26 09:46:52 +00001288 DOUT << "\nPopped off I-WL: " << *I;
Misha Brukmanfd939082005-04-21 23:48:37 +00001289
Chris Lattner82bec2c2004-11-15 04:44:20 +00001290 // "I" got into the work list because it either made the transition from
1291 // bottom to constant
1292 //
1293 // Anything on this worklist that is overdefined need not be visited
1294 // since all of its users will have already been marked as overdefined.
1295 // Update all of the users of this instruction's value...
1296 //
1297 if (!getValueState(I).isOverdefined())
1298 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1299 UI != E; ++UI)
1300 OperandChangedState(*UI);
1301 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001302
Chris Lattner82bec2c2004-11-15 04:44:20 +00001303 // Process the basic block work list...
1304 while (!BBWorkList.empty()) {
1305 BasicBlock *BB = BBWorkList.back();
1306 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001307
Bill Wendlingb7427032006-11-26 09:46:52 +00001308 DOUT << "\nPopped off BBWL: " << *BB;
Misha Brukmanfd939082005-04-21 23:48:37 +00001309
Chris Lattner82bec2c2004-11-15 04:44:20 +00001310 // Notify all instructions in this basic block that they are newly
1311 // executable.
1312 visit(BB);
1313 }
1314 }
1315}
1316
Chris Lattner3bad2532006-12-20 06:21:33 +00001317/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001318/// that branches on undef values cannot reach any of their successors.
1319/// However, this is not a safe assumption. After we solve dataflow, this
1320/// method should be use to handle this. If this returns true, the solver
1321/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001322///
1323/// This method handles this by finding an unresolved branch and marking it one
1324/// of the edges from the block as being feasible, even though the condition
1325/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1326/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001327/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001328/// constraints on the condition of the branch, as that would impact other users
1329/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001330///
1331/// This scan also checks for values that use undefs, whose results are actually
1332/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1333/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1334/// even if X isn't defined.
1335bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001336 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1337 if (!BBExecutable.count(BB))
1338 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001339
1340 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1341 // Look for instructions which produce undef values.
1342 if (I->getType() == Type::VoidTy) continue;
1343
1344 LatticeVal &LV = getValueState(I);
1345 if (!LV.isUndefined()) continue;
1346
1347 // Get the lattice values of the first two operands for use below.
1348 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1349 LatticeVal Op1LV;
1350 if (I->getNumOperands() == 2) {
1351 // If this is a two-operand instruction, and if both operands are
1352 // undefs, the result stays undef.
1353 Op1LV = getValueState(I->getOperand(1));
1354 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1355 continue;
1356 }
1357
1358 // If this is an instructions whose result is defined even if the input is
1359 // not fully defined, propagate the information.
1360 const Type *ITy = I->getType();
1361 switch (I->getOpcode()) {
1362 default: break; // Leave the instruction as an undef.
1363 case Instruction::ZExt:
1364 // After a zero extend, we know the top part is zero. SExt doesn't have
1365 // to be handled here, because we don't know whether the top part is 1's
1366 // or 0's.
1367 assert(Op0LV.isUndefined());
1368 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1369 return true;
1370 case Instruction::Mul:
1371 case Instruction::And:
1372 // undef * X -> 0. X could be zero.
1373 // undef & X -> 0. X could be zero.
1374 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1375 return true;
1376
1377 case Instruction::Or:
1378 // undef | X -> -1. X could be -1.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001379 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1380 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001381 else
1382 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1383 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001384
1385 case Instruction::SDiv:
1386 case Instruction::UDiv:
1387 case Instruction::SRem:
1388 case Instruction::URem:
1389 // X / undef -> undef. No change.
1390 // X % undef -> undef. No change.
1391 if (Op1LV.isUndefined()) break;
1392
1393 // undef / X -> 0. X could be maxint.
1394 // undef % X -> 0. X could be 1.
1395 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1396 return true;
1397
1398 case Instruction::AShr:
1399 // undef >>s X -> undef. No change.
1400 if (Op0LV.isUndefined()) break;
1401
1402 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1403 if (Op0LV.isConstant())
1404 markForcedConstant(LV, I, Op0LV.getConstant());
1405 else
1406 markOverdefined(LV, I);
1407 return true;
1408 case Instruction::LShr:
1409 case Instruction::Shl:
1410 // undef >> X -> undef. No change.
1411 // undef << X -> undef. No change.
1412 if (Op0LV.isUndefined()) break;
1413
1414 // X >> undef -> 0. X could be 0.
1415 // X << undef -> 0. X could be 0.
1416 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1417 return true;
1418 case Instruction::Select:
1419 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1420 if (Op0LV.isUndefined()) {
1421 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1422 Op1LV = getValueState(I->getOperand(2));
1423 } else if (Op1LV.isUndefined()) {
1424 // c ? undef : undef -> undef. No change.
1425 Op1LV = getValueState(I->getOperand(2));
1426 if (Op1LV.isUndefined())
1427 break;
1428 // Otherwise, c ? undef : x -> x.
1429 } else {
1430 // Leave Op1LV as Operand(1)'s LatticeValue.
1431 }
1432
1433 if (Op1LV.isConstant())
1434 markForcedConstant(LV, I, Op1LV.getConstant());
1435 else
1436 markOverdefined(LV, I);
1437 return true;
Chris Lattner60301602008-05-24 03:59:33 +00001438 case Instruction::Call:
1439 // If a call has an undef result, it is because it is constant foldable
1440 // but one of the inputs was undef. Just force the result to
1441 // overdefined.
1442 markOverdefined(LV, I);
1443 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001444 }
1445 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001446
1447 TerminatorInst *TI = BB->getTerminator();
1448 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1449 if (!BI->isConditional()) continue;
1450 if (!getValueState(BI->getCondition()).isUndefined())
1451 continue;
1452 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Dale Johannesen9bca5832008-05-23 01:01:31 +00001453 if (SI->getNumSuccessors()<2) // no cases
1454 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001455 if (!getValueState(SI->getCondition()).isUndefined())
1456 continue;
1457 } else {
1458 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001459 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001460
Chris Lattner05bb7892008-01-28 00:32:30 +00001461 // If the edge to the second successor isn't thought to be feasible yet,
1462 // mark it so now. We pick the second one so that this goes to some
1463 // enumerated value in a switch instead of going to the default destination.
1464 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001465 continue;
1466
1467 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1468 // and return. This will make other blocks reachable, which will allow new
1469 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001470 markEdgeExecutable(BB, TI->getSuccessor(1));
1471
1472 // This must be a conditional branch of switch on undef. At this point,
1473 // force the old terminator to branch to the first successor. This is
1474 // required because we are now influencing the dataflow of the function with
1475 // the assumption that this edge is taken. If we leave the branch condition
1476 // as undef, then further analysis could think the undef went another way
1477 // leading to an inconsistent set of conclusions.
1478 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1479 BI->setCondition(ConstantInt::getFalse());
1480 } else {
1481 SwitchInst *SI = cast<SwitchInst>(TI);
1482 SI->setCondition(SI->getCaseValue(1));
1483 }
1484
Chris Lattnerd2d86702006-10-22 05:59:17 +00001485 return true;
1486 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001487
Chris Lattnerd2d86702006-10-22 05:59:17 +00001488 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001489}
1490
Chris Lattner82bec2c2004-11-15 04:44:20 +00001491
1492namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001493 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001494 //
Chris Lattner14051812004-11-15 07:15:04 +00001495 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001496 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001497 ///
Reid Spencer9133fe22007-02-05 23:32:05 +00001498 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001499 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +00001500 SCCP() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +00001501
Chris Lattner14051812004-11-15 07:15:04 +00001502 // runOnFunction - Run the Sparse Conditional Constant Propagation
1503 // algorithm, and return true if the function was modified.
1504 //
1505 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001506
Chris Lattner14051812004-11-15 07:15:04 +00001507 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1508 AU.setPreservesCFG();
1509 }
1510 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001511} // end anonymous namespace
1512
Dan Gohman844731a2008-05-13 00:00:25 +00001513char SCCP::ID = 0;
1514static RegisterPass<SCCP>
1515X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001516
1517// createSCCPPass - This is the public interface to this file...
1518FunctionPass *llvm::createSCCPPass() {
1519 return new SCCP();
1520}
1521
1522
Chris Lattner82bec2c2004-11-15 04:44:20 +00001523// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1524// and return true if the function was modified.
1525//
1526bool SCCP::runOnFunction(Function &F) {
Chris Lattner5c8e8d72008-05-11 01:55:59 +00001527 DOUT << "SCCP on function '" << F.getNameStart() << "'\n";
Chris Lattner82bec2c2004-11-15 04:44:20 +00001528 SCCPSolver Solver;
1529
1530 // Mark the first block of the function as being executable.
1531 Solver.MarkBlockExecutable(F.begin());
1532
Chris Lattner7e529e42004-11-15 05:45:33 +00001533 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001534 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001535 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001536
Chris Lattner82bec2c2004-11-15 04:44:20 +00001537 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001538 bool ResolvedUndefs = true;
1539 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001540 Solver.Solve();
Chris Lattner3bad2532006-12-20 06:21:33 +00001541 DOUT << "RESOLVING UNDEFs\n";
1542 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001543 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001544
Chris Lattner7e529e42004-11-15 05:45:33 +00001545 bool MadeChanges = false;
1546
1547 // If we decided that there are basic blocks that are dead in this function,
1548 // delete their contents now. Note that we cannot actually delete the blocks,
1549 // as we cannot modify the CFG of the function.
1550 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001551 SmallVector<Instruction*, 512> Insts;
Bill Wendling7a7cf6b2008-08-14 23:05:24 +00001552 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner57939df2007-03-04 04:50:21 +00001553
Chris Lattner7e529e42004-11-15 05:45:33 +00001554 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001555 if (!Solver.isBlockExecutable(BB)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001556 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001557 ++NumDeadBlocks;
1558
Chris Lattner7e529e42004-11-15 05:45:33 +00001559 // Delete the instructions backwards, as it has a reduced likelihood of
1560 // having to update as many def-use and use-def chains.
Chris Lattner7e529e42004-11-15 05:45:33 +00001561 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1562 I != E; ++I)
1563 Insts.push_back(I);
1564 while (!Insts.empty()) {
1565 Instruction *I = Insts.back();
1566 Insts.pop_back();
1567 if (!I->use_empty())
1568 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1569 BB->getInstList().erase(I);
1570 MadeChanges = true;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001571 ++NumInstRemoved;
Chris Lattner7e529e42004-11-15 05:45:33 +00001572 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001573 } else {
1574 // Iterate over all of the instructions in a function, replacing them with
1575 // constants if we have found them to be of constant values.
1576 //
1577 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1578 Instruction *Inst = BI++;
Chris Lattner7cb22ec2008-04-24 00:19:54 +00001579 if (Inst->getType() == Type::VoidTy ||
Chris Lattnerf4023a12008-04-24 00:16:28 +00001580 isa<TerminatorInst>(Inst))
1581 continue;
1582
1583 LatticeVal &IV = Values[Inst];
1584 if (!IV.isConstant() && !IV.isUndefined())
1585 continue;
1586
1587 Constant *Const = IV.isConstant()
1588 ? IV.getConstant() : UndefValue::get(Inst->getType());
1589 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanfd939082005-04-21 23:48:37 +00001590
Chris Lattnerf4023a12008-04-24 00:16:28 +00001591 // Replaces all of the uses of a variable with uses of the constant.
1592 Inst->replaceAllUsesWith(Const);
1593
1594 // Delete the instruction.
1595 Inst->eraseFromParent();
1596
1597 // Hey, we just changed something!
1598 MadeChanges = true;
1599 ++NumInstRemoved;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001600 }
1601 }
1602
1603 return MadeChanges;
1604}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001605
1606namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001607 //===--------------------------------------------------------------------===//
1608 //
1609 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1610 /// Constant Propagation.
1611 ///
Reid Spencer9133fe22007-02-05 23:32:05 +00001612 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001613 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +00001614 IPSCCP() : ModulePass(&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001615 bool runOnModule(Module &M);
1616 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001617} // end anonymous namespace
1618
Dan Gohman844731a2008-05-13 00:00:25 +00001619char IPSCCP::ID = 0;
1620static RegisterPass<IPSCCP>
1621Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1622
Chris Lattner59acc7d2004-12-10 08:02:06 +00001623// createIPSCCPPass - This is the public interface to this file...
1624ModulePass *llvm::createIPSCCPPass() {
1625 return new IPSCCP();
1626}
1627
1628
1629static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001630 // Delete any dead constantexpr klingons.
1631 GV->removeDeadConstantUsers();
1632
Chris Lattner59acc7d2004-12-10 08:02:06 +00001633 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1634 UI != E; ++UI)
1635 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001636 if (SI->getOperand(0) == GV || SI->isVolatile())
1637 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001638 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1639 // Make sure we are calling the function, not passing the address.
1640 CallSite CS = CallSite::get(cast<Instruction>(*UI));
Nick Lewyckyaf386132008-11-03 03:49:14 +00001641 if (CS.hasArgument(GV))
1642 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001643 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1644 if (LI->isVolatile())
1645 return true;
1646 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001647 return true;
1648 }
1649 return false;
1650}
1651
1652bool IPSCCP::runOnModule(Module &M) {
1653 SCCPSolver Solver;
1654
1655 // Loop over all functions, marking arguments to those with their addresses
1656 // taken or that are external as overdefined.
1657 //
Chris Lattner59acc7d2004-12-10 08:02:06 +00001658 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001659 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001660 if (!F->isDeclaration())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001661 Solver.MarkBlockExecutable(F->begin());
Chris Lattner7d27fc02005-04-19 19:16:19 +00001662 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1663 AI != E; ++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001664 Solver.markOverdefined(AI);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001665 } else {
1666 Solver.AddTrackedFunction(F);
1667 }
1668
Chris Lattnerdd336d12004-12-11 05:15:59 +00001669 // Loop over global variables. We inform the solver about any internal global
1670 // variables that do not have their 'addresses taken'. If they don't have
1671 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001672 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1673 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001674 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001675 Solver.TrackValueOfGlobalVariable(G);
1676
Chris Lattner59acc7d2004-12-10 08:02:06 +00001677 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001678 bool ResolvedUndefs = true;
1679 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001680 Solver.Solve();
1681
Chris Lattner3bad2532006-12-20 06:21:33 +00001682 DOUT << "RESOLVING UNDEFS\n";
1683 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001684 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001685 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001686 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001687
1688 bool MadeChanges = false;
1689
1690 // Iterate over all of the instructions in the module, replacing them with
1691 // constants if we have found them to be of constant values.
1692 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001693 SmallVector<Instruction*, 512> Insts;
1694 SmallVector<BasicBlock*, 512> BlocksToErase;
Bill Wendling7a7cf6b2008-08-14 23:05:24 +00001695 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001696
Chris Lattner59acc7d2004-12-10 08:02:06 +00001697 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001698 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1699 AI != E; ++AI)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001700 if (!AI->use_empty()) {
1701 LatticeVal &IV = Values[AI];
1702 if (IV.isConstant() || IV.isUndefined()) {
1703 Constant *CST = IV.isConstant() ?
1704 IV.getConstant() : UndefValue::get(AI->getType());
Bill Wendlingb7427032006-11-26 09:46:52 +00001705 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
Misha Brukmanfd939082005-04-21 23:48:37 +00001706
Chris Lattner59acc7d2004-12-10 08:02:06 +00001707 // Replaces all of the uses of a variable with uses of the
1708 // constant.
1709 AI->replaceAllUsesWith(CST);
1710 ++IPNumArgsElimed;
1711 }
1712 }
1713
1714 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001715 if (!Solver.isBlockExecutable(BB)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001716 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001717 ++IPNumDeadBlocks;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001718
Chris Lattner59acc7d2004-12-10 08:02:06 +00001719 // Delete the instructions backwards, as it has a reduced likelihood of
1720 // having to update as many def-use and use-def chains.
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001721 TerminatorInst *TI = BB->getTerminator();
1722 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001723 Insts.push_back(I);
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001724
Chris Lattner59acc7d2004-12-10 08:02:06 +00001725 while (!Insts.empty()) {
1726 Instruction *I = Insts.back();
1727 Insts.pop_back();
1728 if (!I->use_empty())
1729 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1730 BB->getInstList().erase(I);
1731 MadeChanges = true;
1732 ++IPNumInstRemoved;
1733 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001734
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001735 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1736 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001737 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001738 TI->getSuccessor(i)->removePredecessor(BB);
1739 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001740 if (!TI->use_empty())
1741 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001742 BB->getInstList().erase(TI);
1743
Chris Lattner864737b2004-12-11 05:32:19 +00001744 if (&*BB != &F->front())
1745 BlocksToErase.push_back(BB);
1746 else
1747 new UnreachableInst(BB);
1748
Chris Lattner59acc7d2004-12-10 08:02:06 +00001749 } else {
1750 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1751 Instruction *Inst = BI++;
Chris Lattnerd9d46242009-01-14 21:01:16 +00001752 if (Inst->getType() == Type::VoidTy)
Chris Lattnereb5f4092008-04-24 00:21:50 +00001753 continue;
1754
1755 LatticeVal &IV = Values[Inst];
1756 if (!IV.isConstant() && !IV.isUndefined())
1757 continue;
1758
1759 Constant *Const = IV.isConstant()
1760 ? IV.getConstant() : UndefValue::get(Inst->getType());
1761 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanfd939082005-04-21 23:48:37 +00001762
Chris Lattnereb5f4092008-04-24 00:21:50 +00001763 // Replaces all of the uses of a variable with uses of the
1764 // constant.
1765 Inst->replaceAllUsesWith(Const);
1766
1767 // Delete the instruction.
Chris Lattnerd9d46242009-01-14 21:01:16 +00001768 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
Chris Lattnereb5f4092008-04-24 00:21:50 +00001769 Inst->eraseFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001770
Chris Lattnereb5f4092008-04-24 00:21:50 +00001771 // Hey, we just changed something!
1772 MadeChanges = true;
1773 ++IPNumInstRemoved;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001774 }
1775 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001776
1777 // Now that all instructions in the function are constant folded, erase dead
1778 // blocks, because we can now use ConstantFoldTerminator to get rid of
1779 // in-edges.
1780 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1781 // If there are any PHI nodes in this successor, drop entries for BB now.
1782 BasicBlock *DeadBB = BlocksToErase[i];
1783 while (!DeadBB->use_empty()) {
1784 Instruction *I = cast<Instruction>(DeadBB->use_back());
1785 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001786 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001787 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001788 // if this is a branch or switch on undef. Fold it manually as a
1789 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001790#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001791 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1792 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1793 "Branch should be foldable!");
1794 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1795 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1796 } else {
1797 assert(0 && "Didn't fold away reference to block!");
1798 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001799#endif
Chris Lattnerddaaa372006-10-23 18:57:02 +00001800
1801 // Make this an uncond branch to the first successor.
1802 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001803 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001804
1805 // Remove entries in successor phi nodes to remove edges.
1806 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1807 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1808
1809 // Remove the old terminator.
1810 TI->eraseFromParent();
1811 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001812 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001813
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001814 // Finally, delete the basic block.
1815 F->getBasicBlockList().erase(DeadBB);
1816 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001817 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001818 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001819
1820 // If we inferred constant or undef return values for a function, we replaced
1821 // all call uses with the inferred value. This means we don't need to bother
1822 // actually returning anything from the function. Replace all return
1823 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001824 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001825 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001826 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner0417feb2004-12-11 02:53:57 +00001827 E = RV.end(); I != E; ++I)
1828 if (!I->second.isOverdefined() &&
1829 I->first->getReturnType() != Type::VoidTy) {
1830 Function *F = I->first;
1831 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1832 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1833 if (!isa<UndefValue>(RI->getOperand(0)))
1834 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1835 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001836
1837 // If we infered constant or undef values for globals variables, we can delete
1838 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001839 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1840 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001841 E = TG.end(); I != E; ++I) {
1842 GlobalVariable *GV = I->first;
1843 assert(!I->second.isOverdefined() &&
1844 "Overdefined values should have been taken out of the map!");
Chris Lattner5c8e8d72008-05-11 01:55:59 +00001845 DOUT << "Found that GV '" << GV->getNameStart() << "' is constant!\n";
Chris Lattnerdd336d12004-12-11 05:15:59 +00001846 while (!GV->use_empty()) {
1847 StoreInst *SI = cast<StoreInst>(GV->use_back());
1848 SI->eraseFromParent();
1849 }
1850 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001851 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001852 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001853
Chris Lattner59acc7d2004-12-10 08:02:06 +00001854 return MadeChanges;
1855}