blob: f008348b3b985c08c09b73fb01c3f8ea7ea910a8 [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 Carruth66b31302015-01-04 12:03:27 +000019#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000022#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Instructions.h"
Hal Finkel1e16fa32014-11-03 20:21:32 +000024#include "llvm/IR/IntrinsicInst.h"
25#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Pass.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/RecyclingAllocator.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000029#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Transforms/Utils/Local.h"
Lenny Maiorani9eefc812014-09-20 13:29:20 +000031#include <deque>
Chris Lattner704541b2011-01-02 21:47:05 +000032using namespace llvm;
Hal Finkel1e16fa32014-11-03 20:21:32 +000033using namespace llvm::PatternMatch;
Chris Lattner704541b2011-01-02 21:47:05 +000034
Chandler Carruth964daaa2014-04-22 02:55:47 +000035#define DEBUG_TYPE "early-cse"
36
Chris Lattner4cb36542011-01-03 03:28:23 +000037STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
38STATISTIC(NumCSE, "Number of instructions CSE'd");
Chris Lattner92bb0f92011-01-03 03:41:27 +000039STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
40STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner9e5e9ed2011-01-03 04:17:24 +000041STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattnerb9a8efc2011-01-03 03:18:43 +000042
43static unsigned getHash(const void *V) {
44 return DenseMapInfo<const void*>::getHashValue(V);
45}
Chris Lattner8fac5db2011-01-02 23:19:45 +000046
Chris Lattner79d83062011-01-03 02:20:48 +000047//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +000048// SimpleValue
Chris Lattner79d83062011-01-03 02:20:48 +000049//===----------------------------------------------------------------------===//
50
Chris Lattner704541b2011-01-02 21:47:05 +000051namespace {
Chandler Carruth7253bba2015-01-24 11:33:55 +000052/// SimpleValue - Instances of this struct represent available values in the
53/// scoped hash table.
54struct SimpleValue {
55 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +000056
Chandler Carruth7253bba2015-01-24 11:33:55 +000057 SimpleValue(Instruction *I) : Inst(I) {
58 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
59 }
Nadav Rotem465834c2012-07-24 10:51:42 +000060
Chandler Carruth7253bba2015-01-24 11:33:55 +000061 bool isSentinel() const {
62 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
63 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
64 }
Nadav Rotem465834c2012-07-24 10:51:42 +000065
Chandler Carruth7253bba2015-01-24 11:33:55 +000066 static bool canHandle(Instruction *Inst) {
67 // This can only handle non-void readnone functions.
68 if (CallInst *CI = dyn_cast<CallInst>(Inst))
69 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
70 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
71 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
72 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
73 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
74 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
75 }
76};
Chris Lattner18ae5432011-01-02 23:04:14 +000077}
78
79namespace llvm {
Chandler Carruth7253bba2015-01-24 11:33:55 +000080template <> struct DenseMapInfo<SimpleValue> {
Chris Lattner79d83062011-01-03 02:20:48 +000081 static inline SimpleValue getEmptyKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +000082 return DenseMapInfo<Instruction *>::getEmptyKey();
Chris Lattner18ae5432011-01-02 23:04:14 +000083 }
Chris Lattner79d83062011-01-03 02:20:48 +000084 static inline SimpleValue getTombstoneKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +000085 return DenseMapInfo<Instruction *>::getTombstoneKey();
Chris Lattner18ae5432011-01-02 23:04:14 +000086 }
Chris Lattner79d83062011-01-03 02:20:48 +000087 static unsigned getHashValue(SimpleValue Val);
88 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattner18ae5432011-01-02 23:04:14 +000089};
90}
91
Chris Lattner79d83062011-01-03 02:20:48 +000092unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattner18ae5432011-01-02 23:04:14 +000093 Instruction *Inst = Val.Inst;
Chris Lattner02a97762011-01-03 01:10:08 +000094 // Hash in all of the operands as pointers.
Chandler Carruth7253bba2015-01-24 11:33:55 +000095 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
Michael Ilseman336cb792012-10-09 16:57:38 +000096 Value *LHS = BinOp->getOperand(0);
97 Value *RHS = BinOp->getOperand(1);
98 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
99 std::swap(LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000100
Michael Ilseman336cb792012-10-09 16:57:38 +0000101 if (isa<OverflowingBinaryOperator>(BinOp)) {
102 // Hash the overflow behavior
103 unsigned Overflow =
Chandler Carruth7253bba2015-01-24 11:33:55 +0000104 BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
105 BinOp->hasNoUnsignedWrap() *
106 OverflowingBinaryOperator::NoUnsignedWrap;
Michael Ilseman336cb792012-10-09 16:57:38 +0000107 return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
108 }
109
110 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000111 }
112
Michael Ilseman336cb792012-10-09 16:57:38 +0000113 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
114 Value *LHS = CI->getOperand(0);
115 Value *RHS = CI->getOperand(1);
116 CmpInst::Predicate Pred = CI->getPredicate();
117 if (Inst->getOperand(0) > Inst->getOperand(1)) {
118 std::swap(LHS, RHS);
119 Pred = CI->getSwappedPredicate();
120 }
121 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
122 }
123
124 if (CastInst *CI = dyn_cast<CastInst>(Inst))
125 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
126
127 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
128 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
129 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
130
131 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
132 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
133 IVI->getOperand(1),
134 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
135
136 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
137 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
138 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
Chandler Carruth7253bba2015-01-24 11:33:55 +0000139 isa<ShuffleVectorInst>(Inst)) &&
140 "Invalid/unknown instruction");
Michael Ilseman336cb792012-10-09 16:57:38 +0000141
Chris Lattner02a97762011-01-03 01:10:08 +0000142 // Mix in the opcode.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000143 return hash_combine(
144 Inst->getOpcode(),
145 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattner18ae5432011-01-02 23:04:14 +0000146}
147
Chris Lattner79d83062011-01-03 02:20:48 +0000148bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000149 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
150
151 if (LHS.isSentinel() || RHS.isSentinel())
152 return LHSI == RHSI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000153
Chandler Carruth7253bba2015-01-24 11:33:55 +0000154 if (LHSI->getOpcode() != RHSI->getOpcode())
155 return false;
156 if (LHSI->isIdenticalTo(RHSI))
157 return true;
Michael Ilseman336cb792012-10-09 16:57:38 +0000158
159 // If we're not strictly identical, we still might be a commutable instruction
160 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
161 if (!LHSBinOp->isCommutative())
162 return false;
163
Chandler Carruth7253bba2015-01-24 11:33:55 +0000164 assert(isa<BinaryOperator>(RHSI) &&
165 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000166 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
167
168 // Check overflow attributes
169 if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000170 assert(isa<OverflowingBinaryOperator>(RHSBinOp) &&
171 "same opcode, but different operator type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000172 if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
173 LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
174 return false;
175 }
176
177 // Commuted equality
178 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000179 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
Michael Ilseman336cb792012-10-09 16:57:38 +0000180 }
181 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000182 assert(isa<CmpInst>(RHSI) &&
183 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000184 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
185 // Commuted equality
186 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000187 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
188 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
Michael Ilseman336cb792012-10-09 16:57:38 +0000189 }
190
191 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000192}
193
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000194//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000195// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000196//===----------------------------------------------------------------------===//
197
198namespace {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000199/// CallValue - Instances of this struct represent available call values in
200/// the scoped hash table.
201struct CallValue {
202 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000203
Chandler Carruth7253bba2015-01-24 11:33:55 +0000204 CallValue(Instruction *I) : Inst(I) {
205 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
206 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000207
Chandler Carruth7253bba2015-01-24 11:33:55 +0000208 bool isSentinel() const {
209 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
210 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
211 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000212
Chandler Carruth7253bba2015-01-24 11:33:55 +0000213 static bool canHandle(Instruction *Inst) {
214 // Don't value number anything that returns void.
215 if (Inst->getType()->isVoidTy())
216 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000217
Chandler Carruth7253bba2015-01-24 11:33:55 +0000218 CallInst *CI = dyn_cast<CallInst>(Inst);
219 if (!CI || !CI->onlyReadsMemory())
220 return false;
221 return true;
222 }
223};
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000224}
225
226namespace llvm {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000227template <> struct DenseMapInfo<CallValue> {
228 static inline CallValue getEmptyKey() {
229 return DenseMapInfo<Instruction *>::getEmptyKey();
230 }
231 static inline CallValue getTombstoneKey() {
232 return DenseMapInfo<Instruction *>::getTombstoneKey();
233 }
234 static unsigned getHashValue(CallValue Val);
235 static bool isEqual(CallValue LHS, CallValue RHS);
236};
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000237}
Chandler Carruth7253bba2015-01-24 11:33:55 +0000238
Chris Lattner92bb0f92011-01-03 03:41:27 +0000239unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000240 Instruction *Inst = Val.Inst;
241 // Hash in all of the operands as pointers.
242 unsigned Res = 0;
Chris Lattner16ca19f2011-01-03 18:43:03 +0000243 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) {
244 assert(!Inst->getOperand(i)->getType()->isMetadataTy() &&
245 "Cannot value number calls with metadata operands");
Eli Friedman154a9672011-10-12 22:00:26 +0000246 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
Chris Lattner16ca19f2011-01-03 18:43:03 +0000247 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000248
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000249 // Mix in the opcode.
250 return (Res << 1) ^ Inst->getOpcode();
251}
252
Chris Lattner92bb0f92011-01-03 03:41:27 +0000253bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000254 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000255 if (LHS.isSentinel() || RHS.isSentinel())
256 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000257 return LHSI->isIdenticalTo(RHSI);
258}
259
Chris Lattner79d83062011-01-03 02:20:48 +0000260//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000261// EarlyCSE pass.
Chris Lattner79d83062011-01-03 02:20:48 +0000262//===----------------------------------------------------------------------===//
263
Chris Lattner18ae5432011-01-02 23:04:14 +0000264namespace {
Nadav Rotem465834c2012-07-24 10:51:42 +0000265
Chris Lattner704541b2011-01-02 21:47:05 +0000266/// EarlyCSE - This pass does a simple depth-first walk over the dominator
267/// tree, eliminating trivially redundant instructions and using instsimplify
268/// to canonicalize things as it goes. It is intended to be fast and catch
269/// obvious cases so that instcombine and other passes are more effective. It
270/// is expected that a later pass of GVN will catch the interesting/hard
271/// cases.
272class EarlyCSE : public FunctionPass {
273public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000274 const DataLayout *DL;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000275 const TargetLibraryInfo *TLI;
Chris Lattner18ae5432011-01-02 23:04:14 +0000276 DominatorTree *DT;
Chandler Carruth66b31302015-01-04 12:03:27 +0000277 AssumptionCache *AC;
Chandler Carruth7253bba2015-01-24 11:33:55 +0000278 typedef RecyclingAllocator<
279 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
280 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
Chris Lattnerd815f692011-01-03 01:42:46 +0000281 AllocatorTy> ScopedHTType;
Nadav Rotem465834c2012-07-24 10:51:42 +0000282
Chris Lattner79d83062011-01-03 02:20:48 +0000283 /// AvailableValues - This scoped hash table contains the current values of
284 /// all of our simple scalar expressions. As we walk down the domtree, we
285 /// look to see if instructions are in this: if so, we replace them with what
286 /// we find, otherwise we insert them so that dominated values can succeed in
287 /// their lookup.
288 ScopedHTType *AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000289
Chris Lattner92bb0f92011-01-03 03:41:27 +0000290 /// AvailableLoads - This scoped hash table contains the current values
291 /// of loads. This allows us to get efficient access to dominating loads when
292 /// we have a fully redundant load. In addition to the most recent load, we
293 /// keep track of a generation count of the read, which is compared against
294 /// the current generation count. The current generation count is
295 /// incremented after every possibly writing memory operation, which ensures
296 /// that we only CSE loads with other loads that have no intervening store.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000297 typedef RecyclingAllocator<
298 BumpPtrAllocator,
299 ScopedHashTableVal<Value *, std::pair<Value *, unsigned>>>
300 LoadMapAllocator;
301 typedef ScopedHashTable<Value *, std::pair<Value *, unsigned>,
302 DenseMapInfo<Value *>, LoadMapAllocator> LoadHTType;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000303 LoadHTType *AvailableLoads;
Nadav Rotem465834c2012-07-24 10:51:42 +0000304
Chris Lattner92bb0f92011-01-03 03:41:27 +0000305 /// AvailableCalls - This scoped hash table contains the current values
306 /// of read-only call values. It uses the same generation count as loads.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000307 typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000308 CallHTType *AvailableCalls;
Nadav Rotem465834c2012-07-24 10:51:42 +0000309
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000310 /// CurrentGeneration - This is the current generation of the memory value.
311 unsigned CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000312
Chris Lattner704541b2011-01-02 21:47:05 +0000313 static char ID;
Chris Lattner79d83062011-01-03 02:20:48 +0000314 explicit EarlyCSE() : FunctionPass(ID) {
Chris Lattner704541b2011-01-02 21:47:05 +0000315 initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
316 }
317
Craig Topper3e4c6972014-03-05 09:10:37 +0000318 bool runOnFunction(Function &F) override;
Chris Lattner704541b2011-01-02 21:47:05 +0000319
320private:
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000321 // NodeScope - almost a POD, but needs to call the constructors for the
322 // scoped hash tables so that a new scope gets pushed on. These are RAII so
323 // that the scope gets popped when the NodeScope is destroyed.
324 class NodeScope {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000325 public:
326 NodeScope(ScopedHTType *availableValues, LoadHTType *availableLoads,
327 CallHTType *availableCalls)
328 : Scope(*availableValues), LoadScope(*availableLoads),
329 CallScope(*availableCalls) {}
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000330
Chandler Carruth7253bba2015-01-24 11:33:55 +0000331 private:
332 NodeScope(const NodeScope &) LLVM_DELETED_FUNCTION;
333 void operator=(const NodeScope &) LLVM_DELETED_FUNCTION;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000334
335 ScopedHTType::ScopeTy Scope;
336 LoadHTType::ScopeTy LoadScope;
337 CallHTType::ScopeTy CallScope;
338 };
339
340 // StackNode - contains all the needed information to create a stack for
341 // doing a depth first tranversal of the tree. This includes scopes for
342 // values, loads, and calls as well as the generation. There is a child
343 // iterator so that the children do not need to be store spearately.
344 class StackNode {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000345 public:
346 StackNode(ScopedHTType *availableValues, LoadHTType *availableLoads,
347 CallHTType *availableCalls, unsigned cg, DomTreeNode *n,
348 DomTreeNode::iterator child, DomTreeNode::iterator end)
349 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
350 EndIter(end), Scopes(availableValues, availableLoads, availableCalls),
351 Processed(false) {}
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000352
353 // Accessors.
354 unsigned currentGeneration() { return CurrentGeneration; }
355 unsigned childGeneration() { return ChildGeneration; }
356 void childGeneration(unsigned generation) { ChildGeneration = generation; }
357 DomTreeNode *node() { return Node; }
358 DomTreeNode::iterator childIter() { return ChildIter; }
359 DomTreeNode *nextChild() {
360 DomTreeNode *child = *ChildIter;
361 ++ChildIter;
362 return child;
363 }
364 DomTreeNode::iterator end() { return EndIter; }
365 bool isProcessed() { return Processed; }
366 void process() { Processed = true; }
367
Chandler Carruth7253bba2015-01-24 11:33:55 +0000368 private:
369 StackNode(const StackNode &) LLVM_DELETED_FUNCTION;
370 void operator=(const StackNode &) LLVM_DELETED_FUNCTION;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000371
372 // Members.
373 unsigned CurrentGeneration;
374 unsigned ChildGeneration;
375 DomTreeNode *Node;
376 DomTreeNode::iterator ChildIter;
377 DomTreeNode::iterator EndIter;
378 NodeScope Scopes;
379 bool Processed;
380 };
381
Chris Lattner18ae5432011-01-02 23:04:14 +0000382 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000383
Chris Lattner704541b2011-01-02 21:47:05 +0000384 // This transformation requires dominator postdominator info
Craig Topper3e4c6972014-03-05 09:10:37 +0000385 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000386 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth73523022014-01-13 13:07:17 +0000387 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000388 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chris Lattner704541b2011-01-02 21:47:05 +0000389 AU.setPreservesCFG();
390 }
391};
392}
393
394char EarlyCSE::ID = 0;
395
396// createEarlyCSEPass - The public interface to this file.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000397FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSE(); }
Chris Lattner704541b2011-01-02 21:47:05 +0000398
399INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
Chandler Carruth66b31302015-01-04 12:03:27 +0000400INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth73523022014-01-13 13:07:17 +0000401INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000402INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chris Lattner704541b2011-01-02 21:47:05 +0000403INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
404
Chris Lattner18ae5432011-01-02 23:04:14 +0000405bool EarlyCSE::processNode(DomTreeNode *Node) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000406 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000407
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000408 // If this block has a single predecessor, then the predecessor is the parent
409 // of the domtree node and all of the live out memory values are still current
410 // in this block. If this block has multiple predecessors, then they could
411 // have invalidated the live-out memory values of our parent value. For now,
412 // just be conservative and invalidate memory if this block has multiple
413 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000414 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000415 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000416
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000417 /// LastStore - Keep track of the last non-volatile store that we saw... for
418 /// as long as there in no instruction that reads memory. If we see a store
419 /// to the same location, we delete the dead store. This zaps trivial dead
420 /// stores which can occur in bitfield code among other things.
Craig Topperf40110f2014-04-25 05:29:35 +0000421 StoreInst *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000422
Chris Lattner18ae5432011-01-02 23:04:14 +0000423 bool Changed = false;
424
425 // See if any instructions in the block can be eliminated. If so, do it. If
426 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000427 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000428 Instruction *Inst = I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000429
Chris Lattner18ae5432011-01-02 23:04:14 +0000430 // Dead instructions should just be removed.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000431 if (isInstructionTriviallyDead(Inst, TLI)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000432 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Chris Lattner18ae5432011-01-02 23:04:14 +0000433 Inst->eraseFromParent();
434 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000435 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000436 continue;
437 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000438
Hal Finkel1e16fa32014-11-03 20:21:32 +0000439 // Skip assume intrinsics, they don't really have side effects (although
440 // they're marked as such to ensure preservation of control dependencies),
441 // and this pass will not disturb any of the assumption's control
442 // dependencies.
443 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
444 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
445 continue;
446 }
447
Chris Lattner18ae5432011-01-02 23:04:14 +0000448 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
449 // its simpler value.
Chandler Carruth66b31302015-01-04 12:03:27 +0000450 if (Value *V = SimplifyInstruction(Inst, DL, TLI, DT, AC)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000451 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
Chris Lattner18ae5432011-01-02 23:04:14 +0000452 Inst->replaceAllUsesWith(V);
453 Inst->eraseFromParent();
454 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000455 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000456 continue;
457 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000458
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000459 // If this is a simple instruction that we can value number, process it.
460 if (SimpleValue::canHandle(Inst)) {
461 // See if the instruction has an available value. If so, use it.
Chris Lattner4cb36542011-01-03 03:28:23 +0000462 if (Value *V = AvailableValues->lookup(Inst)) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000463 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
464 Inst->replaceAllUsesWith(V);
465 Inst->eraseFromParent();
466 Changed = true;
467 ++NumCSE;
468 continue;
469 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000470
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000471 // Otherwise, just remember that this value is available.
Chris Lattner4cb36542011-01-03 03:28:23 +0000472 AvailableValues->insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000473 continue;
474 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000475
Chris Lattner92bb0f92011-01-03 03:41:27 +0000476 // If this is a non-volatile load, process it.
477 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
478 // Ignore volatile loads.
Eli Friedman7c5dc122011-09-12 20:23:13 +0000479 if (!LI->isSimple()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000480 LastStore = nullptr;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000481 continue;
482 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000483
Chris Lattner92bb0f92011-01-03 03:41:27 +0000484 // If we have an available version of this load, and if it is the right
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000485 // generation, replace this instruction.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000486 std::pair<Value *, unsigned> InVal =
487 AvailableLoads->lookup(Inst->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +0000488 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000489 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
490 << " to: " << *InVal.first << '\n');
491 if (!Inst->use_empty())
492 Inst->replaceAllUsesWith(InVal.first);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000493 Inst->eraseFromParent();
494 Changed = true;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000495 ++NumCSELoad;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000496 continue;
497 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000498
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000499 // Otherwise, remember that we have this instruction.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000500 AvailableLoads->insert(Inst->getOperand(0), std::pair<Value *, unsigned>(
501 Inst, CurrentGeneration));
Craig Topperf40110f2014-04-25 05:29:35 +0000502 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000503 continue;
504 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000505
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000506 // If this instruction may read from memory, forget LastStore.
507 if (Inst->mayReadFromMemory())
Craig Topperf40110f2014-04-25 05:29:35 +0000508 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000509
Chris Lattner92bb0f92011-01-03 03:41:27 +0000510 // If this is a read-only call, process it.
511 if (CallValue::canHandle(Inst)) {
512 // If we have an available version of this call, and if it is the right
513 // generation, replace this instruction.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000514 std::pair<Value *, unsigned> InVal = AvailableCalls->lookup(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +0000515 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000516 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
517 << " to: " << *InVal.first << '\n');
518 if (!Inst->use_empty())
519 Inst->replaceAllUsesWith(InVal.first);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000520 Inst->eraseFromParent();
521 Changed = true;
522 ++NumCSECall;
523 continue;
524 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000525
Chris Lattner92bb0f92011-01-03 03:41:27 +0000526 // Otherwise, remember that we have this instruction.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000527 AvailableCalls->insert(
528 Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000529 continue;
530 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000531
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000532 // Okay, this isn't something we can CSE at all. Check to see if it is
533 // something that could modify memory. If so, our available memory values
534 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +0000535 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000536 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000537
Chris Lattnere0e32a92011-01-03 03:46:34 +0000538 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000539 // We do a trivial form of DSE if there are two stores to the same
540 // location with no intervening loads. Delete the earlier store.
541 if (LastStore &&
542 LastStore->getPointerOperand() == SI->getPointerOperand()) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000543 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
544 << " due to: " << *Inst << '\n');
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000545 LastStore->eraseFromParent();
546 Changed = true;
547 ++NumDSE;
Craig Topperf40110f2014-04-25 05:29:35 +0000548 LastStore = nullptr;
Philip Reames018dbf12014-11-18 17:46:32 +0000549 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000550 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000551
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000552 // Okay, we just invalidated anything we knew about loaded values. Try
553 // to salvage *something* by remembering that the stored value is a live
554 // version of the pointer. It is safe to forward from volatile stores
555 // to non-volatile loads, so we don't have to check for volatility of
556 // the store.
Chris Lattnere0e32a92011-01-03 03:46:34 +0000557 AvailableLoads->insert(SI->getPointerOperand(),
Chandler Carruth7253bba2015-01-24 11:33:55 +0000558 std::pair<Value *, unsigned>(
559 SI->getValueOperand(), CurrentGeneration));
Nadav Rotem465834c2012-07-24 10:51:42 +0000560
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000561 // Remember that this was the last store we saw for DSE.
Eli Friedman7c5dc122011-09-12 20:23:13 +0000562 if (SI->isSimple())
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000563 LastStore = SI;
Chris Lattnere0e32a92011-01-03 03:46:34 +0000564 }
565 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000566 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000567
Chris Lattner18ae5432011-01-02 23:04:14 +0000568 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +0000569}
Chris Lattner18ae5432011-01-02 23:04:14 +0000570
Chris Lattner18ae5432011-01-02 23:04:14 +0000571bool EarlyCSE::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000572 if (skipOptnoneFunction(F))
573 return false;
574
Chandler Carruth7253bba2015-01-24 11:33:55 +0000575 // Note, deque is being used here because there is significant performance
576 // gains over vector when the container becomes very large due to the
577 // specific access patterns. For more information see the mailing list
578 // discussion on this:
Lenny Maiorani9eefc812014-09-20 13:29:20 +0000579 // http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
580 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000581
Rafael Espindola93512512014-02-25 17:30:31 +0000582 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +0000583 DL = DLP ? &DLP->getDataLayout() : nullptr;
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000584 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruth73523022014-01-13 13:07:17 +0000585 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth66b31302015-01-04 12:03:27 +0000586 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Nadav Rotem465834c2012-07-24 10:51:42 +0000587
Chris Lattner92bb0f92011-01-03 03:41:27 +0000588 // Tables that the pass uses when walking the domtree.
Chris Lattnerd815f692011-01-03 01:42:46 +0000589 ScopedHTType AVTable;
Chris Lattner18ae5432011-01-02 23:04:14 +0000590 AvailableValues = &AVTable;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000591 LoadHTType LoadTable;
592 AvailableLoads = &LoadTable;
593 CallHTType CallTable;
594 AvailableCalls = &CallTable;
Nadav Rotem465834c2012-07-24 10:51:42 +0000595
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000596 CurrentGeneration = 0;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000597 bool Changed = false;
598
599 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000600 nodesToProcess.push_back(new StackNode(
601 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
602 DT->getRootNode(), DT->getRootNode()->begin(), DT->getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000603
604 // Save the current generation.
605 unsigned LiveOutGeneration = CurrentGeneration;
606
607 // Process the stack.
608 while (!nodesToProcess.empty()) {
609 // Grab the first item off the stack. Set the current generation, remove
610 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +0000611 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000612
613 // Initialize class members.
614 CurrentGeneration = NodeToProcess->currentGeneration();
615
616 // Check if the node needs to be processed.
617 if (!NodeToProcess->isProcessed()) {
618 // Process the node.
619 Changed |= processNode(NodeToProcess->node());
620 NodeToProcess->childGeneration(CurrentGeneration);
621 NodeToProcess->process();
622 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
623 // Push the next child onto the stack.
624 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +0000625 nodesToProcess.push_back(
Chandler Carruth7253bba2015-01-24 11:33:55 +0000626 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
627 NodeToProcess->childGeneration(), child, child->begin(),
628 child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000629 } else {
630 // It has been processed, and there are no more children to process,
631 // so delete it and pop it off the stack.
632 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +0000633 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000634 }
635 } // while (!nodes...)
636
637 // Reset the current generation.
638 CurrentGeneration = LiveOutGeneration;
639
640 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +0000641}