blob: ba6e361ecbbec73b3e3e6268e7b3931bcc0da408 [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"
Chris Lattner49650d62008-03-28 06:45:13 +000039#include <list>
Owen Anderson85c40642007-07-24 17:55:58 +000040using namespace llvm;
41
Chris Lattner1be83222008-03-22 04:13:49 +000042STATISTIC(NumGVNInstr, "Number of instructions deleted");
43STATISTIC(NumGVNLoad, "Number of loads deleted");
44STATISTIC(NumMemSetInfer, "Number of memsets inferred");
45
Evan Chenge856f8e2008-03-24 05:28:38 +000046namespace {
47 cl::opt<bool>
48 FormMemSet("form-memset-from-stores",
49 cl::desc("Transform straight-line stores to memsets"),
50 cl::init(false), cl::Hidden);
51}
Chris Lattner1be83222008-03-22 04:13:49 +000052
Owen Anderson85c40642007-07-24 17:55:58 +000053//===----------------------------------------------------------------------===//
54// ValueTable Class
55//===----------------------------------------------------------------------===//
56
57/// This class holds the mapping between values and value numbers. It is used
58/// as an efficient mechanism to determine the expression-wise equivalence of
59/// two values.
60namespace {
61 struct VISIBILITY_HIDDEN Expression {
62 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
63 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
64 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
65 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
66 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
67 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
68 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
69 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
70 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
Owen Anderson5e9366f2007-10-18 19:39:33 +000071 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
Owen Anderson85c40642007-07-24 17:55:58 +000072 TOMBSTONE };
73
74 ExpressionOpcode opcode;
75 const Type* type;
76 uint32_t firstVN;
77 uint32_t secondVN;
78 uint32_t thirdVN;
79 SmallVector<uint32_t, 4> varargs;
Owen Anderson5e9366f2007-10-18 19:39:33 +000080 Value* function;
Owen Anderson85c40642007-07-24 17:55:58 +000081
82 Expression() { }
83 Expression(ExpressionOpcode o) : opcode(o) { }
84
85 bool operator==(const Expression &other) const {
86 if (opcode != other.opcode)
87 return false;
88 else if (opcode == EMPTY || opcode == TOMBSTONE)
89 return true;
90 else if (type != other.type)
91 return false;
Owen Anderson5e9366f2007-10-18 19:39:33 +000092 else if (function != other.function)
93 return false;
Owen Anderson85c40642007-07-24 17:55:58 +000094 else if (firstVN != other.firstVN)
95 return false;
96 else if (secondVN != other.secondVN)
97 return false;
98 else if (thirdVN != other.thirdVN)
99 return false;
100 else {
101 if (varargs.size() != other.varargs.size())
102 return false;
103
104 for (size_t i = 0; i < varargs.size(); ++i)
105 if (varargs[i] != other.varargs[i])
106 return false;
107
108 return true;
109 }
110 }
111
112 bool operator!=(const Expression &other) const {
113 if (opcode != other.opcode)
114 return true;
115 else if (opcode == EMPTY || opcode == TOMBSTONE)
116 return false;
117 else if (type != other.type)
118 return true;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000119 else if (function != other.function)
120 return true;
Owen Anderson85c40642007-07-24 17:55:58 +0000121 else if (firstVN != other.firstVN)
122 return true;
123 else if (secondVN != other.secondVN)
124 return true;
125 else if (thirdVN != other.thirdVN)
126 return true;
127 else {
128 if (varargs.size() != other.varargs.size())
129 return true;
130
131 for (size_t i = 0; i < varargs.size(); ++i)
132 if (varargs[i] != other.varargs[i])
133 return true;
134
135 return false;
136 }
137 }
138 };
139
140 class VISIBILITY_HIDDEN ValueTable {
141 private:
142 DenseMap<Value*, uint32_t> valueNumbering;
143 DenseMap<Expression, uint32_t> expressionNumbering;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000144 AliasAnalysis* AA;
Owen Anderson85c40642007-07-24 17:55:58 +0000145
146 uint32_t nextValueNumber;
147
148 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
149 Expression::ExpressionOpcode getOpcode(CmpInst* C);
150 Expression::ExpressionOpcode getOpcode(CastInst* C);
151 Expression create_expression(BinaryOperator* BO);
152 Expression create_expression(CmpInst* C);
153 Expression create_expression(ShuffleVectorInst* V);
154 Expression create_expression(ExtractElementInst* C);
155 Expression create_expression(InsertElementInst* V);
156 Expression create_expression(SelectInst* V);
157 Expression create_expression(CastInst* C);
158 Expression create_expression(GetElementPtrInst* G);
Owen Anderson5e9366f2007-10-18 19:39:33 +0000159 Expression create_expression(CallInst* C);
Owen Anderson85c40642007-07-24 17:55:58 +0000160 public:
Owen Anderson5e9366f2007-10-18 19:39:33 +0000161 ValueTable() : nextValueNumber(1) { }
Owen Anderson85c40642007-07-24 17:55:58 +0000162 uint32_t lookup_or_add(Value* V);
163 uint32_t lookup(Value* V) const;
164 void add(Value* V, uint32_t num);
165 void clear();
166 void erase(Value* v);
167 unsigned size();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000168 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
Owen Anderson343797c2007-11-26 07:17:19 +0000169 uint32_t hash_operand(Value* v);
Owen Anderson85c40642007-07-24 17:55:58 +0000170 };
171}
172
173namespace llvm {
Chris Lattner92eea072007-09-17 18:34:04 +0000174template <> struct DenseMapInfo<Expression> {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000175 static inline Expression getEmptyKey() {
176 return Expression(Expression::EMPTY);
177 }
178
179 static inline Expression getTombstoneKey() {
180 return Expression(Expression::TOMBSTONE);
181 }
Owen Anderson85c40642007-07-24 17:55:58 +0000182
183 static unsigned getHashValue(const Expression e) {
184 unsigned hash = e.opcode;
185
186 hash = e.firstVN + hash * 37;
187 hash = e.secondVN + hash * 37;
188 hash = e.thirdVN + hash * 37;
189
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000190 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
191 (unsigned)((uintptr_t)e.type >> 9)) +
192 hash * 37;
Owen Anderson85c40642007-07-24 17:55:58 +0000193
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000194 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
195 E = e.varargs.end(); I != E; ++I)
Owen Anderson85c40642007-07-24 17:55:58 +0000196 hash = *I + hash * 37;
197
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000198 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
199 (unsigned)((uintptr_t)e.function >> 9)) +
200 hash * 37;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000201
Owen Anderson85c40642007-07-24 17:55:58 +0000202 return hash;
203 }
Chris Lattner92eea072007-09-17 18:34:04 +0000204 static bool isEqual(const Expression &LHS, const Expression &RHS) {
205 return LHS == RHS;
206 }
Owen Anderson85c40642007-07-24 17:55:58 +0000207 static bool isPod() { return true; }
208};
209}
210
211//===----------------------------------------------------------------------===//
212// ValueTable Internal Functions
213//===----------------------------------------------------------------------===//
Chris Lattner3d7103e2008-03-21 21:14:38 +0000214Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
Owen Anderson85c40642007-07-24 17:55:58 +0000215 switch(BO->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000216 default: // THIS SHOULD NEVER HAPPEN
217 assert(0 && "Binary operator with unknown opcode?");
218 case Instruction::Add: return Expression::ADD;
219 case Instruction::Sub: return Expression::SUB;
220 case Instruction::Mul: return Expression::MUL;
221 case Instruction::UDiv: return Expression::UDIV;
222 case Instruction::SDiv: return Expression::SDIV;
223 case Instruction::FDiv: return Expression::FDIV;
224 case Instruction::URem: return Expression::UREM;
225 case Instruction::SRem: return Expression::SREM;
226 case Instruction::FRem: return Expression::FREM;
227 case Instruction::Shl: return Expression::SHL;
228 case Instruction::LShr: return Expression::LSHR;
229 case Instruction::AShr: return Expression::ASHR;
230 case Instruction::And: return Expression::AND;
231 case Instruction::Or: return Expression::OR;
232 case Instruction::Xor: return Expression::XOR;
Owen Anderson85c40642007-07-24 17:55:58 +0000233 }
234}
235
236Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000237 if (isa<ICmpInst>(C)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000238 switch (C->getPredicate()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000239 default: // THIS SHOULD NEVER HAPPEN
240 assert(0 && "Comparison with unknown predicate?");
241 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
242 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
243 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
244 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
245 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
246 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
247 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
248 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
249 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
250 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
Owen Anderson85c40642007-07-24 17:55:58 +0000251 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000252 }
253 assert(isa<FCmpInst>(C) && "Unknown compare");
254 switch (C->getPredicate()) {
255 default: // THIS SHOULD NEVER HAPPEN
256 assert(0 && "Comparison with unknown predicate?");
257 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
258 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
259 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
260 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
261 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
262 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
263 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
264 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
265 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
266 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
267 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
268 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
269 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
270 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
Owen Anderson85c40642007-07-24 17:55:58 +0000271 }
272}
273
Chris Lattner3d7103e2008-03-21 21:14:38 +0000274Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
Owen Anderson85c40642007-07-24 17:55:58 +0000275 switch(C->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000276 default: // THIS SHOULD NEVER HAPPEN
277 assert(0 && "Cast operator with unknown opcode?");
278 case Instruction::Trunc: return Expression::TRUNC;
279 case Instruction::ZExt: return Expression::ZEXT;
280 case Instruction::SExt: return Expression::SEXT;
281 case Instruction::FPToUI: return Expression::FPTOUI;
282 case Instruction::FPToSI: return Expression::FPTOSI;
283 case Instruction::UIToFP: return Expression::UITOFP;
284 case Instruction::SIToFP: return Expression::SITOFP;
285 case Instruction::FPTrunc: return Expression::FPTRUNC;
286 case Instruction::FPExt: return Expression::FPEXT;
287 case Instruction::PtrToInt: return Expression::PTRTOINT;
288 case Instruction::IntToPtr: return Expression::INTTOPTR;
289 case Instruction::BitCast: return Expression::BITCAST;
Owen Anderson85c40642007-07-24 17:55:58 +0000290 }
291}
292
Owen Anderson343797c2007-11-26 07:17:19 +0000293uint32_t ValueTable::hash_operand(Value* v) {
294 if (CallInst* CI = dyn_cast<CallInst>(v))
Duncan Sands00b24b52007-12-01 07:51:45 +0000295 if (!AA->doesNotAccessMemory(CI))
Owen Anderson343797c2007-11-26 07:17:19 +0000296 return nextValueNumber++;
297
298 return lookup_or_add(v);
299}
300
Owen Anderson5e9366f2007-10-18 19:39:33 +0000301Expression ValueTable::create_expression(CallInst* C) {
302 Expression e;
303
304 e.type = C->getType();
305 e.firstVN = 0;
306 e.secondVN = 0;
307 e.thirdVN = 0;
308 e.function = C->getCalledFunction();
309 e.opcode = Expression::CALL;
310
311 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
312 I != E; ++I)
Owen Anderson343797c2007-11-26 07:17:19 +0000313 e.varargs.push_back(hash_operand(*I));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000314
315 return e;
316}
317
Owen Anderson85c40642007-07-24 17:55:58 +0000318Expression ValueTable::create_expression(BinaryOperator* BO) {
319 Expression e;
320
Owen Anderson343797c2007-11-26 07:17:19 +0000321 e.firstVN = hash_operand(BO->getOperand(0));
322 e.secondVN = hash_operand(BO->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000323 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000324 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000325 e.type = BO->getType();
326 e.opcode = getOpcode(BO);
327
328 return e;
329}
330
331Expression ValueTable::create_expression(CmpInst* C) {
332 Expression e;
333
Owen Anderson343797c2007-11-26 07:17:19 +0000334 e.firstVN = hash_operand(C->getOperand(0));
335 e.secondVN = hash_operand(C->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000336 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000337 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000338 e.type = C->getType();
339 e.opcode = getOpcode(C);
340
341 return e;
342}
343
344Expression ValueTable::create_expression(CastInst* C) {
345 Expression e;
346
Owen Anderson343797c2007-11-26 07:17:19 +0000347 e.firstVN = hash_operand(C->getOperand(0));
Owen Anderson85c40642007-07-24 17:55:58 +0000348 e.secondVN = 0;
349 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000350 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000351 e.type = C->getType();
352 e.opcode = getOpcode(C);
353
354 return e;
355}
356
357Expression ValueTable::create_expression(ShuffleVectorInst* S) {
358 Expression e;
359
Owen Anderson343797c2007-11-26 07:17:19 +0000360 e.firstVN = hash_operand(S->getOperand(0));
361 e.secondVN = hash_operand(S->getOperand(1));
362 e.thirdVN = hash_operand(S->getOperand(2));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000363 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000364 e.type = S->getType();
365 e.opcode = Expression::SHUFFLE;
366
367 return e;
368}
369
370Expression ValueTable::create_expression(ExtractElementInst* E) {
371 Expression e;
372
Owen Anderson343797c2007-11-26 07:17:19 +0000373 e.firstVN = hash_operand(E->getOperand(0));
374 e.secondVN = hash_operand(E->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000375 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000376 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000377 e.type = E->getType();
378 e.opcode = Expression::EXTRACT;
379
380 return e;
381}
382
383Expression ValueTable::create_expression(InsertElementInst* I) {
384 Expression e;
385
Owen Anderson343797c2007-11-26 07:17:19 +0000386 e.firstVN = hash_operand(I->getOperand(0));
387 e.secondVN = hash_operand(I->getOperand(1));
388 e.thirdVN = hash_operand(I->getOperand(2));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000389 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000390 e.type = I->getType();
391 e.opcode = Expression::INSERT;
392
393 return e;
394}
395
396Expression ValueTable::create_expression(SelectInst* I) {
397 Expression e;
398
Owen Anderson343797c2007-11-26 07:17:19 +0000399 e.firstVN = hash_operand(I->getCondition());
400 e.secondVN = hash_operand(I->getTrueValue());
401 e.thirdVN = hash_operand(I->getFalseValue());
Owen Anderson5e9366f2007-10-18 19:39:33 +0000402 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000403 e.type = I->getType();
404 e.opcode = Expression::SELECT;
405
406 return e;
407}
408
409Expression ValueTable::create_expression(GetElementPtrInst* G) {
410 Expression e;
411
Owen Anderson343797c2007-11-26 07:17:19 +0000412 e.firstVN = hash_operand(G->getPointerOperand());
Owen Anderson85c40642007-07-24 17:55:58 +0000413 e.secondVN = 0;
414 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000415 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000416 e.type = G->getType();
417 e.opcode = Expression::GEP;
418
419 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
420 I != E; ++I)
Owen Anderson343797c2007-11-26 07:17:19 +0000421 e.varargs.push_back(hash_operand(*I));
Owen Anderson85c40642007-07-24 17:55:58 +0000422
423 return e;
424}
425
426//===----------------------------------------------------------------------===//
427// ValueTable External Functions
428//===----------------------------------------------------------------------===//
429
430/// lookup_or_add - Returns the value number for the specified value, assigning
431/// it a new number if it did not have one before.
432uint32_t ValueTable::lookup_or_add(Value* V) {
433 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
434 if (VI != valueNumbering.end())
435 return VI->second;
436
Owen Anderson5e9366f2007-10-18 19:39:33 +0000437 if (CallInst* C = dyn_cast<CallInst>(V)) {
Duncan Sands00b24b52007-12-01 07:51:45 +0000438 if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
Owen Anderson5e9366f2007-10-18 19:39:33 +0000439 Expression e = create_expression(C);
440
441 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
442 if (EI != expressionNumbering.end()) {
443 valueNumbering.insert(std::make_pair(V, EI->second));
444 return EI->second;
445 } else {
446 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
447 valueNumbering.insert(std::make_pair(V, nextValueNumber));
448
449 return nextValueNumber++;
450 }
451 } else {
452 valueNumbering.insert(std::make_pair(V, nextValueNumber));
453 return nextValueNumber++;
454 }
455 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000456 Expression e = create_expression(BO);
457
458 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
459 if (EI != expressionNumbering.end()) {
460 valueNumbering.insert(std::make_pair(V, EI->second));
461 return EI->second;
462 } else {
463 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
464 valueNumbering.insert(std::make_pair(V, nextValueNumber));
465
466 return nextValueNumber++;
467 }
468 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
469 Expression e = create_expression(C);
470
471 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
472 if (EI != expressionNumbering.end()) {
473 valueNumbering.insert(std::make_pair(V, EI->second));
474 return EI->second;
475 } else {
476 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
477 valueNumbering.insert(std::make_pair(V, nextValueNumber));
478
479 return nextValueNumber++;
480 }
481 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
482 Expression e = create_expression(U);
483
484 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
485 if (EI != expressionNumbering.end()) {
486 valueNumbering.insert(std::make_pair(V, EI->second));
487 return EI->second;
488 } else {
489 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
490 valueNumbering.insert(std::make_pair(V, nextValueNumber));
491
492 return nextValueNumber++;
493 }
494 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
495 Expression e = create_expression(U);
496
497 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
498 if (EI != expressionNumbering.end()) {
499 valueNumbering.insert(std::make_pair(V, EI->second));
500 return EI->second;
501 } else {
502 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
503 valueNumbering.insert(std::make_pair(V, nextValueNumber));
504
505 return nextValueNumber++;
506 }
507 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
508 Expression e = create_expression(U);
509
510 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
511 if (EI != expressionNumbering.end()) {
512 valueNumbering.insert(std::make_pair(V, EI->second));
513 return EI->second;
514 } else {
515 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
516 valueNumbering.insert(std::make_pair(V, nextValueNumber));
517
518 return nextValueNumber++;
519 }
520 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
521 Expression e = create_expression(U);
522
523 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
524 if (EI != expressionNumbering.end()) {
525 valueNumbering.insert(std::make_pair(V, EI->second));
526 return EI->second;
527 } else {
528 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
529 valueNumbering.insert(std::make_pair(V, nextValueNumber));
530
531 return nextValueNumber++;
532 }
533 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
534 Expression e = create_expression(U);
535
536 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
537 if (EI != expressionNumbering.end()) {
538 valueNumbering.insert(std::make_pair(V, EI->second));
539 return EI->second;
540 } else {
541 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
542 valueNumbering.insert(std::make_pair(V, nextValueNumber));
543
544 return nextValueNumber++;
545 }
546 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
547 Expression e = create_expression(U);
548
549 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
550 if (EI != expressionNumbering.end()) {
551 valueNumbering.insert(std::make_pair(V, EI->second));
552 return EI->second;
553 } else {
554 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
555 valueNumbering.insert(std::make_pair(V, nextValueNumber));
556
557 return nextValueNumber++;
558 }
559 } else {
560 valueNumbering.insert(std::make_pair(V, nextValueNumber));
561 return nextValueNumber++;
562 }
563}
564
565/// lookup - Returns the value number of the specified value. Fails if
566/// the value has not yet been numbered.
567uint32_t ValueTable::lookup(Value* V) const {
568 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000569 assert(VI != valueNumbering.end() && "Value not numbered?");
570 return VI->second;
Owen Anderson85c40642007-07-24 17:55:58 +0000571}
572
573/// clear - Remove all entries from the ValueTable
574void ValueTable::clear() {
575 valueNumbering.clear();
576 expressionNumbering.clear();
577 nextValueNumber = 1;
578}
579
Owen Anderson5aff8002007-07-31 23:27:13 +0000580/// erase - Remove a value from the value numbering
581void ValueTable::erase(Value* V) {
582 valueNumbering.erase(V);
583}
584
Owen Anderson85c40642007-07-24 17:55:58 +0000585//===----------------------------------------------------------------------===//
586// ValueNumberedSet Class
587//===----------------------------------------------------------------------===//
588namespace {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000589class VISIBILITY_HIDDEN ValueNumberedSet {
Owen Anderson85c40642007-07-24 17:55:58 +0000590 private:
591 SmallPtrSet<Value*, 8> contents;
592 BitVector numbers;
593 public:
594 ValueNumberedSet() { numbers.resize(1); }
595 ValueNumberedSet(const ValueNumberedSet& other) {
596 numbers = other.numbers;
597 contents = other.contents;
598 }
599
600 typedef SmallPtrSet<Value*, 8>::iterator iterator;
601
602 iterator begin() { return contents.begin(); }
603 iterator end() { return contents.end(); }
604
605 bool insert(Value* v) { return contents.insert(v); }
606 void insert(iterator I, iterator E) { contents.insert(I, E); }
607 void erase(Value* v) { contents.erase(v); }
608 unsigned count(Value* v) { return contents.count(v); }
609 size_t size() { return contents.size(); }
610
611 void set(unsigned i) {
612 if (i >= numbers.size())
613 numbers.resize(i+1);
614
615 numbers.set(i);
616 }
617
618 void operator=(const ValueNumberedSet& other) {
619 contents = other.contents;
620 numbers = other.numbers;
621 }
622
623 void reset(unsigned i) {
624 if (i < numbers.size())
625 numbers.reset(i);
626 }
627
628 bool test(unsigned i) {
629 if (i >= numbers.size())
630 return false;
631
632 return numbers.test(i);
633 }
634
635 void clear() {
636 contents.clear();
637 numbers.clear();
638 }
639};
640}
641
642//===----------------------------------------------------------------------===//
643// GVN Pass
644//===----------------------------------------------------------------------===//
645
646namespace {
647
648 class VISIBILITY_HIDDEN GVN : public FunctionPass {
649 bool runOnFunction(Function &F);
650 public:
651 static char ID; // Pass identification, replacement for typeid
652 GVN() : FunctionPass((intptr_t)&ID) { }
653
654 private:
655 ValueTable VN;
656
657 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
658
Owen Anderson5b299672007-08-07 23:12:31 +0000659 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
660 PhiMapType phiMap;
661
662
Owen Anderson85c40642007-07-24 17:55:58 +0000663 // This transformation requires dominator postdominator info
664 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
665 AU.setPreservesCFG();
666 AU.addRequired<DominatorTree>();
667 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000668 AU.addRequired<AliasAnalysis>();
Owen Anderson29f73562008-02-19 06:35:43 +0000669 AU.addRequired<TargetData>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000670 AU.addPreserved<AliasAnalysis>();
Owen Anderson85c40642007-07-24 17:55:58 +0000671 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Anderson29f73562008-02-19 06:35:43 +0000672 AU.addPreserved<TargetData>();
Owen Anderson85c40642007-07-24 17:55:58 +0000673 }
674
675 // Helper fuctions
676 // FIXME: eliminate or document these better
677 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
678 void val_insert(ValueNumberedSet& s, Value* v);
679 bool processLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000680 DenseMap<Value*, LoadInst*> &lastLoad,
681 SmallVectorImpl<Instruction*> &toErase);
Chris Lattner248ba4d2008-03-22 00:31:52 +0000682 bool processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase);
Owen Anderson85c40642007-07-24 17:55:58 +0000683 bool processInstruction(Instruction* I,
684 ValueNumberedSet& currAvail,
685 DenseMap<Value*, LoadInst*>& lastSeenLoad,
Chris Lattner7de20452008-03-21 22:01:16 +0000686 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000687 bool processNonLocalLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000688 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonba958332008-02-19 03:09:45 +0000689 bool processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
Chris Lattner7de20452008-03-21 22:01:16 +0000690 SmallVectorImpl<Instruction*> &toErase);
Owen Andersone41ab4c2008-03-12 07:37:44 +0000691 bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C,
Chris Lattner7de20452008-03-21 22:01:16 +0000692 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000693 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
Owen Andersonc6a31b92007-08-02 17:56:05 +0000694 DenseMap<BasicBlock*, Value*> &Phis,
695 bool top_level = false);
Owen Anderson5d72a422007-07-25 19:57:03 +0000696 void dump(DenseMap<BasicBlock*, Value*>& d);
Owen Andersonbe168b32007-08-14 18:04:11 +0000697 bool iterateOnFunction(Function &F);
Owen Andersone02ad522007-08-16 22:51:56 +0000698 Value* CollapsePhi(PHINode* p);
Owen Anderson19625972007-09-16 08:04:16 +0000699 bool isSafeReplacement(PHINode* p, Instruction* inst);
Owen Anderson85c40642007-07-24 17:55:58 +0000700 };
701
702 char GVN::ID = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000703}
704
705// createGVNPass - The public interface to this file...
706FunctionPass *llvm::createGVNPass() { return new GVN(); }
707
708static RegisterPass<GVN> X("gvn",
709 "Global Value Numbering");
710
Owen Anderson85c40642007-07-24 17:55:58 +0000711/// find_leader - Given a set and a value number, return the first
712/// element of the set with that value number, or 0 if no such element
713/// is present
714Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
715 if (!vals.test(v))
716 return 0;
717
718 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
719 I != E; ++I)
720 if (v == VN.lookup(*I))
721 return *I;
722
723 assert(0 && "No leader found, but present bit is set?");
724 return 0;
725}
726
727/// val_insert - Insert a value into a set only if there is not a value
728/// with the same value number already in the set
729void GVN::val_insert(ValueNumberedSet& s, Value* v) {
730 uint32_t num = VN.lookup(v);
731 if (!s.test(num))
732 s.insert(v);
733}
734
Owen Anderson5d72a422007-07-25 19:57:03 +0000735void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
736 printf("{\n");
737 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
738 E = d.end(); I != E; ++I) {
739 if (I->second == MemoryDependenceAnalysis::None)
740 printf("None\n");
741 else
742 I->second->dump();
743 }
744 printf("}\n");
745}
746
Owen Andersone02ad522007-08-16 22:51:56 +0000747Value* GVN::CollapsePhi(PHINode* p) {
748 DominatorTree &DT = getAnalysis<DominatorTree>();
749 Value* constVal = p->hasConstantValue();
750
Chris Lattner3d7103e2008-03-21 21:14:38 +0000751 if (!constVal) return 0;
Owen Andersone02ad522007-08-16 22:51:56 +0000752
Chris Lattner3d7103e2008-03-21 21:14:38 +0000753 Instruction* inst = dyn_cast<Instruction>(constVal);
754 if (!inst)
755 return constVal;
756
757 if (DT.dominates(inst, p))
758 if (isSafeReplacement(p, inst))
759 return inst;
Owen Andersone02ad522007-08-16 22:51:56 +0000760 return 0;
761}
Owen Anderson5d72a422007-07-25 19:57:03 +0000762
Owen Anderson19625972007-09-16 08:04:16 +0000763bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
764 if (!isa<PHINode>(inst))
765 return true;
766
767 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
768 UI != E; ++UI)
769 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
770 if (use_phi->getParent() == inst->getParent())
771 return false;
772
773 return true;
774}
775
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000776/// GetValueForBlock - Get the value to use within the specified basic block.
777/// available values are in Phis.
778Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
Chris Lattner3d7103e2008-03-21 21:14:38 +0000779 DenseMap<BasicBlock*, Value*> &Phis,
780 bool top_level) {
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000781
782 // If we have already computed this value, return the previously computed val.
Owen Andersoned7f9932007-08-03 19:59:35 +0000783 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
784 if (V != Phis.end() && !top_level) return V->second;
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000785
Owen Anderson3f75d122007-08-01 22:01:54 +0000786 BasicBlock* singlePred = BB->getSinglePredecessor();
Owen Anderson30463f12007-08-03 11:03:26 +0000787 if (singlePred) {
Owen Andersoned7f9932007-08-03 19:59:35 +0000788 Value *ret = GetValueForBlock(singlePred, orig, Phis);
789 Phis[BB] = ret;
790 return ret;
Owen Anderson30463f12007-08-03 11:03:26 +0000791 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000792
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000793 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
794 // now, then get values to fill in the incoming values for the PHI.
795 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
796 BB->begin());
797 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
Owen Andersoned7f9932007-08-03 19:59:35 +0000798
799 if (Phis.count(BB) == 0)
800 Phis.insert(std::make_pair(BB, PN));
Owen Anderson48a2c562007-07-30 16:57:08 +0000801
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000802 // Fill in the incoming values for the block.
Owen Anderson9f577412007-07-31 17:43:14 +0000803 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
804 Value* val = GetValueForBlock(*PI, orig, Phis);
Owen Anderson9f577412007-07-31 17:43:14 +0000805 PN->addIncoming(val, *PI);
806 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000807
Nick Lewycky8fba1d02008-02-14 07:11:24 +0000808 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
809 AA.copyValue(orig, PN);
Owen Anderson9f577412007-07-31 17:43:14 +0000810
Owen Andersone0143452007-08-16 22:02:55 +0000811 // Attempt to collapse PHI nodes that are trivially redundant
Owen Andersone02ad522007-08-16 22:51:56 +0000812 Value* v = CollapsePhi(PN);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000813 if (!v) {
814 // Cache our phi construction results
815 phiMap[orig->getPointerOperand()].insert(PN);
816 return PN;
Owen Anderson9f577412007-07-31 17:43:14 +0000817 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000818
819 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Anderson9f577412007-07-31 17:43:14 +0000820
Chris Lattner3d7103e2008-03-21 21:14:38 +0000821 MD.removeInstruction(PN);
822 PN->replaceAllUsesWith(v);
823
824 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
825 E = Phis.end(); I != E; ++I)
826 if (I->second == PN)
827 I->second = v;
828
829 PN->eraseFromParent();
830
831 Phis[BB] = v;
832 return v;
Owen Anderson5d72a422007-07-25 19:57:03 +0000833}
834
Owen Andersone0143452007-08-16 22:02:55 +0000835/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
836/// non-local by performing PHI construction.
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000837bool GVN::processNonLocalLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000838 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson5d72a422007-07-25 19:57:03 +0000839 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
840
Owen Andersone0143452007-08-16 22:02:55 +0000841 // Find the non-local dependencies of the load
Owen Anderson5d72a422007-07-25 19:57:03 +0000842 DenseMap<BasicBlock*, Value*> deps;
Owen Anderson3f75d122007-08-01 22:01:54 +0000843 MD.getNonLocalDependency(L, deps);
Owen Anderson5d72a422007-07-25 19:57:03 +0000844
845 DenseMap<BasicBlock*, Value*> repl;
Owen Anderson5b299672007-08-07 23:12:31 +0000846
Owen Andersone0143452007-08-16 22:02:55 +0000847 // Filter out useless results (non-locals, etc)
Owen Anderson5d72a422007-07-25 19:57:03 +0000848 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
Chris Lattner3d7103e2008-03-21 21:14:38 +0000849 I != E; ++I) {
850 if (I->second == MemoryDependenceAnalysis::None)
Owen Anderson5d72a422007-07-25 19:57:03 +0000851 return false;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000852
853 if (I->second == MemoryDependenceAnalysis::NonLocal)
Owen Andersonb484d1f2007-07-30 17:29:24 +0000854 continue;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000855
856 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
857 if (S->getPointerOperand() != L->getPointerOperand())
Owen Anderson5d72a422007-07-25 19:57:03 +0000858 return false;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000859 repl[I->first] = S->getOperand(0);
Owen Anderson5d72a422007-07-25 19:57:03 +0000860 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000861 if (LD->getPointerOperand() != L->getPointerOperand())
Owen Anderson5d72a422007-07-25 19:57:03 +0000862 return false;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000863 repl[I->first] = LD;
Owen Anderson5d72a422007-07-25 19:57:03 +0000864 } else {
865 return false;
866 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000867 }
Owen Anderson5d72a422007-07-25 19:57:03 +0000868
Owen Andersone0143452007-08-16 22:02:55 +0000869 // Use cached PHI construction information from previous runs
Owen Anderson5b299672007-08-07 23:12:31 +0000870 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
871 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
872 I != E; ++I) {
873 if ((*I)->getParent() == L->getParent()) {
874 MD.removeInstruction(L);
875 L->replaceAllUsesWith(*I);
876 toErase.push_back(L);
877 NumGVNLoad++;
Owen Anderson5b299672007-08-07 23:12:31 +0000878 return true;
Owen Anderson5b299672007-08-07 23:12:31 +0000879 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000880
881 repl.insert(std::make_pair((*I)->getParent(), *I));
Owen Anderson5b299672007-08-07 23:12:31 +0000882 }
883
Owen Andersone0143452007-08-16 22:02:55 +0000884 // Perform PHI construction
Owen Anderson6ce3ae22007-07-25 22:03:06 +0000885 SmallPtrSet<BasicBlock*, 4> visited;
Owen Andersonc6a31b92007-08-02 17:56:05 +0000886 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
Owen Anderson5d72a422007-07-25 19:57:03 +0000887
888 MD.removeInstruction(L);
889 L->replaceAllUsesWith(v);
890 toErase.push_back(L);
Owen Anderson5b299672007-08-07 23:12:31 +0000891 NumGVNLoad++;
Owen Anderson5d72a422007-07-25 19:57:03 +0000892
893 return true;
894}
895
Owen Andersone0143452007-08-16 22:02:55 +0000896/// processLoad - Attempt to eliminate a load, first by eliminating it
897/// locally, and then attempting non-local elimination if that fails.
Chris Lattner7de20452008-03-21 22:01:16 +0000898bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
899 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson85c40642007-07-24 17:55:58 +0000900 if (L->isVolatile()) {
901 lastLoad[L->getPointerOperand()] = L;
902 return false;
903 }
904
905 Value* pointer = L->getPointerOperand();
906 LoadInst*& last = lastLoad[pointer];
907
908 // ... to a pointer that has been loaded from before...
909 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Andersoncc8b3a82007-08-14 17:59:48 +0000910 bool removedNonLocal = false;
Owen Anderson935e39b2007-08-09 04:42:44 +0000911 Instruction* dep = MD.getDependency(L);
Owen Anderson5d72a422007-07-25 19:57:03 +0000912 if (dep == MemoryDependenceAnalysis::NonLocal &&
Owen Andersoncc8b3a82007-08-14 17:59:48 +0000913 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
914 removedNonLocal = processNonLocalLoad(L, toErase);
915
916 if (!removedNonLocal)
917 last = L;
918
919 return removedNonLocal;
920 }
921
922
Owen Anderson85c40642007-07-24 17:55:58 +0000923 bool deletedLoad = false;
924
Owen Andersone0143452007-08-16 22:02:55 +0000925 // Walk up the dependency chain until we either find
926 // a dependency we can use, or we can't walk any further
Owen Anderson85c40642007-07-24 17:55:58 +0000927 while (dep != MemoryDependenceAnalysis::None &&
928 dep != MemoryDependenceAnalysis::NonLocal &&
929 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
930 // ... that depends on a store ...
931 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
932 if (S->getPointerOperand() == pointer) {
933 // Remove it!
934 MD.removeInstruction(L);
935
936 L->replaceAllUsesWith(S->getOperand(0));
937 toErase.push_back(L);
938 deletedLoad = true;
939 NumGVNLoad++;
940 }
941
942 // Whether we removed it or not, we can't
943 // go any further
944 break;
945 } else if (!last) {
946 // If we don't depend on a store, and we haven't
947 // been loaded before, bail.
948 break;
949 } else if (dep == last) {
950 // Remove it!
951 MD.removeInstruction(L);
952
953 L->replaceAllUsesWith(last);
954 toErase.push_back(L);
955 deletedLoad = true;
956 NumGVNLoad++;
957
958 break;
959 } else {
Owen Anderson935e39b2007-08-09 04:42:44 +0000960 dep = MD.getDependency(L, dep);
Owen Anderson85c40642007-07-24 17:55:58 +0000961 }
962 }
Eli Friedman350307f2008-02-12 12:08:14 +0000963
964 if (dep != MemoryDependenceAnalysis::None &&
965 dep != MemoryDependenceAnalysis::NonLocal &&
966 isa<AllocationInst>(dep)) {
967 // Check that this load is actually from the
968 // allocation we found
969 Value* v = L->getOperand(0);
970 while (true) {
971 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
972 v = BC->getOperand(0);
973 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
974 v = GEP->getOperand(0);
975 else
976 break;
977 }
978 if (v == dep) {
979 // If this load depends directly on an allocation, there isn't
980 // anything stored there; therefore, we can optimize this load
981 // to undef.
982 MD.removeInstruction(L);
983
984 L->replaceAllUsesWith(UndefValue::get(L->getType()));
985 toErase.push_back(L);
986 deletedLoad = true;
987 NumGVNLoad++;
988 }
989 }
990
Owen Anderson85c40642007-07-24 17:55:58 +0000991 if (!deletedLoad)
992 last = L;
993
994 return deletedLoad;
995}
996
Chris Lattner248ba4d2008-03-22 00:31:52 +0000997/// isBytewiseValue - If the specified value can be set by repeating the same
998/// byte in memory, return the i8 value that it is represented with. This is
999/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1000/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
1001/// byte store (e.g. i16 0x1234), return null.
1002static Value *isBytewiseValue(Value *V) {
1003 // All byte-wide stores are splatable, even of arbitrary variables.
1004 if (V->getType() == Type::Int8Ty) return V;
1005
1006 // Constant float and double values can be handled as integer values if the
1007 // corresponding integer value is "byteable". An important case is 0.0.
1008 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1009 if (CFP->getType() == Type::FloatTy)
1010 V = ConstantExpr::getBitCast(CFP, Type::Int32Ty);
1011 if (CFP->getType() == Type::DoubleTy)
1012 V = ConstantExpr::getBitCast(CFP, Type::Int64Ty);
1013 // Don't handle long double formats, which have strange constraints.
1014 }
1015
1016 // We can handle constant integers that are power of two in size and a
1017 // multiple of 8 bits.
1018 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1019 unsigned Width = CI->getBitWidth();
1020 if (isPowerOf2_32(Width) && Width > 8) {
1021 // We can handle this value if the recursive binary decomposition is the
1022 // same at all levels.
1023 APInt Val = CI->getValue();
1024 APInt Val2;
1025 while (Val.getBitWidth() != 8) {
1026 unsigned NextWidth = Val.getBitWidth()/2;
1027 Val2 = Val.lshr(NextWidth);
1028 Val2.trunc(Val.getBitWidth()/2);
1029 Val.trunc(Val.getBitWidth()/2);
1030
1031 // If the top/bottom halves aren't the same, reject it.
1032 if (Val != Val2)
1033 return 0;
1034 }
1035 return ConstantInt::get(Val);
1036 }
1037 }
1038
1039 // Conceptually, we could handle things like:
1040 // %a = zext i8 %X to i16
1041 // %b = shl i16 %a, 8
1042 // %c = or i16 %a, %b
1043 // but until there is an example that actually needs this, it doesn't seem
1044 // worth worrying about.
1045 return 0;
1046}
1047
Chris Lattner60b9cb42008-03-22 05:37:16 +00001048static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
1049 bool &VariableIdxFound, TargetData &TD) {
1050 // Skip over the first indices.
1051 gep_type_iterator GTI = gep_type_begin(GEP);
1052 for (unsigned i = 1; i != Idx; ++i, ++GTI)
1053 /*skip along*/;
1054
1055 // Compute the offset implied by the rest of the indices.
1056 int64_t Offset = 0;
1057 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
1058 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
1059 if (OpC == 0)
1060 return VariableIdxFound = true;
1061 if (OpC->isZero()) continue; // No offset.
1062
1063 // Handle struct indices, which add their field offset to the pointer.
1064 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1065 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1066 continue;
1067 }
1068
1069 // Otherwise, we have a sequential type like an array or vector. Multiply
1070 // the index by the ElementSize.
1071 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
1072 Offset += Size*OpC->getSExtValue();
1073 }
1074
1075 return Offset;
1076}
1077
Chris Lattner49650d62008-03-28 06:45:13 +00001078/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
1079/// constant offset, and return that constant offset. For example, Ptr1 might
1080/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
1081static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
1082 TargetData &TD) {
Chris Lattner60b9cb42008-03-22 05:37:16 +00001083 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
1084 // base. After that base, they may have some number of common (and
1085 // potentially variable) indices. After that they handle some constant
1086 // offset, which determines their offset from each other. At this point, we
1087 // handle no other case.
1088 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
1089 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
1090 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
1091 return false;
1092
1093 // Skip any common indices and track the GEP types.
1094 unsigned Idx = 1;
1095 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
1096 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
1097 break;
1098
1099 bool VariableIdxFound = false;
1100 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
1101 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
1102 if (VariableIdxFound) return false;
1103
Chris Lattner49650d62008-03-28 06:45:13 +00001104 Offset = Offset2-Offset1;
1105 return true;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001106}
1107
1108
Chris Lattner49650d62008-03-28 06:45:13 +00001109/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
1110/// This allows us to analyze stores like:
1111/// store 0 -> P+1
1112/// store 0 -> P+0
1113/// store 0 -> P+3
1114/// store 0 -> P+2
1115/// which sometimes happens with stores to arrays of structs etc. When we see
1116/// the first store, we make a range [1, 2). The second store extends the range
1117/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
1118/// two ranges into [0, 3) which is memset'able.
1119namespace {
1120struct MemsetRange {
1121 // Start/End - A semi range that describes the span that this range covers.
1122 // The range is closed at the start and open at the end: [Start, End).
1123 int64_t Start, End;
1124
1125 /// StartPtr - The getelementptr instruction that points to the start of the
1126 /// range.
1127 Value *StartPtr;
1128
1129 /// Alignment - The known alignment of the first store.
1130 unsigned Alignment;
1131
1132 /// TheStores - The actual stores that make up this range.
1133 SmallVector<StoreInst*, 16> TheStores;
1134};
1135
1136
1137class MemsetRanges {
1138 /// Ranges - A sorted list of the memset ranges. We use std::list here
1139 /// because each element is relatively large and expensive to copy.
1140 std::list<MemsetRange> Ranges;
1141 typedef std::list<MemsetRange>::iterator range_iterator;
1142 TargetData &TD;
1143public:
1144 MemsetRanges(TargetData &td) : TD(td) {}
1145
1146 typedef std::list<MemsetRange>::const_iterator const_iterator;
1147 const_iterator begin() const { return Ranges.begin(); }
1148 const_iterator end() const { return Ranges.end(); }
1149
1150
1151 void addStore(int64_t OffsetFromFirst, StoreInst *SI);
1152};
1153
1154}
1155
1156/// addStore - Add a new store to the MemsetRanges data structure. This adds a
1157/// new range for the specified store at the specified offset, merging into
1158/// existing ranges as appropriate.
1159void MemsetRanges::addStore(int64_t Start, StoreInst *SI) {
1160 int64_t End = Start+TD.getTypeStoreSize(SI->getOperand(0)->getType());
1161
1162 // Do a linear search of the ranges to see if this can be joined and/or to
1163 // find the insertion point in the list. We keep the ranges sorted for
1164 // simplicity here. This is a linear search of a linked list, which is ugly,
1165 // however the number of ranges is limited, so this won't get crazy slow.
1166 range_iterator I = Ranges.begin(), E = Ranges.end();
1167
1168 while (I != E && Start > I->End)
1169 ++I;
1170
1171 // We now know that I == E, in which case we didn't find anything to merge
1172 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
1173 // to insert a new range. Handle this now.
1174 if (I == E || End < I->Start) {
1175 MemsetRange &R = *Ranges.insert(I, MemsetRange());
1176 R.Start = Start;
1177 R.End = End;
1178 R.StartPtr = SI->getPointerOperand();
1179 R.Alignment = SI->getAlignment();
1180 R.TheStores.push_back(SI);
1181 return;
1182 }
1183
1184 // This store overlaps with I, add it.
1185 I->TheStores.push_back(SI);
1186
1187 // At this point, we may have an interval that completely contains our store.
1188 // If so, just add it to the interval and return.
1189 if (I->Start <= Start && I->End >= End)
1190 return;
1191
1192 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
1193 // but is not entirely contained within the range.
1194
1195 // See if the range extends the start of the range. In this case, it couldn't
1196 // possibly cause it to join the prior range, because otherwise we would have
1197 // stopped on *it*.
1198 if (Start < I->Start)
1199 I->Start = Start;
1200
1201 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
1202 // is in or right at the end of I), and that End >= I->Start. Extend I out to
1203 // End.
1204 if (End > I->End) {
1205 I->End = End;
1206 range_iterator NextI = I;;
1207 while (++NextI != E && End >= NextI->Start) {
1208 // Merge the range in.
1209 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
1210 if (NextI->End > I->End)
1211 I->End = NextI->End;
1212 Ranges.erase(NextI);
1213 NextI = I;
1214 }
1215 }
1216}
1217
1218
1219
Chris Lattner248ba4d2008-03-22 00:31:52 +00001220/// processStore - When GVN is scanning forward over instructions, we look for
1221/// some other patterns to fold away. In particular, this looks for stores to
1222/// neighboring locations of memory. If it sees enough consequtive ones
1223/// (currently 4) it attempts to merge them together into a memcpy/memset.
1224bool GVN::processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase) {
Evan Chenge856f8e2008-03-24 05:28:38 +00001225 if (!FormMemSet) return false;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001226 if (SI->isVolatile()) return false;
1227
1228 // There are two cases that are interesting for this code to handle: memcpy
1229 // and memset. Right now we only handle memset.
1230
1231 // Ensure that the value being stored is something that can be memset'able a
1232 // byte at a time like "0" or "-1" or any width, as well as things like
1233 // 0xA0A0A0A0 and 0.0.
1234 Value *ByteVal = isBytewiseValue(SI->getOperand(0));
1235 if (!ByteVal)
1236 return false;
1237
1238 TargetData &TD = getAnalysis<TargetData>();
1239 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
1240
Chris Lattner49650d62008-03-28 06:45:13 +00001241 // Okay, so we now have a single store that can be splatable. Scan to find
1242 // all subsequent stores of the same value to offset from the same pointer.
1243 // Join these together into ranges, so we can decide whether contiguous blocks
1244 // are stored.
1245 MemsetRanges Ranges(TD);
1246
1247 // Add our first pointer.
1248 Ranges.addStore(0, SI);
Chris Lattner248ba4d2008-03-22 00:31:52 +00001249 Value *StartPtr = SI->getPointerOperand();
Chris Lattner248ba4d2008-03-22 00:31:52 +00001250
Chris Lattner60b9cb42008-03-22 05:37:16 +00001251 BasicBlock::iterator BI = SI;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001252 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
1253 if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
1254 // If the call is readnone, ignore it, otherwise bail out. We don't even
1255 // allow readonly here because we don't want something like:
1256 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
1257 if (AA.getModRefBehavior(CallSite::get(BI)) ==
1258 AliasAnalysis::DoesNotAccessMemory)
1259 continue;
Chris Lattner1be83222008-03-22 04:13:49 +00001260
1261 // TODO: If this is a memset, try to join it in.
1262
Chris Lattner248ba4d2008-03-22 00:31:52 +00001263 break;
1264 } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
1265 break;
1266
1267 // If this is a non-store instruction it is fine, ignore it.
1268 StoreInst *NextStore = dyn_cast<StoreInst>(BI);
1269 if (NextStore == 0) continue;
1270
1271 // If this is a store, see if we can merge it in.
1272 if (NextStore->isVolatile()) break;
1273
1274 // Check to see if this stored value is of the same byte-splattable value.
1275 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
1276 break;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001277
Chris Lattner49650d62008-03-28 06:45:13 +00001278 // Check to see if this store is to a constant offset from the start ptr.
1279 int64_t Offset;
1280 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, TD))
1281 break;
1282
1283 Ranges.addStore(Offset, NextStore);
Chris Lattner248ba4d2008-03-22 00:31:52 +00001284 }
1285
Chris Lattner49650d62008-03-28 06:45:13 +00001286 Function *MemSetF = 0;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001287
Chris Lattner49650d62008-03-28 06:45:13 +00001288 // Now that we have full information about ranges, loop over the ranges and
1289 // emit memset's for anything big enough to be worthwhile.
1290 bool MadeChange = false;
1291 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
1292 I != E; ++I) {
1293 const MemsetRange &Range = *I;
1294
1295 // If we found less than 4 stores to merge, ignore the subrange: it isn't
1296 // worth losing type information in llvm IR to do the transformation.
1297 if (Range.TheStores.size() < 4)
1298 continue;
1299
1300 // Otherwise, we do want to transform this! Create a new memset. We put
1301 // the memset right after the first store that we found in this block. This
1302 // ensures that the caller will increment the iterator to the memset before
1303 // it deletes all the stores.
1304 BasicBlock::iterator InsertPt = SI; ++InsertPt;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001305
Chris Lattner49650d62008-03-28 06:45:13 +00001306 if (MemSetF == 0)
1307 MemSetF = Intrinsic::getDeclaration(SI->getParent()->getParent()
Chris Lattner1be83222008-03-22 04:13:49 +00001308 ->getParent(), Intrinsic::memset_i64);
Chris Lattner49650d62008-03-28 06:45:13 +00001309
1310 // StartPtr may not dominate the starting point. Instead of using it, base
1311 // the destination pointer off the input to the first store in the block.
1312 StartPtr = SI->getPointerOperand();
Chris Lattner1be83222008-03-22 04:13:49 +00001313
Chris Lattner49650d62008-03-28 06:45:13 +00001314 // Cast the start ptr to be i8* as memset requires.
1315 const Type *i8Ptr = PointerType::getUnqual(Type::Int8Ty);
1316 if (StartPtr->getType() != i8Ptr)
1317 StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getNameStart(),
1318 InsertPt);
Chris Lattner1be83222008-03-22 04:13:49 +00001319
Chris Lattner49650d62008-03-28 06:45:13 +00001320 // Offset the pointer if needed.
1321 if (Range.Start)
1322 StartPtr = new GetElementPtrInst(StartPtr, ConstantInt::get(Type::Int64Ty,
1323 Range.Start),
1324 "ptroffset", InsertPt);
Chris Lattner1be83222008-03-22 04:13:49 +00001325
Chris Lattner49650d62008-03-28 06:45:13 +00001326 Value *Ops[] = {
1327 StartPtr, ByteVal, // Start, value
1328 ConstantInt::get(Type::Int64Ty, Range.End-Range.Start), // size
1329 ConstantInt::get(Type::Int32Ty, Range.Alignment) // align
1330 };
1331 new CallInst(MemSetF, Ops, Ops+4, "", InsertPt);
Chris Lattner1be83222008-03-22 04:13:49 +00001332
Chris Lattner49650d62008-03-28 06:45:13 +00001333 // Zap all the stores.
1334 toErase.append(Range.TheStores.begin(), Range.TheStores.end());
1335 ++NumMemSetInfer;
1336 MadeChange = true;
1337 }
Chris Lattner1be83222008-03-22 04:13:49 +00001338
Chris Lattner49650d62008-03-28 06:45:13 +00001339 return MadeChange;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001340}
1341
1342
Owen Andersone41ab4c2008-03-12 07:37:44 +00001343/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
1344/// and checks for the possibility of a call slot optimization by having
1345/// the call write its result directly into the destination of the memcpy.
Chris Lattner7de20452008-03-21 22:01:16 +00001346bool GVN::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C,
1347 SmallVectorImpl<Instruction*> &toErase) {
Owen Andersone41ab4c2008-03-12 07:37:44 +00001348 // The general transformation to keep in mind is
1349 //
1350 // call @func(..., src, ...)
1351 // memcpy(dest, src, ...)
1352 //
1353 // ->
1354 //
1355 // memcpy(dest, src, ...)
1356 // call @func(..., dest, ...)
1357 //
1358 // Since moving the memcpy is technically awkward, we additionally check that
1359 // src only holds uninitialized values at the moment of the call, meaning that
1360 // the memcpy can be discarded rather than moved.
Owen Anderson556d0e52008-02-19 03:27:34 +00001361
Owen Anderson364b1eb2008-02-19 07:07:51 +00001362 // Deliberately get the source and destination with bitcasts stripped away,
1363 // because we'll need to do type comparisons based on the underlying type.
Owen Anderson282dd322008-02-18 09:24:53 +00001364 Value* cpyDest = cpy->getDest();
Owen Anderson29f73562008-02-19 06:35:43 +00001365 Value* cpySrc = cpy->getSource();
1366 CallSite CS = CallSite::get(C);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001367
1368 // We need to be able to reason about the size of the memcpy, so we require
1369 // that it be a constant.
1370 ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
1371 if (!cpyLength)
Owen Anderson282dd322008-02-18 09:24:53 +00001372 return false;
Owen Andersone41ab4c2008-03-12 07:37:44 +00001373
1374 // Require that src be an alloca. This simplifies the reasoning considerably.
1375 AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
1376 if (!srcAlloca)
1377 return false;
1378
1379 // Check that all of src is copied to dest.
1380 TargetData& TD = getAnalysis<TargetData>();
1381
1382 ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
1383 if (!srcArraySize)
1384 return false;
1385
1386 uint64_t srcSize = TD.getABITypeSize(srcAlloca->getAllocatedType()) *
1387 srcArraySize->getZExtValue();
1388
1389 if (cpyLength->getZExtValue() < srcSize)
1390 return false;
1391
1392 // Check that accessing the first srcSize bytes of dest will not cause a
1393 // trap. Otherwise the transform is invalid since it might cause a trap
1394 // to occur earlier than it otherwise would.
1395 if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
1396 // The destination is an alloca. Check it is larger than srcSize.
1397 ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
1398 if (!destArraySize)
1399 return false;
1400
1401 uint64_t destSize = TD.getABITypeSize(A->getAllocatedType()) *
1402 destArraySize->getZExtValue();
1403
1404 if (destSize < srcSize)
1405 return false;
1406 } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
1407 // If the destination is an sret parameter then only accesses that are
1408 // outside of the returned struct type can trap.
1409 if (!A->hasStructRetAttr())
1410 return false;
1411
1412 const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
1413 uint64_t destSize = TD.getABITypeSize(StructTy);
1414
1415 if (destSize < srcSize)
1416 return false;
1417 } else {
1418 return false;
1419 }
1420
1421 // Check that src is not accessed except via the call and the memcpy. This
1422 // guarantees that it holds only undefined values when passed in (so the final
1423 // memcpy can be dropped), that it is not read or written between the call and
1424 // the memcpy, and that writing beyond the end of it is undefined.
Owen Andersone41ab4c2008-03-12 07:37:44 +00001425 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
1426 srcAlloca->use_end());
1427 while (!srcUseList.empty()) {
1428 User* UI = srcUseList.back();
1429 srcUseList.pop_back();
1430
1431 if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
1432 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
1433 I != E; ++I)
1434 srcUseList.push_back(*I);
1435 } else if (UI != C && UI != cpy) {
1436 return false;
1437 }
1438 }
1439
Owen Anderson05744bd2008-02-25 00:40:41 +00001440 // Since we're changing the parameter to the callsite, we need to make sure
1441 // that what would be the new parameter dominates the callsite.
1442 DominatorTree& DT = getAnalysis<DominatorTree>();
1443 if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
1444 if (!DT.dominates(cpyDestInst, C))
1445 return false;
Owen Andersone41ab4c2008-03-12 07:37:44 +00001446
1447 // In addition to knowing that the call does not access src in some
1448 // unexpected manner, for example via a global, which we deduce from
1449 // the use analysis, we also need to know that it does not sneakily
1450 // access dest. We rely on AA to figure this out for us.
Owen Anderson29f73562008-02-19 06:35:43 +00001451 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
Owen Andersone41ab4c2008-03-12 07:37:44 +00001452 if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
Owen Anderson29f73562008-02-19 06:35:43 +00001453 AliasAnalysis::NoModRef)
1454 return false;
Owen Andersone41ab4c2008-03-12 07:37:44 +00001455
1456 // All the checks have passed, so do the transformation.
1457 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson78a334f2008-03-13 22:07:10 +00001458 if (CS.getArgument(i) == cpySrc) {
1459 if (cpySrc->getType() != cpyDest->getType())
1460 cpyDest = CastInst::createPointerCast(cpyDest, cpySrc->getType(),
1461 cpyDest->getName(), C);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001462 CS.setArgument(i, cpyDest);
Owen Anderson78a334f2008-03-13 22:07:10 +00001463 }
Owen Andersone41ab4c2008-03-12 07:37:44 +00001464
Owen Anderson29f73562008-02-19 06:35:43 +00001465 // Drop any cached information about the call, because we may have changed
1466 // its dependence information by changing its parameter.
Owen Anderson282dd322008-02-18 09:24:53 +00001467 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1468 MD.dropInstruction(C);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001469
Owen Anderson282dd322008-02-18 09:24:53 +00001470 // Remove the memcpy
Owen Andersonff8e2d32008-02-20 08:23:02 +00001471 MD.removeInstruction(cpy);
Owen Anderson282dd322008-02-18 09:24:53 +00001472 toErase.push_back(cpy);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001473
Owen Anderson282dd322008-02-18 09:24:53 +00001474 return true;
1475}
1476
Owen Anderson8d272d52008-02-12 21:15:18 +00001477/// processMemCpy - perform simplication of memcpy's. If we have memcpy A which
1478/// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1479/// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1480/// This allows later passes to remove the first memcpy altogether.
Owen Andersonba958332008-02-19 03:09:45 +00001481bool GVN::processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
Chris Lattner7de20452008-03-21 22:01:16 +00001482 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson8d272d52008-02-12 21:15:18 +00001483 // We can only transforms memcpy's where the dest of one is the source of the
1484 // other
Owen Anderson8d272d52008-02-12 21:15:18 +00001485 if (M->getSource() != MDep->getDest())
1486 return false;
1487
1488 // Second, the length of the memcpy's must be the same, or the preceeding one
1489 // must be larger than the following one.
1490 ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1491 ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1492 if (!C1 || !C2)
1493 return false;
1494
Owen Andersonc318b562008-02-26 23:06:17 +00001495 uint64_t DepSize = C1->getValue().getZExtValue();
1496 uint64_t CpySize = C2->getValue().getZExtValue();
Owen Anderson8d272d52008-02-12 21:15:18 +00001497
1498 if (DepSize < CpySize)
1499 return false;
1500
1501 // Finally, we have to make sure that the dest of the second does not
1502 // alias the source of the first
1503 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1504 if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1505 AliasAnalysis::NoAlias)
1506 return false;
1507 else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1508 AliasAnalysis::NoAlias)
1509 return false;
1510 else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1511 != AliasAnalysis::NoAlias)
1512 return false;
1513
1514 // If all checks passed, then we can transform these memcpy's
Owen Andersonba958332008-02-19 03:09:45 +00001515 Function* MemCpyFun = Intrinsic::getDeclaration(
Owen Anderson8d272d52008-02-12 21:15:18 +00001516 M->getParent()->getParent()->getParent(),
Owen Andersonba958332008-02-19 03:09:45 +00001517 M->getIntrinsicID());
Owen Anderson8d272d52008-02-12 21:15:18 +00001518
1519 std::vector<Value*> args;
1520 args.push_back(M->getRawDest());
1521 args.push_back(MDep->getRawSource());
1522 args.push_back(M->getLength());
1523 args.push_back(M->getAlignment());
1524
Owen Andersonba958332008-02-19 03:09:45 +00001525 CallInst* C = new CallInst(MemCpyFun, args.begin(), args.end(), "", M);
Owen Anderson8d272d52008-02-12 21:15:18 +00001526
Owen Andersonba958332008-02-19 03:09:45 +00001527 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Anderson8d272d52008-02-12 21:15:18 +00001528 if (MD.getDependency(C) == MDep) {
1529 MD.dropInstruction(M);
1530 toErase.push_back(M);
1531 return true;
Owen Anderson8d272d52008-02-12 21:15:18 +00001532 }
Chris Lattner3d7103e2008-03-21 21:14:38 +00001533
1534 MD.removeInstruction(C);
1535 toErase.push_back(C);
1536 return false;
Owen Anderson8d272d52008-02-12 21:15:18 +00001537}
1538
Owen Andersonf631bb62007-08-14 18:16:29 +00001539/// processInstruction - When calculating availability, handle an instruction
Owen Anderson85c40642007-07-24 17:55:58 +00001540/// by inserting it into the appropriate sets
Chris Lattner7de20452008-03-21 22:01:16 +00001541bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
1542 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1543 SmallVectorImpl<Instruction*> &toErase) {
1544 if (LoadInst* L = dyn_cast<LoadInst>(I))
Owen Anderson85c40642007-07-24 17:55:58 +00001545 return processLoad(L, lastSeenLoad, toErase);
Chris Lattner7de20452008-03-21 22:01:16 +00001546
Chris Lattner248ba4d2008-03-22 00:31:52 +00001547 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1548 return processStore(SI, toErase);
1549
Chris Lattner7de20452008-03-21 22:01:16 +00001550 if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
Owen Andersonba958332008-02-19 03:09:45 +00001551 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1552
1553 // The are two possible optimizations we can do for memcpy:
1554 // a) memcpy-memcpy xform which exposes redundance for DSE
Owen Andersone41ab4c2008-03-12 07:37:44 +00001555 // b) call-memcpy xform for return slot optimization
Owen Andersonba958332008-02-19 03:09:45 +00001556 Instruction* dep = MD.getDependency(M);
1557 if (dep == MemoryDependenceAnalysis::None ||
1558 dep == MemoryDependenceAnalysis::NonLocal)
1559 return false;
Chris Lattnerfd18dcd2008-02-19 06:53:20 +00001560 if (MemCpyInst *MemCpy = dyn_cast<MemCpyInst>(dep))
1561 return processMemCpy(M, MemCpy, toErase);
Chris Lattner8bc7a0d2008-02-19 06:52:38 +00001562 if (CallInst* C = dyn_cast<CallInst>(dep))
Owen Andersone41ab4c2008-03-12 07:37:44 +00001563 return performCallSlotOptzn(M, C, toErase);
Chris Lattner8bc7a0d2008-02-19 06:52:38 +00001564 return false;
Owen Anderson85c40642007-07-24 17:55:58 +00001565 }
1566
1567 unsigned num = VN.lookup_or_add(I);
1568
Owen Andersone0143452007-08-16 22:02:55 +00001569 // Collapse PHI nodes
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001570 if (PHINode* p = dyn_cast<PHINode>(I)) {
Owen Andersone02ad522007-08-16 22:51:56 +00001571 Value* constVal = CollapsePhi(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001572
1573 if (constVal) {
Owen Andersone02ad522007-08-16 22:51:56 +00001574 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1575 PI != PE; ++PI)
1576 if (PI->second.count(p))
1577 PI->second.erase(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001578
Owen Andersone02ad522007-08-16 22:51:56 +00001579 p->replaceAllUsesWith(constVal);
1580 toErase.push_back(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001581 }
Owen Andersone0143452007-08-16 22:02:55 +00001582 // Perform value-number based elimination
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001583 } else if (currAvail.test(num)) {
Owen Anderson85c40642007-07-24 17:55:58 +00001584 Value* repl = find_leader(currAvail, num);
1585
Owen Anderson8b6f04e2007-11-26 02:26:36 +00001586 if (CallInst* CI = dyn_cast<CallInst>(I)) {
1587 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
Duncan Sands00b24b52007-12-01 07:51:45 +00001588 if (!AA.doesNotAccessMemory(CI)) {
Owen Anderson8b6f04e2007-11-26 02:26:36 +00001589 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Andersonfb3f6f22007-11-29 18:02:22 +00001590 if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1591 MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
Owen Anderson8b6f04e2007-11-26 02:26:36 +00001592 // There must be an intervening may-alias store, so nothing from
1593 // this point on will be able to be replaced with the preceding call
1594 currAvail.erase(repl);
1595 currAvail.insert(I);
1596
1597 return false;
1598 }
1599 }
1600 }
1601
Owen Andersonc772be72007-12-08 01:37:09 +00001602 // Remove it!
1603 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1604 MD.removeInstruction(I);
1605
Owen Anderson5aff8002007-07-31 23:27:13 +00001606 VN.erase(I);
Owen Anderson85c40642007-07-24 17:55:58 +00001607 I->replaceAllUsesWith(repl);
1608 toErase.push_back(I);
1609 return true;
1610 } else if (!I->isTerminator()) {
1611 currAvail.set(num);
1612 currAvail.insert(I);
1613 }
1614
1615 return false;
1616}
1617
1618// GVN::runOnFunction - This is the main transformation entry point for a
1619// function.
1620//
Owen Andersonbe168b32007-08-14 18:04:11 +00001621bool GVN::runOnFunction(Function& F) {
Owen Anderson5e9366f2007-10-18 19:39:33 +00001622 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1623
Owen Andersonbe168b32007-08-14 18:04:11 +00001624 bool changed = false;
1625 bool shouldContinue = true;
1626
1627 while (shouldContinue) {
1628 shouldContinue = iterateOnFunction(F);
1629 changed |= shouldContinue;
1630 }
1631
1632 return changed;
1633}
1634
1635
1636// GVN::iterateOnFunction - Executes one iteration of GVN
1637bool GVN::iterateOnFunction(Function &F) {
Owen Anderson85c40642007-07-24 17:55:58 +00001638 // Clean out global sets from any previous functions
1639 VN.clear();
1640 availableOut.clear();
Owen Anderson5b299672007-08-07 23:12:31 +00001641 phiMap.clear();
Owen Anderson85c40642007-07-24 17:55:58 +00001642
1643 bool changed_function = false;
1644
1645 DominatorTree &DT = getAnalysis<DominatorTree>();
1646
1647 SmallVector<Instruction*, 4> toErase;
Chris Lattner98054902008-03-21 21:33:23 +00001648 DenseMap<Value*, LoadInst*> lastSeenLoad;
1649
Owen Anderson85c40642007-07-24 17:55:58 +00001650 // Top-down walk of the dominator tree
1651 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1652 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1653
1654 // Get the set to update for this block
1655 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
Chris Lattner98054902008-03-21 21:33:23 +00001656 lastSeenLoad.clear();
1657
Owen Anderson85c40642007-07-24 17:55:58 +00001658 BasicBlock* BB = DI->getBlock();
1659
1660 // A block inherits AVAIL_OUT from its dominator
1661 if (DI->getIDom() != 0)
1662 currAvail = availableOut[DI->getIDom()->getBlock()];
1663
1664 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
Owen Andersonc0403802007-07-30 21:26:39 +00001665 BI != BE; ) {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +00001666 changed_function |= processInstruction(BI, currAvail,
1667 lastSeenLoad, toErase);
Owen Anderson5d72a422007-07-25 19:57:03 +00001668
1669 NumGVNInstr += toErase.size();
1670
Owen Andersonc0403802007-07-30 21:26:39 +00001671 // Avoid iterator invalidation
1672 ++BI;
Owen Andersonc772be72007-12-08 01:37:09 +00001673
Owen Anderson5d72a422007-07-25 19:57:03 +00001674 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
Chris Lattner3d7103e2008-03-21 21:14:38 +00001675 E = toErase.end(); I != E; ++I)
Owen Anderson5d72a422007-07-25 19:57:03 +00001676 (*I)->eraseFromParent();
Owen Andersonc772be72007-12-08 01:37:09 +00001677
Owen Anderson5d72a422007-07-25 19:57:03 +00001678 toErase.clear();
Owen Anderson85c40642007-07-24 17:55:58 +00001679 }
1680 }
1681
Owen Anderson85c40642007-07-24 17:55:58 +00001682 return changed_function;
1683}