blob: e97bfccda011234b188c3b0cd40f175c3fe6361a [file] [log] [blame]
Chris Lattner704541b2011-01-02 21:47:05 +00001//===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs a simple dominator tree walk that eliminates trivially
11// redundant instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner704541b2011-01-02 21:47:05 +000015#include "llvm/Transforms/Scalar.h"
Michael Ilseman336cb792012-10-09 16:57:38 +000016#include "llvm/ADT/Hashing.h"
Chris Lattner18ae5432011-01-02 23:04:14 +000017#include "llvm/ADT/ScopedHashTable.h"
Chris Lattner8fac5db2011-01-02 23:19:45 +000018#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000021#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Instructions.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Pass.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/RecyclingAllocator.h"
26#include "llvm/Target/TargetLibraryInfo.h"
27#include "llvm/Transforms/Utils/Local.h"
Michael Gottesman2bf01732013-12-05 18:42:12 +000028#include <vector>
Chris Lattner704541b2011-01-02 21:47:05 +000029using namespace llvm;
30
Chandler Carruth964daaa2014-04-22 02:55:47 +000031#define DEBUG_TYPE "early-cse"
32
Chris Lattner4cb36542011-01-03 03:28:23 +000033STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
34STATISTIC(NumCSE, "Number of instructions CSE'd");
Chris Lattner92bb0f92011-01-03 03:41:27 +000035STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
36STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner9e5e9ed2011-01-03 04:17:24 +000037STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattnerb9a8efc2011-01-03 03:18:43 +000038
39static unsigned getHash(const void *V) {
40 return DenseMapInfo<const void*>::getHashValue(V);
41}
Chris Lattner8fac5db2011-01-02 23:19:45 +000042
Chris Lattner79d83062011-01-03 02:20:48 +000043//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +000044// SimpleValue
Chris Lattner79d83062011-01-03 02:20:48 +000045//===----------------------------------------------------------------------===//
46
Chris Lattner704541b2011-01-02 21:47:05 +000047namespace {
Chris Lattner79d83062011-01-03 02:20:48 +000048 /// SimpleValue - Instances of this struct represent available values in the
Chris Lattner18ae5432011-01-02 23:04:14 +000049 /// scoped hash table.
Chris Lattner79d83062011-01-03 02:20:48 +000050 struct SimpleValue {
Chris Lattner18ae5432011-01-02 23:04:14 +000051 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +000052
Chris Lattner4cb36542011-01-03 03:28:23 +000053 SimpleValue(Instruction *I) : Inst(I) {
54 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
55 }
Nadav Rotem465834c2012-07-24 10:51:42 +000056
Chris Lattner18ae5432011-01-02 23:04:14 +000057 bool isSentinel() const {
58 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
59 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
60 }
Nadav Rotem465834c2012-07-24 10:51:42 +000061
Chris Lattner18ae5432011-01-02 23:04:14 +000062 static bool canHandle(Instruction *Inst) {
Chris Lattnerbde6ec12011-01-03 23:38:13 +000063 // This can only handle non-void readnone functions.
64 if (CallInst *CI = dyn_cast<CallInst>(Inst))
65 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
Chris Lattner8fac5db2011-01-02 23:19:45 +000066 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
67 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
68 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
69 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
70 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +000071 }
Chris Lattner18ae5432011-01-02 23:04:14 +000072 };
73}
74
75namespace llvm {
Chris Lattner79d83062011-01-03 02:20:48 +000076template<> struct DenseMapInfo<SimpleValue> {
77 static inline SimpleValue getEmptyKey() {
Chris Lattner4cb36542011-01-03 03:28:23 +000078 return DenseMapInfo<Instruction*>::getEmptyKey();
Chris Lattner18ae5432011-01-02 23:04:14 +000079 }
Chris Lattner79d83062011-01-03 02:20:48 +000080 static inline SimpleValue getTombstoneKey() {
Chris Lattner4cb36542011-01-03 03:28:23 +000081 return DenseMapInfo<Instruction*>::getTombstoneKey();
Chris Lattner18ae5432011-01-02 23:04:14 +000082 }
Chris Lattner79d83062011-01-03 02:20:48 +000083 static unsigned getHashValue(SimpleValue Val);
84 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattner18ae5432011-01-02 23:04:14 +000085};
86}
87
Chris Lattner79d83062011-01-03 02:20:48 +000088unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattner18ae5432011-01-02 23:04:14 +000089 Instruction *Inst = Val.Inst;
Chris Lattner02a97762011-01-03 01:10:08 +000090 // Hash in all of the operands as pointers.
Michael Ilseman336cb792012-10-09 16:57:38 +000091 if (BinaryOperator* BinOp = dyn_cast<BinaryOperator>(Inst)) {
92 Value *LHS = BinOp->getOperand(0);
93 Value *RHS = BinOp->getOperand(1);
94 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
95 std::swap(LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +000096
Michael Ilseman336cb792012-10-09 16:57:38 +000097 if (isa<OverflowingBinaryOperator>(BinOp)) {
98 // Hash the overflow behavior
99 unsigned Overflow =
100 BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
101 BinOp->hasNoUnsignedWrap() * OverflowingBinaryOperator::NoUnsignedWrap;
102 return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
103 }
104
105 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000106 }
107
Michael Ilseman336cb792012-10-09 16:57:38 +0000108 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
109 Value *LHS = CI->getOperand(0);
110 Value *RHS = CI->getOperand(1);
111 CmpInst::Predicate Pred = CI->getPredicate();
112 if (Inst->getOperand(0) > Inst->getOperand(1)) {
113 std::swap(LHS, RHS);
114 Pred = CI->getSwappedPredicate();
115 }
116 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
117 }
118
119 if (CastInst *CI = dyn_cast<CastInst>(Inst))
120 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
121
122 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
123 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
124 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
125
126 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
127 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
128 IVI->getOperand(1),
129 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
130
131 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
132 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
133 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
134 isa<ShuffleVectorInst>(Inst)) && "Invalid/unknown instruction");
135
Chris Lattner02a97762011-01-03 01:10:08 +0000136 // Mix in the opcode.
Michael Ilseman336cb792012-10-09 16:57:38 +0000137 return hash_combine(Inst->getOpcode(),
138 hash_combine_range(Inst->value_op_begin(),
139 Inst->value_op_end()));
Chris Lattner18ae5432011-01-02 23:04:14 +0000140}
141
Chris Lattner79d83062011-01-03 02:20:48 +0000142bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000143 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
144
145 if (LHS.isSentinel() || RHS.isSentinel())
146 return LHSI == RHSI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000147
Chris Lattner18ae5432011-01-02 23:04:14 +0000148 if (LHSI->getOpcode() != RHSI->getOpcode()) return false;
Michael Ilseman336cb792012-10-09 16:57:38 +0000149 if (LHSI->isIdenticalTo(RHSI)) return true;
150
151 // If we're not strictly identical, we still might be a commutable instruction
152 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
153 if (!LHSBinOp->isCommutative())
154 return false;
155
156 assert(isa<BinaryOperator>(RHSI)
157 && "same opcode, but different instruction type?");
158 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
159
160 // Check overflow attributes
161 if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
162 assert(isa<OverflowingBinaryOperator>(RHSBinOp)
163 && "same opcode, but different operator type?");
164 if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
165 LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
166 return false;
167 }
168
169 // Commuted equality
170 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
171 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
172 }
173 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
174 assert(isa<CmpInst>(RHSI)
175 && "same opcode, but different instruction type?");
176 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
177 // Commuted equality
178 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
179 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
180 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
181 }
182
183 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000184}
185
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000186//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000187// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000188//===----------------------------------------------------------------------===//
189
190namespace {
Chris Lattner92bb0f92011-01-03 03:41:27 +0000191 /// CallValue - Instances of this struct represent available call values in
192 /// the scoped hash table.
193 struct CallValue {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000194 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000195
Chris Lattner92bb0f92011-01-03 03:41:27 +0000196 CallValue(Instruction *I) : Inst(I) {
Chris Lattner4cb36542011-01-03 03:28:23 +0000197 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
198 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000199
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000200 bool isSentinel() const {
201 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
202 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
203 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000204
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000205 static bool canHandle(Instruction *Inst) {
Chris Lattner16ca19f2011-01-03 18:43:03 +0000206 // Don't value number anything that returns void.
207 if (Inst->getType()->isVoidTy())
208 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000209
Chris Lattner142f1cd2011-01-03 18:28:15 +0000210 CallInst *CI = dyn_cast<CallInst>(Inst);
211 if (CI == 0 || !CI->onlyReadsMemory())
212 return false;
Chris Lattner142f1cd2011-01-03 18:28:15 +0000213 return true;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000214 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000215 };
216}
217
218namespace llvm {
Chris Lattner92bb0f92011-01-03 03:41:27 +0000219 template<> struct DenseMapInfo<CallValue> {
220 static inline CallValue getEmptyKey() {
Chris Lattner4cb36542011-01-03 03:28:23 +0000221 return DenseMapInfo<Instruction*>::getEmptyKey();
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000222 }
Chris Lattner92bb0f92011-01-03 03:41:27 +0000223 static inline CallValue getTombstoneKey() {
Chris Lattner4cb36542011-01-03 03:28:23 +0000224 return DenseMapInfo<Instruction*>::getTombstoneKey();
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000225 }
Chris Lattner92bb0f92011-01-03 03:41:27 +0000226 static unsigned getHashValue(CallValue Val);
227 static bool isEqual(CallValue LHS, CallValue RHS);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000228 };
229}
Chris Lattner92bb0f92011-01-03 03:41:27 +0000230unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000231 Instruction *Inst = Val.Inst;
232 // Hash in all of the operands as pointers.
233 unsigned Res = 0;
Chris Lattner16ca19f2011-01-03 18:43:03 +0000234 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) {
235 assert(!Inst->getOperand(i)->getType()->isMetadataTy() &&
236 "Cannot value number calls with metadata operands");
Eli Friedman154a9672011-10-12 22:00:26 +0000237 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
Chris Lattner16ca19f2011-01-03 18:43:03 +0000238 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000239
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000240 // Mix in the opcode.
241 return (Res << 1) ^ Inst->getOpcode();
242}
243
Chris Lattner92bb0f92011-01-03 03:41:27 +0000244bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000245 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000246 if (LHS.isSentinel() || RHS.isSentinel())
247 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000248 return LHSI->isIdenticalTo(RHSI);
249}
250
Chris Lattner18ae5432011-01-02 23:04:14 +0000251
Chris Lattner79d83062011-01-03 02:20:48 +0000252//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000253// EarlyCSE pass.
Chris Lattner79d83062011-01-03 02:20:48 +0000254//===----------------------------------------------------------------------===//
255
Chris Lattner18ae5432011-01-02 23:04:14 +0000256namespace {
Nadav Rotem465834c2012-07-24 10:51:42 +0000257
Chris Lattner704541b2011-01-02 21:47:05 +0000258/// EarlyCSE - This pass does a simple depth-first walk over the dominator
259/// tree, eliminating trivially redundant instructions and using instsimplify
260/// to canonicalize things as it goes. It is intended to be fast and catch
261/// obvious cases so that instcombine and other passes are more effective. It
262/// is expected that a later pass of GVN will catch the interesting/hard
263/// cases.
264class EarlyCSE : public FunctionPass {
265public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000266 const DataLayout *DL;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000267 const TargetLibraryInfo *TLI;
Chris Lattner18ae5432011-01-02 23:04:14 +0000268 DominatorTree *DT;
Chris Lattnerd815f692011-01-03 01:42:46 +0000269 typedef RecyclingAllocator<BumpPtrAllocator,
Chris Lattner79d83062011-01-03 02:20:48 +0000270 ScopedHashTableVal<SimpleValue, Value*> > AllocatorTy;
271 typedef ScopedHashTable<SimpleValue, Value*, DenseMapInfo<SimpleValue>,
Chris Lattnerd815f692011-01-03 01:42:46 +0000272 AllocatorTy> ScopedHTType;
Nadav Rotem465834c2012-07-24 10:51:42 +0000273
Chris Lattner79d83062011-01-03 02:20:48 +0000274 /// AvailableValues - This scoped hash table contains the current values of
275 /// all of our simple scalar expressions. As we walk down the domtree, we
276 /// look to see if instructions are in this: if so, we replace them with what
277 /// we find, otherwise we insert them so that dominated values can succeed in
278 /// their lookup.
279 ScopedHTType *AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000280
Chris Lattner92bb0f92011-01-03 03:41:27 +0000281 /// AvailableLoads - This scoped hash table contains the current values
282 /// of loads. This allows us to get efficient access to dominating loads when
283 /// we have a fully redundant load. In addition to the most recent load, we
284 /// keep track of a generation count of the read, which is compared against
285 /// the current generation count. The current generation count is
286 /// incremented after every possibly writing memory operation, which ensures
287 /// that we only CSE loads with other loads that have no intervening store.
Chris Lattner4b9a5252011-01-03 03:53:50 +0000288 typedef RecyclingAllocator<BumpPtrAllocator,
289 ScopedHashTableVal<Value*, std::pair<Value*, unsigned> > > LoadMapAllocator;
290 typedef ScopedHashTable<Value*, std::pair<Value*, unsigned>,
291 DenseMapInfo<Value*>, LoadMapAllocator> LoadHTType;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000292 LoadHTType *AvailableLoads;
Nadav Rotem465834c2012-07-24 10:51:42 +0000293
Chris Lattner92bb0f92011-01-03 03:41:27 +0000294 /// AvailableCalls - This scoped hash table contains the current values
295 /// of read-only call values. It uses the same generation count as loads.
296 typedef ScopedHashTable<CallValue, std::pair<Value*, unsigned> > CallHTType;
297 CallHTType *AvailableCalls;
Nadav Rotem465834c2012-07-24 10:51:42 +0000298
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000299 /// CurrentGeneration - This is the current generation of the memory value.
300 unsigned CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000301
Chris Lattner704541b2011-01-02 21:47:05 +0000302 static char ID;
Chris Lattner79d83062011-01-03 02:20:48 +0000303 explicit EarlyCSE() : FunctionPass(ID) {
Chris Lattner704541b2011-01-02 21:47:05 +0000304 initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
305 }
306
Craig Topper3e4c6972014-03-05 09:10:37 +0000307 bool runOnFunction(Function &F) override;
Chris Lattner704541b2011-01-02 21:47:05 +0000308
309private:
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000310
311 // NodeScope - almost a POD, but needs to call the constructors for the
312 // scoped hash tables so that a new scope gets pushed on. These are RAII so
313 // that the scope gets popped when the NodeScope is destroyed.
314 class NodeScope {
315 public:
316 NodeScope(ScopedHTType *availableValues,
317 LoadHTType *availableLoads,
318 CallHTType *availableCalls) :
319 Scope(*availableValues),
320 LoadScope(*availableLoads),
321 CallScope(*availableCalls) {}
322
323 private:
Craig Toppera60c0f12012-09-15 17:09:36 +0000324 NodeScope(const NodeScope&) LLVM_DELETED_FUNCTION;
325 void operator=(const NodeScope&) LLVM_DELETED_FUNCTION;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000326
327 ScopedHTType::ScopeTy Scope;
328 LoadHTType::ScopeTy LoadScope;
329 CallHTType::ScopeTy CallScope;
330 };
331
332 // StackNode - contains all the needed information to create a stack for
333 // doing a depth first tranversal of the tree. This includes scopes for
334 // values, loads, and calls as well as the generation. There is a child
335 // iterator so that the children do not need to be store spearately.
336 class StackNode {
337 public:
338 StackNode(ScopedHTType *availableValues,
339 LoadHTType *availableLoads,
340 CallHTType *availableCalls,
341 unsigned cg, DomTreeNode *n,
342 DomTreeNode::iterator child, DomTreeNode::iterator end) :
343 CurrentGeneration(cg), ChildGeneration(cg), Node(n),
344 ChildIter(child), EndIter(end),
345 Scopes(availableValues, availableLoads, availableCalls),
346 Processed(false) {}
347
348 // Accessors.
349 unsigned currentGeneration() { return CurrentGeneration; }
350 unsigned childGeneration() { return ChildGeneration; }
351 void childGeneration(unsigned generation) { ChildGeneration = generation; }
352 DomTreeNode *node() { return Node; }
353 DomTreeNode::iterator childIter() { return ChildIter; }
354 DomTreeNode *nextChild() {
355 DomTreeNode *child = *ChildIter;
356 ++ChildIter;
357 return child;
358 }
359 DomTreeNode::iterator end() { return EndIter; }
360 bool isProcessed() { return Processed; }
361 void process() { Processed = true; }
362
363 private:
Craig Toppera60c0f12012-09-15 17:09:36 +0000364 StackNode(const StackNode&) LLVM_DELETED_FUNCTION;
365 void operator=(const StackNode&) LLVM_DELETED_FUNCTION;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000366
367 // Members.
368 unsigned CurrentGeneration;
369 unsigned ChildGeneration;
370 DomTreeNode *Node;
371 DomTreeNode::iterator ChildIter;
372 DomTreeNode::iterator EndIter;
373 NodeScope Scopes;
374 bool Processed;
375 };
376
Chris Lattner18ae5432011-01-02 23:04:14 +0000377 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000378
Chris Lattner704541b2011-01-02 21:47:05 +0000379 // This transformation requires dominator postdominator info
Craig Topper3e4c6972014-03-05 09:10:37 +0000380 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000381 AU.addRequired<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000382 AU.addRequired<TargetLibraryInfo>();
Chris Lattner704541b2011-01-02 21:47:05 +0000383 AU.setPreservesCFG();
384 }
385};
386}
387
388char EarlyCSE::ID = 0;
389
390// createEarlyCSEPass - The public interface to this file.
391FunctionPass *llvm::createEarlyCSEPass() {
392 return new EarlyCSE();
393}
394
395INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000396INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chad Rosierc24b86f2011-12-01 03:08:23 +0000397INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Chris Lattner704541b2011-01-02 21:47:05 +0000398INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
399
Chris Lattner18ae5432011-01-02 23:04:14 +0000400bool EarlyCSE::processNode(DomTreeNode *Node) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000401 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000402
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000403 // If this block has a single predecessor, then the predecessor is the parent
404 // of the domtree node and all of the live out memory values are still current
405 // in this block. If this block has multiple predecessors, then they could
406 // have invalidated the live-out memory values of our parent value. For now,
407 // just be conservative and invalidate memory if this block has multiple
408 // predecessors.
409 if (BB->getSinglePredecessor() == 0)
410 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000411
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000412 /// LastStore - Keep track of the last non-volatile store that we saw... for
413 /// as long as there in no instruction that reads memory. If we see a store
414 /// to the same location, we delete the dead store. This zaps trivial dead
415 /// stores which can occur in bitfield code among other things.
416 StoreInst *LastStore = 0;
Nadav Rotem465834c2012-07-24 10:51:42 +0000417
Chris Lattner18ae5432011-01-02 23:04:14 +0000418 bool Changed = false;
419
420 // See if any instructions in the block can be eliminated. If so, do it. If
421 // not, add them to AvailableValues.
422 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
423 Instruction *Inst = I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000424
Chris Lattner18ae5432011-01-02 23:04:14 +0000425 // Dead instructions should just be removed.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000426 if (isInstructionTriviallyDead(Inst, TLI)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000427 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Chris Lattner18ae5432011-01-02 23:04:14 +0000428 Inst->eraseFromParent();
429 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000430 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000431 continue;
432 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000433
Chris Lattner18ae5432011-01-02 23:04:14 +0000434 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
435 // its simpler value.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000436 if (Value *V = SimplifyInstruction(Inst, DL, TLI, DT)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000437 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
Chris Lattner18ae5432011-01-02 23:04:14 +0000438 Inst->replaceAllUsesWith(V);
439 Inst->eraseFromParent();
440 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000441 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000442 continue;
443 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000444
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000445 // If this is a simple instruction that we can value number, process it.
446 if (SimpleValue::canHandle(Inst)) {
447 // See if the instruction has an available value. If so, use it.
Chris Lattner4cb36542011-01-03 03:28:23 +0000448 if (Value *V = AvailableValues->lookup(Inst)) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000449 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
450 Inst->replaceAllUsesWith(V);
451 Inst->eraseFromParent();
452 Changed = true;
453 ++NumCSE;
454 continue;
455 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000456
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000457 // Otherwise, just remember that this value is available.
Chris Lattner4cb36542011-01-03 03:28:23 +0000458 AvailableValues->insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000459 continue;
460 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000461
Chris Lattner92bb0f92011-01-03 03:41:27 +0000462 // If this is a non-volatile load, process it.
463 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
464 // Ignore volatile loads.
Eli Friedman7c5dc122011-09-12 20:23:13 +0000465 if (!LI->isSimple()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000466 LastStore = 0;
467 continue;
468 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000469
Chris Lattner92bb0f92011-01-03 03:41:27 +0000470 // If we have an available version of this load, and if it is the right
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000471 // generation, replace this instruction.
Chris Lattner92bb0f92011-01-03 03:41:27 +0000472 std::pair<Value*, unsigned> InVal =
473 AvailableLoads->lookup(Inst->getOperand(0));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000474 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
Chris Lattner92bb0f92011-01-03 03:41:27 +0000475 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst << " to: "
476 << *InVal.first << '\n');
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000477 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
478 Inst->eraseFromParent();
479 Changed = true;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000480 ++NumCSELoad;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000481 continue;
482 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000483
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000484 // Otherwise, remember that we have this instruction.
Chris Lattner92bb0f92011-01-03 03:41:27 +0000485 AvailableLoads->insert(Inst->getOperand(0),
486 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000487 LastStore = 0;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000488 continue;
489 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000490
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000491 // If this instruction may read from memory, forget LastStore.
492 if (Inst->mayReadFromMemory())
493 LastStore = 0;
Nadav Rotem465834c2012-07-24 10:51:42 +0000494
Chris Lattner92bb0f92011-01-03 03:41:27 +0000495 // If this is a read-only call, process it.
496 if (CallValue::canHandle(Inst)) {
497 // If we have an available version of this call, and if it is the right
498 // generation, replace this instruction.
499 std::pair<Value*, unsigned> InVal = AvailableCalls->lookup(Inst);
500 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
501 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst << " to: "
502 << *InVal.first << '\n');
503 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
504 Inst->eraseFromParent();
505 Changed = true;
506 ++NumCSECall;
507 continue;
508 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000509
Chris Lattner92bb0f92011-01-03 03:41:27 +0000510 // Otherwise, remember that we have this instruction.
511 AvailableCalls->insert(Inst,
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000512 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
513 continue;
514 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000515
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000516 // Okay, this isn't something we can CSE at all. Check to see if it is
517 // something that could modify memory. If so, our available memory values
518 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +0000519 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000520 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000521
Chris Lattnere0e32a92011-01-03 03:46:34 +0000522 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000523 // We do a trivial form of DSE if there are two stores to the same
524 // location with no intervening loads. Delete the earlier store.
525 if (LastStore &&
526 LastStore->getPointerOperand() == SI->getPointerOperand()) {
527 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore << " due to: "
Chris Lattner142f1cd2011-01-03 18:28:15 +0000528 << *Inst << '\n');
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000529 LastStore->eraseFromParent();
530 Changed = true;
531 ++NumDSE;
532 LastStore = 0;
533 continue;
534 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000535
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000536 // Okay, we just invalidated anything we knew about loaded values. Try
537 // to salvage *something* by remembering that the stored value is a live
538 // version of the pointer. It is safe to forward from volatile stores
539 // to non-volatile loads, so we don't have to check for volatility of
540 // the store.
Chris Lattnere0e32a92011-01-03 03:46:34 +0000541 AvailableLoads->insert(SI->getPointerOperand(),
542 std::pair<Value*, unsigned>(SI->getValueOperand(), CurrentGeneration));
Nadav Rotem465834c2012-07-24 10:51:42 +0000543
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000544 // Remember that this was the last store we saw for DSE.
Eli Friedman7c5dc122011-09-12 20:23:13 +0000545 if (SI->isSimple())
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000546 LastStore = SI;
Chris Lattnere0e32a92011-01-03 03:46:34 +0000547 }
548 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000549 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000550
Chris Lattner18ae5432011-01-02 23:04:14 +0000551 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +0000552}
Chris Lattner18ae5432011-01-02 23:04:14 +0000553
554
555bool EarlyCSE::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000556 if (skipOptnoneFunction(F))
557 return false;
558
Michael Gottesman2bf01732013-12-05 18:42:12 +0000559 std::vector<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000560
Rafael Espindola93512512014-02-25 17:30:31 +0000561 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
562 DL = DLP ? &DLP->getDataLayout() : 0;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000563 TLI = &getAnalysis<TargetLibraryInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000564 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Nadav Rotem465834c2012-07-24 10:51:42 +0000565
Chris Lattner92bb0f92011-01-03 03:41:27 +0000566 // Tables that the pass uses when walking the domtree.
Chris Lattnerd815f692011-01-03 01:42:46 +0000567 ScopedHTType AVTable;
Chris Lattner18ae5432011-01-02 23:04:14 +0000568 AvailableValues = &AVTable;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000569 LoadHTType LoadTable;
570 AvailableLoads = &LoadTable;
571 CallHTType CallTable;
572 AvailableCalls = &CallTable;
Nadav Rotem465834c2012-07-24 10:51:42 +0000573
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000574 CurrentGeneration = 0;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000575 bool Changed = false;
576
577 // Process the root node.
Michael Gottesman2bf01732013-12-05 18:42:12 +0000578 nodesToProcess.push_back(
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000579 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
580 CurrentGeneration, DT->getRootNode(),
581 DT->getRootNode()->begin(),
582 DT->getRootNode()->end()));
583
584 // Save the current generation.
585 unsigned LiveOutGeneration = CurrentGeneration;
586
587 // Process the stack.
588 while (!nodesToProcess.empty()) {
589 // Grab the first item off the stack. Set the current generation, remove
590 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +0000591 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000592
593 // Initialize class members.
594 CurrentGeneration = NodeToProcess->currentGeneration();
595
596 // Check if the node needs to be processed.
597 if (!NodeToProcess->isProcessed()) {
598 // Process the node.
599 Changed |= processNode(NodeToProcess->node());
600 NodeToProcess->childGeneration(CurrentGeneration);
601 NodeToProcess->process();
602 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
603 // Push the next child onto the stack.
604 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +0000605 nodesToProcess.push_back(
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000606 new StackNode(AvailableValues,
607 AvailableLoads,
608 AvailableCalls,
609 NodeToProcess->childGeneration(), child,
610 child->begin(), child->end()));
611 } else {
612 // It has been processed, and there are no more children to process,
613 // so delete it and pop it off the stack.
614 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +0000615 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000616 }
617 } // while (!nodes...)
618
619 // Reset the current generation.
620 CurrentGeneration = LiveOutGeneration;
621
622 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +0000623}