blob: dd8859b5e845f7c6d18151e9fedd3272bed21990 [file] [log] [blame]
Chris Lattner159b98f2008-12-05 07:49:08 +00001//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
Owen Anderson85c40642007-07-24 17:55:58 +00002//
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//
John Criswell6e0aa282009-03-10 15:04:53 +000013// Note that this pass does the value numbering itself; it does not use the
Matthijs Kooijman9aac1db2008-06-05 07:55:49 +000014// ValueNumbering analysis passes.
15//
Owen Anderson85c40642007-07-24 17:55:58 +000016//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "gvn"
Owen Anderson85c40642007-07-24 17:55:58 +000019#include "llvm/Transforms/Scalar.h"
Owen Anderson5d72a422007-07-25 19:57:03 +000020#include "llvm/BasicBlock.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000021#include "llvm/Constants.h"
Owen Anderson85c40642007-07-24 17:55:58 +000022#include "llvm/DerivedTypes.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000023#include "llvm/Function.h"
Devang Patela7379552009-03-06 02:59:27 +000024#include "llvm/IntrinsicInst.h"
Owen Anderson24be4c12009-07-03 00:17:18 +000025#include "llvm/LLVMContext.h"
Chris Lattner0907b522009-09-21 05:57:11 +000026#include "llvm/Operator.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000027#include "llvm/Value.h"
Owen Anderson85c40642007-07-24 17:55:58 +000028#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/DepthFirstIterator.h"
Owen Andersona03e7862008-12-15 02:03:00 +000030#include "llvm/ADT/PostOrderIterator.h"
Owen Anderson85c40642007-07-24 17:55:58 +000031#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/Statistic.h"
Owen Anderson5e9366f2007-10-18 19:39:33 +000034#include "llvm/Analysis/Dominators.h"
35#include "llvm/Analysis/AliasAnalysis.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000036#include "llvm/Analysis/MemoryBuiltins.h"
Owen Anderson85c40642007-07-24 17:55:58 +000037#include "llvm/Analysis/MemoryDependenceAnalysis.h"
38#include "llvm/Support/CFG.h"
Owen Andersona2bf7662008-06-19 19:57:25 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner9c5be3c2008-03-29 04:36:18 +000040#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattner0907b522009-09-21 05:57:11 +000042#include "llvm/Support/GetElementPtrTypeIterator.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000043#include "llvm/Support/raw_ostream.h"
Chris Lattner7741aa52009-09-20 19:03:47 +000044#include "llvm/Target/TargetData.h"
Owen Andersonec747c42008-06-19 19:54:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dale Johannesena19b67f2009-06-17 20:48:23 +000046#include "llvm/Transforms/Utils/Local.h"
Chris Lattner6e5ea272009-10-10 23:50:30 +000047#include "llvm/Transforms/Utils/SSAUpdater.h"
Duncan Sands05f68372008-10-08 07:23:46 +000048#include <cstdio>
Owen Anderson85c40642007-07-24 17:55:58 +000049using namespace llvm;
50
Bill Wendling3858cae2008-12-22 22:14:07 +000051STATISTIC(NumGVNInstr, "Number of instructions deleted");
52STATISTIC(NumGVNLoad, "Number of loads deleted");
53STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
Owen Anderson7558f202008-07-15 16:28:06 +000054STATISTIC(NumGVNBlocks, "Number of blocks merged");
Bill Wendling3858cae2008-12-22 22:14:07 +000055STATISTIC(NumPRELoad, "Number of loads PRE'd");
Chris Lattner1be83222008-03-22 04:13:49 +000056
Evan Cheng019a2e12008-06-20 01:01:07 +000057static cl::opt<bool> EnablePRE("enable-pre",
Owen Anderson3a053612008-07-17 19:41:00 +000058 cl::init(true), cl::Hidden);
Dan Gohman828f89f2009-06-15 18:30:15 +000059static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
Owen Andersona2bf7662008-06-19 19:57:25 +000060
Owen Anderson85c40642007-07-24 17:55:58 +000061//===----------------------------------------------------------------------===//
62// ValueTable Class
63//===----------------------------------------------------------------------===//
64
65/// This class holds the mapping between values and value numbers. It is used
66/// as an efficient mechanism to determine the expression-wise equivalence of
67/// two values.
68namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +000069 struct Expression {
Dan Gohman7ce405e2009-06-04 22:49:04 +000070 enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
71 UDIV, SDIV, FDIV, UREM, SREM,
Daniel Dunbar3be44e62009-09-20 02:20:51 +000072 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
73 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
74 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
75 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
76 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
Owen Anderson85c40642007-07-24 17:55:58 +000077 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
78 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
Daniel Dunbar3be44e62009-09-20 02:20:51 +000079 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
Owen Anderson771d1122008-05-13 08:17:22 +000080 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
Owen Andersona7d4c7c2009-10-19 22:14:22 +000081 INSERTVALUE, EXTRACTVALUE, EMPTY, TOMBSTONE };
Owen Anderson85c40642007-07-24 17:55:58 +000082
83 ExpressionOpcode opcode;
84 const Type* type;
Owen Anderson85c40642007-07-24 17:55:58 +000085 SmallVector<uint32_t, 4> varargs;
Chris Lattnerff36c952009-09-21 02:42:51 +000086 Value *function;
Daniel Dunbar3be44e62009-09-20 02:20:51 +000087
Owen Anderson85c40642007-07-24 17:55:58 +000088 Expression() { }
89 Expression(ExpressionOpcode o) : opcode(o) { }
Daniel Dunbar3be44e62009-09-20 02:20:51 +000090
Owen Anderson85c40642007-07-24 17:55:58 +000091 bool operator==(const Expression &other) const {
92 if (opcode != other.opcode)
93 return false;
94 else if (opcode == EMPTY || opcode == TOMBSTONE)
95 return true;
96 else if (type != other.type)
97 return false;
Owen Anderson5e9366f2007-10-18 19:39:33 +000098 else if (function != other.function)
99 return false;
Owen Anderson85c40642007-07-24 17:55:58 +0000100 else {
101 if (varargs.size() != other.varargs.size())
102 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000103
Owen Anderson85c40642007-07-24 17:55:58 +0000104 for (size_t i = 0; i < varargs.size(); ++i)
105 if (varargs[i] != other.varargs[i])
106 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000107
Owen Anderson85c40642007-07-24 17:55:58 +0000108 return true;
109 }
110 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000111
Owen Anderson85c40642007-07-24 17:55:58 +0000112 bool operator!=(const Expression &other) const {
Bill Wendling9b5d4b72008-12-22 22:16:31 +0000113 return !(*this == other);
Owen Anderson85c40642007-07-24 17:55:58 +0000114 }
115 };
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000116
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000117 class ValueTable {
Owen Anderson85c40642007-07-24 17:55:58 +0000118 private:
119 DenseMap<Value*, uint32_t> valueNumbering;
120 DenseMap<Expression, uint32_t> expressionNumbering;
Owen Andersonbcf2bd52008-05-12 20:15:55 +0000121 AliasAnalysis* AA;
122 MemoryDependenceAnalysis* MD;
123 DominatorTree* DT;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000124
Owen Anderson85c40642007-07-24 17:55:58 +0000125 uint32_t nextValueNumber;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000126
Owen Anderson85c40642007-07-24 17:55:58 +0000127 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
128 Expression::ExpressionOpcode getOpcode(CmpInst* C);
129 Expression::ExpressionOpcode getOpcode(CastInst* C);
130 Expression create_expression(BinaryOperator* BO);
131 Expression create_expression(CmpInst* C);
132 Expression create_expression(ShuffleVectorInst* V);
133 Expression create_expression(ExtractElementInst* C);
134 Expression create_expression(InsertElementInst* V);
135 Expression create_expression(SelectInst* V);
136 Expression create_expression(CastInst* C);
137 Expression create_expression(GetElementPtrInst* G);
Owen Anderson5e9366f2007-10-18 19:39:33 +0000138 Expression create_expression(CallInst* C);
Owen Anderson771d1122008-05-13 08:17:22 +0000139 Expression create_expression(Constant* C);
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000140 Expression create_expression(ExtractValueInst* C);
141 Expression create_expression(InsertValueInst* C);
142
143 uint32_t lookup_or_add_call(CallInst* C);
Owen Anderson85c40642007-07-24 17:55:58 +0000144 public:
Dan Gohman936a6522009-04-01 16:37:47 +0000145 ValueTable() : nextValueNumber(1) { }
Chris Lattnerff36c952009-09-21 02:42:51 +0000146 uint32_t lookup_or_add(Value *V);
147 uint32_t lookup(Value *V) const;
148 void add(Value *V, uint32_t num);
Owen Anderson85c40642007-07-24 17:55:58 +0000149 void clear();
Chris Lattnerff36c952009-09-21 02:42:51 +0000150 void erase(Value *v);
Owen Anderson85c40642007-07-24 17:55:58 +0000151 unsigned size();
Owen Andersonbcf2bd52008-05-12 20:15:55 +0000152 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
Chris Lattner02ca4422008-12-01 00:40:32 +0000153 AliasAnalysis *getAliasAnalysis() const { return AA; }
Owen Andersonbcf2bd52008-05-12 20:15:55 +0000154 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
155 void setDomTree(DominatorTree* D) { DT = D; }
Owen Anderson8a8d13c2008-07-03 17:44:33 +0000156 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
Bill Wendling2a023742008-12-22 21:36:08 +0000157 void verifyRemoved(const Value *) const;
Owen Anderson85c40642007-07-24 17:55:58 +0000158 };
159}
160
161namespace llvm {
Chris Lattner92eea072007-09-17 18:34:04 +0000162template <> struct DenseMapInfo<Expression> {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000163 static inline Expression getEmptyKey() {
164 return Expression(Expression::EMPTY);
165 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000166
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000167 static inline Expression getTombstoneKey() {
168 return Expression(Expression::TOMBSTONE);
169 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000170
Owen Anderson85c40642007-07-24 17:55:58 +0000171 static unsigned getHashValue(const Expression e) {
172 unsigned hash = e.opcode;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000173
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000174 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000175 (unsigned)((uintptr_t)e.type >> 9));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000176
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000177 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
178 E = e.varargs.end(); I != E; ++I)
Owen Anderson85c40642007-07-24 17:55:58 +0000179 hash = *I + hash * 37;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000180
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000181 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
182 (unsigned)((uintptr_t)e.function >> 9)) +
183 hash * 37;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000184
Owen Anderson85c40642007-07-24 17:55:58 +0000185 return hash;
186 }
Chris Lattner92eea072007-09-17 18:34:04 +0000187 static bool isEqual(const Expression &LHS, const Expression &RHS) {
188 return LHS == RHS;
189 }
Owen Anderson85c40642007-07-24 17:55:58 +0000190 static bool isPod() { return true; }
191};
192}
193
194//===----------------------------------------------------------------------===//
195// ValueTable Internal Functions
196//===----------------------------------------------------------------------===//
Chris Lattner3d7103e2008-03-21 21:14:38 +0000197Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
Owen Anderson85c40642007-07-24 17:55:58 +0000198 switch(BO->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000199 default: // THIS SHOULD NEVER HAPPEN
Edwin Törökbd448e32009-07-14 16:55:14 +0000200 llvm_unreachable("Binary operator with unknown opcode?");
Chris Lattner3d7103e2008-03-21 21:14:38 +0000201 case Instruction::Add: return Expression::ADD;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000202 case Instruction::FAdd: return Expression::FADD;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000203 case Instruction::Sub: return Expression::SUB;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000204 case Instruction::FSub: return Expression::FSUB;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000205 case Instruction::Mul: return Expression::MUL;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000206 case Instruction::FMul: return Expression::FMUL;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000207 case Instruction::UDiv: return Expression::UDIV;
208 case Instruction::SDiv: return Expression::SDIV;
209 case Instruction::FDiv: return Expression::FDIV;
210 case Instruction::URem: return Expression::UREM;
211 case Instruction::SRem: return Expression::SREM;
212 case Instruction::FRem: return Expression::FREM;
213 case Instruction::Shl: return Expression::SHL;
214 case Instruction::LShr: return Expression::LSHR;
215 case Instruction::AShr: return Expression::ASHR;
216 case Instruction::And: return Expression::AND;
217 case Instruction::Or: return Expression::OR;
218 case Instruction::Xor: return Expression::XOR;
Owen Anderson85c40642007-07-24 17:55:58 +0000219 }
220}
221
222Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Nick Lewycky8f5253b2009-07-08 03:04:38 +0000223 if (isa<ICmpInst>(C)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000224 switch (C->getPredicate()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000225 default: // THIS SHOULD NEVER HAPPEN
Edwin Törökbd448e32009-07-14 16:55:14 +0000226 llvm_unreachable("Comparison with unknown predicate?");
Chris Lattner3d7103e2008-03-21 21:14:38 +0000227 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
228 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
229 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
230 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
231 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
232 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
233 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
234 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
235 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
236 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
Owen Anderson85c40642007-07-24 17:55:58 +0000237 }
Nick Lewycky8f5253b2009-07-08 03:04:38 +0000238 } else {
239 switch (C->getPredicate()) {
240 default: // THIS SHOULD NEVER HAPPEN
Edwin Törökbd448e32009-07-14 16:55:14 +0000241 llvm_unreachable("Comparison with unknown predicate?");
Nick Lewycky8f5253b2009-07-08 03:04:38 +0000242 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
243 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
244 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
245 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
246 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
247 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
248 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
249 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
250 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
251 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
252 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
253 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
254 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
255 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
256 }
Owen Anderson85c40642007-07-24 17:55:58 +0000257 }
258}
259
Chris Lattner3d7103e2008-03-21 21:14:38 +0000260Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
Owen Anderson85c40642007-07-24 17:55:58 +0000261 switch(C->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000262 default: // THIS SHOULD NEVER HAPPEN
Edwin Törökbd448e32009-07-14 16:55:14 +0000263 llvm_unreachable("Cast operator with unknown opcode?");
Chris Lattner3d7103e2008-03-21 21:14:38 +0000264 case Instruction::Trunc: return Expression::TRUNC;
265 case Instruction::ZExt: return Expression::ZEXT;
266 case Instruction::SExt: return Expression::SEXT;
267 case Instruction::FPToUI: return Expression::FPTOUI;
268 case Instruction::FPToSI: return Expression::FPTOSI;
269 case Instruction::UIToFP: return Expression::UITOFP;
270 case Instruction::SIToFP: return Expression::SITOFP;
271 case Instruction::FPTrunc: return Expression::FPTRUNC;
272 case Instruction::FPExt: return Expression::FPEXT;
273 case Instruction::PtrToInt: return Expression::PTRTOINT;
274 case Instruction::IntToPtr: return Expression::INTTOPTR;
275 case Instruction::BitCast: return Expression::BITCAST;
Owen Anderson85c40642007-07-24 17:55:58 +0000276 }
277}
278
Owen Anderson5e9366f2007-10-18 19:39:33 +0000279Expression ValueTable::create_expression(CallInst* C) {
280 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000281
Owen Anderson5e9366f2007-10-18 19:39:33 +0000282 e.type = C->getType();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000283 e.function = C->getCalledFunction();
284 e.opcode = Expression::CALL;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000285
Owen Anderson5e9366f2007-10-18 19:39:33 +0000286 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
287 I != E; ++I)
Owen Anderson07f478f2008-04-11 05:11:49 +0000288 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000289
Owen Anderson5e9366f2007-10-18 19:39:33 +0000290 return e;
291}
292
Owen Anderson85c40642007-07-24 17:55:58 +0000293Expression ValueTable::create_expression(BinaryOperator* BO) {
294 Expression e;
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000295 e.varargs.push_back(lookup_or_add(BO->getOperand(0)));
296 e.varargs.push_back(lookup_or_add(BO->getOperand(1)));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000297 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000298 e.type = BO->getType();
299 e.opcode = getOpcode(BO);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000300
Owen Anderson85c40642007-07-24 17:55:58 +0000301 return e;
302}
303
304Expression ValueTable::create_expression(CmpInst* C) {
305 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000306
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000307 e.varargs.push_back(lookup_or_add(C->getOperand(0)));
308 e.varargs.push_back(lookup_or_add(C->getOperand(1)));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000309 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000310 e.type = C->getType();
311 e.opcode = getOpcode(C);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000312
Owen Anderson85c40642007-07-24 17:55:58 +0000313 return e;
314}
315
316Expression ValueTable::create_expression(CastInst* C) {
317 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000318
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000319 e.varargs.push_back(lookup_or_add(C->getOperand(0)));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000320 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000321 e.type = C->getType();
322 e.opcode = getOpcode(C);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000323
Owen Anderson85c40642007-07-24 17:55:58 +0000324 return e;
325}
326
327Expression ValueTable::create_expression(ShuffleVectorInst* S) {
328 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000329
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000330 e.varargs.push_back(lookup_or_add(S->getOperand(0)));
331 e.varargs.push_back(lookup_or_add(S->getOperand(1)));
332 e.varargs.push_back(lookup_or_add(S->getOperand(2)));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000333 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000334 e.type = S->getType();
335 e.opcode = Expression::SHUFFLE;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000336
Owen Anderson85c40642007-07-24 17:55:58 +0000337 return e;
338}
339
340Expression ValueTable::create_expression(ExtractElementInst* E) {
341 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000342
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000343 e.varargs.push_back(lookup_or_add(E->getOperand(0)));
344 e.varargs.push_back(lookup_or_add(E->getOperand(1)));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000345 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000346 e.type = E->getType();
347 e.opcode = Expression::EXTRACT;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000348
Owen Anderson85c40642007-07-24 17:55:58 +0000349 return e;
350}
351
352Expression ValueTable::create_expression(InsertElementInst* I) {
353 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000354
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000355 e.varargs.push_back(lookup_or_add(I->getOperand(0)));
356 e.varargs.push_back(lookup_or_add(I->getOperand(1)));
357 e.varargs.push_back(lookup_or_add(I->getOperand(2)));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000358 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000359 e.type = I->getType();
360 e.opcode = Expression::INSERT;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000361
Owen Anderson85c40642007-07-24 17:55:58 +0000362 return e;
363}
364
365Expression ValueTable::create_expression(SelectInst* I) {
366 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000367
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000368 e.varargs.push_back(lookup_or_add(I->getCondition()));
369 e.varargs.push_back(lookup_or_add(I->getTrueValue()));
370 e.varargs.push_back(lookup_or_add(I->getFalseValue()));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000371 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000372 e.type = I->getType();
373 e.opcode = Expression::SELECT;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000374
Owen Anderson85c40642007-07-24 17:55:58 +0000375 return e;
376}
377
378Expression ValueTable::create_expression(GetElementPtrInst* G) {
379 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000380
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000381 e.varargs.push_back(lookup_or_add(G->getPointerOperand()));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000382 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000383 e.type = G->getType();
384 e.opcode = Expression::GEP;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000385
Owen Anderson85c40642007-07-24 17:55:58 +0000386 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
387 I != E; ++I)
Owen Anderson07f478f2008-04-11 05:11:49 +0000388 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000389
Owen Anderson85c40642007-07-24 17:55:58 +0000390 return e;
391}
392
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000393Expression ValueTable::create_expression(ExtractValueInst* E) {
394 Expression e;
395
396 e.varargs.push_back(lookup_or_add(E->getAggregateOperand()));
397 for (ExtractValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
398 II != IE; ++II)
399 e.varargs.push_back(*II);
400 e.function = 0;
401 e.type = E->getType();
402 e.opcode = Expression::EXTRACTVALUE;
403
404 return e;
405}
406
407Expression ValueTable::create_expression(InsertValueInst* E) {
408 Expression e;
409
410 e.varargs.push_back(lookup_or_add(E->getAggregateOperand()));
411 e.varargs.push_back(lookup_or_add(E->getInsertedValueOperand()));
412 for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
413 II != IE; ++II)
414 e.varargs.push_back(*II);
415 e.function = 0;
416 e.type = E->getType();
417 e.opcode = Expression::INSERTVALUE;
418
419 return e;
420}
421
Owen Anderson85c40642007-07-24 17:55:58 +0000422//===----------------------------------------------------------------------===//
423// ValueTable External Functions
424//===----------------------------------------------------------------------===//
425
Owen Andersone6b4ff82008-06-18 21:41:49 +0000426/// add - Insert a value into the table with a specified value number.
Chris Lattnerff36c952009-09-21 02:42:51 +0000427void ValueTable::add(Value *V, uint32_t num) {
Owen Andersone6b4ff82008-06-18 21:41:49 +0000428 valueNumbering.insert(std::make_pair(V, num));
429}
430
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000431uint32_t ValueTable::lookup_or_add_call(CallInst* C) {
432 if (AA->doesNotAccessMemory(C)) {
433 Expression exp = create_expression(C);
434 uint32_t& e = expressionNumbering[exp];
435 if (!e) e = nextValueNumber++;
436 valueNumbering[C] = e;
437 return e;
438 } else if (AA->onlyReadsMemory(C)) {
439 Expression exp = create_expression(C);
440 uint32_t& e = expressionNumbering[exp];
441 if (!e) {
442 e = nextValueNumber++;
443 valueNumbering[C] = e;
444 return e;
445 }
446
447 MemDepResult local_dep = MD->getDependency(C);
448
449 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
450 valueNumbering[C] = nextValueNumber;
451 return nextValueNumber++;
452 }
453
454 if (local_dep.isDef()) {
455 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
456
457 if (local_cdep->getNumOperands() != C->getNumOperands()) {
458 valueNumbering[C] = nextValueNumber;
459 return nextValueNumber++;
460 }
461
462 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
463 uint32_t c_vn = lookup_or_add(C->getOperand(i));
464 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
465 if (c_vn != cd_vn) {
466 valueNumbering[C] = nextValueNumber;
467 return nextValueNumber++;
468 }
469 }
470
471 uint32_t v = lookup_or_add(local_cdep);
472 valueNumbering[C] = v;
473 return v;
474 }
475
476 // Non-local case.
477 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
478 MD->getNonLocalCallDependency(CallSite(C));
479 // FIXME: call/call dependencies for readonly calls should return def, not
480 // clobber! Move the checking logic to MemDep!
481 CallInst* cdep = 0;
482
483 // Check to see if we have a single dominating call instruction that is
484 // identical to C.
485 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
486 const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
487 // Ignore non-local dependencies.
488 if (I->second.isNonLocal())
489 continue;
490
491 // We don't handle non-depedencies. If we already have a call, reject
492 // instruction dependencies.
493 if (I->second.isClobber() || cdep != 0) {
494 cdep = 0;
495 break;
496 }
497
498 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
499 // FIXME: All duplicated with non-local case.
500 if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
501 cdep = NonLocalDepCall;
502 continue;
503 }
504
505 cdep = 0;
506 break;
507 }
508
509 if (!cdep) {
510 valueNumbering[C] = nextValueNumber;
511 return nextValueNumber++;
512 }
513
514 if (cdep->getNumOperands() != C->getNumOperands()) {
515 valueNumbering[C] = nextValueNumber;
516 return nextValueNumber++;
517 }
518 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
519 uint32_t c_vn = lookup_or_add(C->getOperand(i));
520 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
521 if (c_vn != cd_vn) {
522 valueNumbering[C] = nextValueNumber;
523 return nextValueNumber++;
524 }
525 }
526
527 uint32_t v = lookup_or_add(cdep);
528 valueNumbering[C] = v;
529 return v;
530
531 } else {
532 valueNumbering[C] = nextValueNumber;
533 return nextValueNumber++;
534 }
535}
536
Owen Anderson85c40642007-07-24 17:55:58 +0000537/// lookup_or_add - Returns the value number for the specified value, assigning
538/// it a new number if it did not have one before.
Chris Lattnerff36c952009-09-21 02:42:51 +0000539uint32_t ValueTable::lookup_or_add(Value *V) {
Owen Anderson85c40642007-07-24 17:55:58 +0000540 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
541 if (VI != valueNumbering.end())
542 return VI->second;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000543
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000544 if (!isa<Instruction>(V)) {
Owen Andersonb472cd82009-10-19 21:14:57 +0000545 valueNumbering[V] = nextValueNumber;
Owen Anderson85c40642007-07-24 17:55:58 +0000546 return nextValueNumber++;
547 }
Owen Andersona7d4c7c2009-10-19 22:14:22 +0000548
549 Instruction* I = cast<Instruction>(V);
550 Expression exp;
551 switch (I->getOpcode()) {
552 case Instruction::Call:
553 return lookup_or_add_call(cast<CallInst>(I));
554 case Instruction::Add:
555 case Instruction::FAdd:
556 case Instruction::Sub:
557 case Instruction::FSub:
558 case Instruction::Mul:
559 case Instruction::FMul:
560 case Instruction::UDiv:
561 case Instruction::SDiv:
562 case Instruction::FDiv:
563 case Instruction::URem:
564 case Instruction::SRem:
565 case Instruction::FRem:
566 case Instruction::Shl:
567 case Instruction::LShr:
568 case Instruction::AShr:
569 case Instruction::And:
570 case Instruction::Or :
571 case Instruction::Xor:
572 exp = create_expression(cast<BinaryOperator>(I));
573 break;
574 case Instruction::ICmp:
575 case Instruction::FCmp:
576 exp = create_expression(cast<CmpInst>(I));
577 break;
578 case Instruction::Trunc:
579 case Instruction::ZExt:
580 case Instruction::SExt:
581 case Instruction::FPToUI:
582 case Instruction::FPToSI:
583 case Instruction::UIToFP:
584 case Instruction::SIToFP:
585 case Instruction::FPTrunc:
586 case Instruction::FPExt:
587 case Instruction::PtrToInt:
588 case Instruction::IntToPtr:
589 case Instruction::BitCast:
590 exp = create_expression(cast<CastInst>(I));
591 break;
592 case Instruction::Select:
593 exp = create_expression(cast<SelectInst>(I));
594 break;
595 case Instruction::ExtractElement:
596 exp = create_expression(cast<ExtractElementInst>(I));
597 break;
598 case Instruction::InsertElement:
599 exp = create_expression(cast<InsertElementInst>(I));
600 break;
601 case Instruction::ShuffleVector:
602 exp = create_expression(cast<ShuffleVectorInst>(I));
603 break;
604 case Instruction::ExtractValue:
605 exp = create_expression(cast<ExtractValueInst>(I));
606 break;
607 case Instruction::InsertValue:
608 exp = create_expression(cast<InsertValueInst>(I));
609 break;
610 case Instruction::GetElementPtr:
611 exp = create_expression(cast<GetElementPtrInst>(I));
612 break;
613 default:
614 valueNumbering[V] = nextValueNumber;
615 return nextValueNumber++;
616 }
617
618 uint32_t& e = expressionNumbering[exp];
619 if (!e) e = nextValueNumber++;
620 valueNumbering[V] = e;
621 return e;
Owen Anderson85c40642007-07-24 17:55:58 +0000622}
623
624/// lookup - Returns the value number of the specified value. Fails if
625/// the value has not yet been numbered.
Chris Lattnerff36c952009-09-21 02:42:51 +0000626uint32_t ValueTable::lookup(Value *V) const {
Owen Anderson85c40642007-07-24 17:55:58 +0000627 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000628 assert(VI != valueNumbering.end() && "Value not numbered?");
629 return VI->second;
Owen Anderson85c40642007-07-24 17:55:58 +0000630}
631
632/// clear - Remove all entries from the ValueTable
633void ValueTable::clear() {
634 valueNumbering.clear();
635 expressionNumbering.clear();
636 nextValueNumber = 1;
637}
638
Owen Anderson5aff8002007-07-31 23:27:13 +0000639/// erase - Remove a value from the value numbering
Chris Lattnerff36c952009-09-21 02:42:51 +0000640void ValueTable::erase(Value *V) {
Owen Anderson5aff8002007-07-31 23:27:13 +0000641 valueNumbering.erase(V);
642}
643
Bill Wendling2a023742008-12-22 21:36:08 +0000644/// verifyRemoved - Verify that the value is removed from all internal data
645/// structures.
646void ValueTable::verifyRemoved(const Value *V) const {
647 for (DenseMap<Value*, uint32_t>::iterator
648 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
649 assert(I->first != V && "Inst still occurs in value numbering map!");
650 }
651}
652
Owen Anderson85c40642007-07-24 17:55:58 +0000653//===----------------------------------------------------------------------===//
Bill Wendling42f17f62008-12-22 22:32:22 +0000654// GVN Pass
Owen Anderson85c40642007-07-24 17:55:58 +0000655//===----------------------------------------------------------------------===//
656
657namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000658 struct ValueNumberScope {
Owen Anderson2a412722008-06-20 01:15:47 +0000659 ValueNumberScope* parent;
660 DenseMap<uint32_t, Value*> table;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000661
Owen Anderson2a412722008-06-20 01:15:47 +0000662 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
663 };
664}
665
666namespace {
Owen Anderson85c40642007-07-24 17:55:58 +0000667
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000668 class GVN : public FunctionPass {
Owen Anderson85c40642007-07-24 17:55:58 +0000669 bool runOnFunction(Function &F);
670 public:
671 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +0000672 GVN() : FunctionPass(&ID) { }
Owen Anderson85c40642007-07-24 17:55:58 +0000673
674 private:
Chris Lattner02ca4422008-12-01 00:40:32 +0000675 MemoryDependenceAnalysis *MD;
676 DominatorTree *DT;
677
Owen Anderson85c40642007-07-24 17:55:58 +0000678 ValueTable VN;
Owen Anderson2a412722008-06-20 01:15:47 +0000679 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000680
Owen Anderson85c40642007-07-24 17:55:58 +0000681 // This transformation requires dominator postdominator info
682 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Anderson85c40642007-07-24 17:55:58 +0000683 AU.addRequired<DominatorTree>();
684 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000685 AU.addRequired<AliasAnalysis>();
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000686
Owen Andersonaef6a922008-06-23 17:49:45 +0000687 AU.addPreserved<DominatorTree>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000688 AU.addPreserved<AliasAnalysis>();
Owen Anderson85c40642007-07-24 17:55:58 +0000689 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000690
Owen Anderson85c40642007-07-24 17:55:58 +0000691 // Helper fuctions
692 // FIXME: eliminate or document these better
Owen Anderson85c40642007-07-24 17:55:58 +0000693 bool processLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000694 SmallVectorImpl<Instruction*> &toErase);
Chris Lattnerff36c952009-09-21 02:42:51 +0000695 bool processInstruction(Instruction *I,
Chris Lattner7de20452008-03-21 22:01:16 +0000696 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000697 bool processNonLocalLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000698 SmallVectorImpl<Instruction*> &toErase);
Chris Lattnerff36c952009-09-21 02:42:51 +0000699 bool processBlock(BasicBlock *BB);
Owen Andersone6b4ff82008-06-18 21:41:49 +0000700 void dump(DenseMap<uint32_t, Value*>& d);
Owen Andersonbe168b32007-08-14 18:04:11 +0000701 bool iterateOnFunction(Function &F);
Chris Lattnerff36c952009-09-21 02:42:51 +0000702 Value *CollapsePhi(PHINode* p);
Owen Andersone6b4ff82008-06-18 21:41:49 +0000703 bool performPRE(Function& F);
Chris Lattnerff36c952009-09-21 02:42:51 +0000704 Value *lookupNumber(BasicBlock *BB, uint32_t num);
Nuno Lopes274474b2008-10-10 16:25:50 +0000705 void cleanupGlobalSets();
Bill Wendling2a023742008-12-22 21:36:08 +0000706 void verifyRemoved(const Instruction *I) const;
Owen Anderson85c40642007-07-24 17:55:58 +0000707 };
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000708
Owen Anderson85c40642007-07-24 17:55:58 +0000709 char GVN::ID = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000710}
711
712// createGVNPass - The public interface to this file...
713FunctionPass *llvm::createGVNPass() { return new GVN(); }
714
715static RegisterPass<GVN> X("gvn",
716 "Global Value Numbering");
717
Owen Andersone6b4ff82008-06-18 21:41:49 +0000718void GVN::dump(DenseMap<uint32_t, Value*>& d) {
Owen Anderson5d72a422007-07-25 19:57:03 +0000719 printf("{\n");
Owen Andersone6b4ff82008-06-18 21:41:49 +0000720 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson5d72a422007-07-25 19:57:03 +0000721 E = d.end(); I != E; ++I) {
Owen Andersone6b4ff82008-06-18 21:41:49 +0000722 printf("%d\n", I->first);
Owen Anderson5d72a422007-07-25 19:57:03 +0000723 I->second->dump();
724 }
725 printf("}\n");
726}
727
Chris Lattnerff36c952009-09-21 02:42:51 +0000728static bool isSafeReplacement(PHINode* p, Instruction *inst) {
Owen Andersond68b1af2009-08-26 22:55:11 +0000729 if (!isa<PHINode>(inst))
730 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000731
Owen Andersond68b1af2009-08-26 22:55:11 +0000732 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
733 UI != E; ++UI)
734 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
735 if (use_phi->getParent() == inst->getParent())
736 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000737
Owen Andersond68b1af2009-08-26 22:55:11 +0000738 return true;
739}
740
Chris Lattnerff36c952009-09-21 02:42:51 +0000741Value *GVN::CollapsePhi(PHINode *PN) {
742 Value *ConstVal = PN->hasConstantValue(DT);
743 if (!ConstVal) return 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000744
Chris Lattnerff36c952009-09-21 02:42:51 +0000745 Instruction *Inst = dyn_cast<Instruction>(ConstVal);
746 if (!Inst)
747 return ConstVal;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000748
Chris Lattnerff36c952009-09-21 02:42:51 +0000749 if (DT->dominates(Inst, PN))
750 if (isSafeReplacement(PN, Inst))
751 return Inst;
Owen Andersone02ad522007-08-16 22:51:56 +0000752 return 0;
753}
Owen Anderson5d72a422007-07-25 19:57:03 +0000754
Chris Lattnerdcded152008-12-02 08:16:11 +0000755/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
756/// we're analyzing is fully available in the specified block. As we go, keep
Chris Lattner159b98f2008-12-05 07:49:08 +0000757/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
758/// map is actually a tri-state map with the following values:
759/// 0) we know the block *is not* fully available.
760/// 1) we know the block *is* fully available.
761/// 2) we do not know whether the block is fully available or not, but we are
762/// currently speculating that it will be.
763/// 3) we are speculating for this block and have used that to speculate for
764/// other blocks.
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000765static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
Chris Lattner159b98f2008-12-05 07:49:08 +0000766 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
Chris Lattnerdcded152008-12-02 08:16:11 +0000767 // Optimistically assume that the block is fully available and check to see
768 // if we already know about this block in one lookup.
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000769 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
Chris Lattner159b98f2008-12-05 07:49:08 +0000770 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
Chris Lattnerdcded152008-12-02 08:16:11 +0000771
772 // If the entry already existed for this block, return the precomputed value.
Chris Lattner159b98f2008-12-05 07:49:08 +0000773 if (!IV.second) {
774 // If this is a speculative "available" value, mark it as being used for
775 // speculation of other blocks.
776 if (IV.first->second == 2)
777 IV.first->second = 3;
778 return IV.first->second != 0;
779 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000780
Chris Lattnerdcded152008-12-02 08:16:11 +0000781 // Otherwise, see if it is fully available in all predecessors.
782 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000783
Chris Lattnerdcded152008-12-02 08:16:11 +0000784 // If this block has no predecessors, it isn't live-in here.
785 if (PI == PE)
Chris Lattner159b98f2008-12-05 07:49:08 +0000786 goto SpeculationFailure;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000787
Chris Lattnerdcded152008-12-02 08:16:11 +0000788 for (; PI != PE; ++PI)
789 // If the value isn't fully available in one of our predecessors, then it
790 // isn't fully available in this block either. Undo our previous
791 // optimistic assumption and bail out.
792 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
Chris Lattner159b98f2008-12-05 07:49:08 +0000793 goto SpeculationFailure;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000794
Chris Lattnerdcded152008-12-02 08:16:11 +0000795 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000796
Chris Lattner159b98f2008-12-05 07:49:08 +0000797// SpeculationFailure - If we get here, we found out that this is not, after
798// all, a fully-available block. We have a problem if we speculated on this and
799// used the speculation to mark other blocks as available.
800SpeculationFailure:
801 char &BBVal = FullyAvailableBlocks[BB];
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000802
Chris Lattner159b98f2008-12-05 07:49:08 +0000803 // If we didn't speculate on this, just return with it set to false.
804 if (BBVal == 2) {
805 BBVal = 0;
806 return false;
807 }
808
809 // If we did speculate on this value, we could have blocks set to 1 that are
810 // incorrect. Walk the (transitive) successors of this block and mark them as
811 // 0 if set to one.
812 SmallVector<BasicBlock*, 32> BBWorklist;
813 BBWorklist.push_back(BB);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000814
Chris Lattner159b98f2008-12-05 07:49:08 +0000815 while (!BBWorklist.empty()) {
816 BasicBlock *Entry = BBWorklist.pop_back_val();
817 // Note that this sets blocks to 0 (unavailable) if they happen to not
818 // already be in FullyAvailableBlocks. This is safe.
819 char &EntryVal = FullyAvailableBlocks[Entry];
820 if (EntryVal == 0) continue; // Already unavailable.
821
822 // Mark as unavailable.
823 EntryVal = 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000824
Chris Lattner159b98f2008-12-05 07:49:08 +0000825 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
826 BBWorklist.push_back(*I);
827 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000828
Chris Lattner159b98f2008-12-05 07:49:08 +0000829 return false;
Chris Lattnerdcded152008-12-02 08:16:11 +0000830}
831
Chris Lattnerd6b1d052009-09-20 20:09:34 +0000832
Chris Lattner012b3602009-09-21 17:24:04 +0000833/// CanCoerceMustAliasedValueToLoad - Return true if
834/// CoerceAvailableValueToLoadType will succeed.
835static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
836 const Type *LoadTy,
837 const TargetData &TD) {
838 // If the loaded or stored value is an first class array or struct, don't try
839 // to transform them. We need to be able to bitcast to integer.
840 if (isa<StructType>(LoadTy) || isa<ArrayType>(LoadTy) ||
841 isa<StructType>(StoredVal->getType()) ||
842 isa<ArrayType>(StoredVal->getType()))
843 return false;
844
845 // The store has to be at least as big as the load.
846 if (TD.getTypeSizeInBits(StoredVal->getType()) <
847 TD.getTypeSizeInBits(LoadTy))
848 return false;
849
850 return true;
851}
852
853
Chris Lattnerd6b1d052009-09-20 20:09:34 +0000854/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
855/// then a load from a must-aliased pointer of a different type, try to coerce
856/// the stored value. LoadedTy is the type of the load we want to replace and
857/// InsertPt is the place to insert new instructions.
858///
859/// If we can't do it, return null.
860static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
861 const Type *LoadedTy,
862 Instruction *InsertPt,
863 const TargetData &TD) {
Chris Lattner012b3602009-09-21 17:24:04 +0000864 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
865 return 0;
866
Chris Lattnerd6b1d052009-09-20 20:09:34 +0000867 const Type *StoredValTy = StoredVal->getType();
868
869 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
870 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
871
872 // If the store and reload are the same size, we can always reuse it.
873 if (StoreSize == LoadSize) {
874 if (isa<PointerType>(StoredValTy) && isa<PointerType>(LoadedTy)) {
875 // Pointer to Pointer -> use bitcast.
876 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
877 }
878
879 // Convert source pointers to integers, which can be bitcast.
880 if (isa<PointerType>(StoredValTy)) {
881 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
882 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
883 }
884
885 const Type *TypeToCastTo = LoadedTy;
886 if (isa<PointerType>(TypeToCastTo))
887 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
888
889 if (StoredValTy != TypeToCastTo)
890 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
891
892 // Cast to pointer if the load needs a pointer type.
893 if (isa<PointerType>(LoadedTy))
894 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
895
896 return StoredVal;
897 }
898
899 // If the loaded value is smaller than the available value, then we can
900 // extract out a piece from it. If the available value is too small, then we
901 // can't do anything.
Chris Lattner012b3602009-09-21 17:24:04 +0000902 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
Chris Lattnerd6b1d052009-09-20 20:09:34 +0000903
904 // Convert source pointers to integers, which can be manipulated.
905 if (isa<PointerType>(StoredValTy)) {
906 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
907 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
908 }
909
910 // Convert vectors and fp to integer, which can be manipulated.
911 if (!isa<IntegerType>(StoredValTy)) {
912 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
913 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
914 }
915
916 // If this is a big-endian system, we need to shift the value down to the low
917 // bits so that a truncate will work.
918 if (TD.isBigEndian()) {
919 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
920 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
921 }
922
923 // Truncate the integer to the right size now.
924 const Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
925 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
926
927 if (LoadedTy == NewIntTy)
928 return StoredVal;
929
930 // If the result is a pointer, inttoptr.
931 if (isa<PointerType>(LoadedTy))
932 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
933
934 // Otherwise, bitcast.
935 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
936}
937
Chris Lattner8f912082009-09-21 06:24:16 +0000938/// GetBaseWithConstantOffset - Analyze the specified pointer to see if it can
939/// be expressed as a base pointer plus a constant offset. Return the base and
940/// offset to the caller.
941static Value *GetBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Chris Lattneraae7fcb2009-09-21 06:48:08 +0000942 const TargetData &TD) {
Chris Lattner8f912082009-09-21 06:24:16 +0000943 Operator *PtrOp = dyn_cast<Operator>(Ptr);
944 if (PtrOp == 0) return Ptr;
945
946 // Just look through bitcasts.
947 if (PtrOp->getOpcode() == Instruction::BitCast)
948 return GetBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
949
950 // If this is a GEP with constant indices, we can look through it.
951 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
952 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
953
954 gep_type_iterator GTI = gep_type_begin(GEP);
955 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
956 ++I, ++GTI) {
957 ConstantInt *OpC = cast<ConstantInt>(*I);
958 if (OpC->isZero()) continue;
959
960 // Handle a struct and array indices which add their offset to the pointer.
961 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattneraae7fcb2009-09-21 06:48:08 +0000962 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
Chris Lattner8f912082009-09-21 06:24:16 +0000963 } else {
Chris Lattneraae7fcb2009-09-21 06:48:08 +0000964 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner8f912082009-09-21 06:24:16 +0000965 Offset += OpC->getSExtValue()*Size;
966 }
967 }
968
969 // Re-sign extend from the pointer size if needed to get overflow edge cases
970 // right.
Chris Lattneraae7fcb2009-09-21 06:48:08 +0000971 unsigned PtrSize = TD.getPointerSizeInBits();
Chris Lattner8f912082009-09-21 06:24:16 +0000972 if (PtrSize < 64)
973 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
974
975 return GetBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
976}
977
978
979/// AnalyzeLoadFromClobberingStore - This function is called when we have a
980/// memdep query of a load that ends up being a clobbering store. This means
981/// that the store *may* provide bits used by the load but we can't be sure
982/// because the pointers don't mustalias. Check this case to see if there is
983/// anything more we can do before we give up. This returns -1 if we have to
984/// give up, or a byte number in the stored value of the piece that feeds the
985/// load.
986static int AnalyzeLoadFromClobberingStore(LoadInst *L, StoreInst *DepSI,
Chris Lattneraae7fcb2009-09-21 06:48:08 +0000987 const TargetData &TD) {
Chris Lattner012b3602009-09-21 17:24:04 +0000988 // If the loaded or stored value is an first class array or struct, don't try
989 // to transform them. We need to be able to bitcast to integer.
990 if (isa<StructType>(L->getType()) || isa<ArrayType>(L->getType()) ||
991 isa<StructType>(DepSI->getOperand(0)->getType()) ||
992 isa<ArrayType>(DepSI->getOperand(0)->getType()))
993 return -1;
994
Chris Lattner8f912082009-09-21 06:24:16 +0000995 int64_t StoreOffset = 0, LoadOffset = 0;
996 Value *StoreBase =
Chris Lattneraae7fcb2009-09-21 06:48:08 +0000997 GetBaseWithConstantOffset(DepSI->getPointerOperand(), StoreOffset, TD);
Chris Lattner8f912082009-09-21 06:24:16 +0000998 Value *LoadBase =
Chris Lattneraae7fcb2009-09-21 06:48:08 +0000999 GetBaseWithConstantOffset(L->getPointerOperand(), LoadOffset, TD);
Chris Lattner8f912082009-09-21 06:24:16 +00001000 if (StoreBase != LoadBase)
1001 return -1;
1002
1003 // If the load and store are to the exact same address, they should have been
1004 // a must alias. AA must have gotten confused.
1005 // FIXME: Study to see if/when this happens.
1006 if (LoadOffset == StoreOffset) {
1007#if 0
1008 errs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
1009 << "Base = " << *StoreBase << "\n"
1010 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1011 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1012 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1013 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1014 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1015 << *L->getParent();
1016#endif
1017 return -1;
1018 }
1019
1020 // If the load and store don't overlap at all, the store doesn't provide
1021 // anything to the load. In this case, they really don't alias at all, AA
1022 // must have gotten confused.
1023 // FIXME: Investigate cases where this bails out, e.g. rdar://7238614. Then
1024 // remove this check, as it is duplicated with what we have below.
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001025 uint64_t StoreSize = TD.getTypeSizeInBits(DepSI->getOperand(0)->getType());
1026 uint64_t LoadSize = TD.getTypeSizeInBits(L->getType());
Chris Lattner8f912082009-09-21 06:24:16 +00001027
1028 if ((StoreSize & 7) | (LoadSize & 7))
1029 return -1;
1030 StoreSize >>= 3; // Convert to bytes.
1031 LoadSize >>= 3;
1032
1033
1034 bool isAAFailure = false;
1035 if (StoreOffset < LoadOffset) {
1036 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
1037 } else {
1038 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
1039 }
1040 if (isAAFailure) {
1041#if 0
1042 errs() << "STORE LOAD DEP WITH COMMON BASE:\n"
1043 << "Base = " << *StoreBase << "\n"
1044 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1045 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1046 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1047 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1048 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1049 << *L->getParent();
1050#endif
1051 return -1;
1052 }
1053
1054 // If the Load isn't completely contained within the stored bits, we don't
1055 // have all the bits to feed it. We could do something crazy in the future
1056 // (issue a smaller load then merge the bits in) but this seems unlikely to be
1057 // valuable.
1058 if (StoreOffset > LoadOffset ||
1059 StoreOffset+StoreSize < LoadOffset+LoadSize)
1060 return -1;
1061
1062 // Okay, we can do this transformation. Return the number of bytes into the
1063 // store that the load is.
1064 return LoadOffset-StoreOffset;
1065}
1066
1067
1068/// GetStoreValueForLoad - This function is called when we have a
1069/// memdep query of a load that ends up being a clobbering store. This means
1070/// that the store *may* provide bits used by the load but we can't be sure
1071/// because the pointers don't mustalias. Check this case to see if there is
1072/// anything more we can do before we give up.
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001073static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
1074 const Type *LoadTy,
1075 Instruction *InsertPt, const TargetData &TD){
Chris Lattner8f912082009-09-21 06:24:16 +00001076 LLVMContext &Ctx = SrcVal->getType()->getContext();
1077
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001078 uint64_t StoreSize = TD.getTypeSizeInBits(SrcVal->getType())/8;
1079 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
Chris Lattner8f912082009-09-21 06:24:16 +00001080
1081
1082 // Compute which bits of the stored value are being used by the load. Convert
1083 // to an integer type to start with.
1084 if (isa<PointerType>(SrcVal->getType()))
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001085 SrcVal = new PtrToIntInst(SrcVal, TD.getIntPtrType(Ctx), "tmp", InsertPt);
Chris Lattner8f912082009-09-21 06:24:16 +00001086 if (!isa<IntegerType>(SrcVal->getType()))
1087 SrcVal = new BitCastInst(SrcVal, IntegerType::get(Ctx, StoreSize*8),
1088 "tmp", InsertPt);
1089
1090 // Shift the bits to the least significant depending on endianness.
1091 unsigned ShiftAmt;
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001092 if (TD.isLittleEndian()) {
Chris Lattner8f912082009-09-21 06:24:16 +00001093 ShiftAmt = Offset*8;
1094 } else {
Chris Lattner1846fa02009-09-21 17:55:47 +00001095 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
Chris Lattner8f912082009-09-21 06:24:16 +00001096 }
1097
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001098 if (ShiftAmt)
1099 SrcVal = BinaryOperator::CreateLShr(SrcVal,
1100 ConstantInt::get(SrcVal->getType(), ShiftAmt), "tmp", InsertPt);
Chris Lattner8f912082009-09-21 06:24:16 +00001101
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001102 if (LoadSize != StoreSize)
1103 SrcVal = new TruncInst(SrcVal, IntegerType::get(Ctx, LoadSize*8),
1104 "tmp", InsertPt);
Chris Lattner8f912082009-09-21 06:24:16 +00001105
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001106 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
Chris Lattner8f912082009-09-21 06:24:16 +00001107}
1108
Chris Lattner19b84b32009-09-21 06:30:24 +00001109struct AvailableValueInBlock {
1110 /// BB - The basic block in question.
1111 BasicBlock *BB;
1112 /// V - The value that is live out of the block.
1113 Value *V;
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001114 /// Offset - The byte offset in V that is interesting for the load query.
1115 unsigned Offset;
Chris Lattner19b84b32009-09-21 06:30:24 +00001116
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001117 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1118 unsigned Offset = 0) {
Chris Lattner19b84b32009-09-21 06:30:24 +00001119 AvailableValueInBlock Res;
1120 Res.BB = BB;
1121 Res.V = V;
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001122 Res.Offset = Offset;
Chris Lattner19b84b32009-09-21 06:30:24 +00001123 return Res;
1124 }
1125};
1126
Chris Lattner6e5ea272009-10-10 23:50:30 +00001127/// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1128/// construct SSA form, allowing us to eliminate LI. This returns the value
1129/// that should be used at LI's definition site.
1130static Value *ConstructSSAForLoadSet(LoadInst *LI,
1131 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1132 const TargetData *TD,
1133 AliasAnalysis *AA) {
1134 SmallVector<PHINode*, 8> NewPHIs;
1135 SSAUpdater SSAUpdate(&NewPHIs);
1136 SSAUpdate.Initialize(LI);
1137
1138 const Type *LoadTy = LI->getType();
1139
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001140 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
Chris Lattner19b84b32009-09-21 06:30:24 +00001141 BasicBlock *BB = ValuesPerBlock[i].BB;
1142 Value *AvailableVal = ValuesPerBlock[i].V;
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001143 unsigned Offset = ValuesPerBlock[i].Offset;
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001144
Chris Lattner6e5ea272009-10-10 23:50:30 +00001145 if (SSAUpdate.HasValueForBlock(BB))
1146 continue;
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001147
1148 if (AvailableVal->getType() != LoadTy) {
1149 assert(TD && "Need target data to handle type mismatch case");
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001150 AvailableVal = GetStoreValueForLoad(AvailableVal, Offset, LoadTy,
1151 BB->getTerminator(), *TD);
1152
1153 if (Offset) {
1154 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
Chris Lattner6e5ea272009-10-10 23:50:30 +00001155 << *ValuesPerBlock[i].V << '\n'
1156 << *AvailableVal << '\n' << "\n\n\n");
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001157 }
1158
1159
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001160 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
Chris Lattner6e5ea272009-10-10 23:50:30 +00001161 << *ValuesPerBlock[i].V << '\n'
1162 << *AvailableVal << '\n' << "\n\n\n");
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001163 }
Chris Lattner6e5ea272009-10-10 23:50:30 +00001164
1165 SSAUpdate.AddAvailableValue(BB, AvailableVal);
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001166 }
Chris Lattner6e5ea272009-10-10 23:50:30 +00001167
1168 // Perform PHI construction.
1169 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1170
1171 // If new PHI nodes were created, notify alias analysis.
1172 if (isa<PointerType>(V->getType()))
1173 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1174 AA->copyValue(LI, NewPHIs[i]);
1175
1176 return V;
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001177}
1178
Owen Andersone0143452007-08-16 22:02:55 +00001179/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1180/// non-local by performing PHI construction.
Chris Lattnerdcded152008-12-02 08:16:11 +00001181bool GVN::processNonLocalLoad(LoadInst *LI,
Chris Lattner7de20452008-03-21 22:01:16 +00001182 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattnerdcded152008-12-02 08:16:11 +00001183 // Find the non-local dependencies of the load.
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001184 SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
Chris Lattneraf713862008-12-09 19:25:07 +00001185 MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
1186 Deps);
Dan Gohman7e124382009-07-31 20:24:18 +00001187 //DEBUG(errs() << "INVESTIGATING NONLOCAL LOAD: "
1188 // << Deps.size() << *LI << '\n');
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001189
Owen Anderson90e717d2008-08-26 22:07:42 +00001190 // If we had to process more than one hundred blocks to find the
1191 // dependencies, this load isn't worth worrying about. Optimizing
1192 // it will be too expensive.
Chris Lattneraf713862008-12-09 19:25:07 +00001193 if (Deps.size() > 100)
Owen Anderson90e717d2008-08-26 22:07:42 +00001194 return false;
Chris Lattner8d1686f2008-12-18 00:51:32 +00001195
1196 // If we had a phi translation failure, we'll have a single entry which is a
1197 // clobber in the current block. Reject this early.
Edwin Török3ffffac2009-06-17 18:48:18 +00001198 if (Deps.size() == 1 && Deps[0].second.isClobber()) {
1199 DEBUG(
Dan Gohman0be10b02009-07-25 01:43:01 +00001200 errs() << "GVN: non-local load ";
1201 WriteAsOperand(errs(), LI);
Dan Gohman7e124382009-07-31 20:24:18 +00001202 errs() << " is clobbered by " << *Deps[0].second.getInst() << '\n';
Edwin Török3ffffac2009-06-17 18:48:18 +00001203 );
Chris Lattner8d1686f2008-12-18 00:51:32 +00001204 return false;
Edwin Török3ffffac2009-06-17 18:48:18 +00001205 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001206
Chris Lattnerdcded152008-12-02 08:16:11 +00001207 // Filter out useless results (non-locals, etc). Keep track of the blocks
1208 // where we have a value available in repl, also keep track of whether we see
1209 // dependencies that produce an unknown value for the load (such as a call
1210 // that could potentially clobber the load).
Chris Lattner19b84b32009-09-21 06:30:24 +00001211 SmallVector<AvailableValueInBlock, 16> ValuesPerBlock;
Chris Lattnerdcded152008-12-02 08:16:11 +00001212 SmallVector<BasicBlock*, 16> UnavailableBlocks;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001213
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001214 const TargetData *TD = 0;
1215
Chris Lattneraf713862008-12-09 19:25:07 +00001216 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
1217 BasicBlock *DepBB = Deps[i].first;
1218 MemDepResult DepInfo = Deps[i].second;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001219
Chris Lattner4531da82008-12-05 21:04:20 +00001220 if (DepInfo.isClobber()) {
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001221 // If the dependence is to a store that writes to a superset of the bits
1222 // read by the load, we can extract the bits we need for the load from the
1223 // stored value.
1224 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1225 if (TD == 0)
1226 TD = getAnalysisIfAvailable<TargetData>();
1227 if (TD) {
1228 int Offset = AnalyzeLoadFromClobberingStore(LI, DepSI, *TD);
1229 if (Offset != -1) {
1230 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1231 DepSI->getOperand(0),
1232 Offset));
1233 continue;
1234 }
1235 }
1236 }
1237
1238 // FIXME: Handle memset/memcpy.
Chris Lattner4531da82008-12-05 21:04:20 +00001239 UnavailableBlocks.push_back(DepBB);
1240 continue;
1241 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001242
Chris Lattner4531da82008-12-05 21:04:20 +00001243 Instruction *DepInst = DepInfo.getInst();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001244
Chris Lattner4531da82008-12-05 21:04:20 +00001245 // Loading the allocation -> undef.
Victor Hernandezb1687302009-10-23 21:09:37 +00001246 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
Chris Lattner19b84b32009-09-21 06:30:24 +00001247 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1248 UndefValue::get(LI->getType())));
Chris Lattner46876282008-12-01 01:15:42 +00001249 continue;
1250 }
Owen Andersonc07861a2009-10-28 07:05:35 +00001251
1252 // Loading immediately after lifetime begin or end -> undef.
1253 if (IntrinsicInst* II = dyn_cast<IntrinsicInst>(DepInst)) {
1254 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1255 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1256 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1257 UndefValue::get(LI->getType())));
1258 }
1259 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001260
Chris Lattner19b84b32009-09-21 06:30:24 +00001261 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001262 // Reject loads and stores that are to the same address but are of
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001263 // different types if we have to.
Chris Lattnerdcded152008-12-02 08:16:11 +00001264 if (S->getOperand(0)->getType() != LI->getType()) {
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001265 if (TD == 0)
1266 TD = getAnalysisIfAvailable<TargetData>();
1267
1268 // If the stored value is larger or equal to the loaded value, we can
1269 // reuse it.
Chris Lattner012b3602009-09-21 17:24:04 +00001270 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getOperand(0),
1271 LI->getType(), *TD)) {
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001272 UnavailableBlocks.push_back(DepBB);
1273 continue;
1274 }
Chris Lattnerdcded152008-12-02 08:16:11 +00001275 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001276
Chris Lattner19b84b32009-09-21 06:30:24 +00001277 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1278 S->getOperand(0)));
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001279 continue;
1280 }
1281
1282 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001283 // If the types mismatch and we can't handle it, reject reuse of the load.
Chris Lattnerdcded152008-12-02 08:16:11 +00001284 if (LD->getType() != LI->getType()) {
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001285 if (TD == 0)
1286 TD = getAnalysisIfAvailable<TargetData>();
1287
1288 // If the stored value is larger or equal to the loaded value, we can
1289 // reuse it.
Chris Lattner012b3602009-09-21 17:24:04 +00001290 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001291 UnavailableBlocks.push_back(DepBB);
1292 continue;
1293 }
Chris Lattnerdcded152008-12-02 08:16:11 +00001294 }
Chris Lattner19b84b32009-09-21 06:30:24 +00001295 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB, LD));
Chris Lattnerdcded152008-12-02 08:16:11 +00001296 continue;
Owen Anderson5d72a422007-07-25 19:57:03 +00001297 }
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001298
1299 UnavailableBlocks.push_back(DepBB);
1300 continue;
Chris Lattner3d7103e2008-03-21 21:14:38 +00001301 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001302
Chris Lattnerdcded152008-12-02 08:16:11 +00001303 // If we have no predecessors that produce a known value for this load, exit
1304 // early.
1305 if (ValuesPerBlock.empty()) return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001306
Chris Lattnerdcded152008-12-02 08:16:11 +00001307 // If all of the instructions we depend on produce a known value for this
1308 // load, then it is fully redundant and we can use PHI insertion to compute
1309 // its value. Insert PHIs and remove the fully redundant value now.
1310 if (UnavailableBlocks.empty()) {
Dan Gohman7e124382009-07-31 20:24:18 +00001311 DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001312
Chris Lattnerdcded152008-12-02 08:16:11 +00001313 // Perform PHI construction.
Chris Lattner6e5ea272009-10-10 23:50:30 +00001314 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, TD,
1315 VN.getAliasAnalysis());
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001316 LI->replaceAllUsesWith(V);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001317
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001318 if (isa<PHINode>(V))
1319 V->takeName(LI);
1320 if (isa<PointerType>(V->getType()))
1321 MD->invalidateCachedPointerInfo(V);
Chris Lattnerdcded152008-12-02 08:16:11 +00001322 toErase.push_back(LI);
1323 NumGVNLoad++;
1324 return true;
1325 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001326
Chris Lattnerdcded152008-12-02 08:16:11 +00001327 if (!EnablePRE || !EnableLoadPRE)
1328 return false;
1329
1330 // Okay, we have *some* definitions of the value. This means that the value
1331 // is available in some of our (transitive) predecessors. Lets think about
1332 // doing PRE of this load. This will involve inserting a new load into the
1333 // predecessor when it's not available. We could do this in general, but
1334 // prefer to not increase code size. As such, we only do this when we know
1335 // that we only have to insert *one* load (which means we're basically moving
1336 // the load, not inserting a new one).
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001337
Owen Andersondd37b182009-05-31 09:03:40 +00001338 SmallPtrSet<BasicBlock *, 4> Blockers;
1339 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1340 Blockers.insert(UnavailableBlocks[i]);
1341
1342 // Lets find first basic block with more than one predecessor. Walk backwards
1343 // through predecessors if needed.
Chris Lattnerdcded152008-12-02 08:16:11 +00001344 BasicBlock *LoadBB = LI->getParent();
Owen Andersondd37b182009-05-31 09:03:40 +00001345 BasicBlock *TmpBB = LoadBB;
1346
1347 bool isSinglePred = false;
Dale Johannesena19b67f2009-06-17 20:48:23 +00001348 bool allSingleSucc = true;
Owen Andersondd37b182009-05-31 09:03:40 +00001349 while (TmpBB->getSinglePredecessor()) {
1350 isSinglePred = true;
1351 TmpBB = TmpBB->getSinglePredecessor();
1352 if (!TmpBB) // If haven't found any, bail now.
1353 return false;
1354 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1355 return false;
1356 if (Blockers.count(TmpBB))
1357 return false;
Dale Johannesena19b67f2009-06-17 20:48:23 +00001358 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1359 allSingleSucc = false;
Owen Andersondd37b182009-05-31 09:03:40 +00001360 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001361
Owen Andersondd37b182009-05-31 09:03:40 +00001362 assert(TmpBB);
1363 LoadBB = TmpBB;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001364
Chris Lattnerdcded152008-12-02 08:16:11 +00001365 // If we have a repl set with LI itself in it, this means we have a loop where
1366 // at least one of the values is LI. Since this means that we won't be able
1367 // to eliminate LI even if we insert uses in the other predecessors, we will
1368 // end up increasing code size. Reject this by scanning for LI.
1369 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner19b84b32009-09-21 06:30:24 +00001370 if (ValuesPerBlock[i].V == LI)
Chris Lattnerdcded152008-12-02 08:16:11 +00001371 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001372
Owen Andersondd37b182009-05-31 09:03:40 +00001373 if (isSinglePred) {
1374 bool isHot = false;
1375 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner19b84b32009-09-21 06:30:24 +00001376 if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].V))
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001377 // "Hot" Instruction is in some loop (because it dominates its dep.
1378 // instruction).
1379 if (DT->dominates(LI, I)) {
1380 isHot = true;
1381 break;
1382 }
Owen Andersondd37b182009-05-31 09:03:40 +00001383
1384 // We are interested only in "hot" instructions. We don't want to do any
1385 // mis-optimizations here.
1386 if (!isHot)
1387 return false;
1388 }
1389
Chris Lattnerdcded152008-12-02 08:16:11 +00001390 // Okay, we have some hope :). Check to see if the loaded value is fully
1391 // available in all but one predecessor.
1392 // FIXME: If we could restructure the CFG, we could make a common pred with
1393 // all the preds that don't have an available LI and insert a new load into
1394 // that one block.
1395 BasicBlock *UnavailablePred = 0;
1396
Chris Lattner159b98f2008-12-05 07:49:08 +00001397 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
Chris Lattnerdcded152008-12-02 08:16:11 +00001398 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner19b84b32009-09-21 06:30:24 +00001399 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
Chris Lattnerdcded152008-12-02 08:16:11 +00001400 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1401 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1402
1403 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1404 PI != E; ++PI) {
1405 if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1406 continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001407
Chris Lattnerdcded152008-12-02 08:16:11 +00001408 // If this load is not available in multiple predecessors, reject it.
1409 if (UnavailablePred && UnavailablePred != *PI)
1410 return false;
1411 UnavailablePred = *PI;
1412 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001413
Chris Lattnerdcded152008-12-02 08:16:11 +00001414 assert(UnavailablePred != 0 &&
1415 "Fully available value should be eliminated above!");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001416
Chris Lattnerdcded152008-12-02 08:16:11 +00001417 // If the loaded pointer is PHI node defined in this block, do PHI translation
1418 // to get its value in the predecessor.
1419 Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001420
Chris Lattnerdcded152008-12-02 08:16:11 +00001421 // Make sure the value is live in the predecessor. If it was defined by a
1422 // non-PHI instruction in this block, we don't know how to recompute it above.
1423 if (Instruction *LPInst = dyn_cast<Instruction>(LoadPtr))
1424 if (!DT->dominates(LPInst->getParent(), UnavailablePred)) {
Daniel Dunbar005975c2009-07-25 00:23:56 +00001425 DEBUG(errs() << "COULDN'T PRE LOAD BECAUSE PTR IS UNAVAILABLE IN PRED: "
Dan Gohman7e124382009-07-31 20:24:18 +00001426 << *LPInst << '\n' << *LI << "\n");
Chris Lattnerdcded152008-12-02 08:16:11 +00001427 return false;
1428 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001429
Chris Lattnerdcded152008-12-02 08:16:11 +00001430 // We don't currently handle critical edges :(
1431 if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
Daniel Dunbar005975c2009-07-25 00:23:56 +00001432 DEBUG(errs() << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
Dan Gohman7e124382009-07-31 20:24:18 +00001433 << UnavailablePred->getName() << "': " << *LI << '\n');
Chris Lattnerdcded152008-12-02 08:16:11 +00001434 return false;
Owen Anderson5b299672007-08-07 23:12:31 +00001435 }
Dale Johannesena19b67f2009-06-17 20:48:23 +00001436
1437 // Make sure it is valid to move this load here. We have to watch out for:
1438 // @1 = getelementptr (i8* p, ...
1439 // test p and branch if == 0
1440 // load @1
1441 // It is valid to have the getelementptr before the test, even if p can be 0,
1442 // as getelementptr only does address arithmetic.
1443 // If we are not pushing the value through any multiple-successor blocks
1444 // we do not have this case. Otherwise, check that the load is safe to
1445 // put anywhere; this can be improved, but should be conservatively safe.
1446 if (!allSingleSucc &&
1447 !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator()))
1448 return false;
1449
Chris Lattnerdcded152008-12-02 08:16:11 +00001450 // Okay, we can eliminate this load by inserting a reload in the predecessor
1451 // and using PHI construction to get the value in the other predecessors, do
1452 // it.
Dan Gohman7e124382009-07-31 20:24:18 +00001453 DEBUG(errs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001454
Chris Lattnerdcded152008-12-02 08:16:11 +00001455 Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1456 LI->getAlignment(),
1457 UnavailablePred->getTerminator());
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001458
Chris Lattner6e5ea272009-10-10 23:50:30 +00001459 // Add the newly created load.
1460 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,NewLoad));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001461
Chris Lattnerdcded152008-12-02 08:16:11 +00001462 // Perform PHI construction.
Chris Lattner6e5ea272009-10-10 23:50:30 +00001463 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, TD,
1464 VN.getAliasAnalysis());
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001465 LI->replaceAllUsesWith(V);
1466 if (isa<PHINode>(V))
1467 V->takeName(LI);
1468 if (isa<PointerType>(V->getType()))
1469 MD->invalidateCachedPointerInfo(V);
Chris Lattnerdcded152008-12-02 08:16:11 +00001470 toErase.push_back(LI);
1471 NumPRELoad++;
Owen Anderson5d72a422007-07-25 19:57:03 +00001472 return true;
1473}
1474
Owen Andersone0143452007-08-16 22:02:55 +00001475/// processLoad - Attempt to eliminate a load, first by eliminating it
1476/// locally, and then attempting non-local elimination if that fails.
Chris Lattner4531da82008-12-05 21:04:20 +00001477bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
1478 if (L->isVolatile())
Owen Anderson85c40642007-07-24 17:55:58 +00001479 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001480
Owen Anderson85c40642007-07-24 17:55:58 +00001481 // ... to a pointer that has been loaded from before...
Chris Lattnerff36c952009-09-21 02:42:51 +00001482 MemDepResult Dep = MD->getDependency(L);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001483
Chris Lattner4531da82008-12-05 21:04:20 +00001484 // If the value isn't available, don't do anything!
Chris Lattnerff36c952009-09-21 02:42:51 +00001485 if (Dep.isClobber()) {
Chris Lattner0907b522009-09-21 05:57:11 +00001486 // FIXME: We should handle memset/memcpy/memmove as dependent instructions
1487 // to forward the value if available.
1488 //if (isa<MemIntrinsic>(Dep.getInst()))
1489 //errs() << "LOAD DEPENDS ON MEM: " << *L << "\n" << *Dep.getInst()<<"\n\n";
1490
1491 // Check to see if we have something like this:
Chris Lattner7741aa52009-09-20 19:03:47 +00001492 // store i32 123, i32* %P
1493 // %A = bitcast i32* %P to i8*
1494 // %B = gep i8* %A, i32 1
1495 // %C = load i8* %B
1496 //
1497 // We could do that by recognizing if the clobber instructions are obviously
1498 // a common base + constant offset, and if the previous store (or memset)
1499 // completely covers this load. This sort of thing can happen in bitfield
1500 // access code.
Chris Lattner0907b522009-09-21 05:57:11 +00001501 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst()))
Chris Lattner41eb59c2009-09-21 06:22:46 +00001502 if (const TargetData *TD = getAnalysisIfAvailable<TargetData>()) {
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001503 int Offset = AnalyzeLoadFromClobberingStore(L, DepSI, *TD);
Chris Lattner41eb59c2009-09-21 06:22:46 +00001504 if (Offset != -1) {
1505 Value *AvailVal = GetStoreValueForLoad(DepSI->getOperand(0), Offset,
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001506 L->getType(), L, *TD);
Chris Lattner0907b522009-09-21 05:57:11 +00001507 DEBUG(errs() << "GVN COERCED STORE BITS:\n" << *DepSI << '\n'
1508 << *AvailVal << '\n' << *L << "\n\n\n");
1509
1510 // Replace the load!
1511 L->replaceAllUsesWith(AvailVal);
1512 if (isa<PointerType>(AvailVal->getType()))
1513 MD->invalidateCachedPointerInfo(AvailVal);
1514 toErase.push_back(L);
1515 NumGVNLoad++;
1516 return true;
1517 }
Chris Lattner41eb59c2009-09-21 06:22:46 +00001518 }
Chris Lattner0907b522009-09-21 05:57:11 +00001519
Edwin Török47cf8842009-05-29 09:46:03 +00001520 DEBUG(
1521 // fast print dep, using operator<< on instruction would be too slow
Dan Gohman0be10b02009-07-25 01:43:01 +00001522 errs() << "GVN: load ";
1523 WriteAsOperand(errs(), L);
Chris Lattnerff36c952009-09-21 02:42:51 +00001524 Instruction *I = Dep.getInst();
Dan Gohman7e124382009-07-31 20:24:18 +00001525 errs() << " is clobbered by " << *I << '\n';
Edwin Török47cf8842009-05-29 09:46:03 +00001526 );
Chris Lattner4531da82008-12-05 21:04:20 +00001527 return false;
Edwin Török47cf8842009-05-29 09:46:03 +00001528 }
Chris Lattner4531da82008-12-05 21:04:20 +00001529
1530 // If it is defined in another block, try harder.
Chris Lattnerff36c952009-09-21 02:42:51 +00001531 if (Dep.isNonLocal())
Chris Lattner4531da82008-12-05 21:04:20 +00001532 return processNonLocalLoad(L, toErase);
Eli Friedman350307f2008-02-12 12:08:14 +00001533
Chris Lattnerff36c952009-09-21 02:42:51 +00001534 Instruction *DepInst = Dep.getInst();
Chris Lattner4531da82008-12-05 21:04:20 +00001535 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
Chris Lattner7741aa52009-09-20 19:03:47 +00001536 Value *StoredVal = DepSI->getOperand(0);
1537
1538 // The store and load are to a must-aliased pointer, but they may not
1539 // actually have the same type. See if we know how to reuse the stored
1540 // value (depending on its type).
1541 const TargetData *TD = 0;
Chris Lattner10460aa2009-10-21 04:11:19 +00001542 if (StoredVal->getType() != L->getType()) {
1543 if ((TD = getAnalysisIfAvailable<TargetData>())) {
1544 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1545 L, *TD);
1546 if (StoredVal == 0)
1547 return false;
1548
1549 DEBUG(errs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1550 << '\n' << *L << "\n\n\n");
1551 }
1552 else
Chris Lattner7741aa52009-09-20 19:03:47 +00001553 return false;
Chris Lattner7741aa52009-09-20 19:03:47 +00001554 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001555
Chris Lattner4531da82008-12-05 21:04:20 +00001556 // Remove it!
Chris Lattner7741aa52009-09-20 19:03:47 +00001557 L->replaceAllUsesWith(StoredVal);
1558 if (isa<PointerType>(StoredVal->getType()))
1559 MD->invalidateCachedPointerInfo(StoredVal);
Chris Lattner4531da82008-12-05 21:04:20 +00001560 toErase.push_back(L);
1561 NumGVNLoad++;
1562 return true;
1563 }
1564
1565 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
Chris Lattner7741aa52009-09-20 19:03:47 +00001566 Value *AvailableVal = DepLI;
1567
1568 // The loads are of a must-aliased pointer, but they may not actually have
1569 // the same type. See if we know how to reuse the previously loaded value
1570 // (depending on its type).
1571 const TargetData *TD = 0;
Chris Lattner10460aa2009-10-21 04:11:19 +00001572 if (DepLI->getType() != L->getType()) {
1573 if ((TD = getAnalysisIfAvailable<TargetData>())) {
1574 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(), L,*TD);
1575 if (AvailableVal == 0)
1576 return false;
Chris Lattner7741aa52009-09-20 19:03:47 +00001577
Chris Lattner10460aa2009-10-21 04:11:19 +00001578 DEBUG(errs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1579 << "\n" << *L << "\n\n\n");
1580 }
1581 else
1582 return false;
Chris Lattner7741aa52009-09-20 19:03:47 +00001583 }
1584
Chris Lattner4531da82008-12-05 21:04:20 +00001585 // Remove it!
Chris Lattner7741aa52009-09-20 19:03:47 +00001586 L->replaceAllUsesWith(AvailableVal);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001587 if (isa<PointerType>(DepLI->getType()))
1588 MD->invalidateCachedPointerInfo(DepLI);
Chris Lattner4531da82008-12-05 21:04:20 +00001589 toErase.push_back(L);
1590 NumGVNLoad++;
1591 return true;
1592 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001593
Chris Lattner8ea60462008-11-30 01:39:32 +00001594 // If this load really doesn't depend on anything, then we must be loading an
1595 // undef value. This can happen when loading for a fresh allocation with no
1596 // intervening stores, for example.
Victor Hernandezb1687302009-10-23 21:09:37 +00001597 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +00001598 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner8ea60462008-11-30 01:39:32 +00001599 toErase.push_back(L);
Chris Lattner8ea60462008-11-30 01:39:32 +00001600 NumGVNLoad++;
Chris Lattner4531da82008-12-05 21:04:20 +00001601 return true;
Eli Friedman350307f2008-02-12 12:08:14 +00001602 }
Owen Andersonc07861a2009-10-28 07:05:35 +00001603
1604 // If this load occurs either right after a lifetime begin or a lifetime end,
1605 // then the loaded value is undefined.
1606 if (IntrinsicInst* II = dyn_cast<IntrinsicInst>(DepInst)) {
1607 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1608 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1609 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1610 toErase.push_back(L);
1611 NumGVNLoad++;
1612 return true;
1613 }
1614 }
Eli Friedman350307f2008-02-12 12:08:14 +00001615
Chris Lattner4531da82008-12-05 21:04:20 +00001616 return false;
Owen Anderson85c40642007-07-24 17:55:58 +00001617}
1618
Chris Lattnerff36c952009-09-21 02:42:51 +00001619Value *GVN::lookupNumber(BasicBlock *BB, uint32_t num) {
Owen Andersonaef6a922008-06-23 17:49:45 +00001620 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1621 if (I == localAvail.end())
1622 return 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001623
Chris Lattnerff36c952009-09-21 02:42:51 +00001624 ValueNumberScope *Locals = I->second;
1625 while (Locals) {
1626 DenseMap<uint32_t, Value*>::iterator I = Locals->table.find(num);
1627 if (I != Locals->table.end())
Owen Anderson2a412722008-06-20 01:15:47 +00001628 return I->second;
Chris Lattnerff36c952009-09-21 02:42:51 +00001629 Locals = Locals->parent;
Owen Anderson2a412722008-06-20 01:15:47 +00001630 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001631
Owen Anderson2a412722008-06-20 01:15:47 +00001632 return 0;
1633}
1634
Owen Andersona03e7862008-12-15 02:03:00 +00001635
Owen Andersonf631bb62007-08-14 18:16:29 +00001636/// processInstruction - When calculating availability, handle an instruction
Owen Anderson85c40642007-07-24 17:55:58 +00001637/// by inserting it into the appropriate sets
Owen Anderson9334fc62008-06-12 19:25:32 +00001638bool GVN::processInstruction(Instruction *I,
Chris Lattner7de20452008-03-21 22:01:16 +00001639 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001640 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1641 bool Changed = processLoad(LI, toErase);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001642
Chris Lattnerff36c952009-09-21 02:42:51 +00001643 if (!Changed) {
1644 unsigned Num = VN.lookup_or_add(LI);
1645 localAvail[I->getParent()]->table.insert(std::make_pair(Num, LI));
Owen Andersone6b4ff82008-06-18 21:41:49 +00001646 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001647
Chris Lattnerff36c952009-09-21 02:42:51 +00001648 return Changed;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001649 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001650
Chris Lattnerff36c952009-09-21 02:42:51 +00001651 uint32_t NextNum = VN.getNextUnusedValueNumber();
1652 unsigned Num = VN.lookup_or_add(I);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001653
Chris Lattnerff36c952009-09-21 02:42:51 +00001654 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1655 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001656
Owen Andersonef8bf0f2009-04-01 23:53:49 +00001657 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1658 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001659
Chris Lattnerff36c952009-09-21 02:42:51 +00001660 Value *BranchCond = BI->getCondition();
1661 uint32_t CondVN = VN.lookup_or_add(BranchCond);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001662
Chris Lattnerff36c952009-09-21 02:42:51 +00001663 BasicBlock *TrueSucc = BI->getSuccessor(0);
1664 BasicBlock *FalseSucc = BI->getSuccessor(1);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001665
Chris Lattnerff36c952009-09-21 02:42:51 +00001666 if (TrueSucc->getSinglePredecessor())
1667 localAvail[TrueSucc]->table[CondVN] =
1668 ConstantInt::getTrue(TrueSucc->getContext());
1669 if (FalseSucc->getSinglePredecessor())
1670 localAvail[FalseSucc]->table[CondVN] =
1671 ConstantInt::getFalse(TrueSucc->getContext());
Owen Andersonef8bf0f2009-04-01 23:53:49 +00001672
1673 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001674
Owen Andersonced50f82008-04-07 09:59:07 +00001675 // Allocations are always uniquely numbered, so we can save time and memory
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001676 // by fast failing them.
Victor Hernandezb1687302009-10-23 21:09:37 +00001677 } else if (isa<AllocaInst>(I) || isa<TerminatorInst>(I)) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001678 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Andersonced50f82008-04-07 09:59:07 +00001679 return false;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001680 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001681
Owen Andersone0143452007-08-16 22:02:55 +00001682 // Collapse PHI nodes
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001683 if (PHINode* p = dyn_cast<PHINode>(I)) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001684 Value *constVal = CollapsePhi(p);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001685
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001686 if (constVal) {
Owen Andersone02ad522007-08-16 22:51:56 +00001687 p->replaceAllUsesWith(constVal);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001688 if (isa<PointerType>(constVal->getType()))
1689 MD->invalidateCachedPointerInfo(constVal);
Owen Anderson575f2812008-12-23 00:49:51 +00001690 VN.erase(p);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001691
Owen Andersone02ad522007-08-16 22:51:56 +00001692 toErase.push_back(p);
Owen Andersone6b4ff82008-06-18 21:41:49 +00001693 } else {
Chris Lattnerff36c952009-09-21 02:42:51 +00001694 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001695 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001696
Owen Anderson8a8d13c2008-07-03 17:44:33 +00001697 // If the number we were assigned was a brand new VN, then we don't
1698 // need to do a lookup to see if the number already exists
1699 // somewhere in the domtree: it can't!
Chris Lattnerff36c952009-09-21 02:42:51 +00001700 } else if (Num == NextNum) {
1701 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001702
Owen Andersona03e7862008-12-15 02:03:00 +00001703 // Perform fast-path value-number based elimination of values inherited from
1704 // dominators.
Chris Lattnerff36c952009-09-21 02:42:51 +00001705 } else if (Value *repl = lookupNumber(I->getParent(), Num)) {
Owen Andersonc772be72007-12-08 01:37:09 +00001706 // Remove it!
Owen Anderson5aff8002007-07-31 23:27:13 +00001707 VN.erase(I);
Owen Anderson85c40642007-07-24 17:55:58 +00001708 I->replaceAllUsesWith(repl);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001709 if (isa<PointerType>(repl->getType()))
1710 MD->invalidateCachedPointerInfo(repl);
Owen Anderson85c40642007-07-24 17:55:58 +00001711 toErase.push_back(I);
1712 return true;
Owen Andersona03e7862008-12-15 02:03:00 +00001713
Owen Anderson8a8d13c2008-07-03 17:44:33 +00001714 } else {
Chris Lattnerff36c952009-09-21 02:42:51 +00001715 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Anderson85c40642007-07-24 17:55:58 +00001716 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001717
Owen Anderson85c40642007-07-24 17:55:58 +00001718 return false;
1719}
1720
Bill Wendling42f17f62008-12-22 22:32:22 +00001721/// runOnFunction - This is the main transformation entry point for a function.
Owen Andersonbe168b32007-08-14 18:04:11 +00001722bool GVN::runOnFunction(Function& F) {
Chris Lattner02ca4422008-12-01 00:40:32 +00001723 MD = &getAnalysis<MemoryDependenceAnalysis>();
1724 DT = &getAnalysis<DominatorTree>();
Owen Andersonbcf2bd52008-05-12 20:15:55 +00001725 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
Chris Lattner02ca4422008-12-01 00:40:32 +00001726 VN.setMemDep(MD);
1727 VN.setDomTree(DT);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001728
Chris Lattnerff36c952009-09-21 02:42:51 +00001729 bool Changed = false;
1730 bool ShouldContinue = true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001731
Owen Anderson26ed2572008-07-16 17:52:31 +00001732 // Merge unconditional branches, allowing PRE to catch more
1733 // optimization opportunities.
1734 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001735 BasicBlock *BB = FI;
Owen Anderson26ed2572008-07-16 17:52:31 +00001736 ++FI;
Owen Andersonf59eef82008-07-17 00:01:40 +00001737 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1738 if (removedBlock) NumGVNBlocks++;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001739
Chris Lattnerff36c952009-09-21 02:42:51 +00001740 Changed |= removedBlock;
Owen Anderson26ed2572008-07-16 17:52:31 +00001741 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001742
Chris Lattner4bab29b2008-12-09 19:21:47 +00001743 unsigned Iteration = 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001744
Chris Lattnerff36c952009-09-21 02:42:51 +00001745 while (ShouldContinue) {
Dan Gohman0be10b02009-07-25 01:43:01 +00001746 DEBUG(errs() << "GVN iteration: " << Iteration << "\n");
Chris Lattnerff36c952009-09-21 02:42:51 +00001747 ShouldContinue = iterateOnFunction(F);
1748 Changed |= ShouldContinue;
Chris Lattner4bab29b2008-12-09 19:21:47 +00001749 ++Iteration;
Owen Andersonbe168b32007-08-14 18:04:11 +00001750 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001751
Owen Anderson916f4732008-07-18 18:03:38 +00001752 if (EnablePRE) {
Owen Anderson9c935902008-09-03 23:06:07 +00001753 bool PREChanged = true;
1754 while (PREChanged) {
1755 PREChanged = performPRE(F);
Chris Lattnerff36c952009-09-21 02:42:51 +00001756 Changed |= PREChanged;
Owen Anderson9c935902008-09-03 23:06:07 +00001757 }
Owen Anderson916f4732008-07-18 18:03:38 +00001758 }
Chris Lattner4bab29b2008-12-09 19:21:47 +00001759 // FIXME: Should perform GVN again after PRE does something. PRE can move
1760 // computations into blocks where they become fully redundant. Note that
1761 // we can't do this until PRE's critical edge splitting updates memdep.
1762 // Actually, when this happens, we should just fully integrate PRE into GVN.
Nuno Lopes274474b2008-10-10 16:25:50 +00001763
1764 cleanupGlobalSets();
1765
Chris Lattnerff36c952009-09-21 02:42:51 +00001766 return Changed;
Owen Andersonbe168b32007-08-14 18:04:11 +00001767}
1768
1769
Chris Lattnerff36c952009-09-21 02:42:51 +00001770bool GVN::processBlock(BasicBlock *BB) {
Chris Lattner4bab29b2008-12-09 19:21:47 +00001771 // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1772 // incrementing BI before processing an instruction).
Owen Anderson9334fc62008-06-12 19:25:32 +00001773 SmallVector<Instruction*, 8> toErase;
Chris Lattnerff36c952009-09-21 02:42:51 +00001774 bool ChangedFunction = false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001775
Owen Anderson9334fc62008-06-12 19:25:32 +00001776 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1777 BI != BE;) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001778 ChangedFunction |= processInstruction(BI, toErase);
Owen Anderson9334fc62008-06-12 19:25:32 +00001779 if (toErase.empty()) {
1780 ++BI;
1781 continue;
1782 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001783
Owen Anderson9334fc62008-06-12 19:25:32 +00001784 // If we need some instructions deleted, do it now.
1785 NumGVNInstr += toErase.size();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001786
Owen Anderson9334fc62008-06-12 19:25:32 +00001787 // Avoid iterator invalidation.
1788 bool AtStart = BI == BB->begin();
1789 if (!AtStart)
1790 --BI;
1791
1792 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
Chris Lattner02ca4422008-12-01 00:40:32 +00001793 E = toErase.end(); I != E; ++I) {
Dan Gohman7e124382009-07-31 20:24:18 +00001794 DEBUG(errs() << "GVN removed: " << **I << '\n');
Chris Lattner02ca4422008-12-01 00:40:32 +00001795 MD->removeInstruction(*I);
Owen Anderson9334fc62008-06-12 19:25:32 +00001796 (*I)->eraseFromParent();
Bill Wendling84049422008-12-22 21:57:30 +00001797 DEBUG(verifyRemoved(*I));
Chris Lattner02ca4422008-12-01 00:40:32 +00001798 }
Chris Lattner4bab29b2008-12-09 19:21:47 +00001799 toErase.clear();
Owen Anderson9334fc62008-06-12 19:25:32 +00001800
1801 if (AtStart)
1802 BI = BB->begin();
1803 else
1804 ++BI;
Owen Anderson9334fc62008-06-12 19:25:32 +00001805 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001806
Chris Lattnerff36c952009-09-21 02:42:51 +00001807 return ChangedFunction;
Owen Anderson9334fc62008-06-12 19:25:32 +00001808}
1809
Owen Andersone6b4ff82008-06-18 21:41:49 +00001810/// performPRE - Perform a purely local form of PRE that looks for diamond
1811/// control flow patterns and attempts to perform simple PRE at the join point.
1812bool GVN::performPRE(Function& F) {
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001813 bool Changed = false;
Owen Andersonec747c42008-06-19 19:54:19 +00001814 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
Chris Lattner3304b562008-12-01 07:29:03 +00001815 DenseMap<BasicBlock*, Value*> predMap;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001816 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1817 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001818 BasicBlock *CurrentBlock = *DI;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001819
Owen Andersone6b4ff82008-06-18 21:41:49 +00001820 // Nothing to PRE in the entry block.
1821 if (CurrentBlock == &F.getEntryBlock()) continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001822
Owen Andersone6b4ff82008-06-18 21:41:49 +00001823 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1824 BE = CurrentBlock->end(); BI != BE; ) {
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001825 Instruction *CurInst = BI++;
Duncan Sands2f500832009-05-06 06:49:50 +00001826
Victor Hernandezb1687302009-10-23 21:09:37 +00001827 if (isa<AllocaInst>(CurInst) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +00001828 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
Devang Patele9d08b82009-10-14 17:29:00 +00001829 CurInst->getType()->isVoidTy() ||
Duncan Sands2f500832009-05-06 06:49:50 +00001830 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
John Criswell6e0aa282009-03-10 15:04:53 +00001831 isa<DbgInfoIntrinsic>(CurInst))
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001832 continue;
Duncan Sands2f500832009-05-06 06:49:50 +00001833
Chris Lattnerff36c952009-09-21 02:42:51 +00001834 uint32_t ValNo = VN.lookup(CurInst);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001835
Owen Andersone6b4ff82008-06-18 21:41:49 +00001836 // Look for the predecessors for PRE opportunities. We're
1837 // only trying to solve the basic diamond case, where
1838 // a value is computed in the successor and one predecessor,
1839 // but not the other. We also explicitly disallow cases
1840 // where the successor is its own predecessor, because they're
1841 // more complicated to get right.
Chris Lattnerff36c952009-09-21 02:42:51 +00001842 unsigned NumWith = 0;
1843 unsigned NumWithout = 0;
1844 BasicBlock *PREPred = 0;
Chris Lattner3304b562008-12-01 07:29:03 +00001845 predMap.clear();
1846
Owen Andersone6b4ff82008-06-18 21:41:49 +00001847 for (pred_iterator PI = pred_begin(CurrentBlock),
1848 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1849 // We're not interested in PRE where the block is its
Owen Anderson2a412722008-06-20 01:15:47 +00001850 // own predecessor, on in blocks with predecessors
1851 // that are not reachable.
1852 if (*PI == CurrentBlock) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001853 NumWithout = 2;
Owen Anderson2a412722008-06-20 01:15:47 +00001854 break;
1855 } else if (!localAvail.count(*PI)) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001856 NumWithout = 2;
Owen Anderson2a412722008-06-20 01:15:47 +00001857 break;
1858 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001859
1860 DenseMap<uint32_t, Value*>::iterator predV =
Chris Lattnerff36c952009-09-21 02:42:51 +00001861 localAvail[*PI]->table.find(ValNo);
Owen Anderson2a412722008-06-20 01:15:47 +00001862 if (predV == localAvail[*PI]->table.end()) {
Owen Andersone6b4ff82008-06-18 21:41:49 +00001863 PREPred = *PI;
Chris Lattnerff36c952009-09-21 02:42:51 +00001864 NumWithout++;
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001865 } else if (predV->second == CurInst) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001866 NumWithout = 2;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001867 } else {
Owen Anderson2a412722008-06-20 01:15:47 +00001868 predMap[*PI] = predV->second;
Chris Lattnerff36c952009-09-21 02:42:51 +00001869 NumWith++;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001870 }
1871 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001872
Owen Andersone6b4ff82008-06-18 21:41:49 +00001873 // Don't do PRE when it might increase code size, i.e. when
1874 // we would need to insert instructions in more than one pred.
Chris Lattnerff36c952009-09-21 02:42:51 +00001875 if (NumWithout != 1 || NumWith == 0)
Owen Andersone6b4ff82008-06-18 21:41:49 +00001876 continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001877
Owen Andersonec747c42008-06-19 19:54:19 +00001878 // We can't do PRE safely on a critical edge, so instead we schedule
1879 // the edge to be split and perform the PRE the next time we iterate
1880 // on the function.
Chris Lattnerff36c952009-09-21 02:42:51 +00001881 unsigned SuccNum = 0;
Owen Andersonec747c42008-06-19 19:54:19 +00001882 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1883 i != e; ++i)
Owen Anderson9c935902008-09-03 23:06:07 +00001884 if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001885 SuccNum = i;
Owen Andersonec747c42008-06-19 19:54:19 +00001886 break;
1887 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001888
Chris Lattnerff36c952009-09-21 02:42:51 +00001889 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
1890 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
Owen Andersonec747c42008-06-19 19:54:19 +00001891 continue;
1892 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001893
Owen Andersone6b4ff82008-06-18 21:41:49 +00001894 // Instantiate the expression the in predecessor that lacked it.
1895 // Because we are going top-down through the block, all value numbers
1896 // will be available in the predecessor by the time we need them. Any
1897 // that weren't original present will have been instantiated earlier
1898 // in this loop.
Nick Lewyckyc94270c2009-09-27 07:38:41 +00001899 Instruction *PREInstr = CurInst->clone();
Owen Andersone6b4ff82008-06-18 21:41:49 +00001900 bool success = true;
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001901 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
1902 Value *Op = PREInstr->getOperand(i);
1903 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
1904 continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001905
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001906 if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
1907 PREInstr->setOperand(i, V);
1908 } else {
1909 success = false;
1910 break;
Owen Anderson14c612f2008-07-11 20:05:13 +00001911 }
Owen Andersone6b4ff82008-06-18 21:41:49 +00001912 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001913
Owen Andersone6b4ff82008-06-18 21:41:49 +00001914 // Fail out if we encounter an operand that is not available in
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001915 // the PRE predecessor. This is typically because of loads which
Owen Andersone6b4ff82008-06-18 21:41:49 +00001916 // are not value numbered precisely.
1917 if (!success) {
1918 delete PREInstr;
Bill Wendling3858cae2008-12-22 22:14:07 +00001919 DEBUG(verifyRemoved(PREInstr));
Owen Andersone6b4ff82008-06-18 21:41:49 +00001920 continue;
1921 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001922
Owen Andersone6b4ff82008-06-18 21:41:49 +00001923 PREInstr->insertBefore(PREPred->getTerminator());
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001924 PREInstr->setName(CurInst->getName() + ".pre");
Owen Anderson2a412722008-06-20 01:15:47 +00001925 predMap[PREPred] = PREInstr;
Chris Lattnerff36c952009-09-21 02:42:51 +00001926 VN.add(PREInstr, ValNo);
Owen Andersone6b4ff82008-06-18 21:41:49 +00001927 NumGVNPRE++;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001928
Owen Andersone6b4ff82008-06-18 21:41:49 +00001929 // Update the availability map to include the new instruction.
Chris Lattnerff36c952009-09-21 02:42:51 +00001930 localAvail[PREPred]->table.insert(std::make_pair(ValNo, PREInstr));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001931
Owen Andersone6b4ff82008-06-18 21:41:49 +00001932 // Create a PHI to make the value available in this block.
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001933 PHINode* Phi = PHINode::Create(CurInst->getType(),
1934 CurInst->getName() + ".pre-phi",
Owen Andersone6b4ff82008-06-18 21:41:49 +00001935 CurrentBlock->begin());
1936 for (pred_iterator PI = pred_begin(CurrentBlock),
1937 PE = pred_end(CurrentBlock); PI != PE; ++PI)
Owen Anderson2a412722008-06-20 01:15:47 +00001938 Phi->addIncoming(predMap[*PI], *PI);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001939
Chris Lattnerff36c952009-09-21 02:42:51 +00001940 VN.add(Phi, ValNo);
1941 localAvail[CurrentBlock]->table[ValNo] = Phi;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001942
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001943 CurInst->replaceAllUsesWith(Phi);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001944 if (isa<PointerType>(Phi->getType()))
1945 MD->invalidateCachedPointerInfo(Phi);
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001946 VN.erase(CurInst);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001947
Dan Gohman7e124382009-07-31 20:24:18 +00001948 DEBUG(errs() << "GVN PRE removed: " << *CurInst << '\n');
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001949 MD->removeInstruction(CurInst);
1950 CurInst->eraseFromParent();
Bill Wendling84049422008-12-22 21:57:30 +00001951 DEBUG(verifyRemoved(CurInst));
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001952 Changed = true;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001953 }
1954 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001955
Owen Andersonec747c42008-06-19 19:54:19 +00001956 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
Anton Korobeynikov2e8710c2008-12-05 19:38:49 +00001957 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
Owen Andersonec747c42008-06-19 19:54:19 +00001958 SplitCriticalEdge(I->first, I->second, this);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001959
Anton Korobeynikov2e8710c2008-12-05 19:38:49 +00001960 return Changed || toSplit.size();
Owen Andersone6b4ff82008-06-18 21:41:49 +00001961}
1962
Bill Wendling42f17f62008-12-22 22:32:22 +00001963/// iterateOnFunction - Executes one iteration of GVN
Owen Andersonbe168b32007-08-14 18:04:11 +00001964bool GVN::iterateOnFunction(Function &F) {
Nuno Lopes274474b2008-10-10 16:25:50 +00001965 cleanupGlobalSets();
Chris Lattner98054902008-03-21 21:33:23 +00001966
Owen Andersonef8bf0f2009-04-01 23:53:49 +00001967 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1968 DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
1969 if (DI->getIDom())
1970 localAvail[DI->getBlock()] =
1971 new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
1972 else
1973 localAvail[DI->getBlock()] = new ValueNumberScope(0);
1974 }
1975
Owen Anderson85c40642007-07-24 17:55:58 +00001976 // Top-down walk of the dominator tree
Chris Lattnerff36c952009-09-21 02:42:51 +00001977 bool Changed = false;
Owen Andersonef136f52008-12-15 03:52:17 +00001978#if 0
1979 // Needed for value numbering with phi construction to work.
Owen Andersona03e7862008-12-15 02:03:00 +00001980 ReversePostOrderTraversal<Function*> RPOT(&F);
1981 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
1982 RE = RPOT.end(); RI != RE; ++RI)
Chris Lattnerff36c952009-09-21 02:42:51 +00001983 Changed |= processBlock(*RI);
Owen Andersonef136f52008-12-15 03:52:17 +00001984#else
1985 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1986 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
Chris Lattnerff36c952009-09-21 02:42:51 +00001987 Changed |= processBlock(DI->getBlock());
Owen Andersonef136f52008-12-15 03:52:17 +00001988#endif
1989
Chris Lattnerff36c952009-09-21 02:42:51 +00001990 return Changed;
Owen Anderson85c40642007-07-24 17:55:58 +00001991}
Nuno Lopes274474b2008-10-10 16:25:50 +00001992
1993void GVN::cleanupGlobalSets() {
1994 VN.clear();
Nuno Lopes274474b2008-10-10 16:25:50 +00001995
1996 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1997 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1998 delete I->second;
1999 localAvail.clear();
2000}
Bill Wendling2a023742008-12-22 21:36:08 +00002001
2002/// verifyRemoved - Verify that the specified instruction does not occur in our
2003/// internal data structures.
Bill Wendlingf9c0e9e2008-12-22 22:28:56 +00002004void GVN::verifyRemoved(const Instruction *Inst) const {
2005 VN.verifyRemoved(Inst);
Bill Wendling3858cae2008-12-22 22:14:07 +00002006
Bill Wendlingf9c0e9e2008-12-22 22:28:56 +00002007 // Walk through the value number scope to make sure the instruction isn't
2008 // ferreted away in it.
2009 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
2010 I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
2011 const ValueNumberScope *VNS = I->second;
2012
2013 while (VNS) {
2014 for (DenseMap<uint32_t, Value*>::iterator
2015 II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
2016 assert(II->second != Inst && "Inst still in value numbering scope!");
2017 }
2018
2019 VNS = VNS->parent;
Bill Wendling3858cae2008-12-22 22:14:07 +00002020 }
2021 }
Bill Wendling2a023742008-12-22 21:36:08 +00002022}