blob: a9445dd853024f9fd8ac8a0c321dcb9a09a1d147 [file] [log] [blame]
Owen Anderson85c40642007-07-24 17:55:58 +00001//===- GVN.cpp - Eliminate redundant values and loads ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-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 Anderson85c40642007-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//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "gvn"
Owen Anderson85c40642007-07-24 17:55:58 +000016#include "llvm/Transforms/Scalar.h"
Owen Anderson5d72a422007-07-25 19:57:03 +000017#include "llvm/BasicBlock.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000018#include "llvm/Constants.h"
Owen Anderson85c40642007-07-24 17:55:58 +000019#include "llvm/DerivedTypes.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000020#include "llvm/Function.h"
Owen Anderson8d272d52008-02-12 21:15:18 +000021#include "llvm/IntrinsicInst.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000022#include "llvm/Instructions.h"
Owen Anderson282dd322008-02-18 09:24:53 +000023#include "llvm/ParameterAttributes.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000024#include "llvm/Value.h"
Owen Anderson85c40642007-07-24 17:55:58 +000025#include "llvm/ADT/BitVector.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/DepthFirstIterator.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/Statistic.h"
Owen Anderson5e9366f2007-10-18 19:39:33 +000031#include "llvm/Analysis/Dominators.h"
32#include "llvm/Analysis/AliasAnalysis.h"
Owen Anderson85c40642007-07-24 17:55:58 +000033#include "llvm/Analysis/MemoryDependenceAnalysis.h"
34#include "llvm/Support/CFG.h"
Evan Chenge856f8e2008-03-24 05:28:38 +000035#include "llvm/Support/CommandLine.h"
Owen Anderson85c40642007-07-24 17:55:58 +000036#include "llvm/Support/Compiler.h"
Chris Lattner60b9cb42008-03-22 05:37:16 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Owen Anderson29f73562008-02-19 06:35:43 +000038#include "llvm/Target/TargetData.h"
Owen Anderson85c40642007-07-24 17:55:58 +000039using namespace llvm;
40
Chris Lattner1be83222008-03-22 04:13:49 +000041STATISTIC(NumGVNInstr, "Number of instructions deleted");
42STATISTIC(NumGVNLoad, "Number of loads deleted");
43STATISTIC(NumMemSetInfer, "Number of memsets inferred");
44
Evan Chenge856f8e2008-03-24 05:28:38 +000045namespace {
46 cl::opt<bool>
47 FormMemSet("form-memset-from-stores",
48 cl::desc("Transform straight-line stores to memsets"),
49 cl::init(false), cl::Hidden);
50}
Chris Lattner1be83222008-03-22 04:13:49 +000051
Owen Anderson85c40642007-07-24 17:55:58 +000052//===----------------------------------------------------------------------===//
53// ValueTable Class
54//===----------------------------------------------------------------------===//
55
56/// This class holds the mapping between values and value numbers. It is used
57/// as an efficient mechanism to determine the expression-wise equivalence of
58/// two values.
59namespace {
60 struct VISIBILITY_HIDDEN Expression {
61 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
62 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
63 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
64 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
65 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
66 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
67 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
68 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
69 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
Owen Anderson5e9366f2007-10-18 19:39:33 +000070 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
Owen Anderson85c40642007-07-24 17:55:58 +000071 TOMBSTONE };
72
73 ExpressionOpcode opcode;
74 const Type* type;
75 uint32_t firstVN;
76 uint32_t secondVN;
77 uint32_t thirdVN;
78 SmallVector<uint32_t, 4> varargs;
Owen Anderson5e9366f2007-10-18 19:39:33 +000079 Value* function;
Owen Anderson85c40642007-07-24 17:55:58 +000080
81 Expression() { }
82 Expression(ExpressionOpcode o) : opcode(o) { }
83
84 bool operator==(const Expression &other) const {
85 if (opcode != other.opcode)
86 return false;
87 else if (opcode == EMPTY || opcode == TOMBSTONE)
88 return true;
89 else if (type != other.type)
90 return false;
Owen Anderson5e9366f2007-10-18 19:39:33 +000091 else if (function != other.function)
92 return false;
Owen Anderson85c40642007-07-24 17:55:58 +000093 else if (firstVN != other.firstVN)
94 return false;
95 else if (secondVN != other.secondVN)
96 return false;
97 else if (thirdVN != other.thirdVN)
98 return false;
99 else {
100 if (varargs.size() != other.varargs.size())
101 return false;
102
103 for (size_t i = 0; i < varargs.size(); ++i)
104 if (varargs[i] != other.varargs[i])
105 return false;
106
107 return true;
108 }
109 }
110
111 bool operator!=(const Expression &other) const {
112 if (opcode != other.opcode)
113 return true;
114 else if (opcode == EMPTY || opcode == TOMBSTONE)
115 return false;
116 else if (type != other.type)
117 return true;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000118 else if (function != other.function)
119 return true;
Owen Anderson85c40642007-07-24 17:55:58 +0000120 else if (firstVN != other.firstVN)
121 return true;
122 else if (secondVN != other.secondVN)
123 return true;
124 else if (thirdVN != other.thirdVN)
125 return true;
126 else {
127 if (varargs.size() != other.varargs.size())
128 return true;
129
130 for (size_t i = 0; i < varargs.size(); ++i)
131 if (varargs[i] != other.varargs[i])
132 return true;
133
134 return false;
135 }
136 }
137 };
138
139 class VISIBILITY_HIDDEN ValueTable {
140 private:
141 DenseMap<Value*, uint32_t> valueNumbering;
142 DenseMap<Expression, uint32_t> expressionNumbering;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000143 AliasAnalysis* AA;
Owen Anderson85c40642007-07-24 17:55:58 +0000144
145 uint32_t nextValueNumber;
146
147 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
148 Expression::ExpressionOpcode getOpcode(CmpInst* C);
149 Expression::ExpressionOpcode getOpcode(CastInst* C);
150 Expression create_expression(BinaryOperator* BO);
151 Expression create_expression(CmpInst* C);
152 Expression create_expression(ShuffleVectorInst* V);
153 Expression create_expression(ExtractElementInst* C);
154 Expression create_expression(InsertElementInst* V);
155 Expression create_expression(SelectInst* V);
156 Expression create_expression(CastInst* C);
157 Expression create_expression(GetElementPtrInst* G);
Owen Anderson5e9366f2007-10-18 19:39:33 +0000158 Expression create_expression(CallInst* C);
Owen Anderson85c40642007-07-24 17:55:58 +0000159 public:
Owen Anderson5e9366f2007-10-18 19:39:33 +0000160 ValueTable() : nextValueNumber(1) { }
Owen Anderson85c40642007-07-24 17:55:58 +0000161 uint32_t lookup_or_add(Value* V);
162 uint32_t lookup(Value* V) const;
163 void add(Value* V, uint32_t num);
164 void clear();
165 void erase(Value* v);
166 unsigned size();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000167 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
Owen Anderson343797c2007-11-26 07:17:19 +0000168 uint32_t hash_operand(Value* v);
Owen Anderson85c40642007-07-24 17:55:58 +0000169 };
170}
171
172namespace llvm {
Chris Lattner92eea072007-09-17 18:34:04 +0000173template <> struct DenseMapInfo<Expression> {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000174 static inline Expression getEmptyKey() {
175 return Expression(Expression::EMPTY);
176 }
177
178 static inline Expression getTombstoneKey() {
179 return Expression(Expression::TOMBSTONE);
180 }
Owen Anderson85c40642007-07-24 17:55:58 +0000181
182 static unsigned getHashValue(const Expression e) {
183 unsigned hash = e.opcode;
184
185 hash = e.firstVN + hash * 37;
186 hash = e.secondVN + hash * 37;
187 hash = e.thirdVN + hash * 37;
188
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000189 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
190 (unsigned)((uintptr_t)e.type >> 9)) +
191 hash * 37;
Owen Anderson85c40642007-07-24 17:55:58 +0000192
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000193 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
194 E = e.varargs.end(); I != E; ++I)
Owen Anderson85c40642007-07-24 17:55:58 +0000195 hash = *I + hash * 37;
196
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000197 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
198 (unsigned)((uintptr_t)e.function >> 9)) +
199 hash * 37;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000200
Owen Anderson85c40642007-07-24 17:55:58 +0000201 return hash;
202 }
Chris Lattner92eea072007-09-17 18:34:04 +0000203 static bool isEqual(const Expression &LHS, const Expression &RHS) {
204 return LHS == RHS;
205 }
Owen Anderson85c40642007-07-24 17:55:58 +0000206 static bool isPod() { return true; }
207};
208}
209
210//===----------------------------------------------------------------------===//
211// ValueTable Internal Functions
212//===----------------------------------------------------------------------===//
Chris Lattner3d7103e2008-03-21 21:14:38 +0000213Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
Owen Anderson85c40642007-07-24 17:55:58 +0000214 switch(BO->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000215 default: // THIS SHOULD NEVER HAPPEN
216 assert(0 && "Binary operator with unknown opcode?");
217 case Instruction::Add: return Expression::ADD;
218 case Instruction::Sub: return Expression::SUB;
219 case Instruction::Mul: return Expression::MUL;
220 case Instruction::UDiv: return Expression::UDIV;
221 case Instruction::SDiv: return Expression::SDIV;
222 case Instruction::FDiv: return Expression::FDIV;
223 case Instruction::URem: return Expression::UREM;
224 case Instruction::SRem: return Expression::SREM;
225 case Instruction::FRem: return Expression::FREM;
226 case Instruction::Shl: return Expression::SHL;
227 case Instruction::LShr: return Expression::LSHR;
228 case Instruction::AShr: return Expression::ASHR;
229 case Instruction::And: return Expression::AND;
230 case Instruction::Or: return Expression::OR;
231 case Instruction::Xor: return Expression::XOR;
Owen Anderson85c40642007-07-24 17:55:58 +0000232 }
233}
234
235Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000236 if (isa<ICmpInst>(C)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000237 switch (C->getPredicate()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000238 default: // THIS SHOULD NEVER HAPPEN
239 assert(0 && "Comparison with unknown predicate?");
240 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
241 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
242 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
243 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
244 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
245 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
246 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
247 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
248 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
249 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
Owen Anderson85c40642007-07-24 17:55:58 +0000250 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000251 }
252 assert(isa<FCmpInst>(C) && "Unknown compare");
253 switch (C->getPredicate()) {
254 default: // THIS SHOULD NEVER HAPPEN
255 assert(0 && "Comparison with unknown predicate?");
256 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
257 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
258 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
259 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
260 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
261 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
262 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
263 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
264 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
265 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
266 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
267 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
268 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
269 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
Owen Anderson85c40642007-07-24 17:55:58 +0000270 }
271}
272
Chris Lattner3d7103e2008-03-21 21:14:38 +0000273Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
Owen Anderson85c40642007-07-24 17:55:58 +0000274 switch(C->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000275 default: // THIS SHOULD NEVER HAPPEN
276 assert(0 && "Cast operator with unknown opcode?");
277 case Instruction::Trunc: return Expression::TRUNC;
278 case Instruction::ZExt: return Expression::ZEXT;
279 case Instruction::SExt: return Expression::SEXT;
280 case Instruction::FPToUI: return Expression::FPTOUI;
281 case Instruction::FPToSI: return Expression::FPTOSI;
282 case Instruction::UIToFP: return Expression::UITOFP;
283 case Instruction::SIToFP: return Expression::SITOFP;
284 case Instruction::FPTrunc: return Expression::FPTRUNC;
285 case Instruction::FPExt: return Expression::FPEXT;
286 case Instruction::PtrToInt: return Expression::PTRTOINT;
287 case Instruction::IntToPtr: return Expression::INTTOPTR;
288 case Instruction::BitCast: return Expression::BITCAST;
Owen Anderson85c40642007-07-24 17:55:58 +0000289 }
290}
291
Owen Anderson343797c2007-11-26 07:17:19 +0000292uint32_t ValueTable::hash_operand(Value* v) {
293 if (CallInst* CI = dyn_cast<CallInst>(v))
Duncan Sands00b24b52007-12-01 07:51:45 +0000294 if (!AA->doesNotAccessMemory(CI))
Owen Anderson343797c2007-11-26 07:17:19 +0000295 return nextValueNumber++;
296
297 return lookup_or_add(v);
298}
299
Owen Anderson5e9366f2007-10-18 19:39:33 +0000300Expression ValueTable::create_expression(CallInst* C) {
301 Expression e;
302
303 e.type = C->getType();
304 e.firstVN = 0;
305 e.secondVN = 0;
306 e.thirdVN = 0;
307 e.function = C->getCalledFunction();
308 e.opcode = Expression::CALL;
309
310 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
311 I != E; ++I)
Owen Anderson343797c2007-11-26 07:17:19 +0000312 e.varargs.push_back(hash_operand(*I));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000313
314 return e;
315}
316
Owen Anderson85c40642007-07-24 17:55:58 +0000317Expression ValueTable::create_expression(BinaryOperator* BO) {
318 Expression e;
319
Owen Anderson343797c2007-11-26 07:17:19 +0000320 e.firstVN = hash_operand(BO->getOperand(0));
321 e.secondVN = hash_operand(BO->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000322 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000323 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000324 e.type = BO->getType();
325 e.opcode = getOpcode(BO);
326
327 return e;
328}
329
330Expression ValueTable::create_expression(CmpInst* C) {
331 Expression e;
332
Owen Anderson343797c2007-11-26 07:17:19 +0000333 e.firstVN = hash_operand(C->getOperand(0));
334 e.secondVN = hash_operand(C->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000335 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000336 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000337 e.type = C->getType();
338 e.opcode = getOpcode(C);
339
340 return e;
341}
342
343Expression ValueTable::create_expression(CastInst* C) {
344 Expression e;
345
Owen Anderson343797c2007-11-26 07:17:19 +0000346 e.firstVN = hash_operand(C->getOperand(0));
Owen Anderson85c40642007-07-24 17:55:58 +0000347 e.secondVN = 0;
348 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000349 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000350 e.type = C->getType();
351 e.opcode = getOpcode(C);
352
353 return e;
354}
355
356Expression ValueTable::create_expression(ShuffleVectorInst* S) {
357 Expression e;
358
Owen Anderson343797c2007-11-26 07:17:19 +0000359 e.firstVN = hash_operand(S->getOperand(0));
360 e.secondVN = hash_operand(S->getOperand(1));
361 e.thirdVN = hash_operand(S->getOperand(2));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000362 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000363 e.type = S->getType();
364 e.opcode = Expression::SHUFFLE;
365
366 return e;
367}
368
369Expression ValueTable::create_expression(ExtractElementInst* E) {
370 Expression e;
371
Owen Anderson343797c2007-11-26 07:17:19 +0000372 e.firstVN = hash_operand(E->getOperand(0));
373 e.secondVN = hash_operand(E->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000374 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000375 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000376 e.type = E->getType();
377 e.opcode = Expression::EXTRACT;
378
379 return e;
380}
381
382Expression ValueTable::create_expression(InsertElementInst* I) {
383 Expression e;
384
Owen Anderson343797c2007-11-26 07:17:19 +0000385 e.firstVN = hash_operand(I->getOperand(0));
386 e.secondVN = hash_operand(I->getOperand(1));
387 e.thirdVN = hash_operand(I->getOperand(2));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000388 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000389 e.type = I->getType();
390 e.opcode = Expression::INSERT;
391
392 return e;
393}
394
395Expression ValueTable::create_expression(SelectInst* I) {
396 Expression e;
397
Owen Anderson343797c2007-11-26 07:17:19 +0000398 e.firstVN = hash_operand(I->getCondition());
399 e.secondVN = hash_operand(I->getTrueValue());
400 e.thirdVN = hash_operand(I->getFalseValue());
Owen Anderson5e9366f2007-10-18 19:39:33 +0000401 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000402 e.type = I->getType();
403 e.opcode = Expression::SELECT;
404
405 return e;
406}
407
408Expression ValueTable::create_expression(GetElementPtrInst* G) {
409 Expression e;
410
Owen Anderson343797c2007-11-26 07:17:19 +0000411 e.firstVN = hash_operand(G->getPointerOperand());
Owen Anderson85c40642007-07-24 17:55:58 +0000412 e.secondVN = 0;
413 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000414 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000415 e.type = G->getType();
416 e.opcode = Expression::GEP;
417
418 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
419 I != E; ++I)
Owen Anderson343797c2007-11-26 07:17:19 +0000420 e.varargs.push_back(hash_operand(*I));
Owen Anderson85c40642007-07-24 17:55:58 +0000421
422 return e;
423}
424
425//===----------------------------------------------------------------------===//
426// ValueTable External Functions
427//===----------------------------------------------------------------------===//
428
429/// lookup_or_add - Returns the value number for the specified value, assigning
430/// it a new number if it did not have one before.
431uint32_t ValueTable::lookup_or_add(Value* V) {
432 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
433 if (VI != valueNumbering.end())
434 return VI->second;
435
Owen Anderson5e9366f2007-10-18 19:39:33 +0000436 if (CallInst* C = dyn_cast<CallInst>(V)) {
Duncan Sands00b24b52007-12-01 07:51:45 +0000437 if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
Owen Anderson5e9366f2007-10-18 19:39:33 +0000438 Expression e = create_expression(C);
439
440 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
441 if (EI != expressionNumbering.end()) {
442 valueNumbering.insert(std::make_pair(V, EI->second));
443 return EI->second;
444 } else {
445 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
446 valueNumbering.insert(std::make_pair(V, nextValueNumber));
447
448 return nextValueNumber++;
449 }
450 } else {
451 valueNumbering.insert(std::make_pair(V, nextValueNumber));
452 return nextValueNumber++;
453 }
454 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000455 Expression e = create_expression(BO);
456
457 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
458 if (EI != expressionNumbering.end()) {
459 valueNumbering.insert(std::make_pair(V, EI->second));
460 return EI->second;
461 } else {
462 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
463 valueNumbering.insert(std::make_pair(V, nextValueNumber));
464
465 return nextValueNumber++;
466 }
467 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
468 Expression e = create_expression(C);
469
470 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
471 if (EI != expressionNumbering.end()) {
472 valueNumbering.insert(std::make_pair(V, EI->second));
473 return EI->second;
474 } else {
475 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
476 valueNumbering.insert(std::make_pair(V, nextValueNumber));
477
478 return nextValueNumber++;
479 }
480 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
481 Expression e = create_expression(U);
482
483 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
484 if (EI != expressionNumbering.end()) {
485 valueNumbering.insert(std::make_pair(V, EI->second));
486 return EI->second;
487 } else {
488 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
489 valueNumbering.insert(std::make_pair(V, nextValueNumber));
490
491 return nextValueNumber++;
492 }
493 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
494 Expression e = create_expression(U);
495
496 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
497 if (EI != expressionNumbering.end()) {
498 valueNumbering.insert(std::make_pair(V, EI->second));
499 return EI->second;
500 } else {
501 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
502 valueNumbering.insert(std::make_pair(V, nextValueNumber));
503
504 return nextValueNumber++;
505 }
506 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
507 Expression e = create_expression(U);
508
509 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
510 if (EI != expressionNumbering.end()) {
511 valueNumbering.insert(std::make_pair(V, EI->second));
512 return EI->second;
513 } else {
514 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
515 valueNumbering.insert(std::make_pair(V, nextValueNumber));
516
517 return nextValueNumber++;
518 }
519 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
520 Expression e = create_expression(U);
521
522 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
523 if (EI != expressionNumbering.end()) {
524 valueNumbering.insert(std::make_pair(V, EI->second));
525 return EI->second;
526 } else {
527 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
528 valueNumbering.insert(std::make_pair(V, nextValueNumber));
529
530 return nextValueNumber++;
531 }
532 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
533 Expression e = create_expression(U);
534
535 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
536 if (EI != expressionNumbering.end()) {
537 valueNumbering.insert(std::make_pair(V, EI->second));
538 return EI->second;
539 } else {
540 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
541 valueNumbering.insert(std::make_pair(V, nextValueNumber));
542
543 return nextValueNumber++;
544 }
545 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
546 Expression e = create_expression(U);
547
548 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
549 if (EI != expressionNumbering.end()) {
550 valueNumbering.insert(std::make_pair(V, EI->second));
551 return EI->second;
552 } else {
553 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
554 valueNumbering.insert(std::make_pair(V, nextValueNumber));
555
556 return nextValueNumber++;
557 }
558 } else {
559 valueNumbering.insert(std::make_pair(V, nextValueNumber));
560 return nextValueNumber++;
561 }
562}
563
564/// lookup - Returns the value number of the specified value. Fails if
565/// the value has not yet been numbered.
566uint32_t ValueTable::lookup(Value* V) const {
567 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000568 assert(VI != valueNumbering.end() && "Value not numbered?");
569 return VI->second;
Owen Anderson85c40642007-07-24 17:55:58 +0000570}
571
572/// clear - Remove all entries from the ValueTable
573void ValueTable::clear() {
574 valueNumbering.clear();
575 expressionNumbering.clear();
576 nextValueNumber = 1;
577}
578
Owen Anderson5aff8002007-07-31 23:27:13 +0000579/// erase - Remove a value from the value numbering
580void ValueTable::erase(Value* V) {
581 valueNumbering.erase(V);
582}
583
Owen Anderson85c40642007-07-24 17:55:58 +0000584//===----------------------------------------------------------------------===//
585// ValueNumberedSet Class
586//===----------------------------------------------------------------------===//
587namespace {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000588class VISIBILITY_HIDDEN ValueNumberedSet {
Owen Anderson85c40642007-07-24 17:55:58 +0000589 private:
590 SmallPtrSet<Value*, 8> contents;
591 BitVector numbers;
592 public:
593 ValueNumberedSet() { numbers.resize(1); }
594 ValueNumberedSet(const ValueNumberedSet& other) {
595 numbers = other.numbers;
596 contents = other.contents;
597 }
598
599 typedef SmallPtrSet<Value*, 8>::iterator iterator;
600
601 iterator begin() { return contents.begin(); }
602 iterator end() { return contents.end(); }
603
604 bool insert(Value* v) { return contents.insert(v); }
605 void insert(iterator I, iterator E) { contents.insert(I, E); }
606 void erase(Value* v) { contents.erase(v); }
607 unsigned count(Value* v) { return contents.count(v); }
608 size_t size() { return contents.size(); }
609
610 void set(unsigned i) {
611 if (i >= numbers.size())
612 numbers.resize(i+1);
613
614 numbers.set(i);
615 }
616
617 void operator=(const ValueNumberedSet& other) {
618 contents = other.contents;
619 numbers = other.numbers;
620 }
621
622 void reset(unsigned i) {
623 if (i < numbers.size())
624 numbers.reset(i);
625 }
626
627 bool test(unsigned i) {
628 if (i >= numbers.size())
629 return false;
630
631 return numbers.test(i);
632 }
633
634 void clear() {
635 contents.clear();
636 numbers.clear();
637 }
638};
639}
640
641//===----------------------------------------------------------------------===//
642// GVN Pass
643//===----------------------------------------------------------------------===//
644
645namespace {
646
647 class VISIBILITY_HIDDEN GVN : public FunctionPass {
648 bool runOnFunction(Function &F);
649 public:
650 static char ID; // Pass identification, replacement for typeid
651 GVN() : FunctionPass((intptr_t)&ID) { }
652
653 private:
654 ValueTable VN;
655
656 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
657
Owen Anderson5b299672007-08-07 23:12:31 +0000658 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
659 PhiMapType phiMap;
660
661
Owen Anderson85c40642007-07-24 17:55:58 +0000662 // This transformation requires dominator postdominator info
663 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
664 AU.setPreservesCFG();
665 AU.addRequired<DominatorTree>();
666 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000667 AU.addRequired<AliasAnalysis>();
Owen Anderson29f73562008-02-19 06:35:43 +0000668 AU.addRequired<TargetData>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000669 AU.addPreserved<AliasAnalysis>();
Owen Anderson85c40642007-07-24 17:55:58 +0000670 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Anderson29f73562008-02-19 06:35:43 +0000671 AU.addPreserved<TargetData>();
Owen Anderson85c40642007-07-24 17:55:58 +0000672 }
673
674 // Helper fuctions
675 // FIXME: eliminate or document these better
676 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
677 void val_insert(ValueNumberedSet& s, Value* v);
678 bool processLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000679 DenseMap<Value*, LoadInst*> &lastLoad,
680 SmallVectorImpl<Instruction*> &toErase);
Chris Lattner248ba4d2008-03-22 00:31:52 +0000681 bool processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase);
Owen Anderson85c40642007-07-24 17:55:58 +0000682 bool processInstruction(Instruction* I,
683 ValueNumberedSet& currAvail,
684 DenseMap<Value*, LoadInst*>& lastSeenLoad,
Chris Lattner7de20452008-03-21 22:01:16 +0000685 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000686 bool processNonLocalLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000687 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonba958332008-02-19 03:09:45 +0000688 bool processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
Chris Lattner7de20452008-03-21 22:01:16 +0000689 SmallVectorImpl<Instruction*> &toErase);
Owen Andersone41ab4c2008-03-12 07:37:44 +0000690 bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C,
Chris Lattner7de20452008-03-21 22:01:16 +0000691 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000692 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
Owen Andersonc6a31b92007-08-02 17:56:05 +0000693 DenseMap<BasicBlock*, Value*> &Phis,
694 bool top_level = false);
Owen Anderson5d72a422007-07-25 19:57:03 +0000695 void dump(DenseMap<BasicBlock*, Value*>& d);
Owen Andersonbe168b32007-08-14 18:04:11 +0000696 bool iterateOnFunction(Function &F);
Owen Andersone02ad522007-08-16 22:51:56 +0000697 Value* CollapsePhi(PHINode* p);
Owen Anderson19625972007-09-16 08:04:16 +0000698 bool isSafeReplacement(PHINode* p, Instruction* inst);
Owen Anderson85c40642007-07-24 17:55:58 +0000699 };
700
701 char GVN::ID = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000702}
703
704// createGVNPass - The public interface to this file...
705FunctionPass *llvm::createGVNPass() { return new GVN(); }
706
707static RegisterPass<GVN> X("gvn",
708 "Global Value Numbering");
709
Owen Anderson85c40642007-07-24 17:55:58 +0000710/// find_leader - Given a set and a value number, return the first
711/// element of the set with that value number, or 0 if no such element
712/// is present
713Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
714 if (!vals.test(v))
715 return 0;
716
717 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
718 I != E; ++I)
719 if (v == VN.lookup(*I))
720 return *I;
721
722 assert(0 && "No leader found, but present bit is set?");
723 return 0;
724}
725
726/// val_insert - Insert a value into a set only if there is not a value
727/// with the same value number already in the set
728void GVN::val_insert(ValueNumberedSet& s, Value* v) {
729 uint32_t num = VN.lookup(v);
730 if (!s.test(num))
731 s.insert(v);
732}
733
Owen Anderson5d72a422007-07-25 19:57:03 +0000734void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
735 printf("{\n");
736 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
737 E = d.end(); I != E; ++I) {
738 if (I->second == MemoryDependenceAnalysis::None)
739 printf("None\n");
740 else
741 I->second->dump();
742 }
743 printf("}\n");
744}
745
Owen Andersone02ad522007-08-16 22:51:56 +0000746Value* GVN::CollapsePhi(PHINode* p) {
747 DominatorTree &DT = getAnalysis<DominatorTree>();
748 Value* constVal = p->hasConstantValue();
749
Chris Lattner3d7103e2008-03-21 21:14:38 +0000750 if (!constVal) return 0;
Owen Andersone02ad522007-08-16 22:51:56 +0000751
Chris Lattner3d7103e2008-03-21 21:14:38 +0000752 Instruction* inst = dyn_cast<Instruction>(constVal);
753 if (!inst)
754 return constVal;
755
756 if (DT.dominates(inst, p))
757 if (isSafeReplacement(p, inst))
758 return inst;
Owen Andersone02ad522007-08-16 22:51:56 +0000759 return 0;
760}
Owen Anderson5d72a422007-07-25 19:57:03 +0000761
Owen Anderson19625972007-09-16 08:04:16 +0000762bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
763 if (!isa<PHINode>(inst))
764 return true;
765
766 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
767 UI != E; ++UI)
768 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
769 if (use_phi->getParent() == inst->getParent())
770 return false;
771
772 return true;
773}
774
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000775/// GetValueForBlock - Get the value to use within the specified basic block.
776/// available values are in Phis.
777Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
Chris Lattner3d7103e2008-03-21 21:14:38 +0000778 DenseMap<BasicBlock*, Value*> &Phis,
779 bool top_level) {
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000780
781 // If we have already computed this value, return the previously computed val.
Owen Andersoned7f9932007-08-03 19:59:35 +0000782 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
783 if (V != Phis.end() && !top_level) return V->second;
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000784
Owen Anderson3f75d122007-08-01 22:01:54 +0000785 BasicBlock* singlePred = BB->getSinglePredecessor();
Owen Anderson30463f12007-08-03 11:03:26 +0000786 if (singlePred) {
Owen Andersoned7f9932007-08-03 19:59:35 +0000787 Value *ret = GetValueForBlock(singlePred, orig, Phis);
788 Phis[BB] = ret;
789 return ret;
Owen Anderson30463f12007-08-03 11:03:26 +0000790 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000791
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000792 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
793 // now, then get values to fill in the incoming values for the PHI.
794 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
795 BB->begin());
796 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
Owen Andersoned7f9932007-08-03 19:59:35 +0000797
798 if (Phis.count(BB) == 0)
799 Phis.insert(std::make_pair(BB, PN));
Owen Anderson48a2c562007-07-30 16:57:08 +0000800
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000801 // Fill in the incoming values for the block.
Owen Anderson9f577412007-07-31 17:43:14 +0000802 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
803 Value* val = GetValueForBlock(*PI, orig, Phis);
Owen Anderson9f577412007-07-31 17:43:14 +0000804 PN->addIncoming(val, *PI);
805 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000806
Nick Lewycky8fba1d02008-02-14 07:11:24 +0000807 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
808 AA.copyValue(orig, PN);
Owen Anderson9f577412007-07-31 17:43:14 +0000809
Owen Andersone0143452007-08-16 22:02:55 +0000810 // Attempt to collapse PHI nodes that are trivially redundant
Owen Andersone02ad522007-08-16 22:51:56 +0000811 Value* v = CollapsePhi(PN);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000812 if (!v) {
813 // Cache our phi construction results
814 phiMap[orig->getPointerOperand()].insert(PN);
815 return PN;
Owen Anderson9f577412007-07-31 17:43:14 +0000816 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000817
818 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Anderson9f577412007-07-31 17:43:14 +0000819
Chris Lattner3d7103e2008-03-21 21:14:38 +0000820 MD.removeInstruction(PN);
821 PN->replaceAllUsesWith(v);
822
823 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
824 E = Phis.end(); I != E; ++I)
825 if (I->second == PN)
826 I->second = v;
827
828 PN->eraseFromParent();
829
830 Phis[BB] = v;
831 return v;
Owen Anderson5d72a422007-07-25 19:57:03 +0000832}
833
Owen Andersone0143452007-08-16 22:02:55 +0000834/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
835/// non-local by performing PHI construction.
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000836bool GVN::processNonLocalLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000837 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson5d72a422007-07-25 19:57:03 +0000838 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
839
Owen Andersone0143452007-08-16 22:02:55 +0000840 // Find the non-local dependencies of the load
Owen Anderson5d72a422007-07-25 19:57:03 +0000841 DenseMap<BasicBlock*, Value*> deps;
Owen Anderson3f75d122007-08-01 22:01:54 +0000842 MD.getNonLocalDependency(L, deps);
Owen Anderson5d72a422007-07-25 19:57:03 +0000843
844 DenseMap<BasicBlock*, Value*> repl;
Owen Anderson5b299672007-08-07 23:12:31 +0000845
Owen Andersone0143452007-08-16 22:02:55 +0000846 // Filter out useless results (non-locals, etc)
Owen Anderson5d72a422007-07-25 19:57:03 +0000847 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
Chris Lattner3d7103e2008-03-21 21:14:38 +0000848 I != E; ++I) {
849 if (I->second == MemoryDependenceAnalysis::None)
Owen Anderson5d72a422007-07-25 19:57:03 +0000850 return false;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000851
852 if (I->second == MemoryDependenceAnalysis::NonLocal)
Owen Andersonb484d1f2007-07-30 17:29:24 +0000853 continue;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000854
855 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
856 if (S->getPointerOperand() != L->getPointerOperand())
Owen Anderson5d72a422007-07-25 19:57:03 +0000857 return false;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000858 repl[I->first] = S->getOperand(0);
Owen Anderson5d72a422007-07-25 19:57:03 +0000859 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000860 if (LD->getPointerOperand() != L->getPointerOperand())
Owen Anderson5d72a422007-07-25 19:57:03 +0000861 return false;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000862 repl[I->first] = LD;
Owen Anderson5d72a422007-07-25 19:57:03 +0000863 } else {
864 return false;
865 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000866 }
Owen Anderson5d72a422007-07-25 19:57:03 +0000867
Owen Andersone0143452007-08-16 22:02:55 +0000868 // Use cached PHI construction information from previous runs
Owen Anderson5b299672007-08-07 23:12:31 +0000869 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
870 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
871 I != E; ++I) {
872 if ((*I)->getParent() == L->getParent()) {
873 MD.removeInstruction(L);
874 L->replaceAllUsesWith(*I);
875 toErase.push_back(L);
876 NumGVNLoad++;
Owen Anderson5b299672007-08-07 23:12:31 +0000877 return true;
Owen Anderson5b299672007-08-07 23:12:31 +0000878 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000879
880 repl.insert(std::make_pair((*I)->getParent(), *I));
Owen Anderson5b299672007-08-07 23:12:31 +0000881 }
882
Owen Andersone0143452007-08-16 22:02:55 +0000883 // Perform PHI construction
Owen Anderson6ce3ae22007-07-25 22:03:06 +0000884 SmallPtrSet<BasicBlock*, 4> visited;
Owen Andersonc6a31b92007-08-02 17:56:05 +0000885 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
Owen Anderson5d72a422007-07-25 19:57:03 +0000886
887 MD.removeInstruction(L);
888 L->replaceAllUsesWith(v);
889 toErase.push_back(L);
Owen Anderson5b299672007-08-07 23:12:31 +0000890 NumGVNLoad++;
Owen Anderson5d72a422007-07-25 19:57:03 +0000891
892 return true;
893}
894
Owen Andersone0143452007-08-16 22:02:55 +0000895/// processLoad - Attempt to eliminate a load, first by eliminating it
896/// locally, and then attempting non-local elimination if that fails.
Chris Lattner7de20452008-03-21 22:01:16 +0000897bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
898 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson85c40642007-07-24 17:55:58 +0000899 if (L->isVolatile()) {
900 lastLoad[L->getPointerOperand()] = L;
901 return false;
902 }
903
904 Value* pointer = L->getPointerOperand();
905 LoadInst*& last = lastLoad[pointer];
906
907 // ... to a pointer that has been loaded from before...
908 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Andersoncc8b3a82007-08-14 17:59:48 +0000909 bool removedNonLocal = false;
Owen Anderson935e39b2007-08-09 04:42:44 +0000910 Instruction* dep = MD.getDependency(L);
Owen Anderson5d72a422007-07-25 19:57:03 +0000911 if (dep == MemoryDependenceAnalysis::NonLocal &&
Owen Andersoncc8b3a82007-08-14 17:59:48 +0000912 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
913 removedNonLocal = processNonLocalLoad(L, toErase);
914
915 if (!removedNonLocal)
916 last = L;
917
918 return removedNonLocal;
919 }
920
921
Owen Anderson85c40642007-07-24 17:55:58 +0000922 bool deletedLoad = false;
923
Owen Andersone0143452007-08-16 22:02:55 +0000924 // Walk up the dependency chain until we either find
925 // a dependency we can use, or we can't walk any further
Owen Anderson85c40642007-07-24 17:55:58 +0000926 while (dep != MemoryDependenceAnalysis::None &&
927 dep != MemoryDependenceAnalysis::NonLocal &&
928 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
929 // ... that depends on a store ...
930 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
931 if (S->getPointerOperand() == pointer) {
932 // Remove it!
933 MD.removeInstruction(L);
934
935 L->replaceAllUsesWith(S->getOperand(0));
936 toErase.push_back(L);
937 deletedLoad = true;
938 NumGVNLoad++;
939 }
940
941 // Whether we removed it or not, we can't
942 // go any further
943 break;
944 } else if (!last) {
945 // If we don't depend on a store, and we haven't
946 // been loaded before, bail.
947 break;
948 } else if (dep == last) {
949 // Remove it!
950 MD.removeInstruction(L);
951
952 L->replaceAllUsesWith(last);
953 toErase.push_back(L);
954 deletedLoad = true;
955 NumGVNLoad++;
956
957 break;
958 } else {
Owen Anderson935e39b2007-08-09 04:42:44 +0000959 dep = MD.getDependency(L, dep);
Owen Anderson85c40642007-07-24 17:55:58 +0000960 }
961 }
Eli Friedman350307f2008-02-12 12:08:14 +0000962
963 if (dep != MemoryDependenceAnalysis::None &&
964 dep != MemoryDependenceAnalysis::NonLocal &&
965 isa<AllocationInst>(dep)) {
966 // Check that this load is actually from the
967 // allocation we found
968 Value* v = L->getOperand(0);
969 while (true) {
970 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
971 v = BC->getOperand(0);
972 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
973 v = GEP->getOperand(0);
974 else
975 break;
976 }
977 if (v == dep) {
978 // If this load depends directly on an allocation, there isn't
979 // anything stored there; therefore, we can optimize this load
980 // to undef.
981 MD.removeInstruction(L);
982
983 L->replaceAllUsesWith(UndefValue::get(L->getType()));
984 toErase.push_back(L);
985 deletedLoad = true;
986 NumGVNLoad++;
987 }
988 }
989
Owen Anderson85c40642007-07-24 17:55:58 +0000990 if (!deletedLoad)
991 last = L;
992
993 return deletedLoad;
994}
995
Chris Lattner248ba4d2008-03-22 00:31:52 +0000996/// isBytewiseValue - If the specified value can be set by repeating the same
997/// byte in memory, return the i8 value that it is represented with. This is
998/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
999/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
1000/// byte store (e.g. i16 0x1234), return null.
1001static Value *isBytewiseValue(Value *V) {
1002 // All byte-wide stores are splatable, even of arbitrary variables.
1003 if (V->getType() == Type::Int8Ty) return V;
1004
1005 // Constant float and double values can be handled as integer values if the
1006 // corresponding integer value is "byteable". An important case is 0.0.
1007 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1008 if (CFP->getType() == Type::FloatTy)
1009 V = ConstantExpr::getBitCast(CFP, Type::Int32Ty);
1010 if (CFP->getType() == Type::DoubleTy)
1011 V = ConstantExpr::getBitCast(CFP, Type::Int64Ty);
1012 // Don't handle long double formats, which have strange constraints.
1013 }
1014
1015 // We can handle constant integers that are power of two in size and a
1016 // multiple of 8 bits.
1017 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1018 unsigned Width = CI->getBitWidth();
1019 if (isPowerOf2_32(Width) && Width > 8) {
1020 // We can handle this value if the recursive binary decomposition is the
1021 // same at all levels.
1022 APInt Val = CI->getValue();
1023 APInt Val2;
1024 while (Val.getBitWidth() != 8) {
1025 unsigned NextWidth = Val.getBitWidth()/2;
1026 Val2 = Val.lshr(NextWidth);
1027 Val2.trunc(Val.getBitWidth()/2);
1028 Val.trunc(Val.getBitWidth()/2);
1029
1030 // If the top/bottom halves aren't the same, reject it.
1031 if (Val != Val2)
1032 return 0;
1033 }
1034 return ConstantInt::get(Val);
1035 }
1036 }
1037
1038 // Conceptually, we could handle things like:
1039 // %a = zext i8 %X to i16
1040 // %b = shl i16 %a, 8
1041 // %c = or i16 %a, %b
1042 // but until there is an example that actually needs this, it doesn't seem
1043 // worth worrying about.
1044 return 0;
1045}
1046
Chris Lattner60b9cb42008-03-22 05:37:16 +00001047static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
1048 bool &VariableIdxFound, TargetData &TD) {
1049 // Skip over the first indices.
1050 gep_type_iterator GTI = gep_type_begin(GEP);
1051 for (unsigned i = 1; i != Idx; ++i, ++GTI)
1052 /*skip along*/;
1053
1054 // Compute the offset implied by the rest of the indices.
1055 int64_t Offset = 0;
1056 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
1057 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
1058 if (OpC == 0)
1059 return VariableIdxFound = true;
1060 if (OpC->isZero()) continue; // No offset.
1061
1062 // Handle struct indices, which add their field offset to the pointer.
1063 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1064 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1065 continue;
1066 }
1067
1068 // Otherwise, we have a sequential type like an array or vector. Multiply
1069 // the index by the ElementSize.
1070 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
1071 Offset += Size*OpC->getSExtValue();
1072 }
1073
1074 return Offset;
1075}
1076
Chris Lattner248ba4d2008-03-22 00:31:52 +00001077/// IsPointerAtOffset - Return true if Ptr1 is exactly provably equal to Ptr2
1078/// plus the specified constant offset. For example, Ptr1 might be &A[42], and
1079/// Ptr2 might be &A[40] and Offset might be 8.
Chris Lattner60b9cb42008-03-22 05:37:16 +00001080static bool IsPointerAtOffset(Value *Ptr1, Value *Ptr2, uint64_t Offset,
1081 TargetData &TD) {
1082 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
1083 // base. After that base, they may have some number of common (and
1084 // potentially variable) indices. After that they handle some constant
1085 // offset, which determines their offset from each other. At this point, we
1086 // handle no other case.
1087 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
1088 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
1089 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
1090 return false;
1091
1092 // Skip any common indices and track the GEP types.
1093 unsigned Idx = 1;
1094 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
1095 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
1096 break;
1097
1098 bool VariableIdxFound = false;
1099 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
1100 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
1101 if (VariableIdxFound) return false;
1102
1103 return Offset1 == Offset2+(int64_t)Offset;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001104}
1105
1106
1107/// processStore - When GVN is scanning forward over instructions, we look for
1108/// some other patterns to fold away. In particular, this looks for stores to
1109/// neighboring locations of memory. If it sees enough consequtive ones
1110/// (currently 4) it attempts to merge them together into a memcpy/memset.
1111bool GVN::processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase) {
Evan Chenge856f8e2008-03-24 05:28:38 +00001112 if (!FormMemSet) return false;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001113 if (SI->isVolatile()) return false;
1114
1115 // There are two cases that are interesting for this code to handle: memcpy
1116 // and memset. Right now we only handle memset.
1117
1118 // Ensure that the value being stored is something that can be memset'able a
1119 // byte at a time like "0" or "-1" or any width, as well as things like
1120 // 0xA0A0A0A0 and 0.0.
1121 Value *ByteVal = isBytewiseValue(SI->getOperand(0));
1122 if (!ByteVal)
1123 return false;
1124
1125 TargetData &TD = getAnalysis<TargetData>();
1126 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
1127
1128 // Okay, so we now have a single store that can be splatable. Try to 'grow'
1129 // this store by looking for neighboring stores to the immediate left or right
1130 // of the store we have so far. While we could in theory handle stores in
1131 // this order: A[0], A[2], A[1]
1132 // in practice, right now we only worry about cases where stores are
1133 // consequtive in increasing or decreasing address order.
1134 uint64_t BytesSoFar = TD.getTypeStoreSize(SI->getOperand(0)->getType());
Chris Lattner1be83222008-03-22 04:13:49 +00001135 uint64_t BytesFromSI = 0;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001136 unsigned StartAlign = SI->getAlignment();
1137 Value *StartPtr = SI->getPointerOperand();
1138 SmallVector<StoreInst*, 16> Stores;
1139 Stores.push_back(SI);
1140
Chris Lattner60b9cb42008-03-22 05:37:16 +00001141 BasicBlock::iterator BI = SI;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001142 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
1143 if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
1144 // If the call is readnone, ignore it, otherwise bail out. We don't even
1145 // allow readonly here because we don't want something like:
1146 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
1147 if (AA.getModRefBehavior(CallSite::get(BI)) ==
1148 AliasAnalysis::DoesNotAccessMemory)
1149 continue;
Chris Lattner1be83222008-03-22 04:13:49 +00001150
1151 // TODO: If this is a memset, try to join it in.
1152
Chris Lattner248ba4d2008-03-22 00:31:52 +00001153 break;
1154 } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
1155 break;
1156
1157 // If this is a non-store instruction it is fine, ignore it.
1158 StoreInst *NextStore = dyn_cast<StoreInst>(BI);
1159 if (NextStore == 0) continue;
1160
1161 // If this is a store, see if we can merge it in.
1162 if (NextStore->isVolatile()) break;
1163
1164 // Check to see if this stored value is of the same byte-splattable value.
1165 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
1166 break;
1167
1168 Value *ThisPointer = NextStore->getPointerOperand();
1169 unsigned AccessSize = TD.getTypeStoreSize(SI->getOperand(0)->getType());
1170
1171 // If so, check to see if the store is before the current range or after it
1172 // in either case, extend the range, otherwise reject it.
Chris Lattner60b9cb42008-03-22 05:37:16 +00001173 if (IsPointerAtOffset(ThisPointer, StartPtr, BytesSoFar, TD)) {
Chris Lattner248ba4d2008-03-22 00:31:52 +00001174 // Okay, this extends the stored area on the end, just add to the bytes
1175 // so far and remember this store.
1176 BytesSoFar += AccessSize;
Chris Lattner1be83222008-03-22 04:13:49 +00001177 Stores.push_back(NextStore);
Chris Lattner248ba4d2008-03-22 00:31:52 +00001178 continue;
1179 }
1180
Chris Lattner60b9cb42008-03-22 05:37:16 +00001181 if (IsPointerAtOffset(StartPtr, ThisPointer, AccessSize, TD)) {
Chris Lattner248ba4d2008-03-22 00:31:52 +00001182 // Okay, the store is before the current range. Reset our start pointer
1183 // and get new alignment info etc.
Chris Lattner1be83222008-03-22 04:13:49 +00001184 BytesSoFar += AccessSize;
1185 BytesFromSI += AccessSize;
1186 Stores.push_back(NextStore);
Chris Lattner248ba4d2008-03-22 00:31:52 +00001187 StartPtr = ThisPointer;
1188 StartAlign = NextStore->getAlignment();
1189 continue;
1190 }
1191
1192 // Otherwise, this store wasn't contiguous with our current range, bail out.
1193 break;
1194 }
1195
1196 // If we found less than 4 stores to merge, bail out, it isn't worth losing
1197 // type information in llvm IR to do the transformation.
1198 if (Stores.size() < 4)
1199 return false;
1200
Chris Lattner1be83222008-03-22 04:13:49 +00001201 // Otherwise, we do want to transform this! Create a new memset. We put the
1202 // memset right after the first store that we found in this block. This
1203 // ensures that the caller will increment the iterator to the memset before
1204 // it deletes all the stores.
1205 BasicBlock::iterator InsertPt = SI; ++InsertPt;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001206
Chris Lattner1be83222008-03-22 04:13:49 +00001207 Function *F = Intrinsic::getDeclaration(SI->getParent()->getParent()
1208 ->getParent(), Intrinsic::memset_i64);
1209
1210 // StartPtr may not dominate the starting point. Instead of using it, base
1211 // the destination pointer off the input to the first store in the block.
1212 StartPtr = SI->getPointerOperand();
1213
1214 // Cast the start ptr to be i8* as memset requires.
1215 const Type *i8Ptr = PointerType::getUnqual(Type::Int8Ty);
1216 if (StartPtr->getType() != i8Ptr)
1217 StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getNameStart(),
1218 InsertPt);
1219
1220 // Offset the pointer if needed.
1221 if (BytesFromSI)
1222 StartPtr = new GetElementPtrInst(StartPtr, ConstantInt::get(Type::Int64Ty,
1223 -BytesFromSI),
1224 "ptroffset", InsertPt);
1225
1226 Value *Ops[] = {
1227 StartPtr, ByteVal, // Start, value
1228 ConstantInt::get(Type::Int64Ty, BytesSoFar), // size
1229 ConstantInt::get(Type::Int32Ty, StartAlign) // align
1230 };
1231 new CallInst(F, Ops, Ops+4, "", InsertPt);
1232
Chris Lattner60b9cb42008-03-22 05:37:16 +00001233 // Zap all the stores.
Chris Lattner1be83222008-03-22 04:13:49 +00001234 toErase.append(Stores.begin(), Stores.end());
1235
1236 ++NumMemSetInfer;
1237 return true;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001238}
1239
1240
Owen Andersone41ab4c2008-03-12 07:37:44 +00001241/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
1242/// and checks for the possibility of a call slot optimization by having
1243/// the call write its result directly into the destination of the memcpy.
Chris Lattner7de20452008-03-21 22:01:16 +00001244bool GVN::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C,
1245 SmallVectorImpl<Instruction*> &toErase) {
Owen Andersone41ab4c2008-03-12 07:37:44 +00001246 // The general transformation to keep in mind is
1247 //
1248 // call @func(..., src, ...)
1249 // memcpy(dest, src, ...)
1250 //
1251 // ->
1252 //
1253 // memcpy(dest, src, ...)
1254 // call @func(..., dest, ...)
1255 //
1256 // Since moving the memcpy is technically awkward, we additionally check that
1257 // src only holds uninitialized values at the moment of the call, meaning that
1258 // the memcpy can be discarded rather than moved.
Owen Anderson556d0e52008-02-19 03:27:34 +00001259
Owen Anderson364b1eb2008-02-19 07:07:51 +00001260 // Deliberately get the source and destination with bitcasts stripped away,
1261 // because we'll need to do type comparisons based on the underlying type.
Owen Anderson282dd322008-02-18 09:24:53 +00001262 Value* cpyDest = cpy->getDest();
Owen Anderson29f73562008-02-19 06:35:43 +00001263 Value* cpySrc = cpy->getSource();
1264 CallSite CS = CallSite::get(C);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001265
1266 // We need to be able to reason about the size of the memcpy, so we require
1267 // that it be a constant.
1268 ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
1269 if (!cpyLength)
Owen Anderson282dd322008-02-18 09:24:53 +00001270 return false;
Owen Andersone41ab4c2008-03-12 07:37:44 +00001271
1272 // Require that src be an alloca. This simplifies the reasoning considerably.
1273 AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
1274 if (!srcAlloca)
1275 return false;
1276
1277 // Check that all of src is copied to dest.
1278 TargetData& TD = getAnalysis<TargetData>();
1279
1280 ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
1281 if (!srcArraySize)
1282 return false;
1283
1284 uint64_t srcSize = TD.getABITypeSize(srcAlloca->getAllocatedType()) *
1285 srcArraySize->getZExtValue();
1286
1287 if (cpyLength->getZExtValue() < srcSize)
1288 return false;
1289
1290 // Check that accessing the first srcSize bytes of dest will not cause a
1291 // trap. Otherwise the transform is invalid since it might cause a trap
1292 // to occur earlier than it otherwise would.
1293 if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
1294 // The destination is an alloca. Check it is larger than srcSize.
1295 ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
1296 if (!destArraySize)
1297 return false;
1298
1299 uint64_t destSize = TD.getABITypeSize(A->getAllocatedType()) *
1300 destArraySize->getZExtValue();
1301
1302 if (destSize < srcSize)
1303 return false;
1304 } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
1305 // If the destination is an sret parameter then only accesses that are
1306 // outside of the returned struct type can trap.
1307 if (!A->hasStructRetAttr())
1308 return false;
1309
1310 const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
1311 uint64_t destSize = TD.getABITypeSize(StructTy);
1312
1313 if (destSize < srcSize)
1314 return false;
1315 } else {
1316 return false;
1317 }
1318
1319 // Check that src is not accessed except via the call and the memcpy. This
1320 // guarantees that it holds only undefined values when passed in (so the final
1321 // memcpy can be dropped), that it is not read or written between the call and
1322 // the memcpy, and that writing beyond the end of it is undefined.
Owen Andersone41ab4c2008-03-12 07:37:44 +00001323 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
1324 srcAlloca->use_end());
1325 while (!srcUseList.empty()) {
1326 User* UI = srcUseList.back();
1327 srcUseList.pop_back();
1328
1329 if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
1330 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
1331 I != E; ++I)
1332 srcUseList.push_back(*I);
1333 } else if (UI != C && UI != cpy) {
1334 return false;
1335 }
1336 }
1337
Owen Anderson05744bd2008-02-25 00:40:41 +00001338 // Since we're changing the parameter to the callsite, we need to make sure
1339 // that what would be the new parameter dominates the callsite.
1340 DominatorTree& DT = getAnalysis<DominatorTree>();
1341 if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
1342 if (!DT.dominates(cpyDestInst, C))
1343 return false;
Owen Andersone41ab4c2008-03-12 07:37:44 +00001344
1345 // In addition to knowing that the call does not access src in some
1346 // unexpected manner, for example via a global, which we deduce from
1347 // the use analysis, we also need to know that it does not sneakily
1348 // access dest. We rely on AA to figure this out for us.
Owen Anderson29f73562008-02-19 06:35:43 +00001349 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
Owen Andersone41ab4c2008-03-12 07:37:44 +00001350 if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
Owen Anderson29f73562008-02-19 06:35:43 +00001351 AliasAnalysis::NoModRef)
1352 return false;
Owen Andersone41ab4c2008-03-12 07:37:44 +00001353
1354 // All the checks have passed, so do the transformation.
1355 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson78a334f2008-03-13 22:07:10 +00001356 if (CS.getArgument(i) == cpySrc) {
1357 if (cpySrc->getType() != cpyDest->getType())
1358 cpyDest = CastInst::createPointerCast(cpyDest, cpySrc->getType(),
1359 cpyDest->getName(), C);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001360 CS.setArgument(i, cpyDest);
Owen Anderson78a334f2008-03-13 22:07:10 +00001361 }
Owen Andersone41ab4c2008-03-12 07:37:44 +00001362
Owen Anderson29f73562008-02-19 06:35:43 +00001363 // Drop any cached information about the call, because we may have changed
1364 // its dependence information by changing its parameter.
Owen Anderson282dd322008-02-18 09:24:53 +00001365 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1366 MD.dropInstruction(C);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001367
Owen Anderson282dd322008-02-18 09:24:53 +00001368 // Remove the memcpy
Owen Andersonff8e2d32008-02-20 08:23:02 +00001369 MD.removeInstruction(cpy);
Owen Anderson282dd322008-02-18 09:24:53 +00001370 toErase.push_back(cpy);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001371
Owen Anderson282dd322008-02-18 09:24:53 +00001372 return true;
1373}
1374
Owen Anderson8d272d52008-02-12 21:15:18 +00001375/// processMemCpy - perform simplication of memcpy's. If we have memcpy A which
1376/// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1377/// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1378/// This allows later passes to remove the first memcpy altogether.
Owen Andersonba958332008-02-19 03:09:45 +00001379bool GVN::processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
Chris Lattner7de20452008-03-21 22:01:16 +00001380 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson8d272d52008-02-12 21:15:18 +00001381 // We can only transforms memcpy's where the dest of one is the source of the
1382 // other
Owen Anderson8d272d52008-02-12 21:15:18 +00001383 if (M->getSource() != MDep->getDest())
1384 return false;
1385
1386 // Second, the length of the memcpy's must be the same, or the preceeding one
1387 // must be larger than the following one.
1388 ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1389 ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1390 if (!C1 || !C2)
1391 return false;
1392
Owen Andersonc318b562008-02-26 23:06:17 +00001393 uint64_t DepSize = C1->getValue().getZExtValue();
1394 uint64_t CpySize = C2->getValue().getZExtValue();
Owen Anderson8d272d52008-02-12 21:15:18 +00001395
1396 if (DepSize < CpySize)
1397 return false;
1398
1399 // Finally, we have to make sure that the dest of the second does not
1400 // alias the source of the first
1401 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1402 if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1403 AliasAnalysis::NoAlias)
1404 return false;
1405 else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1406 AliasAnalysis::NoAlias)
1407 return false;
1408 else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1409 != AliasAnalysis::NoAlias)
1410 return false;
1411
1412 // If all checks passed, then we can transform these memcpy's
Owen Andersonba958332008-02-19 03:09:45 +00001413 Function* MemCpyFun = Intrinsic::getDeclaration(
Owen Anderson8d272d52008-02-12 21:15:18 +00001414 M->getParent()->getParent()->getParent(),
Owen Andersonba958332008-02-19 03:09:45 +00001415 M->getIntrinsicID());
Owen Anderson8d272d52008-02-12 21:15:18 +00001416
1417 std::vector<Value*> args;
1418 args.push_back(M->getRawDest());
1419 args.push_back(MDep->getRawSource());
1420 args.push_back(M->getLength());
1421 args.push_back(M->getAlignment());
1422
Owen Andersonba958332008-02-19 03:09:45 +00001423 CallInst* C = new CallInst(MemCpyFun, args.begin(), args.end(), "", M);
Owen Anderson8d272d52008-02-12 21:15:18 +00001424
Owen Andersonba958332008-02-19 03:09:45 +00001425 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Anderson8d272d52008-02-12 21:15:18 +00001426 if (MD.getDependency(C) == MDep) {
1427 MD.dropInstruction(M);
1428 toErase.push_back(M);
1429 return true;
Owen Anderson8d272d52008-02-12 21:15:18 +00001430 }
Chris Lattner3d7103e2008-03-21 21:14:38 +00001431
1432 MD.removeInstruction(C);
1433 toErase.push_back(C);
1434 return false;
Owen Anderson8d272d52008-02-12 21:15:18 +00001435}
1436
Owen Andersonf631bb62007-08-14 18:16:29 +00001437/// processInstruction - When calculating availability, handle an instruction
Owen Anderson85c40642007-07-24 17:55:58 +00001438/// by inserting it into the appropriate sets
Chris Lattner7de20452008-03-21 22:01:16 +00001439bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
1440 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1441 SmallVectorImpl<Instruction*> &toErase) {
1442 if (LoadInst* L = dyn_cast<LoadInst>(I))
Owen Anderson85c40642007-07-24 17:55:58 +00001443 return processLoad(L, lastSeenLoad, toErase);
Chris Lattner7de20452008-03-21 22:01:16 +00001444
Chris Lattner248ba4d2008-03-22 00:31:52 +00001445 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1446 return processStore(SI, toErase);
1447
Chris Lattner7de20452008-03-21 22:01:16 +00001448 if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
Owen Andersonba958332008-02-19 03:09:45 +00001449 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1450
1451 // The are two possible optimizations we can do for memcpy:
1452 // a) memcpy-memcpy xform which exposes redundance for DSE
Owen Andersone41ab4c2008-03-12 07:37:44 +00001453 // b) call-memcpy xform for return slot optimization
Owen Andersonba958332008-02-19 03:09:45 +00001454 Instruction* dep = MD.getDependency(M);
1455 if (dep == MemoryDependenceAnalysis::None ||
1456 dep == MemoryDependenceAnalysis::NonLocal)
1457 return false;
Chris Lattnerfd18dcd2008-02-19 06:53:20 +00001458 if (MemCpyInst *MemCpy = dyn_cast<MemCpyInst>(dep))
1459 return processMemCpy(M, MemCpy, toErase);
Chris Lattner8bc7a0d2008-02-19 06:52:38 +00001460 if (CallInst* C = dyn_cast<CallInst>(dep))
Owen Andersone41ab4c2008-03-12 07:37:44 +00001461 return performCallSlotOptzn(M, C, toErase);
Chris Lattner8bc7a0d2008-02-19 06:52:38 +00001462 return false;
Owen Anderson85c40642007-07-24 17:55:58 +00001463 }
1464
1465 unsigned num = VN.lookup_or_add(I);
1466
Owen Andersone0143452007-08-16 22:02:55 +00001467 // Collapse PHI nodes
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001468 if (PHINode* p = dyn_cast<PHINode>(I)) {
Owen Andersone02ad522007-08-16 22:51:56 +00001469 Value* constVal = CollapsePhi(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001470
1471 if (constVal) {
Owen Andersone02ad522007-08-16 22:51:56 +00001472 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1473 PI != PE; ++PI)
1474 if (PI->second.count(p))
1475 PI->second.erase(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001476
Owen Andersone02ad522007-08-16 22:51:56 +00001477 p->replaceAllUsesWith(constVal);
1478 toErase.push_back(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001479 }
Owen Andersone0143452007-08-16 22:02:55 +00001480 // Perform value-number based elimination
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001481 } else if (currAvail.test(num)) {
Owen Anderson85c40642007-07-24 17:55:58 +00001482 Value* repl = find_leader(currAvail, num);
1483
Owen Anderson8b6f04e2007-11-26 02:26:36 +00001484 if (CallInst* CI = dyn_cast<CallInst>(I)) {
1485 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
Duncan Sands00b24b52007-12-01 07:51:45 +00001486 if (!AA.doesNotAccessMemory(CI)) {
Owen Anderson8b6f04e2007-11-26 02:26:36 +00001487 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Andersonfb3f6f22007-11-29 18:02:22 +00001488 if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1489 MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
Owen Anderson8b6f04e2007-11-26 02:26:36 +00001490 // There must be an intervening may-alias store, so nothing from
1491 // this point on will be able to be replaced with the preceding call
1492 currAvail.erase(repl);
1493 currAvail.insert(I);
1494
1495 return false;
1496 }
1497 }
1498 }
1499
Owen Andersonc772be72007-12-08 01:37:09 +00001500 // Remove it!
1501 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1502 MD.removeInstruction(I);
1503
Owen Anderson5aff8002007-07-31 23:27:13 +00001504 VN.erase(I);
Owen Anderson85c40642007-07-24 17:55:58 +00001505 I->replaceAllUsesWith(repl);
1506 toErase.push_back(I);
1507 return true;
1508 } else if (!I->isTerminator()) {
1509 currAvail.set(num);
1510 currAvail.insert(I);
1511 }
1512
1513 return false;
1514}
1515
1516// GVN::runOnFunction - This is the main transformation entry point for a
1517// function.
1518//
Owen Andersonbe168b32007-08-14 18:04:11 +00001519bool GVN::runOnFunction(Function& F) {
Owen Anderson5e9366f2007-10-18 19:39:33 +00001520 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1521
Owen Andersonbe168b32007-08-14 18:04:11 +00001522 bool changed = false;
1523 bool shouldContinue = true;
1524
1525 while (shouldContinue) {
1526 shouldContinue = iterateOnFunction(F);
1527 changed |= shouldContinue;
1528 }
1529
1530 return changed;
1531}
1532
1533
1534// GVN::iterateOnFunction - Executes one iteration of GVN
1535bool GVN::iterateOnFunction(Function &F) {
Owen Anderson85c40642007-07-24 17:55:58 +00001536 // Clean out global sets from any previous functions
1537 VN.clear();
1538 availableOut.clear();
Owen Anderson5b299672007-08-07 23:12:31 +00001539 phiMap.clear();
Owen Anderson85c40642007-07-24 17:55:58 +00001540
1541 bool changed_function = false;
1542
1543 DominatorTree &DT = getAnalysis<DominatorTree>();
1544
1545 SmallVector<Instruction*, 4> toErase;
Chris Lattner98054902008-03-21 21:33:23 +00001546 DenseMap<Value*, LoadInst*> lastSeenLoad;
1547
Owen Anderson85c40642007-07-24 17:55:58 +00001548 // Top-down walk of the dominator tree
1549 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1550 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1551
1552 // Get the set to update for this block
1553 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
Chris Lattner98054902008-03-21 21:33:23 +00001554 lastSeenLoad.clear();
1555
Owen Anderson85c40642007-07-24 17:55:58 +00001556 BasicBlock* BB = DI->getBlock();
1557
1558 // A block inherits AVAIL_OUT from its dominator
1559 if (DI->getIDom() != 0)
1560 currAvail = availableOut[DI->getIDom()->getBlock()];
1561
1562 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
Owen Andersonc0403802007-07-30 21:26:39 +00001563 BI != BE; ) {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +00001564 changed_function |= processInstruction(BI, currAvail,
1565 lastSeenLoad, toErase);
Owen Anderson5d72a422007-07-25 19:57:03 +00001566
1567 NumGVNInstr += toErase.size();
1568
Owen Andersonc0403802007-07-30 21:26:39 +00001569 // Avoid iterator invalidation
1570 ++BI;
Owen Andersonc772be72007-12-08 01:37:09 +00001571
Owen Anderson5d72a422007-07-25 19:57:03 +00001572 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
Chris Lattner3d7103e2008-03-21 21:14:38 +00001573 E = toErase.end(); I != E; ++I)
Owen Anderson5d72a422007-07-25 19:57:03 +00001574 (*I)->eraseFromParent();
Owen Andersonc772be72007-12-08 01:37:09 +00001575
Owen Anderson5d72a422007-07-25 19:57:03 +00001576 toErase.clear();
Owen Anderson85c40642007-07-24 17:55:58 +00001577 }
1578 }
1579
Owen Anderson85c40642007-07-24 17:55:58 +00001580 return changed_function;
1581}