blob: 1d7da48321dc2048207ce1e8eaf5eb7994a4e05b [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"
Andrew Kaylorf0f27922016-04-21 17:58:54 +000028#include "llvm/IR/OptBisect.h"
Hal Finkel1e16fa32014-11-03 20:21:32 +000029#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Pass.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/RecyclingAllocator.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +000034#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Transforms/Utils/Local.h"
Lenny Maiorani9eefc812014-09-20 13:29:20 +000036#include <deque>
Chris Lattner704541b2011-01-02 21:47:05 +000037using namespace llvm;
Hal Finkel1e16fa32014-11-03 20:21:32 +000038using namespace llvm::PatternMatch;
Chris Lattner704541b2011-01-02 21:47:05 +000039
Chandler Carruth964daaa2014-04-22 02:55:47 +000040#define DEBUG_TYPE "early-cse"
41
Chris Lattner4cb36542011-01-03 03:28:23 +000042STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
43STATISTIC(NumCSE, "Number of instructions CSE'd");
Chris Lattner92bb0f92011-01-03 03:41:27 +000044STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
45STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner9e5e9ed2011-01-03 04:17:24 +000046STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattnerb9a8efc2011-01-03 03:18:43 +000047
Chris Lattner79d83062011-01-03 02:20:48 +000048//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +000049// SimpleValue
Chris Lattner79d83062011-01-03 02:20:48 +000050//===----------------------------------------------------------------------===//
51
Chris Lattner704541b2011-01-02 21:47:05 +000052namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +000053/// \brief Struct representing the available values in the scoped hash table.
Chandler Carruth7253bba2015-01-24 11:33:55 +000054struct 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};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000077}
Chris Lattner18ae5432011-01-02 23:04:14 +000078
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};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000090}
Chris Lattner18ae5432011-01-02 23:04:14 +000091
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;
David Majnemer9554c132016-04-22 06:37:45 +0000156 if (LHSI->isIdenticalToWhenDefined(RHSI))
Chandler Carruth7253bba2015-01-24 11:33:55 +0000157 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
Michael Ilseman336cb792012-10-09 16:57:38 +0000168 // Commuted equality
169 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000170 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
Michael Ilseman336cb792012-10-09 16:57:38 +0000171 }
172 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000173 assert(isa<CmpInst>(RHSI) &&
174 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000175 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
176 // Commuted equality
177 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000178 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
179 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
Michael Ilseman336cb792012-10-09 16:57:38 +0000180 }
181
182 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000183}
184
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000185//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000186// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000187//===----------------------------------------------------------------------===//
188
189namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000190/// \brief Struct representing the available call values in the scoped hash
191/// table.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000192struct CallValue {
193 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000194
Chandler Carruth7253bba2015-01-24 11:33:55 +0000195 CallValue(Instruction *I) : Inst(I) {
196 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
197 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000198
Chandler Carruth7253bba2015-01-24 11:33:55 +0000199 bool isSentinel() const {
200 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
201 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
202 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000203
Chandler Carruth7253bba2015-01-24 11:33:55 +0000204 static bool canHandle(Instruction *Inst) {
205 // Don't value number anything that returns void.
206 if (Inst->getType()->isVoidTy())
207 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000208
Chandler Carruth7253bba2015-01-24 11:33:55 +0000209 CallInst *CI = dyn_cast<CallInst>(Inst);
210 if (!CI || !CI->onlyReadsMemory())
211 return false;
212 return true;
213 }
214};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000215}
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000216
217namespace llvm {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000218template <> struct DenseMapInfo<CallValue> {
219 static inline CallValue getEmptyKey() {
220 return DenseMapInfo<Instruction *>::getEmptyKey();
221 }
222 static inline CallValue getTombstoneKey() {
223 return DenseMapInfo<Instruction *>::getTombstoneKey();
224 }
225 static unsigned getHashValue(CallValue Val);
226 static bool isEqual(CallValue LHS, CallValue RHS);
227};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000228}
Chandler Carruth7253bba2015-01-24 11:33:55 +0000229
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;
Benjamin Kramer6ab86b12015-02-01 12:30:59 +0000232 // Hash all of the operands as pointers and mix in the opcode.
233 return hash_combine(
234 Inst->getOpcode(),
235 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000236}
237
Chris Lattner92bb0f92011-01-03 03:41:27 +0000238bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000239 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000240 if (LHS.isSentinel() || RHS.isSentinel())
241 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000242 return LHSI->isIdenticalTo(RHSI);
243}
244
Chris Lattner79d83062011-01-03 02:20:48 +0000245//===----------------------------------------------------------------------===//
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000246// EarlyCSE implementation
Chris Lattner79d83062011-01-03 02:20:48 +0000247//===----------------------------------------------------------------------===//
248
Chris Lattner18ae5432011-01-02 23:04:14 +0000249namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000250/// \brief A simple and fast domtree-based CSE pass.
251///
252/// This pass does a simple depth-first walk over the dominator tree,
253/// eliminating trivially redundant instructions and using instsimplify to
254/// canonicalize things as it goes. It is intended to be fast and catch obvious
255/// cases so that instcombine and other passes are more effective. It is
256/// expected that a later pass of GVN will catch the interesting/hard cases.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000257class EarlyCSE {
Chris Lattner704541b2011-01-02 21:47:05 +0000258public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000259 const TargetLibraryInfo &TLI;
260 const TargetTransformInfo &TTI;
261 DominatorTree &DT;
262 AssumptionCache &AC;
Chandler Carruth7253bba2015-01-24 11:33:55 +0000263 typedef RecyclingAllocator<
264 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
265 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
Chris Lattnerd815f692011-01-03 01:42:46 +0000266 AllocatorTy> ScopedHTType;
Nadav Rotem465834c2012-07-24 10:51:42 +0000267
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000268 /// \brief A scoped hash table of the current values of all of our simple
269 /// scalar expressions.
270 ///
271 /// As we walk down the domtree, we look to see if instructions are in this:
272 /// if so, we replace them with what we find, otherwise we insert them so
273 /// that dominated values can succeed in their lookup.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000274 ScopedHTType AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000275
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000276 /// A scoped hash table of the current values of previously encounted memory
277 /// locations.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000278 ///
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000279 /// This allows us to get efficient access to dominating loads or stores when
280 /// we have a fully redundant load. In addition to the most recent load, we
281 /// keep track of a generation count of the read, which is compared against
282 /// the current generation count. The current generation count is incremented
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000283 /// after every possibly writing memory operation, which ensures that we only
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000284 /// CSE loads with other loads that have no intervening store. Ordering
285 /// events (such as fences or atomic instructions) increment the generation
286 /// count as well; essentially, we model these as writes to all possible
287 /// locations. Note that atomic and/or volatile loads and stores can be
288 /// present the table; it is the responsibility of the consumer to inspect
289 /// the atomicity/volatility if needed.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000290 struct LoadValue {
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000291 Value *Data;
292 unsigned Generation;
293 int MatchingId;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000294 bool IsAtomic;
295 LoadValue()
296 : Data(nullptr), Generation(0), MatchingId(-1), IsAtomic(false) {}
297 LoadValue(Value *Data, unsigned Generation, unsigned MatchingId,
298 bool IsAtomic)
299 : Data(Data), Generation(Generation), MatchingId(MatchingId),
300 IsAtomic(IsAtomic) {}
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000301 };
302 typedef RecyclingAllocator<BumpPtrAllocator,
303 ScopedHashTableVal<Value *, LoadValue>>
Chandler Carruth7253bba2015-01-24 11:33:55 +0000304 LoadMapAllocator;
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000305 typedef ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
306 LoadMapAllocator> LoadHTType;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000307 LoadHTType AvailableLoads;
Nadav Rotem465834c2012-07-24 10:51:42 +0000308
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000309 /// \brief A scoped hash table of the current values of read-only call
310 /// values.
311 ///
312 /// It uses the same generation count as loads.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000313 typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000314 CallHTType AvailableCalls;
Nadav Rotem465834c2012-07-24 10:51:42 +0000315
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000316 /// \brief This is the current generation of the memory value.
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000317 unsigned CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000318
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000319 /// \brief Set up the EarlyCSE runner for a particular function.
Benjamin Kramer6db33382015-10-15 15:08:58 +0000320 EarlyCSE(const TargetLibraryInfo &TLI, const TargetTransformInfo &TTI,
321 DominatorTree &DT, AssumptionCache &AC)
322 : 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)
Philip Reames9e5e2d62015-12-07 22:41:23 +0000393 : IsTargetMemInst(false), Inst(Inst) {
394 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
395 if (TTI.getTgtMemIntrinsic(II, Info) && Info.NumMemRefs == 1)
396 IsTargetMemInst = true;
397 }
398 bool isLoad() const {
399 if (IsTargetMemInst) return Info.ReadMem;
400 return isa<LoadInst>(Inst);
401 }
402 bool isStore() const {
403 if (IsTargetMemInst) return Info.WriteMem;
404 return isa<StoreInst>(Inst);
405 }
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000406 bool isAtomic() const {
407 if (IsTargetMemInst) {
408 assert(Info.IsSimple && "need to refine IsSimple in TTI");
409 return false;
410 }
411 return Inst->isAtomic();
412 }
413 bool isUnordered() const {
414 if (IsTargetMemInst) {
415 assert(Info.IsSimple && "need to refine IsSimple in TTI");
416 return true;
417 }
418 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
419 return LI->isUnordered();
420 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
421 return SI->isUnordered();
422 }
423 // Conservative answer
424 return !Inst->isAtomic();
425 }
426
427 bool isVolatile() const {
428 if (IsTargetMemInst) {
429 assert(Info.IsSimple && "need to refine IsSimple in TTI");
430 return false;
431 }
432 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
433 return LI->isVolatile();
434 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
435 return SI->isVolatile();
436 }
437 // Conservative answer
438 return true;
439 }
440
Junmo Park80440eb2016-02-18 10:09:20 +0000441
Arnaud A. de Grandmaison6fd488b2015-10-06 13:35:30 +0000442 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000443 return (getPointerOperand() == Inst.getPointerOperand() &&
444 getMatchingId() == Inst.getMatchingId());
Chad Rosierf9327d62015-01-26 22:51:15 +0000445 }
Philip Reames9e5e2d62015-12-07 22:41:23 +0000446 bool isValid() const { return getPointerOperand() != nullptr; }
Chad Rosierf9327d62015-01-26 22:51:15 +0000447
Chad Rosierf9327d62015-01-26 22:51:15 +0000448 // For regular (non-intrinsic) loads/stores, this is set to -1. For
449 // intrinsic loads/stores, the id is retrieved from the corresponding
450 // field in the MemIntrinsicInfo structure. That field contains
451 // non-negative values only.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000452 int getMatchingId() const {
453 if (IsTargetMemInst) return Info.MatchingId;
454 return -1;
455 }
456 Value *getPointerOperand() const {
457 if (IsTargetMemInst) return Info.PtrVal;
458 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
459 return LI->getPointerOperand();
460 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
461 return SI->getPointerOperand();
462 }
463 return nullptr;
464 }
465 bool mayReadFromMemory() const {
466 if (IsTargetMemInst) return Info.ReadMem;
467 return Inst->mayReadFromMemory();
468 }
469 bool mayWriteToMemory() const {
470 if (IsTargetMemInst) return Info.WriteMem;
471 return Inst->mayWriteToMemory();
472 }
473
474 private:
475 bool IsTargetMemInst;
476 MemIntrinsicInfo Info;
477 Instruction *Inst;
Chad Rosierf9327d62015-01-26 22:51:15 +0000478 };
479
Chris Lattner18ae5432011-01-02 23:04:14 +0000480 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000481
Chad Rosierf9327d62015-01-26 22:51:15 +0000482 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
483 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
484 return LI;
485 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
486 return SI->getValueOperand();
487 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000488 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
489 ExpectedType);
Chad Rosierf9327d62015-01-26 22:51:15 +0000490 }
Chris Lattner704541b2011-01-02 21:47:05 +0000491};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000492}
Chris Lattner704541b2011-01-02 21:47:05 +0000493
Chris Lattner18ae5432011-01-02 23:04:14 +0000494bool EarlyCSE::processNode(DomTreeNode *Node) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000495 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000496
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000497 // If this block has a single predecessor, then the predecessor is the parent
498 // of the domtree node and all of the live out memory values are still current
499 // in this block. If this block has multiple predecessors, then they could
500 // have invalidated the live-out memory values of our parent value. For now,
501 // just be conservative and invalidate memory if this block has multiple
502 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000503 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000504 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000505
Philip Reames7c78ef72015-05-22 23:53:24 +0000506 // If this node has a single predecessor which ends in a conditional branch,
507 // we can infer the value of the branch condition given that we took this
Chad Rosierb346dcb2016-04-20 19:16:23 +0000508 // path. We need the single predecessor to ensure there's not another path
Philip Reames7c78ef72015-05-22 23:53:24 +0000509 // which reaches this block where the condition might hold a different
510 // value. Since we're adding this to the scoped hash table (like any other
511 // def), it will have been popped if we encounter a future merge block.
512 if (BasicBlock *Pred = BB->getSinglePredecessor())
513 if (auto *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
514 if (BI->isConditional())
515 if (auto *CondInst = dyn_cast<Instruction>(BI->getCondition()))
516 if (SimpleValue::canHandle(CondInst)) {
517 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
518 auto *ConditionalConstant = (BI->getSuccessor(0) == BB) ?
519 ConstantInt::getTrue(BB->getContext()) :
520 ConstantInt::getFalse(BB->getContext());
521 AvailableValues.insert(CondInst, ConditionalConstant);
522 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
523 << CondInst->getName() << "' as " << *ConditionalConstant
524 << " in " << BB->getName() << "\n");
525 // Replace all dominated uses with the known value
526 replaceDominatedUsesWith(CondInst, ConditionalConstant, DT,
527 BasicBlockEdge(Pred, BB));
528 }
529
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000530 /// LastStore - Keep track of the last non-volatile store that we saw... for
531 /// as long as there in no instruction that reads memory. If we see a store
532 /// to the same location, we delete the dead store. This zaps trivial dead
533 /// stores which can occur in bitfield code among other things.
Chad Rosierf9327d62015-01-26 22:51:15 +0000534 Instruction *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000535
Chris Lattner18ae5432011-01-02 23:04:14 +0000536 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000537 const DataLayout &DL = BB->getModule()->getDataLayout();
Chris Lattner18ae5432011-01-02 23:04:14 +0000538
539 // See if any instructions in the block can be eliminated. If so, do it. If
540 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000541 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000542 Instruction *Inst = &*I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000543
Chris Lattner18ae5432011-01-02 23:04:14 +0000544 // Dead instructions should just be removed.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000545 if (isInstructionTriviallyDead(Inst, &TLI)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000546 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Chris Lattner18ae5432011-01-02 23:04:14 +0000547 Inst->eraseFromParent();
548 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000549 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000550 continue;
551 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000552
Hal Finkel1e16fa32014-11-03 20:21:32 +0000553 // Skip assume intrinsics, they don't really have side effects (although
554 // they're marked as such to ensure preservation of control dependencies),
555 // and this pass will not disturb any of the assumption's control
556 // dependencies.
557 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
558 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
559 continue;
560 }
561
Chris Lattner18ae5432011-01-02 23:04:14 +0000562 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
563 // its simpler value.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000564 if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000565 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
Chris Lattner18ae5432011-01-02 23:04:14 +0000566 Inst->replaceAllUsesWith(V);
567 Inst->eraseFromParent();
568 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000569 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000570 continue;
571 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000572
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000573 // If this is a simple instruction that we can value number, process it.
574 if (SimpleValue::canHandle(Inst)) {
575 // See if the instruction has an available value. If so, use it.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000576 if (Value *V = AvailableValues.lookup(Inst)) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000577 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
David Majnemer9554c132016-04-22 06:37:45 +0000578 if (auto *I = dyn_cast<Instruction>(V))
579 I->andIRFlags(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000580 Inst->replaceAllUsesWith(V);
581 Inst->eraseFromParent();
582 Changed = true;
583 ++NumCSE;
584 continue;
585 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000586
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000587 // Otherwise, just remember that this value is available.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000588 AvailableValues.insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000589 continue;
590 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000591
Chad Rosierf9327d62015-01-26 22:51:15 +0000592 ParseMemoryInst MemInst(Inst, TTI);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000593 // If this is a non-volatile load, process it.
Chad Rosierf9327d62015-01-26 22:51:15 +0000594 if (MemInst.isValid() && MemInst.isLoad()) {
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000595 // (conservatively) we can't peak past the ordering implied by this
596 // operation, but we can add this load to our set of available values
597 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000598 LastStore = nullptr;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000599 ++CurrentGeneration;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000600 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000601
Chris Lattner92bb0f92011-01-03 03:41:27 +0000602 // If we have an available version of this load, and if it is the right
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000603 // generation, replace this instruction.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000604 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000605 if (InVal.Data != nullptr && InVal.Generation == CurrentGeneration &&
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000606 InVal.MatchingId == MemInst.getMatchingId() &&
607 // We don't yet handle removing loads with ordering of any kind.
608 !MemInst.isVolatile() && MemInst.isUnordered() &&
609 // We can't replace an atomic load with one which isn't also atomic.
610 InVal.IsAtomic >= MemInst.isAtomic()) {
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000611 Value *Op = getOrCreateResult(InVal.Data, Inst->getType());
Chad Rosierf9327d62015-01-26 22:51:15 +0000612 if (Op != nullptr) {
613 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000614 << " to: " << *InVal.Data << '\n');
Chad Rosierf9327d62015-01-26 22:51:15 +0000615 if (!Inst->use_empty())
616 Inst->replaceAllUsesWith(Op);
617 Inst->eraseFromParent();
618 Changed = true;
619 ++NumCSELoad;
620 continue;
621 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000622 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000623
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000624 // Otherwise, remember that we have this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000625 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000626 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000627 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
628 MemInst.isAtomic()));
Craig Topperf40110f2014-04-25 05:29:35 +0000629 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000630 continue;
631 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000632
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000633 // If this instruction may read from memory, forget LastStore.
Chad Rosierf9327d62015-01-26 22:51:15 +0000634 // Load/store intrinsics will indicate both a read and a write to
635 // memory. The target may override this (e.g. so that a store intrinsic
636 // does not read from memory, and thus will be treated the same as a
637 // regular store for commoning purposes).
638 if (Inst->mayReadFromMemory() &&
639 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
Craig Topperf40110f2014-04-25 05:29:35 +0000640 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000641
Chris Lattner92bb0f92011-01-03 03:41:27 +0000642 // If this is a read-only call, process it.
643 if (CallValue::canHandle(Inst)) {
644 // If we have an available version of this call, and if it is the right
645 // generation, replace this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000646 std::pair<Value *, unsigned> InVal = AvailableCalls.lookup(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +0000647 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000648 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
649 << " to: " << *InVal.first << '\n');
650 if (!Inst->use_empty())
651 Inst->replaceAllUsesWith(InVal.first);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000652 Inst->eraseFromParent();
653 Changed = true;
654 ++NumCSECall;
655 continue;
656 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000657
Chris Lattner92bb0f92011-01-03 03:41:27 +0000658 // Otherwise, remember that we have this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000659 AvailableCalls.insert(
Chandler Carruth7253bba2015-01-24 11:33:55 +0000660 Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000661 continue;
662 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000663
Philip Reamesdfd890d2015-08-27 01:32:33 +0000664 // A release fence requires that all stores complete before it, but does
665 // not prevent the reordering of following loads 'before' the fence. As a
666 // result, we don't need to consider it as writing to memory and don't need
667 // to advance the generation. We do need to prevent DSE across the fence,
668 // but that's handled above.
669 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
JF Bastien800f87a2016-04-06 21:19:33 +0000670 if (FI->getOrdering() == AtomicOrdering::Release) {
Philip Reamesdfd890d2015-08-27 01:32:33 +0000671 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
672 continue;
673 }
674
Philip Reamesae1f265b2015-12-16 01:01:30 +0000675 // write back DSE - If we write back the same value we just loaded from
676 // the same location and haven't passed any intervening writes or ordering
677 // operations, we can remove the write. The primary benefit is in allowing
678 // the available load table to remain valid and value forward past where
679 // the store originally was.
680 if (MemInst.isValid() && MemInst.isStore()) {
681 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
682 if (InVal.Data &&
683 InVal.Data == getOrCreateResult(Inst, InVal.Data->getType()) &&
684 InVal.Generation == CurrentGeneration &&
685 InVal.MatchingId == MemInst.getMatchingId() &&
686 // We don't yet handle removing stores with ordering of any kind.
687 !MemInst.isVolatile() && MemInst.isUnordered()) {
688 assert((!LastStore ||
689 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
690 MemInst.getPointerOperand()) &&
691 "can't have an intervening store!");
692 DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n');
693 Inst->eraseFromParent();
694 Changed = true;
695 ++NumDSE;
696 // We can avoid incrementing the generation count since we were able
697 // to eliminate this store.
698 continue;
699 }
700 }
701
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000702 // Okay, this isn't something we can CSE at all. Check to see if it is
703 // something that could modify memory. If so, our available memory values
704 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +0000705 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000706 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000707
Chad Rosierf9327d62015-01-26 22:51:15 +0000708 if (MemInst.isValid() && MemInst.isStore()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000709 // We do a trivial form of DSE if there are two stores to the same
Philip Reames15145fb2015-12-17 18:50:50 +0000710 // location with no intervening loads. Delete the earlier store.
711 // At the moment, we don't remove ordered stores, but do remove
712 // unordered atomic stores. There's no special requirement (for
713 // unordered atomics) about removing atomic stores only in favor of
714 // other atomic stores since we we're going to execute the non-atomic
715 // one anyway and the atomic one might never have become visible.
Chad Rosierf9327d62015-01-26 22:51:15 +0000716 if (LastStore) {
717 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
Philip Reames15145fb2015-12-17 18:50:50 +0000718 assert(LastStoreMemInst.isUnordered() &&
719 !LastStoreMemInst.isVolatile() &&
720 "Violated invariant");
Chad Rosierf9327d62015-01-26 22:51:15 +0000721 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
722 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
723 << " due to: " << *Inst << '\n');
724 LastStore->eraseFromParent();
725 Changed = true;
726 ++NumDSE;
727 LastStore = nullptr;
728 }
Philip Reames018dbf12014-11-18 17:46:32 +0000729 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000730 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000731
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000732 // Okay, we just invalidated anything we knew about loaded values. Try
733 // to salvage *something* by remembering that the stored value is a live
734 // version of the pointer. It is safe to forward from volatile stores
735 // to non-volatile loads, so we don't have to check for volatility of
736 // the store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000737 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000738 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000739 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
740 MemInst.isAtomic()));
Nadav Rotem465834c2012-07-24 10:51:42 +0000741
Philip Reames15145fb2015-12-17 18:50:50 +0000742 // Remember that this was the last unordered store we saw for DSE. We
743 // don't yet handle DSE on ordered or volatile stores since we don't
744 // have a good way to model the ordering requirement for following
745 // passes once the store is removed. We could insert a fence, but
746 // since fences are slightly stronger than stores in their ordering,
747 // it's not clear this is a profitable transform. Another option would
748 // be to merge the ordering with that of the post dominating store.
749 if (MemInst.isUnordered() && !MemInst.isVolatile())
Chad Rosierf9327d62015-01-26 22:51:15 +0000750 LastStore = Inst;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000751 else
752 LastStore = nullptr;
Chris Lattnere0e32a92011-01-03 03:46:34 +0000753 }
754 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000755 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000756
Chris Lattner18ae5432011-01-02 23:04:14 +0000757 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +0000758}
Chris Lattner18ae5432011-01-02 23:04:14 +0000759
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000760bool EarlyCSE::run() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000761 // Note, deque is being used here because there is significant performance
762 // gains over vector when the container becomes very large due to the
763 // specific access patterns. For more information see the mailing list
764 // discussion on this:
Tanya Lattner0d28f802015-08-05 03:51:17 +0000765 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
Lenny Maiorani9eefc812014-09-20 13:29:20 +0000766 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000767
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000768 bool Changed = false;
769
770 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000771 nodesToProcess.push_back(new StackNode(
772 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000773 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000774
775 // Save the current generation.
776 unsigned LiveOutGeneration = CurrentGeneration;
777
778 // Process the stack.
779 while (!nodesToProcess.empty()) {
780 // Grab the first item off the stack. Set the current generation, remove
781 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +0000782 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000783
784 // Initialize class members.
785 CurrentGeneration = NodeToProcess->currentGeneration();
786
787 // Check if the node needs to be processed.
788 if (!NodeToProcess->isProcessed()) {
789 // Process the node.
790 Changed |= processNode(NodeToProcess->node());
791 NodeToProcess->childGeneration(CurrentGeneration);
792 NodeToProcess->process();
793 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
794 // Push the next child onto the stack.
795 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +0000796 nodesToProcess.push_back(
Chandler Carruth7253bba2015-01-24 11:33:55 +0000797 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
798 NodeToProcess->childGeneration(), child, child->begin(),
799 child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000800 } else {
801 // It has been processed, and there are no more children to process,
802 // so delete it and pop it off the stack.
803 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +0000804 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000805 }
806 } // while (!nodes...)
807
808 // Reset the current generation.
809 CurrentGeneration = LiveOutGeneration;
810
811 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +0000812}
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000813
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000814PreservedAnalyses EarlyCSEPass::run(Function &F,
Chandler Carruthb47f8012016-03-11 11:05:24 +0000815 AnalysisManager<Function> &AM) {
Andrew Kaylorf0f27922016-04-21 17:58:54 +0000816 if (skipPassForFunction(name(), F))
817 return PreservedAnalyses::all();
818
Chandler Carruthb47f8012016-03-11 11:05:24 +0000819 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
820 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
821 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
822 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000823
Benjamin Kramer6db33382015-10-15 15:08:58 +0000824 EarlyCSE CSE(TLI, TTI, DT, AC);
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000825
826 if (!CSE.run())
827 return PreservedAnalyses::all();
828
829 // CSE preserves the dominator tree because it doesn't mutate the CFG.
830 // FIXME: Bundle this with other CFG-preservation.
831 PreservedAnalyses PA;
832 PA.preserve<DominatorTreeAnalysis>();
833 return PA;
834}
835
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000836namespace {
837/// \brief A simple and fast domtree-based CSE pass.
838///
839/// This pass does a simple depth-first walk over the dominator tree,
840/// eliminating trivially redundant instructions and using instsimplify to
841/// canonicalize things as it goes. It is intended to be fast and catch obvious
842/// cases so that instcombine and other passes are more effective. It is
843/// expected that a later pass of GVN will catch the interesting/hard cases.
844class EarlyCSELegacyPass : public FunctionPass {
845public:
846 static char ID;
847
848 EarlyCSELegacyPass() : FunctionPass(ID) {
849 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
850 }
851
852 bool runOnFunction(Function &F) override {
Andrew Kaylorf0f27922016-04-21 17:58:54 +0000853 if (skipFunction(F))
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000854 return false;
855
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000856 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000857 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000858 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
859 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
860
Benjamin Kramer6db33382015-10-15 15:08:58 +0000861 EarlyCSE CSE(TLI, TTI, DT, AC);
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000862
863 return CSE.run();
864 }
865
866 void getAnalysisUsage(AnalysisUsage &AU) const override {
867 AU.addRequired<AssumptionCacheTracker>();
868 AU.addRequired<DominatorTreeWrapperPass>();
869 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000870 AU.addRequired<TargetTransformInfoWrapperPass>();
James Molloyefbba722015-09-10 10:22:12 +0000871 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000872 AU.setPreservesCFG();
873 }
874};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000875}
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000876
877char EarlyCSELegacyPass::ID = 0;
878
879FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); }
880
881INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
882 false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000883INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000884INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
885INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
886INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
887INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)