blob: 4dab49372e3aba3eb7b8c5da9713fc80e04dd126 [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
Chandler Carruthe8c686a2015-02-01 10:51:23 +000015#include "llvm/Transforms/Scalar/EarlyCSE.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"
James Molloyefbba722015-09-10 10:22:12 +000019#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000020#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/Analysis/InstructionSimplify.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Chad Rosierf9327d62015-01-26 22:51:15 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Instructions.h"
Hal Finkel1e16fa32014-11-03 20:21:32 +000027#include "llvm/IR/IntrinsicInst.h"
28#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Pass.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/RecyclingAllocator.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000032#include "llvm/Support/raw_ostream.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +000033#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Transforms/Utils/Local.h"
Lenny Maiorani9eefc812014-09-20 13:29:20 +000035#include <deque>
Chris Lattner704541b2011-01-02 21:47:05 +000036using namespace llvm;
Hal Finkel1e16fa32014-11-03 20:21:32 +000037using namespace llvm::PatternMatch;
Chris Lattner704541b2011-01-02 21:47:05 +000038
Chandler Carruth964daaa2014-04-22 02:55:47 +000039#define DEBUG_TYPE "early-cse"
40
Chris Lattner4cb36542011-01-03 03:28:23 +000041STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
42STATISTIC(NumCSE, "Number of instructions CSE'd");
Chris Lattner92bb0f92011-01-03 03:41:27 +000043STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
44STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner9e5e9ed2011-01-03 04:17:24 +000045STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattnerb9a8efc2011-01-03 03:18:43 +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 Carruth9dea5cd2015-01-24 11:44:32 +000052/// \brief Struct representing the available values in the scoped hash table.
Chandler Carruth7253bba2015-01-24 11:33:55 +000053struct SimpleValue {
54 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +000055
Chandler Carruth7253bba2015-01-24 11:33:55 +000056 SimpleValue(Instruction *I) : Inst(I) {
57 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
58 }
Nadav Rotem465834c2012-07-24 10:51:42 +000059
Chandler Carruth7253bba2015-01-24 11:33:55 +000060 bool isSentinel() const {
61 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
62 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
63 }
Nadav Rotem465834c2012-07-24 10:51:42 +000064
Chandler Carruth7253bba2015-01-24 11:33:55 +000065 static bool canHandle(Instruction *Inst) {
66 // This can only handle non-void readnone functions.
67 if (CallInst *CI = dyn_cast<CallInst>(Inst))
68 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
69 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
70 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
71 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
72 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
73 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
74 }
75};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000076}
Chris Lattner18ae5432011-01-02 23:04:14 +000077
78namespace llvm {
Chandler Carruth7253bba2015-01-24 11:33:55 +000079template <> struct DenseMapInfo<SimpleValue> {
Chris Lattner79d83062011-01-03 02:20:48 +000080 static inline SimpleValue getEmptyKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +000081 return DenseMapInfo<Instruction *>::getEmptyKey();
Chris Lattner18ae5432011-01-02 23:04:14 +000082 }
Chris Lattner79d83062011-01-03 02:20:48 +000083 static inline SimpleValue getTombstoneKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +000084 return DenseMapInfo<Instruction *>::getTombstoneKey();
Chris Lattner18ae5432011-01-02 23:04:14 +000085 }
Chris Lattner79d83062011-01-03 02:20:48 +000086 static unsigned getHashValue(SimpleValue Val);
87 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattner18ae5432011-01-02 23:04:14 +000088};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000089}
Chris Lattner18ae5432011-01-02 23:04:14 +000090
Chris Lattner79d83062011-01-03 02:20:48 +000091unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattner18ae5432011-01-02 23:04:14 +000092 Instruction *Inst = Val.Inst;
Chris Lattner02a97762011-01-03 01:10:08 +000093 // Hash in all of the operands as pointers.
Chandler Carruth7253bba2015-01-24 11:33:55 +000094 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
Michael Ilseman336cb792012-10-09 16:57:38 +000095 Value *LHS = BinOp->getOperand(0);
96 Value *RHS = BinOp->getOperand(1);
97 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
98 std::swap(LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +000099
Michael Ilseman336cb792012-10-09 16:57:38 +0000100 if (isa<OverflowingBinaryOperator>(BinOp)) {
101 // Hash the overflow behavior
102 unsigned Overflow =
Chandler Carruth7253bba2015-01-24 11:33:55 +0000103 BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
104 BinOp->hasNoUnsignedWrap() *
105 OverflowingBinaryOperator::NoUnsignedWrap;
Michael Ilseman336cb792012-10-09 16:57:38 +0000106 return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
107 }
108
109 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000110 }
111
Michael Ilseman336cb792012-10-09 16:57:38 +0000112 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
113 Value *LHS = CI->getOperand(0);
114 Value *RHS = CI->getOperand(1);
115 CmpInst::Predicate Pred = CI->getPredicate();
116 if (Inst->getOperand(0) > Inst->getOperand(1)) {
117 std::swap(LHS, RHS);
118 Pred = CI->getSwappedPredicate();
119 }
120 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
121 }
122
123 if (CastInst *CI = dyn_cast<CastInst>(Inst))
124 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
125
126 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
127 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
128 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
129
130 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
131 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
132 IVI->getOperand(1),
133 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
134
135 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
136 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
137 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
Chandler Carruth7253bba2015-01-24 11:33:55 +0000138 isa<ShuffleVectorInst>(Inst)) &&
139 "Invalid/unknown instruction");
Michael Ilseman336cb792012-10-09 16:57:38 +0000140
Chris Lattner02a97762011-01-03 01:10:08 +0000141 // Mix in the opcode.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000142 return hash_combine(
143 Inst->getOpcode(),
144 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattner18ae5432011-01-02 23:04:14 +0000145}
146
Chris Lattner79d83062011-01-03 02:20:48 +0000147bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000148 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
149
150 if (LHS.isSentinel() || RHS.isSentinel())
151 return LHSI == RHSI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000152
Chandler Carruth7253bba2015-01-24 11:33:55 +0000153 if (LHSI->getOpcode() != RHSI->getOpcode())
154 return false;
155 if (LHSI->isIdenticalTo(RHSI))
156 return true;
Michael Ilseman336cb792012-10-09 16:57:38 +0000157
158 // If we're not strictly identical, we still might be a commutable instruction
159 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
160 if (!LHSBinOp->isCommutative())
161 return false;
162
Chandler Carruth7253bba2015-01-24 11:33:55 +0000163 assert(isa<BinaryOperator>(RHSI) &&
164 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000165 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
166
167 // Check overflow attributes
168 if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000169 assert(isa<OverflowingBinaryOperator>(RHSBinOp) &&
170 "same opcode, but different operator type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000171 if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
172 LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
173 return false;
174 }
175
176 // Commuted equality
177 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000178 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
Michael Ilseman336cb792012-10-09 16:57:38 +0000179 }
180 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000181 assert(isa<CmpInst>(RHSI) &&
182 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000183 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
184 // Commuted equality
185 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000186 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
187 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
Michael Ilseman336cb792012-10-09 16:57:38 +0000188 }
189
190 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000191}
192
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000193//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000194// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000195//===----------------------------------------------------------------------===//
196
197namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000198/// \brief Struct representing the available call values in the scoped hash
199/// table.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000200struct CallValue {
201 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000202
Chandler Carruth7253bba2015-01-24 11:33:55 +0000203 CallValue(Instruction *I) : Inst(I) {
204 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
205 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000206
Chandler Carruth7253bba2015-01-24 11:33:55 +0000207 bool isSentinel() const {
208 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
209 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
210 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000211
Chandler Carruth7253bba2015-01-24 11:33:55 +0000212 static bool canHandle(Instruction *Inst) {
213 // Don't value number anything that returns void.
214 if (Inst->getType()->isVoidTy())
215 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000216
Chandler Carruth7253bba2015-01-24 11:33:55 +0000217 CallInst *CI = dyn_cast<CallInst>(Inst);
218 if (!CI || !CI->onlyReadsMemory())
219 return false;
220 return true;
221 }
222};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000223}
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000224
225namespace llvm {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000226template <> struct DenseMapInfo<CallValue> {
227 static inline CallValue getEmptyKey() {
228 return DenseMapInfo<Instruction *>::getEmptyKey();
229 }
230 static inline CallValue getTombstoneKey() {
231 return DenseMapInfo<Instruction *>::getTombstoneKey();
232 }
233 static unsigned getHashValue(CallValue Val);
234 static bool isEqual(CallValue LHS, CallValue RHS);
235};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000236}
Chandler Carruth7253bba2015-01-24 11:33:55 +0000237
Chris Lattner92bb0f92011-01-03 03:41:27 +0000238unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000239 Instruction *Inst = Val.Inst;
Benjamin Kramer6ab86b12015-02-01 12:30:59 +0000240 // Hash all of the operands as pointers and mix in the opcode.
241 return hash_combine(
242 Inst->getOpcode(),
243 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000244}
245
Chris Lattner92bb0f92011-01-03 03:41:27 +0000246bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000247 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000248 if (LHS.isSentinel() || RHS.isSentinel())
249 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000250 return LHSI->isIdenticalTo(RHSI);
251}
252
Chris Lattner79d83062011-01-03 02:20:48 +0000253//===----------------------------------------------------------------------===//
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000254// EarlyCSE implementation
Chris Lattner79d83062011-01-03 02:20:48 +0000255//===----------------------------------------------------------------------===//
256
Chris Lattner18ae5432011-01-02 23:04:14 +0000257namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000258/// \brief A simple and fast domtree-based CSE pass.
259///
260/// This pass does a simple depth-first walk over the dominator tree,
261/// eliminating trivially redundant instructions and using instsimplify to
262/// canonicalize things as it goes. It is intended to be fast and catch obvious
263/// cases so that instcombine and other passes are more effective. It is
264/// expected that a later pass of GVN will catch the interesting/hard cases.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000265class EarlyCSE {
Chris Lattner704541b2011-01-02 21:47:05 +0000266public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000267 Function &F;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000268 const TargetLibraryInfo &TLI;
269 const TargetTransformInfo &TTI;
270 DominatorTree &DT;
271 AssumptionCache &AC;
Chandler Carruth7253bba2015-01-24 11:33:55 +0000272 typedef RecyclingAllocator<
273 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
274 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
Chris Lattnerd815f692011-01-03 01:42:46 +0000275 AllocatorTy> ScopedHTType;
Nadav Rotem465834c2012-07-24 10:51:42 +0000276
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000277 /// \brief A scoped hash table of the current values of all of our simple
278 /// scalar expressions.
279 ///
280 /// As we walk down the domtree, we look to see if instructions are in this:
281 /// if so, we replace them with what we find, otherwise we insert them so
282 /// that dominated values can succeed in their lookup.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000283 ScopedHTType AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000284
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000285 /// \brief A scoped hash table of the current values of loads.
286 ///
287 /// This allows us to get efficient access to dominating loads when we have
288 /// a fully redundant load. In addition to the most recent load, we keep
289 /// track of a generation count of the read, which is compared against the
290 /// current generation count. The current generation count is incremented
291 /// after every possibly writing memory operation, which ensures that we only
292 /// CSE loads with other loads that have no intervening store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000293 struct LoadValue {
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000294 Value *Data;
295 unsigned Generation;
296 int MatchingId;
297 LoadValue() : Data(nullptr), Generation(0), MatchingId(-1) {}
298 LoadValue(Value *Data, unsigned Generation, unsigned MatchingId)
299 : Data(Data), Generation(Generation), MatchingId(MatchingId) {}
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000300 };
301 typedef RecyclingAllocator<BumpPtrAllocator,
302 ScopedHashTableVal<Value *, LoadValue>>
Chandler Carruth7253bba2015-01-24 11:33:55 +0000303 LoadMapAllocator;
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000304 typedef ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
305 LoadMapAllocator> LoadHTType;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000306 LoadHTType AvailableLoads;
Nadav Rotem465834c2012-07-24 10:51:42 +0000307
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000308 /// \brief A scoped hash table of the current values of read-only call
309 /// values.
310 ///
311 /// It uses the same generation count as loads.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000312 typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000313 CallHTType AvailableCalls;
Nadav Rotem465834c2012-07-24 10:51:42 +0000314
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000315 /// \brief This is the current generation of the memory value.
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000316 unsigned CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000317
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000318 /// \brief Set up the EarlyCSE runner for a particular function.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000319 EarlyCSE(Function &F, const TargetLibraryInfo &TLI,
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000320 const TargetTransformInfo &TTI, DominatorTree &DT,
321 AssumptionCache &AC)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000322 : F(F), TLI(TLI), TTI(TTI), DT(DT), AC(AC), CurrentGeneration(0) {}
Chris Lattner704541b2011-01-02 21:47:05 +0000323
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000324 bool run();
Chris Lattner704541b2011-01-02 21:47:05 +0000325
326private:
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000327 // Almost a POD, but needs to call the constructors for the scoped hash
328 // tables so that a new scope gets pushed on. These are RAII so that the
329 // scope gets popped when the NodeScope is destroyed.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000330 class NodeScope {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000331 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000332 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
333 CallHTType &AvailableCalls)
334 : Scope(AvailableValues), LoadScope(AvailableLoads),
335 CallScope(AvailableCalls) {}
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000336
Chandler Carruth7253bba2015-01-24 11:33:55 +0000337 private:
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000338 NodeScope(const NodeScope &) = delete;
339 void operator=(const NodeScope &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000340
341 ScopedHTType::ScopeTy Scope;
342 LoadHTType::ScopeTy LoadScope;
343 CallHTType::ScopeTy CallScope;
344 };
345
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000346 // Contains all the needed information to create a stack for doing a depth
347 // first tranversal of the tree. This includes scopes for values, loads, and
348 // calls as well as the generation. There is a child iterator so that the
349 // children do not need to be store spearately.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000350 class StackNode {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000351 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000352 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
353 CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n,
Chandler Carruth7253bba2015-01-24 11:33:55 +0000354 DomTreeNode::iterator child, DomTreeNode::iterator end)
355 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000356 EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls),
Chandler Carruth7253bba2015-01-24 11:33:55 +0000357 Processed(false) {}
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000358
359 // Accessors.
360 unsigned currentGeneration() { return CurrentGeneration; }
361 unsigned childGeneration() { return ChildGeneration; }
362 void childGeneration(unsigned generation) { ChildGeneration = generation; }
363 DomTreeNode *node() { return Node; }
364 DomTreeNode::iterator childIter() { return ChildIter; }
365 DomTreeNode *nextChild() {
366 DomTreeNode *child = *ChildIter;
367 ++ChildIter;
368 return child;
369 }
370 DomTreeNode::iterator end() { return EndIter; }
371 bool isProcessed() { return Processed; }
372 void process() { Processed = true; }
373
Chandler Carruth7253bba2015-01-24 11:33:55 +0000374 private:
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000375 StackNode(const StackNode &) = delete;
376 void operator=(const StackNode &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000377
378 // Members.
379 unsigned CurrentGeneration;
380 unsigned ChildGeneration;
381 DomTreeNode *Node;
382 DomTreeNode::iterator ChildIter;
383 DomTreeNode::iterator EndIter;
384 NodeScope Scopes;
385 bool Processed;
386 };
387
Chad Rosierf9327d62015-01-26 22:51:15 +0000388 /// \brief Wrapper class to handle memory instructions, including loads,
389 /// stores and intrinsic loads and stores defined by the target.
390 class ParseMemoryInst {
391 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000392 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
Chad Rosierf9327d62015-01-26 22:51:15 +0000393 : Load(false), Store(false), Vol(false), MayReadFromMemory(false),
394 MayWriteToMemory(false), MatchingId(-1), Ptr(nullptr) {
395 MayReadFromMemory = Inst->mayReadFromMemory();
396 MayWriteToMemory = Inst->mayWriteToMemory();
397 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
398 MemIntrinsicInfo Info;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000399 if (!TTI.getTgtMemIntrinsic(II, Info))
Chad Rosierf9327d62015-01-26 22:51:15 +0000400 return;
401 if (Info.NumMemRefs == 1) {
402 Store = Info.WriteMem;
403 Load = Info.ReadMem;
404 MatchingId = Info.MatchingId;
405 MayReadFromMemory = Info.ReadMem;
406 MayWriteToMemory = Info.WriteMem;
407 Vol = Info.Vol;
408 Ptr = Info.PtrVal;
409 }
410 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
411 Load = true;
412 Vol = !LI->isSimple();
413 Ptr = LI->getPointerOperand();
414 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
415 Store = true;
416 Vol = !SI->isSimple();
417 Ptr = SI->getPointerOperand();
418 }
419 }
Arnaud A. de Grandmaison6fd488b2015-10-06 13:35:30 +0000420 bool isLoad() const { return Load; }
421 bool isStore() const { return Store; }
422 bool isVolatile() const { return Vol; }
423 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
Chad Rosierf9327d62015-01-26 22:51:15 +0000424 return Ptr == Inst.Ptr && MatchingId == Inst.MatchingId;
425 }
Arnaud A. de Grandmaison6fd488b2015-10-06 13:35:30 +0000426 bool isValid() const { return Ptr != nullptr; }
427 int getMatchingId() const { return MatchingId; }
428 Value *getPtr() const { return Ptr; }
429 bool mayReadFromMemory() const { return MayReadFromMemory; }
430 bool mayWriteToMemory() const { return MayWriteToMemory; }
Chad Rosierf9327d62015-01-26 22:51:15 +0000431
432 private:
433 bool Load;
434 bool Store;
435 bool Vol;
436 bool MayReadFromMemory;
437 bool MayWriteToMemory;
438 // For regular (non-intrinsic) loads/stores, this is set to -1. For
439 // intrinsic loads/stores, the id is retrieved from the corresponding
440 // field in the MemIntrinsicInfo structure. That field contains
441 // non-negative values only.
442 int MatchingId;
443 Value *Ptr;
444 };
445
Chris Lattner18ae5432011-01-02 23:04:14 +0000446 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000447
Chad Rosierf9327d62015-01-26 22:51:15 +0000448 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
449 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
450 return LI;
451 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
452 return SI->getValueOperand();
453 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000454 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
455 ExpectedType);
Chad Rosierf9327d62015-01-26 22:51:15 +0000456 }
Chris Lattner704541b2011-01-02 21:47:05 +0000457};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000458}
Chris Lattner704541b2011-01-02 21:47:05 +0000459
Chris Lattner18ae5432011-01-02 23:04:14 +0000460bool EarlyCSE::processNode(DomTreeNode *Node) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000461 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000462
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000463 // If this block has a single predecessor, then the predecessor is the parent
464 // of the domtree node and all of the live out memory values are still current
465 // in this block. If this block has multiple predecessors, then they could
466 // have invalidated the live-out memory values of our parent value. For now,
467 // just be conservative and invalidate memory if this block has multiple
468 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000469 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000470 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000471
Philip Reames7c78ef72015-05-22 23:53:24 +0000472 // If this node has a single predecessor which ends in a conditional branch,
473 // we can infer the value of the branch condition given that we took this
474 // path. We need the single predeccesor to ensure there's not another path
475 // which reaches this block where the condition might hold a different
476 // value. Since we're adding this to the scoped hash table (like any other
477 // def), it will have been popped if we encounter a future merge block.
478 if (BasicBlock *Pred = BB->getSinglePredecessor())
479 if (auto *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
480 if (BI->isConditional())
481 if (auto *CondInst = dyn_cast<Instruction>(BI->getCondition()))
482 if (SimpleValue::canHandle(CondInst)) {
483 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
484 auto *ConditionalConstant = (BI->getSuccessor(0) == BB) ?
485 ConstantInt::getTrue(BB->getContext()) :
486 ConstantInt::getFalse(BB->getContext());
487 AvailableValues.insert(CondInst, ConditionalConstant);
488 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
489 << CondInst->getName() << "' as " << *ConditionalConstant
490 << " in " << BB->getName() << "\n");
491 // Replace all dominated uses with the known value
492 replaceDominatedUsesWith(CondInst, ConditionalConstant, DT,
493 BasicBlockEdge(Pred, BB));
494 }
495
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000496 /// LastStore - Keep track of the last non-volatile store that we saw... for
497 /// as long as there in no instruction that reads memory. If we see a store
498 /// to the same location, we delete the dead store. This zaps trivial dead
499 /// stores which can occur in bitfield code among other things.
Chad Rosierf9327d62015-01-26 22:51:15 +0000500 Instruction *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000501
Chris Lattner18ae5432011-01-02 23:04:14 +0000502 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000503 const DataLayout &DL = BB->getModule()->getDataLayout();
Chris Lattner18ae5432011-01-02 23:04:14 +0000504
505 // See if any instructions in the block can be eliminated. If so, do it. If
506 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000507 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000508 Instruction *Inst = I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000509
Chris Lattner18ae5432011-01-02 23:04:14 +0000510 // Dead instructions should just be removed.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000511 if (isInstructionTriviallyDead(Inst, &TLI)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000512 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Chris Lattner18ae5432011-01-02 23:04:14 +0000513 Inst->eraseFromParent();
514 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000515 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000516 continue;
517 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000518
Hal Finkel1e16fa32014-11-03 20:21:32 +0000519 // Skip assume intrinsics, they don't really have side effects (although
520 // they're marked as such to ensure preservation of control dependencies),
521 // and this pass will not disturb any of the assumption's control
522 // dependencies.
523 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
524 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
525 continue;
526 }
527
Chris Lattner18ae5432011-01-02 23:04:14 +0000528 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
529 // its simpler value.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000530 if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000531 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
Chris Lattner18ae5432011-01-02 23:04:14 +0000532 Inst->replaceAllUsesWith(V);
533 Inst->eraseFromParent();
534 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000535 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000536 continue;
537 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000538
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000539 // If this is a simple instruction that we can value number, process it.
540 if (SimpleValue::canHandle(Inst)) {
541 // See if the instruction has an available value. If so, use it.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000542 if (Value *V = AvailableValues.lookup(Inst)) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000543 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
544 Inst->replaceAllUsesWith(V);
545 Inst->eraseFromParent();
546 Changed = true;
547 ++NumCSE;
548 continue;
549 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000550
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000551 // Otherwise, just remember that this value is available.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000552 AvailableValues.insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000553 continue;
554 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000555
Chad Rosierf9327d62015-01-26 22:51:15 +0000556 ParseMemoryInst MemInst(Inst, TTI);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000557 // If this is a non-volatile load, process it.
Chad Rosierf9327d62015-01-26 22:51:15 +0000558 if (MemInst.isValid() && MemInst.isLoad()) {
Chris Lattner92bb0f92011-01-03 03:41:27 +0000559 // Ignore volatile loads.
Chad Rosierf9327d62015-01-26 22:51:15 +0000560 if (MemInst.isVolatile()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000561 LastStore = nullptr;
David Majnemer76793002015-02-10 23:09:43 +0000562 // Don't CSE across synchronization boundaries.
563 if (Inst->mayWriteToMemory())
564 ++CurrentGeneration;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000565 continue;
566 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000567
Chris Lattner92bb0f92011-01-03 03:41:27 +0000568 // If we have an available version of this load, and if it is the right
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000569 // generation, replace this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000570 LoadValue InVal = AvailableLoads.lookup(MemInst.getPtr());
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000571 if (InVal.Data != nullptr && InVal.Generation == CurrentGeneration &&
572 InVal.MatchingId == MemInst.getMatchingId()) {
573 Value *Op = getOrCreateResult(InVal.Data, Inst->getType());
Chad Rosierf9327d62015-01-26 22:51:15 +0000574 if (Op != nullptr) {
575 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000576 << " to: " << *InVal.Data << '\n');
Chad Rosierf9327d62015-01-26 22:51:15 +0000577 if (!Inst->use_empty())
578 Inst->replaceAllUsesWith(Op);
579 Inst->eraseFromParent();
580 Changed = true;
581 ++NumCSELoad;
582 continue;
583 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000584 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000585
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000586 // Otherwise, remember that we have this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000587 AvailableLoads.insert(
588 MemInst.getPtr(),
589 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId()));
Craig Topperf40110f2014-04-25 05:29:35 +0000590 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000591 continue;
592 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000593
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000594 // If this instruction may read from memory, forget LastStore.
Chad Rosierf9327d62015-01-26 22:51:15 +0000595 // Load/store intrinsics will indicate both a read and a write to
596 // memory. The target may override this (e.g. so that a store intrinsic
597 // does not read from memory, and thus will be treated the same as a
598 // regular store for commoning purposes).
599 if (Inst->mayReadFromMemory() &&
600 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
Craig Topperf40110f2014-04-25 05:29:35 +0000601 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000602
Chris Lattner92bb0f92011-01-03 03:41:27 +0000603 // If this is a read-only call, process it.
604 if (CallValue::canHandle(Inst)) {
605 // If we have an available version of this call, and if it is the right
606 // generation, replace this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000607 std::pair<Value *, unsigned> InVal = AvailableCalls.lookup(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +0000608 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000609 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
610 << " to: " << *InVal.first << '\n');
611 if (!Inst->use_empty())
612 Inst->replaceAllUsesWith(InVal.first);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000613 Inst->eraseFromParent();
614 Changed = true;
615 ++NumCSECall;
616 continue;
617 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000618
Chris Lattner92bb0f92011-01-03 03:41:27 +0000619 // Otherwise, remember that we have this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000620 AvailableCalls.insert(
Chandler Carruth7253bba2015-01-24 11:33:55 +0000621 Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000622 continue;
623 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000624
Philip Reamesdfd890d2015-08-27 01:32:33 +0000625 // A release fence requires that all stores complete before it, but does
626 // not prevent the reordering of following loads 'before' the fence. As a
627 // result, we don't need to consider it as writing to memory and don't need
628 // to advance the generation. We do need to prevent DSE across the fence,
629 // but that's handled above.
630 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
631 if (FI->getOrdering() == Release) {
632 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
633 continue;
634 }
635
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000636 // Okay, this isn't something we can CSE at all. Check to see if it is
637 // something that could modify memory. If so, our available memory values
638 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +0000639 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000640 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000641
Chad Rosierf9327d62015-01-26 22:51:15 +0000642 if (MemInst.isValid() && MemInst.isStore()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000643 // We do a trivial form of DSE if there are two stores to the same
644 // location with no intervening loads. Delete the earlier store.
Chad Rosierf9327d62015-01-26 22:51:15 +0000645 if (LastStore) {
646 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
647 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
648 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
649 << " due to: " << *Inst << '\n');
650 LastStore->eraseFromParent();
651 Changed = true;
652 ++NumDSE;
653 LastStore = nullptr;
654 }
Philip Reames018dbf12014-11-18 17:46:32 +0000655 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000656 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000657
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000658 // Okay, we just invalidated anything we knew about loaded values. Try
659 // to salvage *something* by remembering that the stored value is a live
660 // version of the pointer. It is safe to forward from volatile stores
661 // to non-volatile loads, so we don't have to check for volatility of
662 // the store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000663 AvailableLoads.insert(
664 MemInst.getPtr(),
665 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId()));
Nadav Rotem465834c2012-07-24 10:51:42 +0000666
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000667 // Remember that this was the last store we saw for DSE.
Chad Rosierf9327d62015-01-26 22:51:15 +0000668 if (!MemInst.isVolatile())
669 LastStore = Inst;
Chris Lattnere0e32a92011-01-03 03:46:34 +0000670 }
671 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000672 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000673
Chris Lattner18ae5432011-01-02 23:04:14 +0000674 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +0000675}
Chris Lattner18ae5432011-01-02 23:04:14 +0000676
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000677bool EarlyCSE::run() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000678 // Note, deque is being used here because there is significant performance
679 // gains over vector when the container becomes very large due to the
680 // specific access patterns. For more information see the mailing list
681 // discussion on this:
Tanya Lattner0d28f802015-08-05 03:51:17 +0000682 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
Lenny Maiorani9eefc812014-09-20 13:29:20 +0000683 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000684
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000685 bool Changed = false;
686
687 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000688 nodesToProcess.push_back(new StackNode(
689 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000690 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000691
692 // Save the current generation.
693 unsigned LiveOutGeneration = CurrentGeneration;
694
695 // Process the stack.
696 while (!nodesToProcess.empty()) {
697 // Grab the first item off the stack. Set the current generation, remove
698 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +0000699 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000700
701 // Initialize class members.
702 CurrentGeneration = NodeToProcess->currentGeneration();
703
704 // Check if the node needs to be processed.
705 if (!NodeToProcess->isProcessed()) {
706 // Process the node.
707 Changed |= processNode(NodeToProcess->node());
708 NodeToProcess->childGeneration(CurrentGeneration);
709 NodeToProcess->process();
710 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
711 // Push the next child onto the stack.
712 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +0000713 nodesToProcess.push_back(
Chandler Carruth7253bba2015-01-24 11:33:55 +0000714 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
715 NodeToProcess->childGeneration(), child, child->begin(),
716 child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000717 } else {
718 // It has been processed, and there are no more children to process,
719 // so delete it and pop it off the stack.
720 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +0000721 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000722 }
723 } // while (!nodes...)
724
725 // Reset the current generation.
726 CurrentGeneration = LiveOutGeneration;
727
728 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +0000729}
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000730
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000731PreservedAnalyses EarlyCSEPass::run(Function &F,
732 AnalysisManager<Function> *AM) {
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000733 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
734 auto &TTI = AM->getResult<TargetIRAnalysis>(F);
735 auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
736 auto &AC = AM->getResult<AssumptionAnalysis>(F);
737
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000738 EarlyCSE CSE(F, TLI, TTI, DT, AC);
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000739
740 if (!CSE.run())
741 return PreservedAnalyses::all();
742
743 // CSE preserves the dominator tree because it doesn't mutate the CFG.
744 // FIXME: Bundle this with other CFG-preservation.
745 PreservedAnalyses PA;
746 PA.preserve<DominatorTreeAnalysis>();
747 return PA;
748}
749
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000750namespace {
751/// \brief A simple and fast domtree-based CSE pass.
752///
753/// This pass does a simple depth-first walk over the dominator tree,
754/// eliminating trivially redundant instructions and using instsimplify to
755/// canonicalize things as it goes. It is intended to be fast and catch obvious
756/// cases so that instcombine and other passes are more effective. It is
757/// expected that a later pass of GVN will catch the interesting/hard cases.
758class EarlyCSELegacyPass : public FunctionPass {
759public:
760 static char ID;
761
762 EarlyCSELegacyPass() : FunctionPass(ID) {
763 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
764 }
765
766 bool runOnFunction(Function &F) override {
767 if (skipOptnoneFunction(F))
768 return false;
769
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000770 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000771 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000772 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
773 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
774
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000775 EarlyCSE CSE(F, TLI, TTI, DT, AC);
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000776
777 return CSE.run();
778 }
779
780 void getAnalysisUsage(AnalysisUsage &AU) const override {
781 AU.addRequired<AssumptionCacheTracker>();
782 AU.addRequired<DominatorTreeWrapperPass>();
783 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000784 AU.addRequired<TargetTransformInfoWrapperPass>();
James Molloyefbba722015-09-10 10:22:12 +0000785 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000786 AU.setPreservesCFG();
787 }
788};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000789}
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000790
791char EarlyCSELegacyPass::ID = 0;
792
793FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); }
794
795INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
796 false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000797INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000798INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
799INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
800INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
801INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)