blob: ad4bcc942d00ab5727968caf253b559cf799e4fc [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"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000031#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000032#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez83d63912009-09-18 22:35:49 +000033#include "llvm/Analysis/MallocHelper.h"
Dan Gohmanc4b65ea2008-06-20 01:15:44 +000034#include "llvm/Analysis/ValueTracking.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000035#include "llvm/Transforms/Utils/Local.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000036#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000037#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000038#include "llvm/Support/ErrorHandling.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000039#include "llvm/Support/InstVisitor.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000040#include "llvm/Support/raw_ostream.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000041#include "llvm/ADT/DenseMap.h"
Chris Lattnercf712de2008-08-23 23:36:38 +000042#include "llvm/ADT/DenseSet.h"
Chris Lattnercc56aad2007-02-02 20:57:39 +000043#include "llvm/ADT/SmallSet.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000044#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000045#include "llvm/ADT/Statistic.h"
46#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000047#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000048#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000049using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000050
Chris Lattner0e5f4992006-12-19 21:40:18 +000051STATISTIC(NumInstRemoved, "Number of instructions removed");
52STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
53
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000054STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000055STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
56STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
57STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
58
Chris Lattner0dbfc052002-04-29 21:26:08 +000059namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000060/// LatticeVal class - This class represents the different lattice values that
61/// an LLVM value may occupy. It is a simple class with value semantics.
62///
Chris Lattner3e8b6632009-09-02 06:11:42 +000063class LatticeVal {
Misha Brukmanfd939082005-04-21 23:48:37 +000064 enum {
Chris Lattner3bad2532006-12-20 06:21:33 +000065 /// undefined - This LLVM Value has no known value yet.
66 undefined,
67
68 /// constant - This LLVM Value has a specific constant value.
69 constant,
70
71 /// forcedconstant - This LLVM Value was thought to be undef until
72 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
73 /// with another (different) constant, it goes to overdefined, instead of
74 /// asserting.
75 forcedconstant,
76
77 /// overdefined - This instruction is not known to be constant, and we know
78 /// it has a value.
79 overdefined
80 } LatticeValue; // The current lattice position
81
Chris Lattnere9bb2df2001-12-03 22:26:30 +000082 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner138a1242001-06-27 23:38:11 +000083public:
Chris Lattneref36dfd2004-11-15 05:03:30 +000084 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000085
Chris Lattner138a1242001-06-27 23:38:11 +000086 // markOverdefined - Return true if this is a new status to be in...
87 inline bool markOverdefined() {
Chris Lattnere9bb2df2001-12-03 22:26:30 +000088 if (LatticeValue != overdefined) {
89 LatticeValue = overdefined;
Chris Lattner138a1242001-06-27 23:38:11 +000090 return true;
91 }
92 return false;
93 }
94
Chris Lattner3bad2532006-12-20 06:21:33 +000095 // markConstant - Return true if this is a new status for us.
Chris Lattnere9bb2df2001-12-03 22:26:30 +000096 inline bool markConstant(Constant *V) {
97 if (LatticeValue != constant) {
Chris Lattner3bad2532006-12-20 06:21:33 +000098 if (LatticeValue == undefined) {
99 LatticeValue = constant;
Jim Laskey52ab9042007-01-03 00:11:03 +0000100 assert(V && "Marking constant with NULL");
Chris Lattner3bad2532006-12-20 06:21:33 +0000101 ConstantVal = V;
102 } else {
103 assert(LatticeValue == forcedconstant &&
104 "Cannot move from overdefined to constant!");
105 // Stay at forcedconstant if the constant is the same.
106 if (V == ConstantVal) return false;
107
108 // Otherwise, we go to overdefined. Assumptions made based on the
109 // forced value are possibly wrong. Assuming this is another constant
110 // could expose a contradiction.
111 LatticeValue = overdefined;
112 }
Chris Lattner138a1242001-06-27 23:38:11 +0000113 return true;
114 } else {
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000115 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner138a1242001-06-27 23:38:11 +0000116 }
117 return false;
118 }
119
Chris Lattner3bad2532006-12-20 06:21:33 +0000120 inline void markForcedConstant(Constant *V) {
121 assert(LatticeValue == undefined && "Can't force a defined value!");
122 LatticeValue = forcedconstant;
123 ConstantVal = V;
124 }
125
126 inline bool isUndefined() const { return LatticeValue == undefined; }
127 inline bool isConstant() const {
128 return LatticeValue == constant || LatticeValue == forcedconstant;
129 }
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000130 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner138a1242001-06-27 23:38:11 +0000131
Chris Lattner1daee8b2004-01-12 03:57:30 +0000132 inline Constant *getConstant() const {
133 assert(isConstant() && "Cannot get the constant of a non-constant!");
134 return ConstantVal;
135 }
Chris Lattner138a1242001-06-27 23:38:11 +0000136};
137
Chris Lattner138a1242001-06-27 23:38:11 +0000138//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000139//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000140/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
141/// Constant Propagation.
142///
143class SCCPSolver : public InstVisitor<SCCPSolver> {
Owen Anderson07cf79e2009-07-06 23:00:19 +0000144 LLVMContext *Context;
Chris Lattnercf712de2008-08-23 23:36:38 +0000145 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000146 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000147
Chris Lattnerdd336d12004-12-11 05:15:59 +0000148 /// GlobalValue - If we are tracking any values for the contents of a global
149 /// variable, we keep a mapping from the constant accessor to the element of
150 /// the global, to the currently known value. If the value becomes
151 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000152 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000153
Devang Patel7c490d42008-03-11 05:46:42 +0000154 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000155 /// value out of a function, it will have an entry in this map, indicating
156 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000157 DenseMap<Function*, LatticeVal> TrackedRetVals;
158
159 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
160 /// that return multiple values.
Chris Lattnercf712de2008-08-23 23:36:38 +0000161 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000162
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000163 // The reason for two worklists is that overdefined is the lowest state
164 // on the lattice, and moving things to overdefined as fast as possible
165 // makes SCCP converge much faster.
166 // By having a separate worklist, we accomplish this because everything
167 // possibly overdefined will become overdefined at the soonest possible
168 // point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000169 SmallVector<Value*, 64> OverdefinedInstWorkList;
170 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000171
172
Chris Lattnercf712de2008-08-23 23:36:38 +0000173 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000174
Chris Lattner1daee8b2004-01-12 03:57:30 +0000175 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
176 /// overdefined, despite the fact that the PHI node is overdefined.
177 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
178
Chris Lattner16b18fd2003-10-08 16:55:34 +0000179 /// KnownFeasibleEdges - Entries in this set are edges which have already had
180 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000181 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
182 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000183public:
Owen Anderson07cf79e2009-07-06 23:00:19 +0000184 void setContext(LLVMContext *C) { Context = C; }
Chris Lattner138a1242001-06-27 23:38:11 +0000185
Chris Lattner82bec2c2004-11-15 04:44:20 +0000186 /// MarkBlockExecutable - This method can be used by clients to mark all of
187 /// the blocks that are known to be intrinsically live in the processed unit.
188 void MarkBlockExecutable(BasicBlock *BB) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000189 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +0000190 BBExecutable.insert(BB); // Basic block is executable!
191 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner0dbfc052002-04-29 21:26:08 +0000192 }
193
Chris Lattnerdd336d12004-12-11 05:15:59 +0000194 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000195 /// inform the SCCPSolver that it should track loads and stores to the
196 /// specified global variable if it can. This is only legal to call if
197 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000198 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
199 const Type *ElTy = GV->getType()->getElementType();
200 if (ElTy->isFirstClassType()) {
201 LatticeVal &IV = TrackedGlobals[GV];
202 if (!isa<UndefValue>(GV->getInitializer()))
203 IV.markConstant(GV->getInitializer());
204 }
205 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000206
207 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
208 /// and out of the specified function (which cannot have its address taken),
209 /// this method must be called.
210 void AddTrackedFunction(Function *F) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000211 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Chris Lattner59acc7d2004-12-10 08:02:06 +0000212 // Add an entry, F -> undef.
Devang Patel7c490d42008-03-11 05:46:42 +0000213 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
214 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000215 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
216 LatticeVal()));
217 } else
218 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000219 }
220
Chris Lattner82bec2c2004-11-15 04:44:20 +0000221 /// Solve - Solve for constants and executable blocks.
222 ///
223 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000224
Chris Lattner3bad2532006-12-20 06:21:33 +0000225 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000226 /// that branches on undef values cannot reach any of their successors.
227 /// However, this is not a safe assumption. After we solve dataflow, this
228 /// method should be use to handle this. If this returns true, the solver
229 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000230 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000231
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000232 bool isBlockExecutable(BasicBlock *BB) const {
233 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000234 }
235
236 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattneref36dfd2004-11-15 05:03:30 +0000237 /// LLVM values to LatticeVals.
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000238 std::map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000239 return ValueState;
240 }
241
Devang Patel7c490d42008-03-11 05:46:42 +0000242 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000243 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000244 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
245 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000246 }
247
Chris Lattnerdd336d12004-12-11 05:15:59 +0000248 /// getTrackedGlobals - Get and return the set of inferred initializers for
249 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000250 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000251 return TrackedGlobals;
252 }
253
Chris Lattner57939df2007-03-04 04:50:21 +0000254 inline void markOverdefined(Value *V) {
255 markOverdefined(ValueState[V], V);
256 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000257
Chris Lattner138a1242001-06-27 23:38:11 +0000258private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000259 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000260 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000261 // the users of the instruction are updated later.
262 //
Chris Lattner59acc7d2004-12-10 08:02:06 +0000263 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000264 if (IV.markConstant(C)) {
Dan Gohman87325772009-08-17 15:25:05 +0000265 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
Chris Lattner59acc7d2004-12-10 08:02:06 +0000266 InstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000267 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000268 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000269
270 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
271 IV.markForcedConstant(C);
Dan Gohman87325772009-08-17 15:25:05 +0000272 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Chris Lattner3bad2532006-12-20 06:21:33 +0000273 InstWorkList.push_back(V);
274 }
275
Chris Lattner59acc7d2004-12-10 08:02:06 +0000276 inline void markConstant(Value *V, Constant *C) {
277 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000278 }
279
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000280 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000281 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000282 // work list so that the users of the instruction are updated later.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000283 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000284 if (IV.markOverdefined()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000285 DEBUG(errs() << "markOverdefined: ";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000286 if (Function *F = dyn_cast<Function>(V))
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000287 errs() << "Function '" << F->getName() << "'\n";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000288 else
Dan Gohman87325772009-08-17 15:25:05 +0000289 errs() << *V << '\n');
Chris Lattner82bec2c2004-11-15 04:44:20 +0000290 // Only instructions go on the work list
Chris Lattner59acc7d2004-12-10 08:02:06 +0000291 OverdefinedInstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000292 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000293 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000294
295 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
296 if (IV.isOverdefined() || MergeWithV.isUndefined())
297 return; // Noop.
298 if (MergeWithV.isOverdefined())
299 markOverdefined(IV, V);
300 else if (IV.isUndefined())
301 markConstant(IV, V, MergeWithV.getConstant());
302 else if (IV.getConstant() != MergeWithV.getConstant())
303 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000304 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000305
306 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
307 return mergeInValue(ValueState[V], V, MergeWithV);
308 }
309
Chris Lattner138a1242001-06-27 23:38:11 +0000310
Chris Lattneref36dfd2004-11-15 05:03:30 +0000311 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman5560c9d2003-08-18 14:43:39 +0000312 // This function is necessary because not all values should start out in the
Chris Lattner73e21422002-04-09 19:48:49 +0000313 // underdefined state... Argument's should be overdefined, and
Chris Lattner79df7c02002-03-26 18:01:55 +0000314 // constants should be marked as constants. If a value is not known to be an
Chris Lattner138a1242001-06-27 23:38:11 +0000315 // Instruction object, then use this accessor to get its value from the map.
316 //
Chris Lattneref36dfd2004-11-15 05:03:30 +0000317 inline LatticeVal &getValueState(Value *V) {
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000318 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000319 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000320
Chris Lattner3bad2532006-12-20 06:21:33 +0000321 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner7e529e42004-11-15 05:45:33 +0000322 if (isa<UndefValue>(V)) {
323 // Nothing to do, remain undefined.
324 } else {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000325 LatticeVal &LV = ValueState[C];
326 LV.markConstant(C); // Constants are constant
327 return LV;
Chris Lattner7e529e42004-11-15 05:45:33 +0000328 }
Chris Lattner2a88bb72002-08-30 23:39:00 +0000329 }
Chris Lattner138a1242001-06-27 23:38:11 +0000330 // All others are underdefined by default...
331 return ValueState[V];
332 }
333
Misha Brukmanfd939082005-04-21 23:48:37 +0000334 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner138a1242001-06-27 23:38:11 +0000335 // work list if it is not already executable...
Misha Brukmanfd939082005-04-21 23:48:37 +0000336 //
Chris Lattner16b18fd2003-10-08 16:55:34 +0000337 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
338 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
339 return; // This edge is already known to be executable!
340
341 if (BBExecutable.count(Dest)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000342 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
343 << " -> " << Dest->getName() << "\n");
Chris Lattner16b18fd2003-10-08 16:55:34 +0000344
345 // The destination is already executable, but we just made an edge
Chris Lattner929c6fb2003-10-08 16:56:11 +0000346 // feasible that wasn't before. Revisit the PHI nodes in the block
347 // because they have potentially new operands.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000348 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
349 visitPHINode(*cast<PHINode>(I));
Chris Lattner9de28282003-04-25 02:50:03 +0000350
351 } else {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000352 MarkBlockExecutable(Dest);
Chris Lattner9de28282003-04-25 02:50:03 +0000353 }
Chris Lattner138a1242001-06-27 23:38:11 +0000354 }
355
Chris Lattner82bec2c2004-11-15 04:44:20 +0000356 // getFeasibleSuccessors - Return a vector of booleans to indicate which
357 // successors are reachable from a given terminator instruction.
358 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000359 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000360
361 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
362 // block to the 'To' basic block is currently feasible...
363 //
364 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
365
366 // OperandChangedState - This method is invoked on all of the users of an
367 // instruction that was just changed state somehow.... Based on this
368 // information, we need to update the specified user of this instruction.
369 //
370 void OperandChangedState(User *U) {
371 // Only instructions use other variable values!
372 Instruction &I = cast<Instruction>(*U);
373 if (BBExecutable.count(I.getParent())) // Inst is executable?
374 visit(I);
375 }
376
377private:
378 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000379
Misha Brukmanfd939082005-04-21 23:48:37 +0000380 // visit implementations - Something changed in this instruction... Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000381 // operand made a transition, or the instruction is newly executable. Change
382 // the value type of I to reflect these changes if appropriate.
383 //
Chris Lattner7e708292002-06-25 16:13:24 +0000384 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000385
386 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000387 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000388 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000389
Chris Lattnerb8047602002-08-14 17:53:45 +0000390 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000391 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000392 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000393 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000394 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000395 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000396 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000397 void visitExtractValueInst(ExtractValueInst &EVI);
398 void visitInsertValueInst(InsertValueInst &IVI);
Chris Lattner2a632552002-04-18 15:13:15 +0000399
400 // Instructions that cannot be folded away...
Chris Lattnerdd336d12004-12-11 05:15:59 +0000401 void visitStoreInst (Instruction &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000402 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000403 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez83d63912009-09-18 22:35:49 +0000404 void visitCallInst (CallInst &I) {
405 if (isMalloc(&I))
406 markOverdefined(&I);
407 else
408 visitCallSite(CallSite::get(&I));
409 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000410 void visitInvokeInst (InvokeInst &II) {
411 visitCallSite(CallSite::get(&II));
412 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000413 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000414 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000415 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000416 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner7e708292002-06-25 16:13:24 +0000417 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000418 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
419 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner7e708292002-06-25 16:13:24 +0000420 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner2a632552002-04-18 15:13:15 +0000421
Chris Lattner7e708292002-06-25 16:13:24 +0000422 void visitInstruction(Instruction &I) {
Chris Lattner2a632552002-04-18 15:13:15 +0000423 // If a new instruction is added to LLVM that we don't handle...
Chris Lattnerbdff5482009-08-23 04:37:46 +0000424 errs() << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000425 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000426 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000427};
Chris Lattnerf6293092002-07-23 18:06:35 +0000428
Duncan Sandse2abf122007-07-20 08:56:21 +0000429} // end anonymous namespace
430
431
Chris Lattnerb9a66342002-05-02 21:44:00 +0000432// getFeasibleSuccessors - Return a vector of booleans to indicate which
433// successors are reachable from a given terminator instruction.
434//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000435void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000436 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000437 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000438 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000439 if (BI->isUnconditional()) {
440 Succs[0] = true;
441 } else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000442 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000443 if (BCValue.isOverdefined() ||
Reid Spencer579dca12007-01-12 04:24:46 +0000444 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
Chris Lattner84831642004-01-12 17:40:36 +0000445 // Overdefined condition variables, and branches on unfoldable constant
446 // conditions, mean the branch could go either way.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000447 Succs[0] = Succs[1] = true;
448 } else if (BCValue.isConstant()) {
449 // Constant condition variables mean the branch can only go a single way
Owen Anderson5defacc2009-07-31 17:39:07 +0000450 Succs[BCValue.getConstant() == ConstantInt::getFalse(*Context)] = true;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000451 }
452 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000453 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000454 // Invoke instructions successors are always executable.
455 Succs[0] = Succs[1] = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000456 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000457 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000458 if (SCValue.isOverdefined() || // Overdefined condition?
459 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000460 // All destinations are executable!
Chris Lattner7e708292002-06-25 16:13:24 +0000461 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner3a73c9e2008-05-10 23:56:54 +0000462 } else if (SCValue.isConstant())
463 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000464 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000465 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000466 }
467}
468
469
Chris Lattner59f0ce22002-05-02 21:18:01 +0000470// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
471// block to the 'To' basic block is currently feasible...
472//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000473bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000474 assert(BBExecutable.count(To) && "Dest should always be alive!");
475
476 // Make sure the source basic block is executable!!
477 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000478
Chris Lattnerb9a66342002-05-02 21:44:00 +0000479 // Check to make sure this edge itself is actually feasible now...
Chris Lattner7d275f42003-10-08 15:47:41 +0000480 TerminatorInst *TI = From->getTerminator();
481 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
482 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000483 return true;
Chris Lattner7d275f42003-10-08 15:47:41 +0000484 else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000485 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000486 if (BCValue.isOverdefined()) {
487 // Overdefined condition variables mean the branch could go either way.
488 return true;
489 } else if (BCValue.isConstant()) {
Chris Lattner84831642004-01-12 17:40:36 +0000490 // Not branching on an evaluatable constant?
Chris Lattner54a525d2007-01-13 00:42:58 +0000491 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
Chris Lattner84831642004-01-12 17:40:36 +0000492
Chris Lattner7d275f42003-10-08 15:47:41 +0000493 // Constant condition variables mean the branch can only go a single way
Misha Brukmanfd939082005-04-21 23:48:37 +0000494 return BI->getSuccessor(BCValue.getConstant() ==
Owen Anderson5defacc2009-07-31 17:39:07 +0000495 ConstantInt::getFalse(*Context)) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000496 }
497 return false;
498 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000499 } else if (isa<InvokeInst>(TI)) {
Chris Lattner7d275f42003-10-08 15:47:41 +0000500 // Invoke instructions successors are always executable.
501 return true;
502 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000503 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000504 if (SCValue.isOverdefined()) { // Overdefined condition?
505 // All destinations are executable!
506 return true;
507 } else if (SCValue.isConstant()) {
508 Constant *CPV = SCValue.getConstant();
Chris Lattner84831642004-01-12 17:40:36 +0000509 if (!isa<ConstantInt>(CPV))
510 return true; // not a foldable constant?
511
Chris Lattner7d275f42003-10-08 15:47:41 +0000512 // Make sure to skip the "default value" which isn't a value
513 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
514 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
515 return SI->getSuccessor(i) == To;
516
517 // Constant value not equal to any of the branches... must execute
518 // default branch then...
519 return SI->getDefaultDest() == To;
520 }
521 return false;
522 } else {
Torok Edwin7d696d82009-07-11 13:10:19 +0000523#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000524 errs() << "Unknown terminator instruction: " << *TI << '\n';
Torok Edwin7d696d82009-07-11 13:10:19 +0000525#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000526 llvm_unreachable(0);
Chris Lattner7d275f42003-10-08 15:47:41 +0000527 }
Chris Lattner59f0ce22002-05-02 21:18:01 +0000528}
Chris Lattner138a1242001-06-27 23:38:11 +0000529
Chris Lattner2a632552002-04-18 15:13:15 +0000530// visit Implementations - Something changed in this instruction... Either an
Chris Lattner138a1242001-06-27 23:38:11 +0000531// operand made a transition, or the instruction is newly executable. Change
532// the value type of I to reflect these changes if appropriate. This method
533// makes sure to do the following actions:
534//
535// 1. If a phi node merges two constants in, and has conflicting value coming
536// from different branches, or if the PHI node merges in an overdefined
537// value, then the PHI node becomes overdefined.
538// 2. If a phi node merges only constants in, and they all agree on value, the
539// PHI node becomes a constant value equal to that.
540// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
541// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
542// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
543// 6. If a conditional branch has a value that is constant, make the selected
544// destination executable
545// 7. If a conditional branch has a value that is overdefined, make all
546// successors executable.
547//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000548void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000549 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000550 if (PNIV.isOverdefined()) {
551 // There may be instructions using this PHI node that are not overdefined
552 // themselves. If so, make sure that they know that the PHI node operand
553 // changed.
554 std::multimap<PHINode*, Instruction*>::iterator I, E;
555 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
556 if (I != E) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000557 SmallVector<Instruction*, 16> Users;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000558 for (; I != E; ++I) Users.push_back(I->second);
559 while (!Users.empty()) {
560 visit(Users.back());
561 Users.pop_back();
562 }
563 }
564 return; // Quick exit
565 }
Chris Lattner138a1242001-06-27 23:38:11 +0000566
Chris Lattnera2f652d2004-03-16 19:49:59 +0000567 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
568 // and slow us down a lot. Just mark them overdefined.
569 if (PN.getNumIncomingValues() > 64) {
570 markOverdefined(PNIV, &PN);
571 return;
572 }
573
Chris Lattner2a632552002-04-18 15:13:15 +0000574 // Look at all of the executable operands of the PHI node. If any of them
575 // are overdefined, the PHI becomes overdefined as well. If they are all
576 // constant, and they agree with each other, the PHI becomes the identical
577 // constant. If they are constant and don't agree, the PHI is overdefined.
578 // If there are no executable operands, the PHI remains undefined.
579 //
Chris Lattner9de28282003-04-25 02:50:03 +0000580 Constant *OperandVal = 0;
581 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000582 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000583 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000584
Chris Lattner7e708292002-06-25 16:13:24 +0000585 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner38b5ae42003-06-24 20:29:52 +0000586 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattnercf712de2008-08-23 23:36:38 +0000587 markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000588 return;
589 }
590
Chris Lattner9de28282003-04-25 02:50:03 +0000591 if (OperandVal == 0) { // Grab the first value...
592 OperandVal = IV.getConstant();
Chris Lattner2a632552002-04-18 15:13:15 +0000593 } else { // Another value is being merged in!
594 // There is already a reachable operand. If we conflict with it,
595 // then the PHI node becomes overdefined. If we agree with it, we
596 // can continue on.
Misha Brukmanfd939082005-04-21 23:48:37 +0000597
Chris Lattner2a632552002-04-18 15:13:15 +0000598 // Check to see if there are two different constants merging...
Chris Lattner9de28282003-04-25 02:50:03 +0000599 if (IV.getConstant() != OperandVal) {
Chris Lattner2a632552002-04-18 15:13:15 +0000600 // Yes there is. This means the PHI node is not constant.
601 // You must be overdefined poor PHI.
602 //
Chris Lattnercf712de2008-08-23 23:36:38 +0000603 markOverdefined(&PN); // The PHI node now becomes overdefined
Chris Lattner2a632552002-04-18 15:13:15 +0000604 return; // I'm done analyzing you
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000605 }
Chris Lattner138a1242001-06-27 23:38:11 +0000606 }
607 }
Chris Lattner138a1242001-06-27 23:38:11 +0000608 }
609
Chris Lattner2a632552002-04-18 15:13:15 +0000610 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000611 // arguments that agree with each other(and OperandVal is the constant) or
612 // OperandVal is null because there are no defined incoming arguments. If
613 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000614 //
Chris Lattner9de28282003-04-25 02:50:03 +0000615 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000616 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000617}
618
Chris Lattner59acc7d2004-12-10 08:02:06 +0000619void SCCPSolver::visitReturnInst(ReturnInst &I) {
620 if (I.getNumOperands() == 0) return; // Ret void
621
Chris Lattner59acc7d2004-12-10 08:02:06 +0000622 Function *F = I.getParent()->getParent();
Devang Patel7c490d42008-03-11 05:46:42 +0000623 // If we are tracking the return value of this function, merge it in.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000624 if (!F->hasLocalLinkage())
Devang Patel7c490d42008-03-11 05:46:42 +0000625 return;
626
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000627 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000628 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000629 TrackedRetVals.find(F);
630 if (TFRVI != TrackedRetVals.end() &&
Chris Lattner59acc7d2004-12-10 08:02:06 +0000631 !TFRVI->second.isOverdefined()) {
632 LatticeVal &IV = getValueState(I.getOperand(0));
633 mergeInValue(TFRVI->second, F, IV);
Devang Patel7c490d42008-03-11 05:46:42 +0000634 return;
635 }
636 }
637
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000638 // Handle functions that return multiple values.
639 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
640 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000641 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000642 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
643 if (It == TrackedMultipleRetVals.end()) break;
644 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000645 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000646 } else if (!TrackedMultipleRetVals.empty() &&
647 I.getNumOperands() == 1 &&
648 isa<StructType>(I.getOperand(0)->getType())) {
649 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
650 i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000651 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000652 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
653 if (It == TrackedMultipleRetVals.end()) break;
Owen Andersone922c022009-07-22 00:24:57 +0000654 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewyckyd7f20b62009-06-06 23:13:08 +0000655 mergeInValue(It->second, F, getValueState(Val));
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000656 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000657 }
658}
659
Chris Lattner82bec2c2004-11-15 04:44:20 +0000660void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000661 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000662 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000663
Chris Lattner16b18fd2003-10-08 16:55:34 +0000664 BasicBlock *BB = TI.getParent();
665
Chris Lattnerb9a66342002-05-02 21:44:00 +0000666 // Mark all feasible successors executable...
667 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000668 if (SuccFeasible[i])
669 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000670}
671
Chris Lattner82bec2c2004-11-15 04:44:20 +0000672void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000673 Value *V = I.getOperand(0);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000674 LatticeVal &VState = getValueState(V);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000675 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000676 markOverdefined(&I);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000677 else if (VState.isConstant()) // Propagate constant value
Owen Andersonbaf3c402009-07-29 18:55:55 +0000678 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Reid Spencer4da49122006-12-12 05:05:00 +0000679 VState.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000680}
681
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000682void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000683 Value *Aggr = EVI.getAggregateOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000684
Dan Gohman60ea2682008-06-20 16:41:17 +0000685 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000686 if (isa<UndefValue>(Aggr))
687 return;
688
689 // Currently only handle single-index extractvalues.
690 if (EVI.getNumIndices() != 1) {
691 markOverdefined(&EVI);
692 return;
693 }
694
695 Function *F = 0;
696 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
697 F = CI->getCalledFunction();
698 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
699 F = II->getCalledFunction();
700
701 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
702 // result back!
703 if (F == 0 || TrackedMultipleRetVals.empty()) {
704 markOverdefined(&EVI);
705 return;
706 }
707
Chris Lattnercf712de2008-08-23 23:36:38 +0000708 // See if we are tracking the result of the callee. If not tracking this
709 // function (for example, it is a declaration) just move to overdefined.
710 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000711 markOverdefined(&EVI);
712 return;
713 }
714
715 // Otherwise, the value will be merged in here as a result of CallSite
716 // handling.
717}
718
719void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000720 Value *Aggr = IVI.getAggregateOperand();
721 Value *Val = IVI.getInsertedValueOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000722
Dan Gohman60ea2682008-06-20 16:41:17 +0000723 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohmandfaceb42008-06-20 16:39:44 +0000724 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000725 return;
726
727 // Currently only handle single-index insertvalues.
728 if (IVI.getNumIndices() != 1) {
729 markOverdefined(&IVI);
730 return;
731 }
Dan Gohmandfaceb42008-06-20 16:39:44 +0000732
733 // Currently only handle insertvalue instructions that are in a single-use
734 // chain that builds up a return value.
735 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
736 if (!TmpIVI->hasOneUse()) {
737 markOverdefined(&IVI);
738 return;
739 }
740 const Value *V = *TmpIVI->use_begin();
741 if (isa<ReturnInst>(V))
742 break;
743 TmpIVI = dyn_cast<InsertValueInst>(V);
744 if (!TmpIVI) {
745 markOverdefined(&IVI);
746 return;
747 }
748 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000749
750 // See if we are tracking the result of the callee.
751 Function *F = IVI.getParent()->getParent();
Chris Lattnercf712de2008-08-23 23:36:38 +0000752 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000753 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
754
755 // Merge in the inserted member value.
756 if (It != TrackedMultipleRetVals.end())
757 mergeInValue(It->second, F, getValueState(Val));
758
Dan Gohman60ea2682008-06-20 16:41:17 +0000759 // Mark the aggregate result of the IVI overdefined; any tracking that we do
760 // will be done on the individual member values.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000761 markOverdefined(&IVI);
762}
763
Chris Lattner82bec2c2004-11-15 04:44:20 +0000764void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000765 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000766 if (CondValue.isUndefined())
767 return;
Reid Spencer579dca12007-01-12 04:24:46 +0000768 if (CondValue.isConstant()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000769 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencer579dca12007-01-12 04:24:46 +0000770 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000771 : I.getFalseValue()));
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000772 return;
773 }
774 }
775
776 // Otherwise, the condition is overdefined or a constant we can't evaluate.
777 // See if we can produce something better than overdefined based on the T/F
778 // value.
779 LatticeVal &TVal = getValueState(I.getTrueValue());
780 LatticeVal &FVal = getValueState(I.getFalseValue());
781
782 // select ?, C, C -> C.
783 if (TVal.isConstant() && FVal.isConstant() &&
784 TVal.getConstant() == FVal.getConstant()) {
785 markConstant(&I, FVal.getConstant());
786 return;
787 }
788
789 if (TVal.isUndefined()) { // select ?, undef, X -> X.
790 mergeInValue(&I, FVal);
791 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
792 mergeInValue(&I, TVal);
793 } else {
794 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000795 }
796}
797
Chris Lattner2a632552002-04-18 15:13:15 +0000798// Handle BinaryOperators and Shift Instructions...
Chris Lattner82bec2c2004-11-15 04:44:20 +0000799void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000800 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000801 if (IV.isOverdefined()) return;
802
Chris Lattneref36dfd2004-11-15 05:03:30 +0000803 LatticeVal &V1State = getValueState(I.getOperand(0));
804 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000805
Chris Lattner2a632552002-04-18 15:13:15 +0000806 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnera177c672004-12-11 23:15:19 +0000807 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
808 // operand is overdefined.
809 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
810 LatticeVal *NonOverdefVal = 0;
811 if (!V1State.isOverdefined()) {
812 NonOverdefVal = &V1State;
813 } else if (!V2State.isOverdefined()) {
814 NonOverdefVal = &V2State;
815 }
816
817 if (NonOverdefVal) {
818 if (NonOverdefVal->isUndefined()) {
819 // Could annihilate value.
820 if (I.getOpcode() == Instruction::And)
Owen Andersona7235ea2009-07-31 20:28:14 +0000821 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +0000822 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
Owen Andersona7235ea2009-07-31 20:28:14 +0000823 markConstant(IV, &I, Constant::getAllOnesValue(PT));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +0000824 else
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000825 markConstant(IV, &I,
Owen Andersona7235ea2009-07-31 20:28:14 +0000826 Constant::getAllOnesValue(I.getType()));
Chris Lattnera177c672004-12-11 23:15:19 +0000827 return;
828 } else {
829 if (I.getOpcode() == Instruction::And) {
830 if (NonOverdefVal->getConstant()->isNullValue()) {
831 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskey52ab9042007-01-03 00:11:03 +0000832 return; // X and 0 = 0
Chris Lattnera177c672004-12-11 23:15:19 +0000833 }
834 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000835 if (ConstantInt *CI =
836 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnera177c672004-12-11 23:15:19 +0000837 if (CI->isAllOnesValue()) {
838 markConstant(IV, &I, NonOverdefVal->getConstant());
839 return; // X or -1 = -1
840 }
841 }
842 }
843 }
844 }
845
846
Chris Lattner1daee8b2004-01-12 03:57:30 +0000847 // If both operands are PHI nodes, it is possible that this instruction has
848 // a constant value, despite the fact that the PHI node doesn't. Check for
849 // this condition now.
850 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
851 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
852 if (PN1->getParent() == PN2->getParent()) {
853 // Since the two PHI nodes are in the same basic block, they must have
854 // entries for the same predecessors. Walk the predecessor list, and
855 // if all of the incoming values are constants, and the result of
856 // evaluating this expression with all incoming value pairs is the
857 // same, then this expression is a constant even though the PHI node
858 // is not a constant!
Chris Lattneref36dfd2004-11-15 05:03:30 +0000859 LatticeVal Result;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000860 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000861 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000862 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000863 LatticeVal &In2 =
864 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000865
866 if (In1.isOverdefined() || In2.isOverdefined()) {
867 Result.markOverdefined();
868 break; // Cannot fold this operation over the PHI nodes!
869 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000870 Constant *V =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000871 ConstantExpr::get(I.getOpcode(), In1.getConstant(),
Chris Lattnerb16689b2004-01-12 19:08:43 +0000872 In2.getConstant());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000873 if (Result.isUndefined())
Chris Lattnerb16689b2004-01-12 19:08:43 +0000874 Result.markConstant(V);
875 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000876 Result.markOverdefined();
877 break;
878 }
879 }
880 }
881
882 // If we found a constant value here, then we know the instruction is
883 // constant despite the fact that the PHI nodes are overdefined.
884 if (Result.isConstant()) {
885 markConstant(IV, &I, Result.getConstant());
886 // Remember that this instruction is virtually using the PHI node
887 // operands.
888 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
889 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
890 return;
891 } else if (Result.isUndefined()) {
892 return;
893 }
894
895 // Okay, this really is overdefined now. Since we might have
896 // speculatively thought that this was not overdefined before, and
897 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
898 // make sure to clean out any entries that we put there, for
899 // efficiency.
900 std::multimap<PHINode*, Instruction*>::iterator It, E;
901 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
902 while (It != E) {
903 if (It->second == &I) {
904 UsersOfOverdefinedPHIs.erase(It++);
905 } else
906 ++It;
907 }
908 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
909 while (It != E) {
910 if (It->second == &I) {
911 UsersOfOverdefinedPHIs.erase(It++);
912 } else
913 ++It;
914 }
915 }
916
917 markOverdefined(IV, &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000918 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000919 markConstant(IV, &I,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000920 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
Chris Lattnerb16689b2004-01-12 19:08:43 +0000921 V2State.getConstant()));
Chris Lattner2a632552002-04-18 15:13:15 +0000922 }
923}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000924
Reid Spencere4d87aa2006-12-23 06:05:41 +0000925// Handle ICmpInst instruction...
926void SCCPSolver::visitCmpInst(CmpInst &I) {
927 LatticeVal &IV = ValueState[&I];
928 if (IV.isOverdefined()) return;
929
930 LatticeVal &V1State = getValueState(I.getOperand(0));
931 LatticeVal &V2State = getValueState(I.getOperand(1));
932
933 if (V1State.isOverdefined() || V2State.isOverdefined()) {
934 // If both operands are PHI nodes, it is possible that this instruction has
935 // a constant value, despite the fact that the PHI node doesn't. Check for
936 // this condition now.
937 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
938 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
939 if (PN1->getParent() == PN2->getParent()) {
940 // Since the two PHI nodes are in the same basic block, they must have
941 // entries for the same predecessors. Walk the predecessor list, and
942 // if all of the incoming values are constants, and the result of
943 // evaluating this expression with all incoming value pairs is the
944 // same, then this expression is a constant even though the PHI node
945 // is not a constant!
946 LatticeVal Result;
947 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
948 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
949 BasicBlock *InBlock = PN1->getIncomingBlock(i);
950 LatticeVal &In2 =
951 getValueState(PN2->getIncomingValueForBlock(InBlock));
952
953 if (In1.isOverdefined() || In2.isOverdefined()) {
954 Result.markOverdefined();
955 break; // Cannot fold this operation over the PHI nodes!
956 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000957 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000958 In1.getConstant(),
959 In2.getConstant());
960 if (Result.isUndefined())
961 Result.markConstant(V);
962 else if (Result.isConstant() && Result.getConstant() != V) {
963 Result.markOverdefined();
964 break;
965 }
966 }
967 }
968
969 // If we found a constant value here, then we know the instruction is
970 // constant despite the fact that the PHI nodes are overdefined.
971 if (Result.isConstant()) {
972 markConstant(IV, &I, Result.getConstant());
973 // Remember that this instruction is virtually using the PHI node
974 // operands.
975 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
976 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
977 return;
978 } else if (Result.isUndefined()) {
979 return;
980 }
981
982 // Okay, this really is overdefined now. Since we might have
983 // speculatively thought that this was not overdefined before, and
984 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
985 // make sure to clean out any entries that we put there, for
986 // efficiency.
987 std::multimap<PHINode*, Instruction*>::iterator It, E;
988 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
989 while (It != E) {
990 if (It->second == &I) {
991 UsersOfOverdefinedPHIs.erase(It++);
992 } else
993 ++It;
994 }
995 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
996 while (It != E) {
997 if (It->second == &I) {
998 UsersOfOverdefinedPHIs.erase(It++);
999 } else
1000 ++It;
1001 }
1002 }
1003
1004 markOverdefined(IV, &I);
1005 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001006 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001007 V1State.getConstant(),
1008 V2State.getConstant()));
1009 }
1010}
1011
Robert Bocchino56107e22006-01-10 19:05:05 +00001012void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001013 // FIXME : SCCP does not handle vectors properly.
1014 markOverdefined(&I);
1015 return;
1016
1017#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +00001018 LatticeVal &ValState = getValueState(I.getOperand(0));
1019 LatticeVal &IdxState = getValueState(I.getOperand(1));
1020
1021 if (ValState.isOverdefined() || IdxState.isOverdefined())
1022 markOverdefined(&I);
1023 else if(ValState.isConstant() && IdxState.isConstant())
1024 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1025 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001026#endif
Robert Bocchino56107e22006-01-10 19:05:05 +00001027}
1028
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001029void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001030 // FIXME : SCCP does not handle vectors properly.
1031 markOverdefined(&I);
1032 return;
1033#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001034 LatticeVal &ValState = getValueState(I.getOperand(0));
1035 LatticeVal &EltState = getValueState(I.getOperand(1));
1036 LatticeVal &IdxState = getValueState(I.getOperand(2));
1037
1038 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1039 IdxState.isOverdefined())
1040 markOverdefined(&I);
1041 else if(ValState.isConstant() && EltState.isConstant() &&
1042 IdxState.isConstant())
1043 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1044 EltState.getConstant(),
1045 IdxState.getConstant()));
1046 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +00001047 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +00001048 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1049 EltState.getConstant(),
1050 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001051#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001052}
1053
Chris Lattner543abdf2006-04-08 01:19:12 +00001054void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001055 // FIXME : SCCP does not handle vectors properly.
1056 markOverdefined(&I);
1057 return;
1058#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +00001059 LatticeVal &V1State = getValueState(I.getOperand(0));
1060 LatticeVal &V2State = getValueState(I.getOperand(1));
1061 LatticeVal &MaskState = getValueState(I.getOperand(2));
1062
1063 if (MaskState.isUndefined() ||
1064 (V1State.isUndefined() && V2State.isUndefined()))
1065 return; // Undefined output if mask or both inputs undefined.
1066
1067 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1068 MaskState.isOverdefined()) {
1069 markOverdefined(&I);
1070 } else {
1071 // A mix of constant/undef inputs.
1072 Constant *V1 = V1State.isConstant() ?
1073 V1State.getConstant() : UndefValue::get(I.getType());
1074 Constant *V2 = V2State.isConstant() ?
1075 V2State.getConstant() : UndefValue::get(I.getType());
1076 Constant *Mask = MaskState.isConstant() ?
1077 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1078 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1079 }
Devang Patel67a821d2006-12-04 23:54:59 +00001080#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001081}
1082
Chris Lattner2a88bb72002-08-30 23:39:00 +00001083// Handle getelementptr instructions... if all operands are constants then we
1084// can turn this into a getelementptr ConstantExpr.
1085//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001086void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001087 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001088 if (IV.isOverdefined()) return;
1089
Chris Lattnere777ff22007-02-02 20:51:48 +00001090 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001091 Operands.reserve(I.getNumOperands());
1092
1093 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001094 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001095 if (State.isUndefined())
1096 return; // Operands are not resolved yet...
1097 else if (State.isOverdefined()) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001098 markOverdefined(IV, &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +00001099 return;
1100 }
1101 assert(State.isConstant() && "Unknown state!");
1102 Operands.push_back(State.getConstant());
1103 }
1104
1105 Constant *Ptr = Operands[0];
1106 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1107
Owen Andersonbaf3c402009-07-29 18:55:55 +00001108 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
Chris Lattnere777ff22007-02-02 20:51:48 +00001109 Operands.size()));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001110}
Brian Gaeked0fde302003-11-11 22:41:34 +00001111
Chris Lattnerdd336d12004-12-11 05:15:59 +00001112void SCCPSolver::visitStoreInst(Instruction &SI) {
1113 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1114 return;
1115 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001116 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001117 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1118
1119 // Get the value we are storing into the global.
1120 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1121
1122 mergeInValue(I->second, GV, PtrVal);
1123 if (I->second.isOverdefined())
1124 TrackedGlobals.erase(I); // No need to keep tracking this!
1125}
1126
1127
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001128// Handle load instructions. If the operand is a constant pointer to a constant
1129// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001130void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001131 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001132 if (IV.isOverdefined()) return;
1133
Chris Lattneref36dfd2004-11-15 05:03:30 +00001134 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001135 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1136 if (PtrVal.isConstant() && !I.isVolatile()) {
1137 Value *Ptr = PtrVal.getConstant();
Christopher Lambb15147e2007-12-29 07:56:53 +00001138 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +00001139 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0) {
Chris Lattnerc76d8032004-03-07 22:16:24 +00001140 // load null -> null
Owen Andersona7235ea2009-07-31 20:28:14 +00001141 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattnerc76d8032004-03-07 22:16:24 +00001142 return;
1143 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001144
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001145 // Transform load (constant global) into the value loaded.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001146 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1147 if (GV->isConstant()) {
Duncan Sands64da9402009-03-21 21:27:31 +00001148 if (GV->hasDefinitiveInitializer()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001149 markConstant(IV, &I, GV->getInitializer());
1150 return;
1151 }
1152 } else if (!TrackedGlobals.empty()) {
1153 // If we are tracking this global, merge in the known value for it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001154 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
Chris Lattnerdd336d12004-12-11 05:15:59 +00001155 TrackedGlobals.find(GV);
1156 if (It != TrackedGlobals.end()) {
1157 mergeInValue(IV, &I, It->second);
1158 return;
1159 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001160 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001161 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001162
1163 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1164 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1165 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen9d809302005-04-23 21:38:35 +00001166 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +00001167 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Jeff Cohen9d809302005-04-23 21:38:35 +00001168 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +00001169 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +00001170 *Context)) {
Jeff Cohen9d809302005-04-23 21:38:35 +00001171 markConstant(IV, &I, V);
1172 return;
1173 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001174 }
1175
1176 // Otherwise we cannot say for certain what value this load will produce.
1177 // Bail out.
1178 markOverdefined(IV, &I);
1179}
Chris Lattner58b7b082004-04-13 19:43:54 +00001180
Chris Lattner59acc7d2004-12-10 08:02:06 +00001181void SCCPSolver::visitCallSite(CallSite CS) {
1182 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001183 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001184
1185 // The common case is that we aren't tracking the callee, either because we
1186 // are not doing interprocedural analysis or the callee is indirect, or is
1187 // external. Handle these cases first.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001188 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001189CallOverdefined:
1190 // Void return and not tracking callee, just bail.
Owen Anderson1d0be152009-08-13 21:58:54 +00001191 if (I->getType() == Type::getVoidTy(I->getContext())) return;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001192
1193 // Otherwise, if we have a single return value case, and if the function is
1194 // a declaration, maybe we can constant fold it.
1195 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1196 canConstantFoldCallTo(F)) {
1197
1198 SmallVector<Constant*, 8> Operands;
1199 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1200 AI != E; ++AI) {
1201 LatticeVal &State = getValueState(*AI);
1202 if (State.isUndefined())
1203 return; // Operands are not resolved yet.
1204 else if (State.isOverdefined()) {
1205 markOverdefined(I);
1206 return;
1207 }
1208 assert(State.isConstant() && "Unknown state!");
1209 Operands.push_back(State.getConstant());
1210 }
1211
1212 // If we can constant fold this, mark the result of the call as a
1213 // constant.
Nick Lewyckye3f1fb12009-05-28 04:08:10 +00001214 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001215 markConstant(I, C);
1216 return;
1217 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001218 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001219
1220 // Otherwise, we don't know anything about this call, mark it overdefined.
1221 markOverdefined(I);
1222 return;
Chris Lattner58b7b082004-04-13 19:43:54 +00001223 }
1224
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001225 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001226 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1227 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001228 // If so, propagate the return value of the callee into this call result.
1229 mergeInValue(I, TFRVI->second);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001230 } else if (isa<StructType>(I->getType())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001231 // Check to see if we're tracking this callee, if not, handle it in the
1232 // common path above.
Chris Lattnercf712de2008-08-23 23:36:38 +00001233 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1234 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001235 if (TMRVI == TrackedMultipleRetVals.end())
1236 goto CallOverdefined;
1237
1238 // If we are tracking this callee, propagate the return values of the call
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001239 // into this call site. We do this by walking all the uses. Single-index
1240 // ExtractValueInst uses can be tracked; anything more complicated is
1241 // currently handled conservatively.
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001242 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1243 UI != E; ++UI) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001244 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1245 if (EVI->getNumIndices() == 1) {
1246 mergeInValue(EVI,
Dan Gohman60ea2682008-06-20 16:41:17 +00001247 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001248 continue;
1249 }
1250 }
1251 // The aggregate value is used in a way not handled here. Assume nothing.
1252 markOverdefined(*UI);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001253 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001254 } else {
1255 // Otherwise we're not tracking this callee, so handle it in the
1256 // common path above.
1257 goto CallOverdefined;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001258 }
1259
1260 // Finally, if this is the first call to the function hit, mark its entry
1261 // block executable.
1262 if (!BBExecutable.count(F->begin()))
1263 MarkBlockExecutable(F->begin());
1264
1265 // Propagate information from this call site into the callee.
1266 CallSite::arg_iterator CAI = CS.arg_begin();
1267 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1268 AI != E; ++AI, ++CAI) {
1269 LatticeVal &IV = ValueState[AI];
Torok Edwinc3384992009-09-24 18:33:42 +00001270 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Torok Edwin30a94e32009-09-24 09:47:18 +00001271 IV.markOverdefined();
1272 continue;
1273 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001274 if (!IV.isOverdefined())
1275 mergeInValue(IV, AI, getValueState(*CAI));
1276 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001277}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001278
1279
1280void SCCPSolver::Solve() {
1281 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001282 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001283 !OverdefinedInstWorkList.empty()) {
Chris Lattner82bec2c2004-11-15 04:44:20 +00001284 // Process the instruction work list...
1285 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001286 Value *I = OverdefinedInstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001287 OverdefinedInstWorkList.pop_back();
1288
Dan Gohman87325772009-08-17 15:25:05 +00001289 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001290
Chris Lattner82bec2c2004-11-15 04:44:20 +00001291 // "I" got into the work list because it either made the transition from
1292 // bottom to constant
1293 //
1294 // Anything on this worklist that is overdefined need not be visited
1295 // since all of its users will have already been marked as overdefined
1296 // Update all of the users of this instruction's value...
1297 //
1298 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1299 UI != E; ++UI)
1300 OperandChangedState(*UI);
1301 }
1302 // Process the instruction work list...
1303 while (!InstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001304 Value *I = InstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001305 InstWorkList.pop_back();
1306
Dan Gohman87325772009-08-17 15:25:05 +00001307 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001308
Chris Lattner82bec2c2004-11-15 04:44:20 +00001309 // "I" got into the work list because it either made the transition from
1310 // bottom to constant
1311 //
1312 // Anything on this worklist that is overdefined need not be visited
1313 // since all of its users will have already been marked as overdefined.
1314 // Update all of the users of this instruction's value...
1315 //
1316 if (!getValueState(I).isOverdefined())
1317 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1318 UI != E; ++UI)
1319 OperandChangedState(*UI);
1320 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001321
Chris Lattner82bec2c2004-11-15 04:44:20 +00001322 // Process the basic block work list...
1323 while (!BBWorkList.empty()) {
1324 BasicBlock *BB = BBWorkList.back();
1325 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001326
Dan Gohman87325772009-08-17 15:25:05 +00001327 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001328
Chris Lattner82bec2c2004-11-15 04:44:20 +00001329 // Notify all instructions in this basic block that they are newly
1330 // executable.
1331 visit(BB);
1332 }
1333 }
1334}
1335
Chris Lattner3bad2532006-12-20 06:21:33 +00001336/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001337/// that branches on undef values cannot reach any of their successors.
1338/// However, this is not a safe assumption. After we solve dataflow, this
1339/// method should be use to handle this. If this returns true, the solver
1340/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001341///
1342/// This method handles this by finding an unresolved branch and marking it one
1343/// of the edges from the block as being feasible, even though the condition
1344/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1345/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001346/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001347/// constraints on the condition of the branch, as that would impact other users
1348/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001349///
1350/// This scan also checks for values that use undefs, whose results are actually
1351/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1352/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1353/// even if X isn't defined.
1354bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001355 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1356 if (!BBExecutable.count(BB))
1357 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001358
1359 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1360 // Look for instructions which produce undef values.
Owen Anderson1d0be152009-08-13 21:58:54 +00001361 if (I->getType() == Type::getVoidTy(F.getContext())) continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001362
1363 LatticeVal &LV = getValueState(I);
1364 if (!LV.isUndefined()) continue;
1365
1366 // Get the lattice values of the first two operands for use below.
1367 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1368 LatticeVal Op1LV;
1369 if (I->getNumOperands() == 2) {
1370 // If this is a two-operand instruction, and if both operands are
1371 // undefs, the result stays undef.
1372 Op1LV = getValueState(I->getOperand(1));
1373 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1374 continue;
1375 }
1376
1377 // If this is an instructions whose result is defined even if the input is
1378 // not fully defined, propagate the information.
1379 const Type *ITy = I->getType();
1380 switch (I->getOpcode()) {
1381 default: break; // Leave the instruction as an undef.
1382 case Instruction::ZExt:
1383 // After a zero extend, we know the top part is zero. SExt doesn't have
1384 // to be handled here, because we don't know whether the top part is 1's
1385 // or 0's.
1386 assert(Op0LV.isUndefined());
Owen Andersona7235ea2009-07-31 20:28:14 +00001387 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001388 return true;
1389 case Instruction::Mul:
1390 case Instruction::And:
1391 // undef * X -> 0. X could be zero.
1392 // undef & X -> 0. X could be zero.
Owen Andersona7235ea2009-07-31 20:28:14 +00001393 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001394 return true;
1395
1396 case Instruction::Or:
1397 // undef | X -> -1. X could be -1.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001398 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001399 markForcedConstant(LV, I,
Owen Andersona7235ea2009-07-31 20:28:14 +00001400 Constant::getAllOnesValue(PTy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001401 else
Owen Andersona7235ea2009-07-31 20:28:14 +00001402 markForcedConstant(LV, I, Constant::getAllOnesValue(ITy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001403 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001404
1405 case Instruction::SDiv:
1406 case Instruction::UDiv:
1407 case Instruction::SRem:
1408 case Instruction::URem:
1409 // X / undef -> undef. No change.
1410 // X % undef -> undef. No change.
1411 if (Op1LV.isUndefined()) break;
1412
1413 // undef / X -> 0. X could be maxint.
1414 // undef % X -> 0. X could be 1.
Owen Andersona7235ea2009-07-31 20:28:14 +00001415 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001416 return true;
1417
1418 case Instruction::AShr:
1419 // undef >>s X -> undef. No change.
1420 if (Op0LV.isUndefined()) break;
1421
1422 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1423 if (Op0LV.isConstant())
1424 markForcedConstant(LV, I, Op0LV.getConstant());
1425 else
1426 markOverdefined(LV, I);
1427 return true;
1428 case Instruction::LShr:
1429 case Instruction::Shl:
1430 // undef >> X -> undef. No change.
1431 // undef << X -> undef. No change.
1432 if (Op0LV.isUndefined()) break;
1433
1434 // X >> undef -> 0. X could be 0.
1435 // X << undef -> 0. X could be 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001436 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001437 return true;
1438 case Instruction::Select:
1439 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1440 if (Op0LV.isUndefined()) {
1441 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1442 Op1LV = getValueState(I->getOperand(2));
1443 } else if (Op1LV.isUndefined()) {
1444 // c ? undef : undef -> undef. No change.
1445 Op1LV = getValueState(I->getOperand(2));
1446 if (Op1LV.isUndefined())
1447 break;
1448 // Otherwise, c ? undef : x -> x.
1449 } else {
1450 // Leave Op1LV as Operand(1)'s LatticeValue.
1451 }
1452
1453 if (Op1LV.isConstant())
1454 markForcedConstant(LV, I, Op1LV.getConstant());
1455 else
1456 markOverdefined(LV, I);
1457 return true;
Chris Lattner60301602008-05-24 03:59:33 +00001458 case Instruction::Call:
1459 // If a call has an undef result, it is because it is constant foldable
1460 // but one of the inputs was undef. Just force the result to
1461 // overdefined.
1462 markOverdefined(LV, I);
1463 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001464 }
1465 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001466
1467 TerminatorInst *TI = BB->getTerminator();
1468 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1469 if (!BI->isConditional()) continue;
1470 if (!getValueState(BI->getCondition()).isUndefined())
1471 continue;
1472 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Dale Johannesen9bca5832008-05-23 01:01:31 +00001473 if (SI->getNumSuccessors()<2) // no cases
1474 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001475 if (!getValueState(SI->getCondition()).isUndefined())
1476 continue;
1477 } else {
1478 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001479 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001480
Chris Lattner05bb7892008-01-28 00:32:30 +00001481 // If the edge to the second successor isn't thought to be feasible yet,
1482 // mark it so now. We pick the second one so that this goes to some
1483 // enumerated value in a switch instead of going to the default destination.
1484 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001485 continue;
1486
1487 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1488 // and return. This will make other blocks reachable, which will allow new
1489 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001490 markEdgeExecutable(BB, TI->getSuccessor(1));
1491
1492 // This must be a conditional branch of switch on undef. At this point,
1493 // force the old terminator to branch to the first successor. This is
1494 // required because we are now influencing the dataflow of the function with
1495 // the assumption that this edge is taken. If we leave the branch condition
1496 // as undef, then further analysis could think the undef went another way
1497 // leading to an inconsistent set of conclusions.
1498 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00001499 BI->setCondition(ConstantInt::getFalse(*Context));
Chris Lattner05bb7892008-01-28 00:32:30 +00001500 } else {
1501 SwitchInst *SI = cast<SwitchInst>(TI);
1502 SI->setCondition(SI->getCaseValue(1));
1503 }
1504
Chris Lattnerd2d86702006-10-22 05:59:17 +00001505 return true;
1506 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001507
Chris Lattnerd2d86702006-10-22 05:59:17 +00001508 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001509}
1510
Chris Lattner82bec2c2004-11-15 04:44:20 +00001511
1512namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001513 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001514 //
Chris Lattner14051812004-11-15 07:15:04 +00001515 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001516 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001517 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001518 struct SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001519 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +00001520 SCCP() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +00001521
Chris Lattner14051812004-11-15 07:15:04 +00001522 // runOnFunction - Run the Sparse Conditional Constant Propagation
1523 // algorithm, and return true if the function was modified.
1524 //
1525 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001526
Chris Lattner14051812004-11-15 07:15:04 +00001527 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1528 AU.setPreservesCFG();
1529 }
1530 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001531} // end anonymous namespace
1532
Dan Gohman844731a2008-05-13 00:00:25 +00001533char SCCP::ID = 0;
1534static RegisterPass<SCCP>
1535X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001536
1537// createSCCPPass - This is the public interface to this file...
1538FunctionPass *llvm::createSCCPPass() {
1539 return new SCCP();
1540}
1541
1542
Chris Lattner82bec2c2004-11-15 04:44:20 +00001543// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1544// and return true if the function was modified.
1545//
1546bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001547 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001548 SCCPSolver Solver;
Owen Andersone922c022009-07-22 00:24:57 +00001549 Solver.setContext(&F.getContext());
Chris Lattner82bec2c2004-11-15 04:44:20 +00001550
1551 // Mark the first block of the function as being executable.
1552 Solver.MarkBlockExecutable(F.begin());
1553
Chris Lattner7e529e42004-11-15 05:45:33 +00001554 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001555 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001556 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001557
Chris Lattner82bec2c2004-11-15 04:44:20 +00001558 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001559 bool ResolvedUndefs = true;
1560 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001561 Solver.Solve();
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001562 DEBUG(errs() << "RESOLVING UNDEFs\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001563 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001564 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001565
Chris Lattner7e529e42004-11-15 05:45:33 +00001566 bool MadeChanges = false;
1567
1568 // If we decided that there are basic blocks that are dead in this function,
1569 // delete their contents now. Note that we cannot actually delete the blocks,
1570 // as we cannot modify the CFG of the function.
1571 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001572 SmallVector<Instruction*, 512> Insts;
Bill Wendling7a7cf6b2008-08-14 23:05:24 +00001573 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner57939df2007-03-04 04:50:21 +00001574
Chris Lattner7e529e42004-11-15 05:45:33 +00001575 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001576 if (!Solver.isBlockExecutable(BB)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001577 DEBUG(errs() << " BasicBlock Dead:" << *BB);
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001578 ++NumDeadBlocks;
1579
Chris Lattner7e529e42004-11-15 05:45:33 +00001580 // Delete the instructions backwards, as it has a reduced likelihood of
1581 // having to update as many def-use and use-def chains.
Chris Lattner7e529e42004-11-15 05:45:33 +00001582 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1583 I != E; ++I)
1584 Insts.push_back(I);
1585 while (!Insts.empty()) {
1586 Instruction *I = Insts.back();
1587 Insts.pop_back();
1588 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001589 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattner7e529e42004-11-15 05:45:33 +00001590 BB->getInstList().erase(I);
1591 MadeChanges = true;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001592 ++NumInstRemoved;
Chris Lattner7e529e42004-11-15 05:45:33 +00001593 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001594 } else {
1595 // Iterate over all of the instructions in a function, replacing them with
1596 // constants if we have found them to be of constant values.
1597 //
1598 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1599 Instruction *Inst = BI++;
Owen Anderson1d0be152009-08-13 21:58:54 +00001600 if (Inst->getType() == Type::getVoidTy(F.getContext()) ||
Chris Lattnerf4023a12008-04-24 00:16:28 +00001601 isa<TerminatorInst>(Inst))
1602 continue;
1603
1604 LatticeVal &IV = Values[Inst];
1605 if (!IV.isConstant() && !IV.isUndefined())
1606 continue;
1607
1608 Constant *Const = IV.isConstant()
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001609 ? IV.getConstant() : UndefValue::get(Inst->getType());
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001610 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
Misha Brukmanfd939082005-04-21 23:48:37 +00001611
Chris Lattnerf4023a12008-04-24 00:16:28 +00001612 // Replaces all of the uses of a variable with uses of the constant.
1613 Inst->replaceAllUsesWith(Const);
1614
1615 // Delete the instruction.
1616 Inst->eraseFromParent();
1617
1618 // Hey, we just changed something!
1619 MadeChanges = true;
1620 ++NumInstRemoved;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001621 }
1622 }
1623
1624 return MadeChanges;
1625}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001626
1627namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001628 //===--------------------------------------------------------------------===//
1629 //
1630 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1631 /// Constant Propagation.
1632 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001633 struct IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001634 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +00001635 IPSCCP() : ModulePass(&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001636 bool runOnModule(Module &M);
1637 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001638} // end anonymous namespace
1639
Dan Gohman844731a2008-05-13 00:00:25 +00001640char IPSCCP::ID = 0;
1641static RegisterPass<IPSCCP>
1642Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1643
Chris Lattner59acc7d2004-12-10 08:02:06 +00001644// createIPSCCPPass - This is the public interface to this file...
1645ModulePass *llvm::createIPSCCPPass() {
1646 return new IPSCCP();
1647}
1648
1649
1650static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001651 // Delete any dead constantexpr klingons.
1652 GV->removeDeadConstantUsers();
1653
Chris Lattner59acc7d2004-12-10 08:02:06 +00001654 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1655 UI != E; ++UI)
1656 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001657 if (SI->getOperand(0) == GV || SI->isVolatile())
1658 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001659 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1660 // Make sure we are calling the function, not passing the address.
1661 CallSite CS = CallSite::get(cast<Instruction>(*UI));
Nick Lewyckyaf386132008-11-03 03:49:14 +00001662 if (CS.hasArgument(GV))
1663 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001664 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1665 if (LI->isVolatile())
1666 return true;
1667 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001668 return true;
1669 }
1670 return false;
1671}
1672
1673bool IPSCCP::runOnModule(Module &M) {
Owen Andersone922c022009-07-22 00:24:57 +00001674 LLVMContext *Context = &M.getContext();
Owen Anderson001dbfe2009-07-16 18:04:31 +00001675
Chris Lattner59acc7d2004-12-10 08:02:06 +00001676 SCCPSolver Solver;
Owen Anderson001dbfe2009-07-16 18:04:31 +00001677 Solver.setContext(Context);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001678
1679 // Loop over all functions, marking arguments to those with their addresses
1680 // taken or that are external as overdefined.
1681 //
Chris Lattner59acc7d2004-12-10 08:02:06 +00001682 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001683 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001684 if (!F->isDeclaration())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001685 Solver.MarkBlockExecutable(F->begin());
Chris Lattner7d27fc02005-04-19 19:16:19 +00001686 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1687 AI != E; ++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001688 Solver.markOverdefined(AI);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001689 } else {
1690 Solver.AddTrackedFunction(F);
1691 }
1692
Chris Lattnerdd336d12004-12-11 05:15:59 +00001693 // Loop over global variables. We inform the solver about any internal global
1694 // variables that do not have their 'addresses taken'. If they don't have
1695 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001696 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1697 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001698 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001699 Solver.TrackValueOfGlobalVariable(G);
1700
Chris Lattner59acc7d2004-12-10 08:02:06 +00001701 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001702 bool ResolvedUndefs = true;
1703 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001704 Solver.Solve();
1705
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001706 DEBUG(errs() << "RESOLVING UNDEFS\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001707 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001708 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001709 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001710 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001711
1712 bool MadeChanges = false;
1713
1714 // Iterate over all of the instructions in the module, replacing them with
1715 // constants if we have found them to be of constant values.
1716 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001717 SmallVector<Instruction*, 512> Insts;
1718 SmallVector<BasicBlock*, 512> BlocksToErase;
Bill Wendling7a7cf6b2008-08-14 23:05:24 +00001719 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001720
Chris Lattner59acc7d2004-12-10 08:02:06 +00001721 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001722 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1723 AI != E; ++AI)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001724 if (!AI->use_empty()) {
1725 LatticeVal &IV = Values[AI];
1726 if (IV.isConstant() || IV.isUndefined()) {
1727 Constant *CST = IV.isConstant() ?
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001728 IV.getConstant() : UndefValue::get(AI->getType());
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001729 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Misha Brukmanfd939082005-04-21 23:48:37 +00001730
Chris Lattner59acc7d2004-12-10 08:02:06 +00001731 // Replaces all of the uses of a variable with uses of the
1732 // constant.
1733 AI->replaceAllUsesWith(CST);
1734 ++IPNumArgsElimed;
1735 }
1736 }
1737
1738 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001739 if (!Solver.isBlockExecutable(BB)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001740 DEBUG(errs() << " BasicBlock Dead:" << *BB);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001741 ++IPNumDeadBlocks;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001742
Chris Lattner59acc7d2004-12-10 08:02:06 +00001743 // Delete the instructions backwards, as it has a reduced likelihood of
1744 // having to update as many def-use and use-def chains.
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001745 TerminatorInst *TI = BB->getTerminator();
1746 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001747 Insts.push_back(I);
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001748
Chris Lattner59acc7d2004-12-10 08:02:06 +00001749 while (!Insts.empty()) {
1750 Instruction *I = Insts.back();
1751 Insts.pop_back();
1752 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001753 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattner59acc7d2004-12-10 08:02:06 +00001754 BB->getInstList().erase(I);
1755 MadeChanges = true;
1756 ++IPNumInstRemoved;
1757 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001758
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001759 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1760 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001761 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001762 TI->getSuccessor(i)->removePredecessor(BB);
1763 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001764 if (!TI->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001765 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001766 BB->getInstList().erase(TI);
1767
Chris Lattner864737b2004-12-11 05:32:19 +00001768 if (&*BB != &F->front())
1769 BlocksToErase.push_back(BB);
1770 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001771 new UnreachableInst(M.getContext(), BB);
Chris Lattner864737b2004-12-11 05:32:19 +00001772
Chris Lattner59acc7d2004-12-10 08:02:06 +00001773 } else {
1774 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1775 Instruction *Inst = BI++;
Owen Anderson1d0be152009-08-13 21:58:54 +00001776 if (Inst->getType() == Type::getVoidTy(M.getContext()))
Chris Lattnereb5f4092008-04-24 00:21:50 +00001777 continue;
1778
1779 LatticeVal &IV = Values[Inst];
1780 if (!IV.isConstant() && !IV.isUndefined())
1781 continue;
1782
1783 Constant *Const = IV.isConstant()
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001784 ? IV.getConstant() : UndefValue::get(Inst->getType());
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001785 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
Misha Brukmanfd939082005-04-21 23:48:37 +00001786
Chris Lattnereb5f4092008-04-24 00:21:50 +00001787 // Replaces all of the uses of a variable with uses of the
1788 // constant.
1789 Inst->replaceAllUsesWith(Const);
1790
1791 // Delete the instruction.
Chris Lattnerd9d46242009-01-14 21:01:16 +00001792 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
Chris Lattnereb5f4092008-04-24 00:21:50 +00001793 Inst->eraseFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001794
Chris Lattnereb5f4092008-04-24 00:21:50 +00001795 // Hey, we just changed something!
1796 MadeChanges = true;
1797 ++IPNumInstRemoved;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001798 }
1799 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001800
1801 // Now that all instructions in the function are constant folded, erase dead
1802 // blocks, because we can now use ConstantFoldTerminator to get rid of
1803 // in-edges.
1804 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1805 // If there are any PHI nodes in this successor, drop entries for BB now.
1806 BasicBlock *DeadBB = BlocksToErase[i];
1807 while (!DeadBB->use_empty()) {
1808 Instruction *I = cast<Instruction>(DeadBB->use_back());
1809 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001810 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001811 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001812 // if this is a branch or switch on undef. Fold it manually as a
1813 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001814#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001815 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1816 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1817 "Branch should be foldable!");
1818 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1819 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1820 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001821 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerddaaa372006-10-23 18:57:02 +00001822 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001823#endif
Chris Lattnerddaaa372006-10-23 18:57:02 +00001824
1825 // Make this an uncond branch to the first successor.
1826 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001827 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001828
1829 // Remove entries in successor phi nodes to remove edges.
1830 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1831 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1832
1833 // Remove the old terminator.
1834 TI->eraseFromParent();
1835 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001836 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001837
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001838 // Finally, delete the basic block.
1839 F->getBasicBlockList().erase(DeadBB);
1840 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001841 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001842 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001843
1844 // If we inferred constant or undef return values for a function, we replaced
1845 // all call uses with the inferred value. This means we don't need to bother
1846 // actually returning anything from the function. Replace all return
1847 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001848 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001849 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001850 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner0417feb2004-12-11 02:53:57 +00001851 E = RV.end(); I != E; ++I)
1852 if (!I->second.isOverdefined() &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001853 I->first->getReturnType() != Type::getVoidTy(M.getContext())) {
Chris Lattner0417feb2004-12-11 02:53:57 +00001854 Function *F = I->first;
1855 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1856 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1857 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001858 RI->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattner0417feb2004-12-11 02:53:57 +00001859 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001860
1861 // If we infered constant or undef values for globals variables, we can delete
1862 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001863 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1864 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001865 E = TG.end(); I != E; ++I) {
1866 GlobalVariable *GV = I->first;
1867 assert(!I->second.isOverdefined() &&
1868 "Overdefined values should have been taken out of the map!");
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001869 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattnerdd336d12004-12-11 05:15:59 +00001870 while (!GV->use_empty()) {
1871 StoreInst *SI = cast<StoreInst>(GV->use_back());
1872 SI->eraseFromParent();
1873 }
1874 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001875 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001876 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001877
Chris Lattner59acc7d2004-12-10 08:02:06 +00001878 return MadeChanges;
1879}