blob: 2ed4a638adf408c4cb1e05982f8dcfe39f7b7354 [file] [log] [blame]
Chris Lattnerd2a653a2008-12-05 07:49:08 +00001//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Owen Andersonab6ec2e2007-07-24 17:55:58 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs global value numbering to eliminate fully redundant
11// instructions. It also performs simple dead load elimination.
12//
John Criswell073e4d12009-03-10 15:04:53 +000013// Note that this pass does the value numbering itself; it does not use the
Matthijs Kooijman5afc2742008-06-05 07:55:49 +000014// ValueNumbering analysis passes.
15//
Owen Andersonab6ec2e2007-07-24 17:55:58 +000016//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "gvn"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000019#include "llvm/Transforms/Scalar.h"
Owen Anderson5e5599b2007-07-25 19:57:03 +000020#include "llvm/BasicBlock.h"
Owen Andersondbf23cc2007-07-26 18:26:51 +000021#include "llvm/Constants.h"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000022#include "llvm/DerivedTypes.h"
Owen Andersondbf23cc2007-07-26 18:26:51 +000023#include "llvm/Function.h"
Devang Patele8c6d312009-03-06 02:59:27 +000024#include "llvm/IntrinsicInst.h"
Owen Andersonb5618da2009-07-03 00:17:18 +000025#include "llvm/LLVMContext.h"
Chris Lattner0a9616d2009-09-21 05:57:11 +000026#include "llvm/Operator.h"
Owen Andersondbf23cc2007-07-26 18:26:51 +000027#include "llvm/Value.h"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000028#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/DepthFirstIterator.h"
Owen Andersonbfe133e2008-12-15 02:03:00 +000030#include "llvm/ADT/PostOrderIterator.h"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000031#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/Statistic.h"
Owen Anderson09b83ba2007-10-18 19:39:33 +000034#include "llvm/Analysis/Dominators.h"
35#include "llvm/Analysis/AliasAnalysis.h"
Victor Hernandez5d034492009-09-18 22:35:49 +000036#include "llvm/Analysis/MallocHelper.h"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000037#include "llvm/Analysis/MemoryDependenceAnalysis.h"
38#include "llvm/Support/CFG.h"
Owen Andersone780d662008-06-19 19:57:25 +000039#include "llvm/Support/CommandLine.h"
Chris Lattnerd528b212008-03-29 04:36:18 +000040#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattner0a9616d2009-09-21 05:57:11 +000042#include "llvm/Support/GetElementPtrTypeIterator.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000043#include "llvm/Support/raw_ostream.h"
Chris Lattner1dd48c32009-09-20 19:03:47 +000044#include "llvm/Target/TargetData.h"
Owen Andersonfdf9f162008-06-19 19:54:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dale Johannesen81b64632009-06-17 20:48:23 +000046#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerb6c65fa2009-10-10 23:50:30 +000047#include "llvm/Transforms/Utils/SSAUpdater.h"
Duncan Sands26ff6f92008-10-08 07:23:46 +000048#include <cstdio>
Owen Andersonab6ec2e2007-07-24 17:55:58 +000049using namespace llvm;
50
Bill Wendling3c793442008-12-22 22:14:07 +000051STATISTIC(NumGVNInstr, "Number of instructions deleted");
52STATISTIC(NumGVNLoad, "Number of loads deleted");
53STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
Owen Anderson53d546e2008-07-15 16:28:06 +000054STATISTIC(NumGVNBlocks, "Number of blocks merged");
Bill Wendling3c793442008-12-22 22:14:07 +000055STATISTIC(NumPRELoad, "Number of loads PRE'd");
Chris Lattner168be762008-03-22 04:13:49 +000056
Evan Cheng9598f932008-06-20 01:01:07 +000057static cl::opt<bool> EnablePRE("enable-pre",
Owen Andersonaddbe3e2008-07-17 19:41:00 +000058 cl::init(true), cl::Hidden);
Dan Gohmana8f8a852009-06-15 18:30:15 +000059static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
Owen Andersone780d662008-06-19 19:57:25 +000060
Owen Andersonab6ec2e2007-07-24 17:55:58 +000061//===----------------------------------------------------------------------===//
62// ValueTable Class
63//===----------------------------------------------------------------------===//
64
65/// This class holds the mapping between values and value numbers. It is used
66/// as an efficient mechanism to determine the expression-wise equivalence of
67/// two values.
68namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000069 struct Expression {
Dan Gohmana5b96452009-06-04 22:49:04 +000070 enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
71 UDIV, SDIV, FDIV, UREM, SREM,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000072 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
73 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
74 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
75 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
76 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
Owen Andersonab6ec2e2007-07-24 17:55:58 +000077 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
78 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000079 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
Owen Anderson69057b82008-05-13 08:17:22 +000080 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
Owen Anderson45d37012008-06-19 17:25:39 +000081 EMPTY, TOMBSTONE };
Owen Andersonab6ec2e2007-07-24 17:55:58 +000082
83 ExpressionOpcode opcode;
84 const Type* type;
85 uint32_t firstVN;
86 uint32_t secondVN;
87 uint32_t thirdVN;
88 SmallVector<uint32_t, 4> varargs;
Chris Lattner1eefa9c2009-09-21 02:42:51 +000089 Value *function;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000090
Owen Andersonab6ec2e2007-07-24 17:55:58 +000091 Expression() { }
92 Expression(ExpressionOpcode o) : opcode(o) { }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000093
Owen Andersonab6ec2e2007-07-24 17:55:58 +000094 bool operator==(const Expression &other) const {
95 if (opcode != other.opcode)
96 return false;
97 else if (opcode == EMPTY || opcode == TOMBSTONE)
98 return true;
99 else if (type != other.type)
100 return false;
Owen Anderson09b83ba2007-10-18 19:39:33 +0000101 else if (function != other.function)
102 return false;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000103 else if (firstVN != other.firstVN)
104 return false;
105 else if (secondVN != other.secondVN)
106 return false;
107 else if (thirdVN != other.thirdVN)
108 return false;
109 else {
110 if (varargs.size() != other.varargs.size())
111 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000112
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000113 for (size_t i = 0; i < varargs.size(); ++i)
114 if (varargs[i] != other.varargs[i])
115 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000116
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000117 return true;
118 }
119 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000120
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000121 bool operator!=(const Expression &other) const {
Bill Wendling86f01cb2008-12-22 22:16:31 +0000122 return !(*this == other);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000123 }
124 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000125
Chris Lattner2dd09db2009-09-02 06:11:42 +0000126 class ValueTable {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000127 private:
128 DenseMap<Value*, uint32_t> valueNumbering;
129 DenseMap<Expression, uint32_t> expressionNumbering;
Owen Andersonf7928602008-05-12 20:15:55 +0000130 AliasAnalysis* AA;
131 MemoryDependenceAnalysis* MD;
132 DominatorTree* DT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000133
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000134 uint32_t nextValueNumber;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000135
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000136 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
137 Expression::ExpressionOpcode getOpcode(CmpInst* C);
138 Expression::ExpressionOpcode getOpcode(CastInst* C);
139 Expression create_expression(BinaryOperator* BO);
140 Expression create_expression(CmpInst* C);
141 Expression create_expression(ShuffleVectorInst* V);
142 Expression create_expression(ExtractElementInst* C);
143 Expression create_expression(InsertElementInst* V);
144 Expression create_expression(SelectInst* V);
145 Expression create_expression(CastInst* C);
146 Expression create_expression(GetElementPtrInst* G);
Owen Anderson09b83ba2007-10-18 19:39:33 +0000147 Expression create_expression(CallInst* C);
Owen Anderson69057b82008-05-13 08:17:22 +0000148 Expression create_expression(Constant* C);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000149 public:
Dan Gohmanc4971722009-04-01 16:37:47 +0000150 ValueTable() : nextValueNumber(1) { }
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000151 uint32_t lookup_or_add(Value *V);
152 uint32_t lookup(Value *V) const;
153 void add(Value *V, uint32_t num);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000154 void clear();
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000155 void erase(Value *v);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000156 unsigned size();
Owen Andersonf7928602008-05-12 20:15:55 +0000157 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
Chris Lattner8541ede2008-12-01 00:40:32 +0000158 AliasAnalysis *getAliasAnalysis() const { return AA; }
Owen Andersonf7928602008-05-12 20:15:55 +0000159 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
160 void setDomTree(DominatorTree* D) { DT = D; }
Owen Anderson3ea90a72008-07-03 17:44:33 +0000161 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
Bill Wendling6b18a392008-12-22 21:36:08 +0000162 void verifyRemoved(const Value *) const;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000163 };
164}
165
166namespace llvm {
Chris Lattner0625bd62007-09-17 18:34:04 +0000167template <> struct DenseMapInfo<Expression> {
Owen Anderson9699a6e2007-08-02 18:16:06 +0000168 static inline Expression getEmptyKey() {
169 return Expression(Expression::EMPTY);
170 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000171
Owen Anderson9699a6e2007-08-02 18:16:06 +0000172 static inline Expression getTombstoneKey() {
173 return Expression(Expression::TOMBSTONE);
174 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000175
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000176 static unsigned getHashValue(const Expression e) {
177 unsigned hash = e.opcode;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000178
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000179 hash = e.firstVN + hash * 37;
180 hash = e.secondVN + hash * 37;
181 hash = e.thirdVN + hash * 37;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000182
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000183 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
184 (unsigned)((uintptr_t)e.type >> 9)) +
185 hash * 37;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000186
Owen Anderson9699a6e2007-08-02 18:16:06 +0000187 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
188 E = e.varargs.end(); I != E; ++I)
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000189 hash = *I + hash * 37;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000190
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000191 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
192 (unsigned)((uintptr_t)e.function >> 9)) +
193 hash * 37;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000194
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000195 return hash;
196 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000197 static bool isEqual(const Expression &LHS, const Expression &RHS) {
198 return LHS == RHS;
199 }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000200 static bool isPod() { return true; }
201};
202}
203
204//===----------------------------------------------------------------------===//
205// ValueTable Internal Functions
206//===----------------------------------------------------------------------===//
Chris Lattner2876a642008-03-21 21:14:38 +0000207Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000208 switch(BO->getOpcode()) {
Chris Lattner2876a642008-03-21 21:14:38 +0000209 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinfbcc6632009-07-14 16:55:14 +0000210 llvm_unreachable("Binary operator with unknown opcode?");
Chris Lattner2876a642008-03-21 21:14:38 +0000211 case Instruction::Add: return Expression::ADD;
Dan Gohmana5b96452009-06-04 22:49:04 +0000212 case Instruction::FAdd: return Expression::FADD;
Chris Lattner2876a642008-03-21 21:14:38 +0000213 case Instruction::Sub: return Expression::SUB;
Dan Gohmana5b96452009-06-04 22:49:04 +0000214 case Instruction::FSub: return Expression::FSUB;
Chris Lattner2876a642008-03-21 21:14:38 +0000215 case Instruction::Mul: return Expression::MUL;
Dan Gohmana5b96452009-06-04 22:49:04 +0000216 case Instruction::FMul: return Expression::FMUL;
Chris Lattner2876a642008-03-21 21:14:38 +0000217 case Instruction::UDiv: return Expression::UDIV;
218 case Instruction::SDiv: return Expression::SDIV;
219 case Instruction::FDiv: return Expression::FDIV;
220 case Instruction::URem: return Expression::UREM;
221 case Instruction::SRem: return Expression::SREM;
222 case Instruction::FRem: return Expression::FREM;
223 case Instruction::Shl: return Expression::SHL;
224 case Instruction::LShr: return Expression::LSHR;
225 case Instruction::AShr: return Expression::ASHR;
226 case Instruction::And: return Expression::AND;
227 case Instruction::Or: return Expression::OR;
228 case Instruction::Xor: return Expression::XOR;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000229 }
230}
231
232Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +0000233 if (isa<ICmpInst>(C)) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000234 switch (C->getPredicate()) {
Chris Lattner2876a642008-03-21 21:14:38 +0000235 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinfbcc6632009-07-14 16:55:14 +0000236 llvm_unreachable("Comparison with unknown predicate?");
Chris Lattner2876a642008-03-21 21:14:38 +0000237 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
238 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
239 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
240 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
241 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
242 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
243 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
244 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
245 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
246 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000247 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +0000248 } else {
249 switch (C->getPredicate()) {
250 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinfbcc6632009-07-14 16:55:14 +0000251 llvm_unreachable("Comparison with unknown predicate?");
Nick Lewyckya21d3da2009-07-08 03:04:38 +0000252 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
253 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
254 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
255 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
256 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
257 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
258 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
259 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
260 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
261 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
262 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
263 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
264 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
265 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
266 }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000267 }
268}
269
Chris Lattner2876a642008-03-21 21:14:38 +0000270Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000271 switch(C->getOpcode()) {
Chris Lattner2876a642008-03-21 21:14:38 +0000272 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinfbcc6632009-07-14 16:55:14 +0000273 llvm_unreachable("Cast operator with unknown opcode?");
Chris Lattner2876a642008-03-21 21:14:38 +0000274 case Instruction::Trunc: return Expression::TRUNC;
275 case Instruction::ZExt: return Expression::ZEXT;
276 case Instruction::SExt: return Expression::SEXT;
277 case Instruction::FPToUI: return Expression::FPTOUI;
278 case Instruction::FPToSI: return Expression::FPTOSI;
279 case Instruction::UIToFP: return Expression::UITOFP;
280 case Instruction::SIToFP: return Expression::SITOFP;
281 case Instruction::FPTrunc: return Expression::FPTRUNC;
282 case Instruction::FPExt: return Expression::FPEXT;
283 case Instruction::PtrToInt: return Expression::PTRTOINT;
284 case Instruction::IntToPtr: return Expression::INTTOPTR;
285 case Instruction::BitCast: return Expression::BITCAST;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000286 }
287}
288
Owen Anderson09b83ba2007-10-18 19:39:33 +0000289Expression ValueTable::create_expression(CallInst* C) {
290 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000291
Owen Anderson09b83ba2007-10-18 19:39:33 +0000292 e.type = C->getType();
293 e.firstVN = 0;
294 e.secondVN = 0;
295 e.thirdVN = 0;
296 e.function = C->getCalledFunction();
297 e.opcode = Expression::CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000298
Owen Anderson09b83ba2007-10-18 19:39:33 +0000299 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
300 I != E; ++I)
Owen Anderson1e73f292008-04-11 05:11:49 +0000301 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000302
Owen Anderson09b83ba2007-10-18 19:39:33 +0000303 return e;
304}
305
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000306Expression ValueTable::create_expression(BinaryOperator* BO) {
307 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000308
Owen Anderson1e73f292008-04-11 05:11:49 +0000309 e.firstVN = lookup_or_add(BO->getOperand(0));
310 e.secondVN = lookup_or_add(BO->getOperand(1));
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000311 e.thirdVN = 0;
Owen Anderson09b83ba2007-10-18 19:39:33 +0000312 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000313 e.type = BO->getType();
314 e.opcode = getOpcode(BO);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000315
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000316 return e;
317}
318
319Expression ValueTable::create_expression(CmpInst* C) {
320 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000321
Owen Anderson1e73f292008-04-11 05:11:49 +0000322 e.firstVN = lookup_or_add(C->getOperand(0));
323 e.secondVN = lookup_or_add(C->getOperand(1));
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000324 e.thirdVN = 0;
Owen Anderson09b83ba2007-10-18 19:39:33 +0000325 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000326 e.type = C->getType();
327 e.opcode = getOpcode(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000328
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000329 return e;
330}
331
332Expression ValueTable::create_expression(CastInst* C) {
333 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000334
Owen Anderson1e73f292008-04-11 05:11:49 +0000335 e.firstVN = lookup_or_add(C->getOperand(0));
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000336 e.secondVN = 0;
337 e.thirdVN = 0;
Owen Anderson09b83ba2007-10-18 19:39:33 +0000338 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000339 e.type = C->getType();
340 e.opcode = getOpcode(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000341
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000342 return e;
343}
344
345Expression ValueTable::create_expression(ShuffleVectorInst* S) {
346 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000347
Owen Anderson1e73f292008-04-11 05:11:49 +0000348 e.firstVN = lookup_or_add(S->getOperand(0));
349 e.secondVN = lookup_or_add(S->getOperand(1));
350 e.thirdVN = lookup_or_add(S->getOperand(2));
Owen Anderson09b83ba2007-10-18 19:39:33 +0000351 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000352 e.type = S->getType();
353 e.opcode = Expression::SHUFFLE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000354
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000355 return e;
356}
357
358Expression ValueTable::create_expression(ExtractElementInst* E) {
359 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000360
Owen Anderson1e73f292008-04-11 05:11:49 +0000361 e.firstVN = lookup_or_add(E->getOperand(0));
362 e.secondVN = lookup_or_add(E->getOperand(1));
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000363 e.thirdVN = 0;
Owen Anderson09b83ba2007-10-18 19:39:33 +0000364 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000365 e.type = E->getType();
366 e.opcode = Expression::EXTRACT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000367
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000368 return e;
369}
370
371Expression ValueTable::create_expression(InsertElementInst* I) {
372 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000373
Owen Anderson1e73f292008-04-11 05:11:49 +0000374 e.firstVN = lookup_or_add(I->getOperand(0));
375 e.secondVN = lookup_or_add(I->getOperand(1));
376 e.thirdVN = lookup_or_add(I->getOperand(2));
Owen Anderson09b83ba2007-10-18 19:39:33 +0000377 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000378 e.type = I->getType();
379 e.opcode = Expression::INSERT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000380
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000381 return e;
382}
383
384Expression ValueTable::create_expression(SelectInst* I) {
385 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000386
Owen Anderson1e73f292008-04-11 05:11:49 +0000387 e.firstVN = lookup_or_add(I->getCondition());
388 e.secondVN = lookup_or_add(I->getTrueValue());
389 e.thirdVN = lookup_or_add(I->getFalseValue());
Owen Anderson09b83ba2007-10-18 19:39:33 +0000390 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000391 e.type = I->getType();
392 e.opcode = Expression::SELECT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000393
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000394 return e;
395}
396
397Expression ValueTable::create_expression(GetElementPtrInst* G) {
398 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000399
Owen Anderson1e73f292008-04-11 05:11:49 +0000400 e.firstVN = lookup_or_add(G->getPointerOperand());
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000401 e.secondVN = 0;
402 e.thirdVN = 0;
Owen Anderson09b83ba2007-10-18 19:39:33 +0000403 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000404 e.type = G->getType();
405 e.opcode = Expression::GEP;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000406
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000407 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
408 I != E; ++I)
Owen Anderson1e73f292008-04-11 05:11:49 +0000409 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000410
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000411 return e;
412}
413
414//===----------------------------------------------------------------------===//
415// ValueTable External Functions
416//===----------------------------------------------------------------------===//
417
Owen Anderson6a903bc2008-06-18 21:41:49 +0000418/// add - Insert a value into the table with a specified value number.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000419void ValueTable::add(Value *V, uint32_t num) {
Owen Anderson6a903bc2008-06-18 21:41:49 +0000420 valueNumbering.insert(std::make_pair(V, num));
421}
422
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000423/// lookup_or_add - Returns the value number for the specified value, assigning
424/// it a new number if it did not have one before.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000425uint32_t ValueTable::lookup_or_add(Value *V) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000426 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
427 if (VI != valueNumbering.end())
428 return VI->second;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000429
Owen Anderson09b83ba2007-10-18 19:39:33 +0000430 if (CallInst* C = dyn_cast<CallInst>(V)) {
Owen Anderson1e73f292008-04-11 05:11:49 +0000431 if (AA->doesNotAccessMemory(C)) {
Owen Anderson09b83ba2007-10-18 19:39:33 +0000432 Expression e = create_expression(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000433
Owen Anderson09b83ba2007-10-18 19:39:33 +0000434 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
435 if (EI != expressionNumbering.end()) {
436 valueNumbering.insert(std::make_pair(V, EI->second));
437 return EI->second;
438 } else {
439 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
440 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000441
Owen Anderson09b83ba2007-10-18 19:39:33 +0000442 return nextValueNumber++;
443 }
Owen Andersonf9ae76d2008-04-17 05:36:50 +0000444 } else if (AA->onlyReadsMemory(C)) {
445 Expression e = create_expression(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000446
Owen Anderson69057b82008-05-13 08:17:22 +0000447 if (expressionNumbering.find(e) == expressionNumbering.end()) {
Owen Andersonf9ae76d2008-04-17 05:36:50 +0000448 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
449 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Anderson69057b82008-05-13 08:17:22 +0000450 return nextValueNumber++;
451 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000452
Chris Lattner7f9c8a02008-11-29 02:29:27 +0000453 MemDepResult local_dep = MD->getDependency(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000454
Chris Lattner0e3d6332008-12-05 21:04:20 +0000455 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
Owen Anderson17816b32008-05-13 23:18:30 +0000456 valueNumbering.insert(std::make_pair(V, nextValueNumber));
457 return nextValueNumber++;
Chris Lattner80c7d812008-11-30 23:39:23 +0000458 }
Chris Lattner0e3d6332008-12-05 21:04:20 +0000459
460 if (local_dep.isDef()) {
461 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000462
Chris Lattner0e3d6332008-12-05 21:04:20 +0000463 if (local_cdep->getNumOperands() != C->getNumOperands()) {
Owen Anderson17816b32008-05-13 23:18:30 +0000464 valueNumbering.insert(std::make_pair(V, nextValueNumber));
465 return nextValueNumber++;
466 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000467
Chris Lattner80c7d812008-11-30 23:39:23 +0000468 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
469 uint32_t c_vn = lookup_or_add(C->getOperand(i));
470 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
471 if (c_vn != cd_vn) {
472 valueNumbering.insert(std::make_pair(V, nextValueNumber));
473 return nextValueNumber++;
474 }
475 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000476
Chris Lattner80c7d812008-11-30 23:39:23 +0000477 uint32_t v = lookup_or_add(local_cdep);
478 valueNumbering.insert(std::make_pair(V, v));
479 return v;
Owen Anderson17816b32008-05-13 23:18:30 +0000480 }
Chris Lattner7e61daf2008-12-01 01:15:42 +0000481
Chris Lattner0e3d6332008-12-05 21:04:20 +0000482 // Non-local case.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000483 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
Chris Lattner254314e2008-12-09 19:38:05 +0000484 MD->getNonLocalCallDependency(CallSite(C));
Chris Lattner0e3d6332008-12-05 21:04:20 +0000485 // FIXME: call/call dependencies for readonly calls should return def, not
486 // clobber! Move the checking logic to MemDep!
Owen Anderson8c2391d2008-05-13 13:41:23 +0000487 CallInst* cdep = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000488
Chris Lattner80c7d812008-11-30 23:39:23 +0000489 // Check to see if we have a single dominating call instruction that is
490 // identical to C.
Chris Lattner7e61daf2008-12-01 01:15:42 +0000491 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
492 const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
Chris Lattner80c7d812008-11-30 23:39:23 +0000493 // Ignore non-local dependencies.
494 if (I->second.isNonLocal())
495 continue;
Owen Anderson69057b82008-05-13 08:17:22 +0000496
Chris Lattner80c7d812008-11-30 23:39:23 +0000497 // We don't handle non-depedencies. If we already have a call, reject
498 // instruction dependencies.
Chris Lattner0e3d6332008-12-05 21:04:20 +0000499 if (I->second.isClobber() || cdep != 0) {
Chris Lattner80c7d812008-11-30 23:39:23 +0000500 cdep = 0;
501 break;
Owen Anderson69057b82008-05-13 08:17:22 +0000502 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000503
Chris Lattner80c7d812008-11-30 23:39:23 +0000504 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
505 // FIXME: All duplicated with non-local case.
506 if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
507 cdep = NonLocalDepCall;
508 continue;
509 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000510
Chris Lattner80c7d812008-11-30 23:39:23 +0000511 cdep = 0;
512 break;
Owen Anderson69057b82008-05-13 08:17:22 +0000513 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000514
Owen Anderson8c2391d2008-05-13 13:41:23 +0000515 if (!cdep) {
Owen Anderson69057b82008-05-13 08:17:22 +0000516 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Andersonf9ae76d2008-04-17 05:36:50 +0000517 return nextValueNumber++;
518 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000519
Chris Lattner0e3d6332008-12-05 21:04:20 +0000520 if (cdep->getNumOperands() != C->getNumOperands()) {
Owen Anderson69057b82008-05-13 08:17:22 +0000521 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Andersonf9ae76d2008-04-17 05:36:50 +0000522 return nextValueNumber++;
Owen Andersonf9ae76d2008-04-17 05:36:50 +0000523 }
Chris Lattner80c7d812008-11-30 23:39:23 +0000524 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
525 uint32_t c_vn = lookup_or_add(C->getOperand(i));
526 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
527 if (c_vn != cd_vn) {
528 valueNumbering.insert(std::make_pair(V, nextValueNumber));
529 return nextValueNumber++;
530 }
531 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000532
Chris Lattner80c7d812008-11-30 23:39:23 +0000533 uint32_t v = lookup_or_add(cdep);
534 valueNumbering.insert(std::make_pair(V, v));
535 return v;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000536
Owen Anderson09b83ba2007-10-18 19:39:33 +0000537 } else {
538 valueNumbering.insert(std::make_pair(V, nextValueNumber));
539 return nextValueNumber++;
540 }
541 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000542 Expression e = create_expression(BO);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000543
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000544 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
545 if (EI != expressionNumbering.end()) {
546 valueNumbering.insert(std::make_pair(V, EI->second));
547 return EI->second;
548 } else {
549 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
550 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000551
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000552 return nextValueNumber++;
553 }
554 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
555 Expression e = create_expression(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000556
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000557 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
558 if (EI != expressionNumbering.end()) {
559 valueNumbering.insert(std::make_pair(V, EI->second));
560 return EI->second;
561 } else {
562 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
563 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000564
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000565 return nextValueNumber++;
566 }
567 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
568 Expression e = create_expression(U);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000569
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000570 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
571 if (EI != expressionNumbering.end()) {
572 valueNumbering.insert(std::make_pair(V, EI->second));
573 return EI->second;
574 } else {
575 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
576 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000577
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000578 return nextValueNumber++;
579 }
580 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
581 Expression e = create_expression(U);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000582
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000583 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
584 if (EI != expressionNumbering.end()) {
585 valueNumbering.insert(std::make_pair(V, EI->second));
586 return EI->second;
587 } else {
588 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
589 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000590
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000591 return nextValueNumber++;
592 }
593 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
594 Expression e = create_expression(U);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000595
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000596 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
597 if (EI != expressionNumbering.end()) {
598 valueNumbering.insert(std::make_pair(V, EI->second));
599 return EI->second;
600 } else {
601 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
602 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000603
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000604 return nextValueNumber++;
605 }
606 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
607 Expression e = create_expression(U);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000608
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000609 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
610 if (EI != expressionNumbering.end()) {
611 valueNumbering.insert(std::make_pair(V, EI->second));
612 return EI->second;
613 } else {
614 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
615 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000616
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000617 return nextValueNumber++;
618 }
619 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
620 Expression e = create_expression(U);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000621
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000622 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
623 if (EI != expressionNumbering.end()) {
624 valueNumbering.insert(std::make_pair(V, EI->second));
625 return EI->second;
626 } else {
627 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
628 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000629
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000630 return nextValueNumber++;
631 }
632 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
633 Expression e = create_expression(U);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000634
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000635 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
636 if (EI != expressionNumbering.end()) {
637 valueNumbering.insert(std::make_pair(V, EI->second));
638 return EI->second;
639 } else {
640 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
641 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000642
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000643 return nextValueNumber++;
644 }
645 } else {
646 valueNumbering.insert(std::make_pair(V, nextValueNumber));
647 return nextValueNumber++;
648 }
649}
650
651/// lookup - Returns the value number of the specified value. Fails if
652/// the value has not yet been numbered.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000653uint32_t ValueTable::lookup(Value *V) const {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000654 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Chris Lattner2876a642008-03-21 21:14:38 +0000655 assert(VI != valueNumbering.end() && "Value not numbered?");
656 return VI->second;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000657}
658
659/// clear - Remove all entries from the ValueTable
660void ValueTable::clear() {
661 valueNumbering.clear();
662 expressionNumbering.clear();
663 nextValueNumber = 1;
664}
665
Owen Anderson10ffa862007-07-31 23:27:13 +0000666/// erase - Remove a value from the value numbering
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000667void ValueTable::erase(Value *V) {
Owen Anderson10ffa862007-07-31 23:27:13 +0000668 valueNumbering.erase(V);
669}
670
Bill Wendling6b18a392008-12-22 21:36:08 +0000671/// verifyRemoved - Verify that the value is removed from all internal data
672/// structures.
673void ValueTable::verifyRemoved(const Value *V) const {
674 for (DenseMap<Value*, uint32_t>::iterator
675 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
676 assert(I->first != V && "Inst still occurs in value numbering map!");
677 }
678}
679
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000680//===----------------------------------------------------------------------===//
Bill Wendling456e8852008-12-22 22:32:22 +0000681// GVN Pass
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000682//===----------------------------------------------------------------------===//
683
684namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +0000685 struct ValueNumberScope {
Owen Anderson1b3ea962008-06-20 01:15:47 +0000686 ValueNumberScope* parent;
687 DenseMap<uint32_t, Value*> table;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000688
Owen Anderson1b3ea962008-06-20 01:15:47 +0000689 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
690 };
691}
692
693namespace {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000694
Chris Lattner2dd09db2009-09-02 06:11:42 +0000695 class GVN : public FunctionPass {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000696 bool runOnFunction(Function &F);
697 public:
698 static char ID; // Pass identification, replacement for typeid
Dan Gohmana79db302008-09-04 17:05:41 +0000699 GVN() : FunctionPass(&ID) { }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000700
701 private:
Chris Lattner8541ede2008-12-01 00:40:32 +0000702 MemoryDependenceAnalysis *MD;
703 DominatorTree *DT;
704
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000705 ValueTable VN;
Owen Anderson1b3ea962008-06-20 01:15:47 +0000706 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000707
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000708 // This transformation requires dominator postdominator info
709 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000710 AU.addRequired<DominatorTree>();
711 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson09b83ba2007-10-18 19:39:33 +0000712 AU.addRequired<AliasAnalysis>();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000713
Owen Anderson54e02192008-06-23 17:49:45 +0000714 AU.addPreserved<DominatorTree>();
Owen Anderson09b83ba2007-10-18 19:39:33 +0000715 AU.addPreserved<AliasAnalysis>();
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000716 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000717
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000718 // Helper fuctions
719 // FIXME: eliminate or document these better
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000720 bool processLoad(LoadInst* L,
Chris Lattner804209d2008-03-21 22:01:16 +0000721 SmallVectorImpl<Instruction*> &toErase);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000722 bool processInstruction(Instruction *I,
Chris Lattner804209d2008-03-21 22:01:16 +0000723 SmallVectorImpl<Instruction*> &toErase);
Owen Anderson9699a6e2007-08-02 18:16:06 +0000724 bool processNonLocalLoad(LoadInst* L,
Chris Lattner804209d2008-03-21 22:01:16 +0000725 SmallVectorImpl<Instruction*> &toErase);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000726 bool processBlock(BasicBlock *BB);
Owen Anderson6a903bc2008-06-18 21:41:49 +0000727 void dump(DenseMap<uint32_t, Value*>& d);
Owen Anderson676070d2007-08-14 18:04:11 +0000728 bool iterateOnFunction(Function &F);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000729 Value *CollapsePhi(PHINode* p);
Owen Anderson6a903bc2008-06-18 21:41:49 +0000730 bool performPRE(Function& F);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000731 Value *lookupNumber(BasicBlock *BB, uint32_t num);
Nuno Lopese3127f32008-10-10 16:25:50 +0000732 void cleanupGlobalSets();
Bill Wendling6b18a392008-12-22 21:36:08 +0000733 void verifyRemoved(const Instruction *I) const;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000734 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000735
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000736 char GVN::ID = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000737}
738
739// createGVNPass - The public interface to this file...
740FunctionPass *llvm::createGVNPass() { return new GVN(); }
741
742static RegisterPass<GVN> X("gvn",
743 "Global Value Numbering");
744
Owen Anderson6a903bc2008-06-18 21:41:49 +0000745void GVN::dump(DenseMap<uint32_t, Value*>& d) {
Owen Anderson5e5599b2007-07-25 19:57:03 +0000746 printf("{\n");
Owen Anderson6a903bc2008-06-18 21:41:49 +0000747 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson5e5599b2007-07-25 19:57:03 +0000748 E = d.end(); I != E; ++I) {
Owen Anderson6a903bc2008-06-18 21:41:49 +0000749 printf("%d\n", I->first);
Owen Anderson5e5599b2007-07-25 19:57:03 +0000750 I->second->dump();
751 }
752 printf("}\n");
753}
754
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000755static bool isSafeReplacement(PHINode* p, Instruction *inst) {
Owen Anderson109ca5a2009-08-26 22:55:11 +0000756 if (!isa<PHINode>(inst))
757 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000758
Owen Anderson109ca5a2009-08-26 22:55:11 +0000759 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
760 UI != E; ++UI)
761 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
762 if (use_phi->getParent() == inst->getParent())
763 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000764
Owen Anderson109ca5a2009-08-26 22:55:11 +0000765 return true;
766}
767
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000768Value *GVN::CollapsePhi(PHINode *PN) {
769 Value *ConstVal = PN->hasConstantValue(DT);
770 if (!ConstVal) return 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000771
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000772 Instruction *Inst = dyn_cast<Instruction>(ConstVal);
773 if (!Inst)
774 return ConstVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000775
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000776 if (DT->dominates(Inst, PN))
777 if (isSafeReplacement(PN, Inst))
778 return Inst;
Owen Andersonf5023a72007-08-16 22:51:56 +0000779 return 0;
780}
Owen Anderson5e5599b2007-07-25 19:57:03 +0000781
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000782/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
783/// we're analyzing is fully available in the specified block. As we go, keep
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000784/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
785/// map is actually a tri-state map with the following values:
786/// 0) we know the block *is not* fully available.
787/// 1) we know the block *is* fully available.
788/// 2) we do not know whether the block is fully available or not, but we are
789/// currently speculating that it will be.
790/// 3) we are speculating for this block and have used that to speculate for
791/// other blocks.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000792static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000793 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000794 // Optimistically assume that the block is fully available and check to see
795 // if we already know about this block in one lookup.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000796 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000797 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000798
799 // If the entry already existed for this block, return the precomputed value.
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000800 if (!IV.second) {
801 // If this is a speculative "available" value, mark it as being used for
802 // speculation of other blocks.
803 if (IV.first->second == 2)
804 IV.first->second = 3;
805 return IV.first->second != 0;
806 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000807
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000808 // Otherwise, see if it is fully available in all predecessors.
809 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000810
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000811 // If this block has no predecessors, it isn't live-in here.
812 if (PI == PE)
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000813 goto SpeculationFailure;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000814
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000815 for (; PI != PE; ++PI)
816 // If the value isn't fully available in one of our predecessors, then it
817 // isn't fully available in this block either. Undo our previous
818 // optimistic assumption and bail out.
819 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000820 goto SpeculationFailure;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000821
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000822 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000823
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000824// SpeculationFailure - If we get here, we found out that this is not, after
825// all, a fully-available block. We have a problem if we speculated on this and
826// used the speculation to mark other blocks as available.
827SpeculationFailure:
828 char &BBVal = FullyAvailableBlocks[BB];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000829
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000830 // If we didn't speculate on this, just return with it set to false.
831 if (BBVal == 2) {
832 BBVal = 0;
833 return false;
834 }
835
836 // If we did speculate on this value, we could have blocks set to 1 that are
837 // incorrect. Walk the (transitive) successors of this block and mark them as
838 // 0 if set to one.
839 SmallVector<BasicBlock*, 32> BBWorklist;
840 BBWorklist.push_back(BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000841
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000842 while (!BBWorklist.empty()) {
843 BasicBlock *Entry = BBWorklist.pop_back_val();
844 // Note that this sets blocks to 0 (unavailable) if they happen to not
845 // already be in FullyAvailableBlocks. This is safe.
846 char &EntryVal = FullyAvailableBlocks[Entry];
847 if (EntryVal == 0) continue; // Already unavailable.
848
849 // Mark as unavailable.
850 EntryVal = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000851
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000852 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
853 BBWorklist.push_back(*I);
854 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000855
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000856 return false;
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000857}
858
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000859
Chris Lattner9045f232009-09-21 17:24:04 +0000860/// CanCoerceMustAliasedValueToLoad - Return true if
861/// CoerceAvailableValueToLoadType will succeed.
862static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
863 const Type *LoadTy,
864 const TargetData &TD) {
865 // If the loaded or stored value is an first class array or struct, don't try
866 // to transform them. We need to be able to bitcast to integer.
867 if (isa<StructType>(LoadTy) || isa<ArrayType>(LoadTy) ||
868 isa<StructType>(StoredVal->getType()) ||
869 isa<ArrayType>(StoredVal->getType()))
870 return false;
871
872 // The store has to be at least as big as the load.
873 if (TD.getTypeSizeInBits(StoredVal->getType()) <
874 TD.getTypeSizeInBits(LoadTy))
875 return false;
876
877 return true;
878}
879
880
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000881/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
882/// then a load from a must-aliased pointer of a different type, try to coerce
883/// the stored value. LoadedTy is the type of the load we want to replace and
884/// InsertPt is the place to insert new instructions.
885///
886/// If we can't do it, return null.
887static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
888 const Type *LoadedTy,
889 Instruction *InsertPt,
890 const TargetData &TD) {
Chris Lattner9045f232009-09-21 17:24:04 +0000891 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
892 return 0;
893
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000894 const Type *StoredValTy = StoredVal->getType();
895
896 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
897 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
898
899 // If the store and reload are the same size, we can always reuse it.
900 if (StoreSize == LoadSize) {
901 if (isa<PointerType>(StoredValTy) && isa<PointerType>(LoadedTy)) {
902 // Pointer to Pointer -> use bitcast.
903 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
904 }
905
906 // Convert source pointers to integers, which can be bitcast.
907 if (isa<PointerType>(StoredValTy)) {
908 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
909 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
910 }
911
912 const Type *TypeToCastTo = LoadedTy;
913 if (isa<PointerType>(TypeToCastTo))
914 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
915
916 if (StoredValTy != TypeToCastTo)
917 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
918
919 // Cast to pointer if the load needs a pointer type.
920 if (isa<PointerType>(LoadedTy))
921 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
922
923 return StoredVal;
924 }
925
926 // If the loaded value is smaller than the available value, then we can
927 // extract out a piece from it. If the available value is too small, then we
928 // can't do anything.
Chris Lattner9045f232009-09-21 17:24:04 +0000929 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000930
931 // Convert source pointers to integers, which can be manipulated.
932 if (isa<PointerType>(StoredValTy)) {
933 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
934 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
935 }
936
937 // Convert vectors and fp to integer, which can be manipulated.
938 if (!isa<IntegerType>(StoredValTy)) {
939 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
940 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
941 }
942
943 // If this is a big-endian system, we need to shift the value down to the low
944 // bits so that a truncate will work.
945 if (TD.isBigEndian()) {
946 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
947 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
948 }
949
950 // Truncate the integer to the right size now.
951 const Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
952 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
953
954 if (LoadedTy == NewIntTy)
955 return StoredVal;
956
957 // If the result is a pointer, inttoptr.
958 if (isa<PointerType>(LoadedTy))
959 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
960
961 // Otherwise, bitcast.
962 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
963}
964
Chris Lattnerd28f9082009-09-21 06:24:16 +0000965/// GetBaseWithConstantOffset - Analyze the specified pointer to see if it can
966/// be expressed as a base pointer plus a constant offset. Return the base and
967/// offset to the caller.
968static Value *GetBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Chris Lattner4d8af2f2009-09-21 06:48:08 +0000969 const TargetData &TD) {
Chris Lattnerd28f9082009-09-21 06:24:16 +0000970 Operator *PtrOp = dyn_cast<Operator>(Ptr);
971 if (PtrOp == 0) return Ptr;
972
973 // Just look through bitcasts.
974 if (PtrOp->getOpcode() == Instruction::BitCast)
975 return GetBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
976
977 // If this is a GEP with constant indices, we can look through it.
978 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
979 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
980
981 gep_type_iterator GTI = gep_type_begin(GEP);
982 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
983 ++I, ++GTI) {
984 ConstantInt *OpC = cast<ConstantInt>(*I);
985 if (OpC->isZero()) continue;
986
987 // Handle a struct and array indices which add their offset to the pointer.
988 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner4d8af2f2009-09-21 06:48:08 +0000989 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
Chris Lattnerd28f9082009-09-21 06:24:16 +0000990 } else {
Chris Lattner4d8af2f2009-09-21 06:48:08 +0000991 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnerd28f9082009-09-21 06:24:16 +0000992 Offset += OpC->getSExtValue()*Size;
993 }
994 }
995
996 // Re-sign extend from the pointer size if needed to get overflow edge cases
997 // right.
Chris Lattner4d8af2f2009-09-21 06:48:08 +0000998 unsigned PtrSize = TD.getPointerSizeInBits();
Chris Lattnerd28f9082009-09-21 06:24:16 +0000999 if (PtrSize < 64)
1000 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1001
1002 return GetBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1003}
1004
1005
1006/// AnalyzeLoadFromClobberingStore - This function is called when we have a
1007/// memdep query of a load that ends up being a clobbering store. This means
1008/// that the store *may* provide bits used by the load but we can't be sure
1009/// because the pointers don't mustalias. Check this case to see if there is
1010/// anything more we can do before we give up. This returns -1 if we have to
1011/// give up, or a byte number in the stored value of the piece that feeds the
1012/// load.
1013static int AnalyzeLoadFromClobberingStore(LoadInst *L, StoreInst *DepSI,
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001014 const TargetData &TD) {
Chris Lattner9045f232009-09-21 17:24:04 +00001015 // If the loaded or stored value is an first class array or struct, don't try
1016 // to transform them. We need to be able to bitcast to integer.
1017 if (isa<StructType>(L->getType()) || isa<ArrayType>(L->getType()) ||
1018 isa<StructType>(DepSI->getOperand(0)->getType()) ||
1019 isa<ArrayType>(DepSI->getOperand(0)->getType()))
1020 return -1;
1021
Chris Lattnerd28f9082009-09-21 06:24:16 +00001022 int64_t StoreOffset = 0, LoadOffset = 0;
1023 Value *StoreBase =
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001024 GetBaseWithConstantOffset(DepSI->getPointerOperand(), StoreOffset, TD);
Chris Lattnerd28f9082009-09-21 06:24:16 +00001025 Value *LoadBase =
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001026 GetBaseWithConstantOffset(L->getPointerOperand(), LoadOffset, TD);
Chris Lattnerd28f9082009-09-21 06:24:16 +00001027 if (StoreBase != LoadBase)
1028 return -1;
1029
1030 // If the load and store are to the exact same address, they should have been
1031 // a must alias. AA must have gotten confused.
1032 // FIXME: Study to see if/when this happens.
1033 if (LoadOffset == StoreOffset) {
1034#if 0
1035 errs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
1036 << "Base = " << *StoreBase << "\n"
1037 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1038 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1039 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1040 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1041 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1042 << *L->getParent();
1043#endif
1044 return -1;
1045 }
1046
1047 // If the load and store don't overlap at all, the store doesn't provide
1048 // anything to the load. In this case, they really don't alias at all, AA
1049 // must have gotten confused.
1050 // FIXME: Investigate cases where this bails out, e.g. rdar://7238614. Then
1051 // remove this check, as it is duplicated with what we have below.
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001052 uint64_t StoreSize = TD.getTypeSizeInBits(DepSI->getOperand(0)->getType());
1053 uint64_t LoadSize = TD.getTypeSizeInBits(L->getType());
Chris Lattnerd28f9082009-09-21 06:24:16 +00001054
1055 if ((StoreSize & 7) | (LoadSize & 7))
1056 return -1;
1057 StoreSize >>= 3; // Convert to bytes.
1058 LoadSize >>= 3;
1059
1060
1061 bool isAAFailure = false;
1062 if (StoreOffset < LoadOffset) {
1063 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
1064 } else {
1065 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
1066 }
1067 if (isAAFailure) {
1068#if 0
1069 errs() << "STORE LOAD DEP WITH COMMON BASE:\n"
1070 << "Base = " << *StoreBase << "\n"
1071 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1072 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1073 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1074 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1075 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1076 << *L->getParent();
1077#endif
1078 return -1;
1079 }
1080
1081 // If the Load isn't completely contained within the stored bits, we don't
1082 // have all the bits to feed it. We could do something crazy in the future
1083 // (issue a smaller load then merge the bits in) but this seems unlikely to be
1084 // valuable.
1085 if (StoreOffset > LoadOffset ||
1086 StoreOffset+StoreSize < LoadOffset+LoadSize)
1087 return -1;
1088
1089 // Okay, we can do this transformation. Return the number of bytes into the
1090 // store that the load is.
1091 return LoadOffset-StoreOffset;
1092}
1093
1094
1095/// GetStoreValueForLoad - This function is called when we have a
1096/// memdep query of a load that ends up being a clobbering store. This means
1097/// that the store *may* provide bits used by the load but we can't be sure
1098/// because the pointers don't mustalias. Check this case to see if there is
1099/// anything more we can do before we give up.
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001100static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
1101 const Type *LoadTy,
1102 Instruction *InsertPt, const TargetData &TD){
Chris Lattnerd28f9082009-09-21 06:24:16 +00001103 LLVMContext &Ctx = SrcVal->getType()->getContext();
1104
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001105 uint64_t StoreSize = TD.getTypeSizeInBits(SrcVal->getType())/8;
1106 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
Chris Lattnerd28f9082009-09-21 06:24:16 +00001107
1108
1109 // Compute which bits of the stored value are being used by the load. Convert
1110 // to an integer type to start with.
1111 if (isa<PointerType>(SrcVal->getType()))
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001112 SrcVal = new PtrToIntInst(SrcVal, TD.getIntPtrType(Ctx), "tmp", InsertPt);
Chris Lattnerd28f9082009-09-21 06:24:16 +00001113 if (!isa<IntegerType>(SrcVal->getType()))
1114 SrcVal = new BitCastInst(SrcVal, IntegerType::get(Ctx, StoreSize*8),
1115 "tmp", InsertPt);
1116
1117 // Shift the bits to the least significant depending on endianness.
1118 unsigned ShiftAmt;
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001119 if (TD.isLittleEndian()) {
Chris Lattnerd28f9082009-09-21 06:24:16 +00001120 ShiftAmt = Offset*8;
1121 } else {
Chris Lattner24705382009-09-21 17:55:47 +00001122 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
Chris Lattnerd28f9082009-09-21 06:24:16 +00001123 }
1124
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001125 if (ShiftAmt)
1126 SrcVal = BinaryOperator::CreateLShr(SrcVal,
1127 ConstantInt::get(SrcVal->getType(), ShiftAmt), "tmp", InsertPt);
Chris Lattnerd28f9082009-09-21 06:24:16 +00001128
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001129 if (LoadSize != StoreSize)
1130 SrcVal = new TruncInst(SrcVal, IntegerType::get(Ctx, LoadSize*8),
1131 "tmp", InsertPt);
Chris Lattnerd28f9082009-09-21 06:24:16 +00001132
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001133 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
Chris Lattnerd28f9082009-09-21 06:24:16 +00001134}
1135
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001136struct AvailableValueInBlock {
1137 /// BB - The basic block in question.
1138 BasicBlock *BB;
1139 /// V - The value that is live out of the block.
1140 Value *V;
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001141 /// Offset - The byte offset in V that is interesting for the load query.
1142 unsigned Offset;
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001143
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001144 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1145 unsigned Offset = 0) {
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001146 AvailableValueInBlock Res;
1147 Res.BB = BB;
1148 Res.V = V;
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001149 Res.Offset = Offset;
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001150 return Res;
1151 }
1152};
1153
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001154/// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1155/// construct SSA form, allowing us to eliminate LI. This returns the value
1156/// that should be used at LI's definition site.
1157static Value *ConstructSSAForLoadSet(LoadInst *LI,
1158 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1159 const TargetData *TD,
1160 AliasAnalysis *AA) {
1161 SmallVector<PHINode*, 8> NewPHIs;
1162 SSAUpdater SSAUpdate(&NewPHIs);
1163 SSAUpdate.Initialize(LI);
1164
1165 const Type *LoadTy = LI->getType();
1166
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001167 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001168 BasicBlock *BB = ValuesPerBlock[i].BB;
1169 Value *AvailableVal = ValuesPerBlock[i].V;
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001170 unsigned Offset = ValuesPerBlock[i].Offset;
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001171
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001172 if (SSAUpdate.HasValueForBlock(BB))
1173 continue;
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001174
1175 if (AvailableVal->getType() != LoadTy) {
1176 assert(TD && "Need target data to handle type mismatch case");
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001177 AvailableVal = GetStoreValueForLoad(AvailableVal, Offset, LoadTy,
1178 BB->getTerminator(), *TD);
1179
1180 if (Offset) {
1181 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001182 << *ValuesPerBlock[i].V << '\n'
1183 << *AvailableVal << '\n' << "\n\n\n");
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001184 }
1185
1186
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001187 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001188 << *ValuesPerBlock[i].V << '\n'
1189 << *AvailableVal << '\n' << "\n\n\n");
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001190 }
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001191
1192 SSAUpdate.AddAvailableValue(BB, AvailableVal);
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001193 }
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001194
1195 // Perform PHI construction.
1196 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1197
1198 // If new PHI nodes were created, notify alias analysis.
1199 if (isa<PointerType>(V->getType()))
1200 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1201 AA->copyValue(LI, NewPHIs[i]);
1202
1203 return V;
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001204}
1205
Owen Anderson221a4362007-08-16 22:02:55 +00001206/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1207/// non-local by performing PHI construction.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001208bool GVN::processNonLocalLoad(LoadInst *LI,
Chris Lattner804209d2008-03-21 22:01:16 +00001209 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001210 // Find the non-local dependencies of the load.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001211 SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
Chris Lattnerb6fc4b82008-12-09 19:25:07 +00001212 MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
1213 Deps);
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001214 //DEBUG(errs() << "INVESTIGATING NONLOCAL LOAD: "
1215 // << Deps.size() << *LI << '\n');
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001216
Owen Andersonb39e0de2008-08-26 22:07:42 +00001217 // If we had to process more than one hundred blocks to find the
1218 // dependencies, this load isn't worth worrying about. Optimizing
1219 // it will be too expensive.
Chris Lattnerb6fc4b82008-12-09 19:25:07 +00001220 if (Deps.size() > 100)
Owen Andersonb39e0de2008-08-26 22:07:42 +00001221 return false;
Chris Lattnerb6372932008-12-18 00:51:32 +00001222
1223 // If we had a phi translation failure, we'll have a single entry which is a
1224 // clobber in the current block. Reject this early.
Torok Edwinba93ea72009-06-17 18:48:18 +00001225 if (Deps.size() == 1 && Deps[0].second.isClobber()) {
1226 DEBUG(
Dan Gohman1ddf98a2009-07-25 01:43:01 +00001227 errs() << "GVN: non-local load ";
1228 WriteAsOperand(errs(), LI);
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001229 errs() << " is clobbered by " << *Deps[0].second.getInst() << '\n';
Torok Edwinba93ea72009-06-17 18:48:18 +00001230 );
Chris Lattnerb6372932008-12-18 00:51:32 +00001231 return false;
Torok Edwinba93ea72009-06-17 18:48:18 +00001232 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001233
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001234 // Filter out useless results (non-locals, etc). Keep track of the blocks
1235 // where we have a value available in repl, also keep track of whether we see
1236 // dependencies that produce an unknown value for the load (such as a call
1237 // that could potentially clobber the load).
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001238 SmallVector<AvailableValueInBlock, 16> ValuesPerBlock;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001239 SmallVector<BasicBlock*, 16> UnavailableBlocks;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001240
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001241 const TargetData *TD = 0;
1242
Chris Lattnerb6fc4b82008-12-09 19:25:07 +00001243 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
1244 BasicBlock *DepBB = Deps[i].first;
1245 MemDepResult DepInfo = Deps[i].second;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001246
Chris Lattner0e3d6332008-12-05 21:04:20 +00001247 if (DepInfo.isClobber()) {
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001248 // If the dependence is to a store that writes to a superset of the bits
1249 // read by the load, we can extract the bits we need for the load from the
1250 // stored value.
1251 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1252 if (TD == 0)
1253 TD = getAnalysisIfAvailable<TargetData>();
1254 if (TD) {
1255 int Offset = AnalyzeLoadFromClobberingStore(LI, DepSI, *TD);
1256 if (Offset != -1) {
1257 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1258 DepSI->getOperand(0),
1259 Offset));
1260 continue;
1261 }
1262 }
1263 }
1264
1265 // FIXME: Handle memset/memcpy.
Chris Lattner0e3d6332008-12-05 21:04:20 +00001266 UnavailableBlocks.push_back(DepBB);
1267 continue;
1268 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001269
Chris Lattner0e3d6332008-12-05 21:04:20 +00001270 Instruction *DepInst = DepInfo.getInst();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001271
Chris Lattner0e3d6332008-12-05 21:04:20 +00001272 // Loading the allocation -> undef.
Victor Hernandez5d034492009-09-18 22:35:49 +00001273 if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001274 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1275 UndefValue::get(LI->getType())));
Chris Lattner7e61daf2008-12-01 01:15:42 +00001276 continue;
1277 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001278
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001279 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001280 // Reject loads and stores that are to the same address but are of
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001281 // different types if we have to.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001282 if (S->getOperand(0)->getType() != LI->getType()) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001283 if (TD == 0)
1284 TD = getAnalysisIfAvailable<TargetData>();
1285
1286 // If the stored value is larger or equal to the loaded value, we can
1287 // reuse it.
Chris Lattner9045f232009-09-21 17:24:04 +00001288 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getOperand(0),
1289 LI->getType(), *TD)) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001290 UnavailableBlocks.push_back(DepBB);
1291 continue;
1292 }
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001293 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001294
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001295 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1296 S->getOperand(0)));
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001297 continue;
1298 }
1299
1300 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001301 // If the types mismatch and we can't handle it, reject reuse of the load.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001302 if (LD->getType() != LI->getType()) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001303 if (TD == 0)
1304 TD = getAnalysisIfAvailable<TargetData>();
1305
1306 // If the stored value is larger or equal to the loaded value, we can
1307 // reuse it.
Chris Lattner9045f232009-09-21 17:24:04 +00001308 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001309 UnavailableBlocks.push_back(DepBB);
1310 continue;
1311 }
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001312 }
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001313 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB, LD));
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001314 continue;
Owen Anderson5e5599b2007-07-25 19:57:03 +00001315 }
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001316
1317 UnavailableBlocks.push_back(DepBB);
1318 continue;
Chris Lattner2876a642008-03-21 21:14:38 +00001319 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001320
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001321 // If we have no predecessors that produce a known value for this load, exit
1322 // early.
1323 if (ValuesPerBlock.empty()) return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001324
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001325 // If all of the instructions we depend on produce a known value for this
1326 // load, then it is fully redundant and we can use PHI insertion to compute
1327 // its value. Insert PHIs and remove the fully redundant value now.
1328 if (UnavailableBlocks.empty()) {
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001329 DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001330
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001331 // Perform PHI construction.
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001332 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, TD,
1333 VN.getAliasAnalysis());
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001334 LI->replaceAllUsesWith(V);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001335
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001336 if (isa<PHINode>(V))
1337 V->takeName(LI);
1338 if (isa<PointerType>(V->getType()))
1339 MD->invalidateCachedPointerInfo(V);
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001340 toErase.push_back(LI);
1341 NumGVNLoad++;
1342 return true;
1343 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001344
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001345 if (!EnablePRE || !EnableLoadPRE)
1346 return false;
1347
1348 // Okay, we have *some* definitions of the value. This means that the value
1349 // is available in some of our (transitive) predecessors. Lets think about
1350 // doing PRE of this load. This will involve inserting a new load into the
1351 // predecessor when it's not available. We could do this in general, but
1352 // prefer to not increase code size. As such, we only do this when we know
1353 // that we only have to insert *one* load (which means we're basically moving
1354 // the load, not inserting a new one).
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001355
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001356 SmallPtrSet<BasicBlock *, 4> Blockers;
1357 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1358 Blockers.insert(UnavailableBlocks[i]);
1359
1360 // Lets find first basic block with more than one predecessor. Walk backwards
1361 // through predecessors if needed.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001362 BasicBlock *LoadBB = LI->getParent();
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001363 BasicBlock *TmpBB = LoadBB;
1364
1365 bool isSinglePred = false;
Dale Johannesen81b64632009-06-17 20:48:23 +00001366 bool allSingleSucc = true;
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001367 while (TmpBB->getSinglePredecessor()) {
1368 isSinglePred = true;
1369 TmpBB = TmpBB->getSinglePredecessor();
1370 if (!TmpBB) // If haven't found any, bail now.
1371 return false;
1372 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1373 return false;
1374 if (Blockers.count(TmpBB))
1375 return false;
Dale Johannesen81b64632009-06-17 20:48:23 +00001376 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1377 allSingleSucc = false;
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001378 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001379
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001380 assert(TmpBB);
1381 LoadBB = TmpBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001382
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001383 // If we have a repl set with LI itself in it, this means we have a loop where
1384 // at least one of the values is LI. Since this means that we won't be able
1385 // to eliminate LI even if we insert uses in the other predecessors, we will
1386 // end up increasing code size. Reject this by scanning for LI.
1387 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001388 if (ValuesPerBlock[i].V == LI)
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001389 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001390
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001391 if (isSinglePred) {
1392 bool isHot = false;
1393 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001394 if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].V))
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001395 // "Hot" Instruction is in some loop (because it dominates its dep.
1396 // instruction).
1397 if (DT->dominates(LI, I)) {
1398 isHot = true;
1399 break;
1400 }
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001401
1402 // We are interested only in "hot" instructions. We don't want to do any
1403 // mis-optimizations here.
1404 if (!isHot)
1405 return false;
1406 }
1407
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001408 // Okay, we have some hope :). Check to see if the loaded value is fully
1409 // available in all but one predecessor.
1410 // FIXME: If we could restructure the CFG, we could make a common pred with
1411 // all the preds that don't have an available LI and insert a new load into
1412 // that one block.
1413 BasicBlock *UnavailablePred = 0;
1414
Chris Lattnerd2a653a2008-12-05 07:49:08 +00001415 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001416 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001417 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001418 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1419 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1420
1421 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1422 PI != E; ++PI) {
1423 if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1424 continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001425
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001426 // If this load is not available in multiple predecessors, reject it.
1427 if (UnavailablePred && UnavailablePred != *PI)
1428 return false;
1429 UnavailablePred = *PI;
1430 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001431
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001432 assert(UnavailablePred != 0 &&
1433 "Fully available value should be eliminated above!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001434
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001435 // If the loaded pointer is PHI node defined in this block, do PHI translation
1436 // to get its value in the predecessor.
1437 Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001438
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001439 // Make sure the value is live in the predecessor. If it was defined by a
1440 // non-PHI instruction in this block, we don't know how to recompute it above.
1441 if (Instruction *LPInst = dyn_cast<Instruction>(LoadPtr))
1442 if (!DT->dominates(LPInst->getParent(), UnavailablePred)) {
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001443 DEBUG(errs() << "COULDN'T PRE LOAD BECAUSE PTR IS UNAVAILABLE IN PRED: "
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001444 << *LPInst << '\n' << *LI << "\n");
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001445 return false;
1446 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001447
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001448 // We don't currently handle critical edges :(
1449 if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001450 DEBUG(errs() << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001451 << UnavailablePred->getName() << "': " << *LI << '\n');
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001452 return false;
Owen Anderson0cc1a762007-08-07 23:12:31 +00001453 }
Dale Johannesen81b64632009-06-17 20:48:23 +00001454
1455 // Make sure it is valid to move this load here. We have to watch out for:
1456 // @1 = getelementptr (i8* p, ...
1457 // test p and branch if == 0
1458 // load @1
1459 // It is valid to have the getelementptr before the test, even if p can be 0,
1460 // as getelementptr only does address arithmetic.
1461 // If we are not pushing the value through any multiple-successor blocks
1462 // we do not have this case. Otherwise, check that the load is safe to
1463 // put anywhere; this can be improved, but should be conservatively safe.
1464 if (!allSingleSucc &&
1465 !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator()))
1466 return false;
1467
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001468 // Okay, we can eliminate this load by inserting a reload in the predecessor
1469 // and using PHI construction to get the value in the other predecessors, do
1470 // it.
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001471 DEBUG(errs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001472
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001473 Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1474 LI->getAlignment(),
1475 UnavailablePred->getTerminator());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001476
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001477 // Add the newly created load.
1478 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,NewLoad));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001479
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001480 // Perform PHI construction.
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001481 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, TD,
1482 VN.getAliasAnalysis());
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001483 LI->replaceAllUsesWith(V);
1484 if (isa<PHINode>(V))
1485 V->takeName(LI);
1486 if (isa<PointerType>(V->getType()))
1487 MD->invalidateCachedPointerInfo(V);
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001488 toErase.push_back(LI);
1489 NumPRELoad++;
Owen Anderson5e5599b2007-07-25 19:57:03 +00001490 return true;
1491}
1492
Owen Anderson221a4362007-08-16 22:02:55 +00001493/// processLoad - Attempt to eliminate a load, first by eliminating it
1494/// locally, and then attempting non-local elimination if that fails.
Chris Lattner0e3d6332008-12-05 21:04:20 +00001495bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
1496 if (L->isVolatile())
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001497 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001498
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001499 // ... to a pointer that has been loaded from before...
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001500 MemDepResult Dep = MD->getDependency(L);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001501
Chris Lattner0e3d6332008-12-05 21:04:20 +00001502 // If the value isn't available, don't do anything!
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001503 if (Dep.isClobber()) {
Chris Lattner0a9616d2009-09-21 05:57:11 +00001504 // FIXME: We should handle memset/memcpy/memmove as dependent instructions
1505 // to forward the value if available.
1506 //if (isa<MemIntrinsic>(Dep.getInst()))
1507 //errs() << "LOAD DEPENDS ON MEM: " << *L << "\n" << *Dep.getInst()<<"\n\n";
1508
1509 // Check to see if we have something like this:
Chris Lattner1dd48c32009-09-20 19:03:47 +00001510 // store i32 123, i32* %P
1511 // %A = bitcast i32* %P to i8*
1512 // %B = gep i8* %A, i32 1
1513 // %C = load i8* %B
1514 //
1515 // We could do that by recognizing if the clobber instructions are obviously
1516 // a common base + constant offset, and if the previous store (or memset)
1517 // completely covers this load. This sort of thing can happen in bitfield
1518 // access code.
Chris Lattner0a9616d2009-09-21 05:57:11 +00001519 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst()))
Chris Lattner9d7fb292009-09-21 06:22:46 +00001520 if (const TargetData *TD = getAnalysisIfAvailable<TargetData>()) {
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001521 int Offset = AnalyzeLoadFromClobberingStore(L, DepSI, *TD);
Chris Lattner9d7fb292009-09-21 06:22:46 +00001522 if (Offset != -1) {
1523 Value *AvailVal = GetStoreValueForLoad(DepSI->getOperand(0), Offset,
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001524 L->getType(), L, *TD);
Chris Lattner0a9616d2009-09-21 05:57:11 +00001525 DEBUG(errs() << "GVN COERCED STORE BITS:\n" << *DepSI << '\n'
1526 << *AvailVal << '\n' << *L << "\n\n\n");
1527
1528 // Replace the load!
1529 L->replaceAllUsesWith(AvailVal);
1530 if (isa<PointerType>(AvailVal->getType()))
1531 MD->invalidateCachedPointerInfo(AvailVal);
1532 toErase.push_back(L);
1533 NumGVNLoad++;
1534 return true;
1535 }
Chris Lattner9d7fb292009-09-21 06:22:46 +00001536 }
Chris Lattner0a9616d2009-09-21 05:57:11 +00001537
Torok Edwin72070282009-05-29 09:46:03 +00001538 DEBUG(
1539 // fast print dep, using operator<< on instruction would be too slow
Dan Gohman1ddf98a2009-07-25 01:43:01 +00001540 errs() << "GVN: load ";
1541 WriteAsOperand(errs(), L);
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001542 Instruction *I = Dep.getInst();
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001543 errs() << " is clobbered by " << *I << '\n';
Torok Edwin72070282009-05-29 09:46:03 +00001544 );
Chris Lattner0e3d6332008-12-05 21:04:20 +00001545 return false;
Torok Edwin72070282009-05-29 09:46:03 +00001546 }
Chris Lattner0e3d6332008-12-05 21:04:20 +00001547
1548 // If it is defined in another block, try harder.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001549 if (Dep.isNonLocal())
Chris Lattner0e3d6332008-12-05 21:04:20 +00001550 return processNonLocalLoad(L, toErase);
Eli Friedman716c10c2008-02-12 12:08:14 +00001551
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001552 Instruction *DepInst = Dep.getInst();
Chris Lattner0e3d6332008-12-05 21:04:20 +00001553 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
Chris Lattner1dd48c32009-09-20 19:03:47 +00001554 Value *StoredVal = DepSI->getOperand(0);
1555
1556 // The store and load are to a must-aliased pointer, but they may not
1557 // actually have the same type. See if we know how to reuse the stored
1558 // value (depending on its type).
1559 const TargetData *TD = 0;
1560 if (StoredVal->getType() != L->getType() &&
1561 (TD = getAnalysisIfAvailable<TargetData>())) {
Chris Lattner9045f232009-09-21 17:24:04 +00001562 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1563 L, *TD);
Chris Lattner1dd48c32009-09-20 19:03:47 +00001564 if (StoredVal == 0)
1565 return false;
1566
1567 DEBUG(errs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1568 << '\n' << *L << "\n\n\n");
1569 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001570
Chris Lattner0e3d6332008-12-05 21:04:20 +00001571 // Remove it!
Chris Lattner1dd48c32009-09-20 19:03:47 +00001572 L->replaceAllUsesWith(StoredVal);
1573 if (isa<PointerType>(StoredVal->getType()))
1574 MD->invalidateCachedPointerInfo(StoredVal);
Chris Lattner0e3d6332008-12-05 21:04:20 +00001575 toErase.push_back(L);
1576 NumGVNLoad++;
1577 return true;
1578 }
1579
1580 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
Chris Lattner1dd48c32009-09-20 19:03:47 +00001581 Value *AvailableVal = DepLI;
1582
1583 // The loads are of a must-aliased pointer, but they may not actually have
1584 // the same type. See if we know how to reuse the previously loaded value
1585 // (depending on its type).
1586 const TargetData *TD = 0;
1587 if (DepLI->getType() != L->getType() &&
1588 (TD = getAnalysisIfAvailable<TargetData>())) {
Chris Lattner9045f232009-09-21 17:24:04 +00001589 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(), L,*TD);
Chris Lattner1dd48c32009-09-20 19:03:47 +00001590 if (AvailableVal == 0)
1591 return false;
1592
1593 DEBUG(errs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1594 << "\n" << *L << "\n\n\n");
1595 }
1596
Chris Lattner0e3d6332008-12-05 21:04:20 +00001597 // Remove it!
Chris Lattner1dd48c32009-09-20 19:03:47 +00001598 L->replaceAllUsesWith(AvailableVal);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001599 if (isa<PointerType>(DepLI->getType()))
1600 MD->invalidateCachedPointerInfo(DepLI);
Chris Lattner0e3d6332008-12-05 21:04:20 +00001601 toErase.push_back(L);
1602 NumGVNLoad++;
1603 return true;
1604 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001605
Chris Lattner3ff6d012008-11-30 01:39:32 +00001606 // If this load really doesn't depend on anything, then we must be loading an
1607 // undef value. This can happen when loading for a fresh allocation with no
1608 // intervening stores, for example.
Victor Hernandez5d034492009-09-18 22:35:49 +00001609 if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001610 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner3ff6d012008-11-30 01:39:32 +00001611 toErase.push_back(L);
Chris Lattner3ff6d012008-11-30 01:39:32 +00001612 NumGVNLoad++;
Chris Lattner0e3d6332008-12-05 21:04:20 +00001613 return true;
Eli Friedman716c10c2008-02-12 12:08:14 +00001614 }
1615
Chris Lattner0e3d6332008-12-05 21:04:20 +00001616 return false;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001617}
1618
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001619Value *GVN::lookupNumber(BasicBlock *BB, uint32_t num) {
Owen Anderson54e02192008-06-23 17:49:45 +00001620 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1621 if (I == localAvail.end())
1622 return 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001623
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001624 ValueNumberScope *Locals = I->second;
1625 while (Locals) {
1626 DenseMap<uint32_t, Value*>::iterator I = Locals->table.find(num);
1627 if (I != Locals->table.end())
Owen Anderson1b3ea962008-06-20 01:15:47 +00001628 return I->second;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001629 Locals = Locals->parent;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001630 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001631
Owen Anderson1b3ea962008-06-20 01:15:47 +00001632 return 0;
1633}
1634
Owen Andersonbfe133e2008-12-15 02:03:00 +00001635
Owen Anderson398602a2007-08-14 18:16:29 +00001636/// processInstruction - When calculating availability, handle an instruction
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001637/// by inserting it into the appropriate sets
Owen Andersonaccdca12008-06-12 19:25:32 +00001638bool GVN::processInstruction(Instruction *I,
Chris Lattner804209d2008-03-21 22:01:16 +00001639 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001640 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1641 bool Changed = processLoad(LI, toErase);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001642
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001643 if (!Changed) {
1644 unsigned Num = VN.lookup_or_add(LI);
1645 localAvail[I->getParent()]->table.insert(std::make_pair(Num, LI));
Owen Anderson6a903bc2008-06-18 21:41:49 +00001646 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001647
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001648 return Changed;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001649 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001650
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001651 uint32_t NextNum = VN.getNextUnusedValueNumber();
1652 unsigned Num = VN.lookup_or_add(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001653
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001654 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1655 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001656
Owen Anderson98f912b2009-04-01 23:53:49 +00001657 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1658 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001659
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001660 Value *BranchCond = BI->getCondition();
1661 uint32_t CondVN = VN.lookup_or_add(BranchCond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001662
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001663 BasicBlock *TrueSucc = BI->getSuccessor(0);
1664 BasicBlock *FalseSucc = BI->getSuccessor(1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001665
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001666 if (TrueSucc->getSinglePredecessor())
1667 localAvail[TrueSucc]->table[CondVN] =
1668 ConstantInt::getTrue(TrueSucc->getContext());
1669 if (FalseSucc->getSinglePredecessor())
1670 localAvail[FalseSucc]->table[CondVN] =
1671 ConstantInt::getFalse(TrueSucc->getContext());
Owen Anderson98f912b2009-04-01 23:53:49 +00001672
1673 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001674
Owen Anderson0c1e6342008-04-07 09:59:07 +00001675 // Allocations are always uniquely numbered, so we can save time and memory
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001676 // by fast failing them.
Chris Lattner44256602009-09-27 21:46:50 +00001677 } else if (isa<AllocationInst>(I) || isa<TerminatorInst>(I)) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001678 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Anderson0c1e6342008-04-07 09:59:07 +00001679 return false;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001680 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001681
Owen Anderson221a4362007-08-16 22:02:55 +00001682 // Collapse PHI nodes
Owen Andersonbc271a02007-08-14 18:33:27 +00001683 if (PHINode* p = dyn_cast<PHINode>(I)) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001684 Value *constVal = CollapsePhi(p);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001685
Owen Andersonbc271a02007-08-14 18:33:27 +00001686 if (constVal) {
Owen Andersonf5023a72007-08-16 22:51:56 +00001687 p->replaceAllUsesWith(constVal);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001688 if (isa<PointerType>(constVal->getType()))
1689 MD->invalidateCachedPointerInfo(constVal);
Owen Anderson164274e2008-12-23 00:49:51 +00001690 VN.erase(p);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001691
Owen Andersonf5023a72007-08-16 22:51:56 +00001692 toErase.push_back(p);
Owen Anderson6a903bc2008-06-18 21:41:49 +00001693 } else {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001694 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Andersonbc271a02007-08-14 18:33:27 +00001695 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001696
Owen Anderson3ea90a72008-07-03 17:44:33 +00001697 // If the number we were assigned was a brand new VN, then we don't
1698 // need to do a lookup to see if the number already exists
1699 // somewhere in the domtree: it can't!
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001700 } else if (Num == NextNum) {
1701 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001702
Owen Andersonbfe133e2008-12-15 02:03:00 +00001703 // Perform fast-path value-number based elimination of values inherited from
1704 // dominators.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001705 } else if (Value *repl = lookupNumber(I->getParent(), Num)) {
Owen Anderson086b2c42007-12-08 01:37:09 +00001706 // Remove it!
Owen Anderson10ffa862007-07-31 23:27:13 +00001707 VN.erase(I);
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001708 I->replaceAllUsesWith(repl);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001709 if (isa<PointerType>(repl->getType()))
1710 MD->invalidateCachedPointerInfo(repl);
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001711 toErase.push_back(I);
1712 return true;
Owen Andersonbfe133e2008-12-15 02:03:00 +00001713
Owen Anderson3ea90a72008-07-03 17:44:33 +00001714 } else {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001715 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001716 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001717
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001718 return false;
1719}
1720
Bill Wendling456e8852008-12-22 22:32:22 +00001721/// runOnFunction - This is the main transformation entry point for a function.
Owen Anderson676070d2007-08-14 18:04:11 +00001722bool GVN::runOnFunction(Function& F) {
Chris Lattner8541ede2008-12-01 00:40:32 +00001723 MD = &getAnalysis<MemoryDependenceAnalysis>();
1724 DT = &getAnalysis<DominatorTree>();
Owen Andersonf7928602008-05-12 20:15:55 +00001725 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
Chris Lattner8541ede2008-12-01 00:40:32 +00001726 VN.setMemDep(MD);
1727 VN.setDomTree(DT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001728
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001729 bool Changed = false;
1730 bool ShouldContinue = true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001731
Owen Andersonac310962008-07-16 17:52:31 +00001732 // Merge unconditional branches, allowing PRE to catch more
1733 // optimization opportunities.
1734 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001735 BasicBlock *BB = FI;
Owen Andersonac310962008-07-16 17:52:31 +00001736 ++FI;
Owen Andersonc0623812008-07-17 00:01:40 +00001737 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1738 if (removedBlock) NumGVNBlocks++;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001739
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001740 Changed |= removedBlock;
Owen Andersonac310962008-07-16 17:52:31 +00001741 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001742
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001743 unsigned Iteration = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001744
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001745 while (ShouldContinue) {
Dan Gohman1ddf98a2009-07-25 01:43:01 +00001746 DEBUG(errs() << "GVN iteration: " << Iteration << "\n");
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001747 ShouldContinue = iterateOnFunction(F);
1748 Changed |= ShouldContinue;
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001749 ++Iteration;
Owen Anderson676070d2007-08-14 18:04:11 +00001750 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001751
Owen Anderson04a6e0b2008-07-18 18:03:38 +00001752 if (EnablePRE) {
Owen Anderson2fbfb702008-09-03 23:06:07 +00001753 bool PREChanged = true;
1754 while (PREChanged) {
1755 PREChanged = performPRE(F);
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001756 Changed |= PREChanged;
Owen Anderson2fbfb702008-09-03 23:06:07 +00001757 }
Owen Anderson04a6e0b2008-07-18 18:03:38 +00001758 }
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001759 // FIXME: Should perform GVN again after PRE does something. PRE can move
1760 // computations into blocks where they become fully redundant. Note that
1761 // we can't do this until PRE's critical edge splitting updates memdep.
1762 // Actually, when this happens, we should just fully integrate PRE into GVN.
Nuno Lopese3127f32008-10-10 16:25:50 +00001763
1764 cleanupGlobalSets();
1765
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001766 return Changed;
Owen Anderson676070d2007-08-14 18:04:11 +00001767}
1768
1769
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001770bool GVN::processBlock(BasicBlock *BB) {
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001771 // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1772 // incrementing BI before processing an instruction).
Owen Andersonaccdca12008-06-12 19:25:32 +00001773 SmallVector<Instruction*, 8> toErase;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001774 bool ChangedFunction = false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001775
Owen Andersonaccdca12008-06-12 19:25:32 +00001776 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1777 BI != BE;) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001778 ChangedFunction |= processInstruction(BI, toErase);
Owen Andersonaccdca12008-06-12 19:25:32 +00001779 if (toErase.empty()) {
1780 ++BI;
1781 continue;
1782 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001783
Owen Andersonaccdca12008-06-12 19:25:32 +00001784 // If we need some instructions deleted, do it now.
1785 NumGVNInstr += toErase.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001786
Owen Andersonaccdca12008-06-12 19:25:32 +00001787 // Avoid iterator invalidation.
1788 bool AtStart = BI == BB->begin();
1789 if (!AtStart)
1790 --BI;
1791
1792 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
Chris Lattner8541ede2008-12-01 00:40:32 +00001793 E = toErase.end(); I != E; ++I) {
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001794 DEBUG(errs() << "GVN removed: " << **I << '\n');
Chris Lattner8541ede2008-12-01 00:40:32 +00001795 MD->removeInstruction(*I);
Owen Andersonaccdca12008-06-12 19:25:32 +00001796 (*I)->eraseFromParent();
Bill Wendlingebb6a542008-12-22 21:57:30 +00001797 DEBUG(verifyRemoved(*I));
Chris Lattner8541ede2008-12-01 00:40:32 +00001798 }
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001799 toErase.clear();
Owen Andersonaccdca12008-06-12 19:25:32 +00001800
1801 if (AtStart)
1802 BI = BB->begin();
1803 else
1804 ++BI;
Owen Andersonaccdca12008-06-12 19:25:32 +00001805 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001806
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001807 return ChangedFunction;
Owen Andersonaccdca12008-06-12 19:25:32 +00001808}
1809
Owen Anderson6a903bc2008-06-18 21:41:49 +00001810/// performPRE - Perform a purely local form of PRE that looks for diamond
1811/// control flow patterns and attempts to perform simple PRE at the join point.
1812bool GVN::performPRE(Function& F) {
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001813 bool Changed = false;
Owen Andersonfdf9f162008-06-19 19:54:19 +00001814 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
Chris Lattnerf00aae42008-12-01 07:29:03 +00001815 DenseMap<BasicBlock*, Value*> predMap;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001816 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1817 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001818 BasicBlock *CurrentBlock = *DI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001819
Owen Anderson6a903bc2008-06-18 21:41:49 +00001820 // Nothing to PRE in the entry block.
1821 if (CurrentBlock == &F.getEntryBlock()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001822
Owen Anderson6a903bc2008-06-18 21:41:49 +00001823 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1824 BE = CurrentBlock->end(); BI != BE; ) {
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001825 Instruction *CurInst = BI++;
Duncan Sands1efabaa2009-05-06 06:49:50 +00001826
Chris Lattner44256602009-09-27 21:46:50 +00001827 if (isa<AllocationInst>(CurInst) ||
Victor Hernandez5d034492009-09-18 22:35:49 +00001828 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
Devang Patel92f86192009-10-14 17:29:00 +00001829 CurInst->getType()->isVoidTy() ||
Duncan Sands1efabaa2009-05-06 06:49:50 +00001830 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
John Criswell073e4d12009-03-10 15:04:53 +00001831 isa<DbgInfoIntrinsic>(CurInst))
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001832 continue;
Duncan Sands1efabaa2009-05-06 06:49:50 +00001833
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001834 uint32_t ValNo = VN.lookup(CurInst);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001835
Owen Anderson6a903bc2008-06-18 21:41:49 +00001836 // Look for the predecessors for PRE opportunities. We're
1837 // only trying to solve the basic diamond case, where
1838 // a value is computed in the successor and one predecessor,
1839 // but not the other. We also explicitly disallow cases
1840 // where the successor is its own predecessor, because they're
1841 // more complicated to get right.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001842 unsigned NumWith = 0;
1843 unsigned NumWithout = 0;
1844 BasicBlock *PREPred = 0;
Chris Lattnerf00aae42008-12-01 07:29:03 +00001845 predMap.clear();
1846
Owen Anderson6a903bc2008-06-18 21:41:49 +00001847 for (pred_iterator PI = pred_begin(CurrentBlock),
1848 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1849 // We're not interested in PRE where the block is its
Owen Anderson1b3ea962008-06-20 01:15:47 +00001850 // own predecessor, on in blocks with predecessors
1851 // that are not reachable.
1852 if (*PI == CurrentBlock) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001853 NumWithout = 2;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001854 break;
1855 } else if (!localAvail.count(*PI)) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001856 NumWithout = 2;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001857 break;
1858 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001859
1860 DenseMap<uint32_t, Value*>::iterator predV =
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001861 localAvail[*PI]->table.find(ValNo);
Owen Anderson1b3ea962008-06-20 01:15:47 +00001862 if (predV == localAvail[*PI]->table.end()) {
Owen Anderson6a903bc2008-06-18 21:41:49 +00001863 PREPred = *PI;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001864 NumWithout++;
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001865 } else if (predV->second == CurInst) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001866 NumWithout = 2;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001867 } else {
Owen Anderson1b3ea962008-06-20 01:15:47 +00001868 predMap[*PI] = predV->second;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001869 NumWith++;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001870 }
1871 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001872
Owen Anderson6a903bc2008-06-18 21:41:49 +00001873 // Don't do PRE when it might increase code size, i.e. when
1874 // we would need to insert instructions in more than one pred.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001875 if (NumWithout != 1 || NumWith == 0)
Owen Anderson6a903bc2008-06-18 21:41:49 +00001876 continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001877
Owen Andersonfdf9f162008-06-19 19:54:19 +00001878 // We can't do PRE safely on a critical edge, so instead we schedule
1879 // the edge to be split and perform the PRE the next time we iterate
1880 // on the function.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001881 unsigned SuccNum = 0;
Owen Andersonfdf9f162008-06-19 19:54:19 +00001882 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1883 i != e; ++i)
Owen Anderson2fbfb702008-09-03 23:06:07 +00001884 if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001885 SuccNum = i;
Owen Andersonfdf9f162008-06-19 19:54:19 +00001886 break;
1887 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001888
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001889 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
1890 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
Owen Andersonfdf9f162008-06-19 19:54:19 +00001891 continue;
1892 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001893
Owen Anderson6a903bc2008-06-18 21:41:49 +00001894 // Instantiate the expression the in predecessor that lacked it.
1895 // Because we are going top-down through the block, all value numbers
1896 // will be available in the predecessor by the time we need them. Any
1897 // that weren't original present will have been instantiated earlier
1898 // in this loop.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001899 Instruction *PREInstr = CurInst->clone();
Owen Anderson6a903bc2008-06-18 21:41:49 +00001900 bool success = true;
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001901 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
1902 Value *Op = PREInstr->getOperand(i);
1903 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
1904 continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001905
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001906 if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
1907 PREInstr->setOperand(i, V);
1908 } else {
1909 success = false;
1910 break;
Owen Anderson8e462e92008-07-11 20:05:13 +00001911 }
Owen Anderson6a903bc2008-06-18 21:41:49 +00001912 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001913
Owen Anderson6a903bc2008-06-18 21:41:49 +00001914 // Fail out if we encounter an operand that is not available in
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001915 // the PRE predecessor. This is typically because of loads which
Owen Anderson6a903bc2008-06-18 21:41:49 +00001916 // are not value numbered precisely.
1917 if (!success) {
1918 delete PREInstr;
Bill Wendling3c793442008-12-22 22:14:07 +00001919 DEBUG(verifyRemoved(PREInstr));
Owen Anderson6a903bc2008-06-18 21:41:49 +00001920 continue;
1921 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001922
Owen Anderson6a903bc2008-06-18 21:41:49 +00001923 PREInstr->insertBefore(PREPred->getTerminator());
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001924 PREInstr->setName(CurInst->getName() + ".pre");
Owen Anderson1b3ea962008-06-20 01:15:47 +00001925 predMap[PREPred] = PREInstr;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001926 VN.add(PREInstr, ValNo);
Owen Anderson6a903bc2008-06-18 21:41:49 +00001927 NumGVNPRE++;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001928
Owen Anderson6a903bc2008-06-18 21:41:49 +00001929 // Update the availability map to include the new instruction.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001930 localAvail[PREPred]->table.insert(std::make_pair(ValNo, PREInstr));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001931
Owen Anderson6a903bc2008-06-18 21:41:49 +00001932 // Create a PHI to make the value available in this block.
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001933 PHINode* Phi = PHINode::Create(CurInst->getType(),
1934 CurInst->getName() + ".pre-phi",
Owen Anderson6a903bc2008-06-18 21:41:49 +00001935 CurrentBlock->begin());
1936 for (pred_iterator PI = pred_begin(CurrentBlock),
1937 PE = pred_end(CurrentBlock); PI != PE; ++PI)
Owen Anderson1b3ea962008-06-20 01:15:47 +00001938 Phi->addIncoming(predMap[*PI], *PI);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001939
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001940 VN.add(Phi, ValNo);
1941 localAvail[CurrentBlock]->table[ValNo] = Phi;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001942
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001943 CurInst->replaceAllUsesWith(Phi);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001944 if (isa<PointerType>(Phi->getType()))
1945 MD->invalidateCachedPointerInfo(Phi);
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001946 VN.erase(CurInst);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001947
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001948 DEBUG(errs() << "GVN PRE removed: " << *CurInst << '\n');
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001949 MD->removeInstruction(CurInst);
1950 CurInst->eraseFromParent();
Bill Wendlingebb6a542008-12-22 21:57:30 +00001951 DEBUG(verifyRemoved(CurInst));
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001952 Changed = true;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001953 }
1954 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001955
Owen Andersonfdf9f162008-06-19 19:54:19 +00001956 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
Anton Korobeynikov24600bf2008-12-05 19:38:49 +00001957 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
Owen Andersonfdf9f162008-06-19 19:54:19 +00001958 SplitCriticalEdge(I->first, I->second, this);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001959
Anton Korobeynikov24600bf2008-12-05 19:38:49 +00001960 return Changed || toSplit.size();
Owen Anderson6a903bc2008-06-18 21:41:49 +00001961}
1962
Bill Wendling456e8852008-12-22 22:32:22 +00001963/// iterateOnFunction - Executes one iteration of GVN
Owen Anderson676070d2007-08-14 18:04:11 +00001964bool GVN::iterateOnFunction(Function &F) {
Nuno Lopese3127f32008-10-10 16:25:50 +00001965 cleanupGlobalSets();
Chris Lattnerbeb216d2008-03-21 21:33:23 +00001966
Owen Anderson98f912b2009-04-01 23:53:49 +00001967 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1968 DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
1969 if (DI->getIDom())
1970 localAvail[DI->getBlock()] =
1971 new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
1972 else
1973 localAvail[DI->getBlock()] = new ValueNumberScope(0);
1974 }
1975
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001976 // Top-down walk of the dominator tree
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001977 bool Changed = false;
Owen Anderson03aacba2008-12-15 03:52:17 +00001978#if 0
1979 // Needed for value numbering with phi construction to work.
Owen Andersonbfe133e2008-12-15 02:03:00 +00001980 ReversePostOrderTraversal<Function*> RPOT(&F);
1981 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
1982 RE = RPOT.end(); RI != RE; ++RI)
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001983 Changed |= processBlock(*RI);
Owen Anderson03aacba2008-12-15 03:52:17 +00001984#else
1985 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1986 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001987 Changed |= processBlock(DI->getBlock());
Owen Anderson03aacba2008-12-15 03:52:17 +00001988#endif
1989
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001990 return Changed;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001991}
Nuno Lopese3127f32008-10-10 16:25:50 +00001992
1993void GVN::cleanupGlobalSets() {
1994 VN.clear();
Nuno Lopese3127f32008-10-10 16:25:50 +00001995
1996 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1997 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1998 delete I->second;
1999 localAvail.clear();
2000}
Bill Wendling6b18a392008-12-22 21:36:08 +00002001
2002/// verifyRemoved - Verify that the specified instruction does not occur in our
2003/// internal data structures.
Bill Wendlinge7f08e72008-12-22 22:28:56 +00002004void GVN::verifyRemoved(const Instruction *Inst) const {
2005 VN.verifyRemoved(Inst);
Bill Wendling3c793442008-12-22 22:14:07 +00002006
Bill Wendlinge7f08e72008-12-22 22:28:56 +00002007 // Walk through the value number scope to make sure the instruction isn't
2008 // ferreted away in it.
2009 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
2010 I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
2011 const ValueNumberScope *VNS = I->second;
2012
2013 while (VNS) {
2014 for (DenseMap<uint32_t, Value*>::iterator
2015 II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
2016 assert(II->second != Inst && "Inst still in value numbering scope!");
2017 }
2018
2019 VNS = VNS->parent;
Bill Wendling3c793442008-12-22 22:14:07 +00002020 }
2021 }
Bill Wendling6b18a392008-12-22 21:36:08 +00002022}